Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b83b2bab7 | ||
|
|
871e54917c | ||
|
|
30141b13ac | ||
|
|
1d2a484b31 | ||
|
|
7f8afdcdbb | ||
|
|
a7ba6360e5 | ||
|
|
8a4880d5ec | ||
|
|
b388e7112d | ||
|
|
b878523d51 | ||
|
|
016fc707d1 | ||
|
|
9243fe4d3f | ||
|
|
c55a6596d0 |
No files matched your search
@@ -29,6 +29,12 @@ ART_STORAGE_DIR=var/album-art
|
||||
# Largest image a user may upload as their own album art (bytes). Uploaded art is
|
||||
# stored in ART_STORAGE_DIR too, so back that directory up.
|
||||
ART_UPLOAD_MAX_BYTES=5242880
|
||||
# Largest profile image a user may upload (bytes). Stored in an "avatars" folder inside
|
||||
# ART_STORAGE_DIR, so the same backups cover it.
|
||||
AVATAR_UPLOAD_MAX_BYTES=2097152
|
||||
# Let users use their Gravatar as their profile image. The server fetches it, sending
|
||||
# Gravatar a hash of the user's email address, so it's off unless you turn it on.
|
||||
AVATAR_GRAVATAR_ENABLED=false
|
||||
|
||||
# docker compose host ports (defaults shown)
|
||||
API_PORT=5050
|
||||
|
||||
@@ -184,7 +184,7 @@ jobs:
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger ScrobbledDeploy
|
||||
- name: Trigger scrobbler deploy (matt/playbooks)
|
||||
env:
|
||||
VERSION: ${{ needs.images.outputs.version }}
|
||||
TOKEN: ${{ secrets.SCROBBLEDDEPLOY_DISPATCH_TOKEN }}
|
||||
@@ -193,7 +193,7 @@ jobs:
|
||||
-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"
|
||||
"https://git.daubney.dev/api/v1/repos/matt/playbooks/actions/workflows/deploy-scrobbler.yml/dispatches"
|
||||
|
||||
notify:
|
||||
needs: [lint, test, validate-monitoring, federation-interop, images, assets, python-package, trigger-deploy]
|
||||
|
||||
@@ -33,7 +33,7 @@ cp .env.example .env # then set SECRET_KEY and POSTGRES_PAS
|
||||
docker compose up -d # db, api (:5050), worker, ui (:8080)
|
||||
```
|
||||
|
||||
Open http://localhost:8080, create an account, then go to **Apps** and create an app for
|
||||
Open http://localhost:8080, create an account, then open **Apps** from the account menu (top right) and create an app for
|
||||
a player. See [docs/admin-guide.md](docs/admin-guide.md) for the published images, full
|
||||
configuration reference and production notes.
|
||||
|
||||
|
||||
+8
-1
@@ -35,7 +35,7 @@ cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD
|
||||
SCROBBLER_IMAGE_TAG=main docker compose up -d --no-build # or drop --no-build to build locally
|
||||
```
|
||||
|
||||
Open `http://localhost:8080`, create an account, then go to **Apps** and create an app
|
||||
Open `http://localhost:8080`, create an account, then open **Apps** from the account menu (top right) and create an app
|
||||
for each player. Add `--profile monitoring` for Prometheus and Grafana.
|
||||
|
||||
Published images: `pkgs.daubney.dev/scrobbler/scrobbler-api` and
|
||||
@@ -62,6 +62,8 @@ read **Putting it behind TLS** below — the quick start above serves plain HTTP
|
||||
| `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) |
|
||||
| `MUSICBRAINZ_CONTACT` | api, worker | `UI_BASE_URL` | Contact URL/email sent to MusicBrainz for album art lookups (no key needed, but they ask for one) |
|
||||
| `ART_STORAGE_DIR` | api, worker | `var/album-art` | Where downloaded album art is stored; the worker writes it, the api serves it — both need access to the same directory (`docker compose` mounts a shared volume there) |
|
||||
| `AVATAR_UPLOAD_MAX_BYTES` | api | 2 MB | Largest profile image a user may upload (a reverse proxy needs a body limit at least this large too). Images are stored in `avatars/` inside `ART_STORAGE_DIR` |
|
||||
| `AVATAR_GRAVATAR_ENABLED` | api | off | Lets users use their Gravatar as their profile image. The api then calls gravatar.com (outbound HTTPS needed), sending it a SHA-256 hash of the user's email address; browsers never contact Gravatar |
|
||||
| `ART_UPLOAD_MAX_BYTES` | api | 5 MB | Largest image a user may upload as their own album art. A reverse proxy in front of the api needs a body limit at least this large |
|
||||
| `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted |
|
||||
| `WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port |
|
||||
@@ -201,6 +203,11 @@ disposable cache — it's simply re-downloaded the next time it's requested. Ima
|
||||
volume and can't be re-created, so include the volume in your backups. The database rows
|
||||
that point at them are in `user_album_art`; restore the two together.
|
||||
|
||||
Profile images (uploads, and copies of users' Gravatars) are in `avatars/` in that volume,
|
||||
one file per user id, and likewise belong in your backups. The `users` table records
|
||||
which users have one (`avatar_source`); a missing file just shows as no image. Gravatar
|
||||
copies can be re-fetched by their users, but uploads can't be re-created.
|
||||
|
||||
## Upgrades
|
||||
|
||||
```sh
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
# Plan: Last.fm-compatible scrobbling server (Flask API + separate static UI, PostgreSQL)
|
||||
|
||||
## Context
|
||||
`ScrobblingService` is an empty uv project (Python 3.13, no dependencies, no code). The goal is a self-hosted scrobbling server that implements the **Last.fm / Audioscrobbler 2.0 API**, so existing players and scrobblers (Navidrome, Pano Scrobbler, foobar2000, pylast, etc.) can point at it by changing only the API root URL. The first version includes:
|
||||
- users with API-key auth,
|
||||
- now-playing,
|
||||
- stats,
|
||||
- a web UI.
|
||||
|
||||
**Architecture requirement:** Flask is an API layer only and serves no HTML. The UI is a separate, self-hosted static frontend (plain HTML/CSS/JS) that calls Flask over HTTP.
|
||||
|
||||
```
|
||||
players/scrobblers ──► Flask /2.0/ (Last.fm-compatible API)
|
||||
static UI (frontend/) ─► Flask /api/v1/ (JSON REST API for the UI)
|
||||
Flask ──► PostgreSQL
|
||||
```
|
||||
|
||||
## Stack & dependencies
|
||||
- **Backend** (`pyproject.toml`, `uv add`):
|
||||
- Runtime: `flask`, `flask-sqlalchemy` (SQLAlchemy 2.0 style), `flask-migrate` (Alembic), `flask-cors`, `flask-smorest` (OpenAPI 3 + marshmallow schemas + docs UI), `prometheus-client`, `psycopg[binary]`, `python-dotenv`, `gunicorn`.
|
||||
- Dev: `pytest`, `pylast`, `openapi-spec-validator`.
|
||||
- **Frontend** (`frontend/`): plain HTML, CSS and vanilla JS ES modules. There is no build step and no npm, so any static server (nginx, Caddy, `python -m http.server`) can host it. `frontend/config.js` holds `API_BASE_URL`.
|
||||
- **`docker-compose.yml`** has three core services:
|
||||
- `db`: Postgres 16, creating the `scrobbler` and `scrobbler_test` databases.
|
||||
- `api`: gunicorn.
|
||||
- `ui`: nginx serving `frontend/` read-only.
|
||||
- A `monitoring` compose profile adds three more:
|
||||
- `prometheus`
|
||||
- `grafana`
|
||||
- `postgres-exporter`
|
||||
- **Config** comes from env vars: `DATABASE_URL`, `TEST_DATABASE_URL`, `SECRET_KEY`, `CORS_ORIGINS` (the UI origin), `UI_BASE_URL`. A `.env.example` documents them.
|
||||
|
||||
## Layout
|
||||
```
|
||||
src/scrobbler/
|
||||
__init__.py # create_app(): extensions, CORS, blueprints, JSON error handlers
|
||||
config.py # includes OPENAPI_* settings
|
||||
extensions.py # db, migrate, smorest Api
|
||||
openapi/lastfm.py # hand-written OpenAPI path + component definitions for /2.0/
|
||||
schemas/ # marshmallow schemas (request + response) for /api/v1
|
||||
metrics/
|
||||
__init__.py # metric definitions (single place, all names prefixed scrobbler_)
|
||||
http.py # before/after-request hooks: RED metrics per route
|
||||
db.py # SQLAlchemy event hooks: query timing, pool gauges
|
||||
collectors.py # cached DB-backed gauges (users, active users, now-playing)
|
||||
server.py # separate metrics HTTP server (multiprocess-aware)
|
||||
gunicorn.conf.py # PROMETHEUS_MULTIPROC_DIR setup, child_exit mark_process_dead, start metrics server
|
||||
deploy/
|
||||
nginx.conf
|
||||
prometheus/prometheus.yml, prometheus/alerts.yml
|
||||
grafana/provisioning/datasources/prometheus.yml
|
||||
grafana/provisioning/dashboards/dashboards.yml
|
||||
grafana/dashboards/{api-overview,lastfm-api,usage,database}.json
|
||||
models.py
|
||||
services/
|
||||
accounts.py # register, password check, API apps, sessions, UI tokens
|
||||
scrobbles.py # validate + store scrobbles, now-playing upsert
|
||||
stats.py # top artists/albums/tracks, recent, counts by period
|
||||
lastfm/ # Last.fm blueprint at /2.0/
|
||||
__init__.py # dispatcher: method=... -> handler registry
|
||||
signature.py # api_sig verification
|
||||
responses.py # dict -> XML (default) or JSON (format=json)
|
||||
errors.py # LastFMError + codes
|
||||
methods/auth.py # auth.getToken, auth.getSession, auth.getMobileSession
|
||||
methods/track.py # track.scrobble, track.updateNowPlaying
|
||||
methods/user.py # user.getInfo, getRecentTracks, getTopArtists/Albums/Tracks
|
||||
api/ # JSON REST blueprint at /api/v1/ used by the UI
|
||||
auth.py # register, login, logout, me
|
||||
apps.py # API applications CRUD
|
||||
sessions.py # list/revoke client sessions
|
||||
tokens.py # approve desktop auth token
|
||||
stats.py # now-playing, recent, top*, counts
|
||||
decorators.py # @require_ui_token -> g.user
|
||||
frontend/
|
||||
index.html # dashboard
|
||||
login.html, register.html, history.html, apps.html, sessions.html, approve.html
|
||||
config.js # API_BASE_URL
|
||||
js/api.js # fetch wrapper: bearer token, JSON, error handling
|
||||
js/<page>.js # one module per page
|
||||
css/style.css
|
||||
migrations/ tests/ docker-compose.yml .env.example README.md
|
||||
```
|
||||
|
||||
## Data model (`models.py`)
|
||||
- **User**: id, username (unique, case-insensitive), email, password_hash (werkzeug `generate_password_hash`), created_at.
|
||||
- **ApiApp**: api_key (32-char hex), shared_secret (32-char hex), name, owner user_id, created_at. These are what scrobbling clients use.
|
||||
- **UiToken**: token_hash, user_id, created_at, last_used_at, expires_at (30 days). This is the bearer token for the web UI. Only the sha256 of the token is stored.
|
||||
- **AuthToken**: token, api_app_id, user_id (null until the user approves it), created_at. Tokens expire after 60 minutes. Used for the Last.fm desktop auth flow.
|
||||
- **Session**: session_key (32-char hex), user_id, api_app_id, created_at. Sessions don't expire but can be revoked.
|
||||
- **Scrobble**: id, user_id, artist, track, album, album_artist, track_number, duration, mbid, played_at (timestamptz), submitted_at, api_app_id.
|
||||
- Index on `(user_id, played_at DESC)`.
|
||||
- Unique on `(user_id, played_at, artist, track)`; inserts use `ON CONFLICT DO NOTHING`.
|
||||
- **NowPlaying**: user_id (PK), artist, track, album, album_artist, duration, started_at, expires_at (start + duration, or 10 min by default).
|
||||
|
||||
Stats group by `lower(artist)` etc. so capitalization differences don't split counts. Normalized artist/album tables can come later.
|
||||
|
||||
## Last.fm API (`/2.0/`)
|
||||
- **Endpoint:** `GET|POST /2.0/`. Params come from the query string or a form body. The registry declares for each handler whether it needs a signature and whether it needs a session key.
|
||||
- **Signature:**
|
||||
- Take every param except `format`, `callback` and `api_sig`, and sort them by name.
|
||||
- Concatenate each name followed by its value, append the shared secret, and take the md5 hash.
|
||||
- Compare the result to `api_sig` with `hmac.compare_digest`.
|
||||
- **Responses:** XML `<lfm status="ok">` by default, JSON when `format=json`. Errors use the Last.fm shapes. Codes: 2, 3, 4, 6, 9, 10, 13, 14, 15, 29.
|
||||
- **auth.getMobileSession:** signed; takes username and password, and returns `<session><name/><key/><subscriber>0</subscriber></session>`.
|
||||
- **Desktop flow:** `auth.getToken`, then the user approves, then `auth.getSession`.
|
||||
- Clients send users to `<root>/api/auth/?api_key=…&token=…`. Flask answers that path with a **302 redirect to `UI_BASE_URL/approve.html?...`**. That keeps Flask HTML-free while existing clients still work.
|
||||
- The UI page calls `POST /api/v1/tokens/approve`.
|
||||
- **track.updateNowPlaying:** signed, needs a session key. Upserts NowPlaying and echoes the corrected fields.
|
||||
- **track.scrobble:** signed, needs a session key. Takes a batch of up to 50 tracks as `artist[i]`, `track[i]`, `timestamp[i]`, `album[i]`, `albumArtist[i]`, `duration[i]`, `trackNumber[i]`, `mbid[i]`.
|
||||
- Ignore codes: 1 for a missing artist, 2 for a missing track, 3 for a timestamp over 14 days old, 4 for a timestamp more than 5 minutes in the future.
|
||||
- Duplicates count as accepted, for idempotent retries.
|
||||
- The response carries accepted/ignored counts and one `<scrobble>` per track.
|
||||
- Scrobbling a track clears a matching now-playing entry.
|
||||
- **user.getRecentTracks:** includes the now-playing track with `nowplaying="true"`. Also `user.getTopArtists`, `user.getTopAlbums`, `user.getTopTracks` and `user.getInfo`. They support `period` (overall/7day/1month/3month/6month/12month), `limit` and `page`, and take an api_key with no signature.
|
||||
|
||||
## UI REST API (`/api/v1/`, JSON only)
|
||||
- **Auth:** `POST /auth/register`, `POST /auth/login` (returns `{token, user}`), `POST /auth/logout`, `GET /auth/me`.
|
||||
- Every other route uses `Authorization: Bearer <token>`. A bearer token rather than cookies avoids cross-origin cookie/CSRF complexity.
|
||||
- **Apps:** `GET/POST /apps`, `DELETE /apps/<api_key>`. POST returns the key and secret.
|
||||
- **Sessions:** `GET /sessions`, `DELETE /sessions/<id>`.
|
||||
- **Tokens:** `GET /tokens/<token>` (app name, for the confirm screen), `POST /tokens/approve`.
|
||||
- **Stats:**
|
||||
- `GET /me/now-playing`
|
||||
- `GET /me/recent?limit&page`
|
||||
- `GET /me/top/{artists|albums|tracks}?period&limit&page`
|
||||
- `GET /me/counts?bucket=day&period=`
|
||||
- `GET /me/summary` (total scrobbles, distinct artists)
|
||||
- Errors use one JSON shape, `{"error": {"code": "...", "message": "..."}}`, with proper HTTP statuses.
|
||||
- CORS allows only the `CORS_ORIGINS` origins, with the `Authorization` header allowed.
|
||||
- The Last.fm `user.*` methods and these endpoints both call `services/stats.py`, so the logic isn't duplicated.
|
||||
|
||||
## OpenAPI document & docs
|
||||
- **Library:** `flask-smorest` owns the spec (OpenAPI 3.1).
|
||||
- The `/api/v1` blueprints are `smorest.Blueprint`s. Every route uses `@blp.arguments(Schema)` / `@blp.response(code, Schema)` / `@blp.alt_response` for errors, with summaries and descriptions from docstrings. The spec is generated from the code, so it can't drift.
|
||||
- The bearer token is declared as an `http`/`bearer` security scheme. Routes that need it are marked, so Swagger UI's "Authorize" button works.
|
||||
- Tags: Auth, Apps, Sessions, Tokens, Stats, Last.fm.
|
||||
- **Documenting `/2.0/`:** it is a single `method=` dispatcher, which OpenAPI can't express as one operation per method on the same path.
|
||||
- `openapi/lastfm.py` registers it with `api.spec.path()` as `GET /2.0/` and `POST /2.0/` operations. `method` is an enum parameter, and the common params are listed: `api_key`, `api_sig`, `sk`, `format`.
|
||||
- Each method's request and response is in the description plus `oneOf` response examples in both XML and JSON.
|
||||
- Each method's params also appear as a named schema component (e.g. `LastfmTrackScrobbleRequest`) so they're browsable.
|
||||
- The per-method details come from the same handler registry the dispatcher uses (each handler declares name, params, auth/signature needs and an example). The docs therefore list exactly the methods that exist.
|
||||
- **Exposed endpoints (on the API server):**
|
||||
- `GET /api/openapi.json`: the spec.
|
||||
- `GET /api/docs`: Swagger UI, interactive with "try it out".
|
||||
- `GET /api/redoc`: ReDoc, for reading.
|
||||
- These are API-tooling pages generated by the library, not part of the app UI. The Swagger/ReDoc assets load from a CDN by default. The URLs can be pointed at self-hosted copies with `OPENAPI_SWAGGER_UI_URL` / `OPENAPI_REDOC_URL`, and `OPENAPI_DOCS_ENABLED` can turn the docs off in production.
|
||||
- **CLI:** `flask openapi write docs/openapi.json` (built into flask-smorest) exports the spec, which is committed to the repo for clients and codegen.
|
||||
- The README and the UI's "apps" page link to `/api/docs`.
|
||||
|
||||
## Metrics (Prometheus, `prometheus-client`)
|
||||
- **Exposure:**
|
||||
- Metrics are served on a **separate port** (`METRICS_PORT`, default 9100) at `/metrics`, not on the public API port. Only Prometheus on the internal network reaches it, and it stays out of the OpenAPI spec.
|
||||
- Gunicorn runs with `PROMETHEUS_MULTIPROC_DIR`, so counters and histograms aggregate across workers. The Flask dev server uses the same code in single-process mode.
|
||||
- **Label cardinality is kept bounded:**
|
||||
- `endpoint` is the Flask endpoint name (e.g. `api_v1.apps.list`), never the raw path. Unmatched requests get `unmatched`.
|
||||
- `lastfm_method` comes only from the registry; anything else gets `unknown`.
|
||||
- No user, api_key or track labels.
|
||||
|
||||
| Metric | Type | Labels | Source |
|
||||
|---|---|---|---|
|
||||
| `scrobbler_http_requests_total` | counter | endpoint, http_method, status | request hooks |
|
||||
| `scrobbler_http_request_duration_seconds` | histogram | endpoint, http_method | request hooks |
|
||||
| `scrobbler_http_requests_in_progress` | gauge | endpoint | request hooks |
|
||||
| `scrobbler_lastfm_requests_total` | counter | lastfm_method, format, outcome (ok/error) | dispatcher |
|
||||
| `scrobbler_lastfm_request_duration_seconds` | histogram | lastfm_method | dispatcher |
|
||||
| `scrobbler_lastfm_errors_total` | counter | lastfm_method, code | LastFMError handler |
|
||||
| `scrobbler_scrobbles_total` | counter | result (accepted/duplicate/ignored) | scrobble service |
|
||||
| `scrobbler_scrobbles_ignored_total` | counter | reason (1–4) | scrobble service |
|
||||
| `scrobbler_scrobble_batch_size` | histogram (1,2,5,10,25,50) | — | track.scrobble |
|
||||
| `scrobbler_scrobble_lag_seconds` | histogram | — | submitted_at − played_at (spots offline-cache flushes) |
|
||||
| `scrobbler_now_playing_updates_total` | counter | — | now-playing service |
|
||||
| `scrobbler_auth_sessions_created_total` | counter | flow (mobile/desktop) | Last.fm auth |
|
||||
| `scrobbler_auth_failures_total` | counter | reason (bad_password/bad_signature/bad_api_key/bad_session/token_expired/token_unauthorized) | Last.fm auth + sig check |
|
||||
| `scrobbler_ui_logins_total` | counter | result (success/failure) | /api/v1/auth |
|
||||
| `scrobbler_registrations_total` | counter | — | /api/v1/auth |
|
||||
| `scrobbler_db_query_duration_seconds` | histogram | operation (select/insert/update/delete) | SQLAlchemy events |
|
||||
| `scrobbler_db_pool_connections` | gauge | state (checked_out/idle/overflow) | pool events |
|
||||
| `scrobbler_users` | gauge | — | cached collector (60s TTL) |
|
||||
| `scrobbler_active_users` | gauge | window (1h/24h/7d) | cached collector |
|
||||
| `scrobbler_now_playing_active` | gauge | — | cached collector |
|
||||
| `scrobbler_build_info` | gauge (=1) | version, python_version | startup |
|
||||
|
||||
- The DB-backed gauges are computed by a custom collector at most once per 60s and cached, so frequent scrapes don't load Postgres. In multiprocess mode, only the metrics-server process registers the collector.
|
||||
- `postgres-exporter` supplies database-side metrics: connections, transactions, cache hit ratio, DB size, locks and deadlocks.
|
||||
|
||||
## Grafana dashboards (provisioned from files, `deploy/grafana/`)
|
||||
- A Prometheus datasource and a dashboard provider are provisioned. The dashboards go in a "Scrobbler" folder, with `$interval` and `$endpoint`/`$lastfm_method` template variables where they're useful.
|
||||
- **API Overview (RED):**
|
||||
- request rate by endpoint,
|
||||
- error ratio (4xx and 5xx separately),
|
||||
- p50/p95/p99 latency by endpoint (`histogram_quantile`),
|
||||
- in-flight requests,
|
||||
- a "slowest endpoints" table (top-k p95),
|
||||
- scrape `up` status and build info.
|
||||
- **Last.fm API:**
|
||||
- calls/sec by method,
|
||||
- error rate by Last.fm error code (stacked),
|
||||
- signature/auth failures by reason,
|
||||
- scrobbles accepted vs duplicate vs ignored,
|
||||
- ignore reasons,
|
||||
- batch size heatmap,
|
||||
- scrobble lag distribution,
|
||||
- now-playing update rate,
|
||||
- sessions created by flow.
|
||||
- **Usage:**
|
||||
- scrobbles per minute and per day,
|
||||
- total and active users (1h/24h/7d),
|
||||
- listeners now playing,
|
||||
- registrations and logins (success vs failure).
|
||||
- **Database:**
|
||||
- app-side query latency percentiles by operation,
|
||||
- pool usage vs size,
|
||||
- Postgres connections, TPS, cache hit ratio, DB size growth, locks and deadlocks (from postgres-exporter).
|
||||
- **Alert rules** (`deploy/prometheus/alerts.yml`, shown in Grafana through the datasource):
|
||||
- `ScrobblerDown` (`up == 0` for 2m)
|
||||
- `HighErrorRate` (5xx ratio > 5% for 5m)
|
||||
- `HighLatency` (p95 > 1s for 10m)
|
||||
- `AuthFailureSpike` (auth failures > 10/s)
|
||||
- `ScrobbleIgnoreRateHigh` (ignored > 20% of submitted)
|
||||
- `DBPoolExhausted`
|
||||
- Alertmanager routing is out of scope. The rules are defined and visible, but no notifications go out.
|
||||
|
||||
## Source control, CI/CD, packages & notifications
|
||||
### Git
|
||||
- `git init` on branch `main`, with a `.gitignore` covering `.venv`, `.idea`, `.env`, `__pycache__`, `.pytest_cache` and `prometheus_multiproc/`.
|
||||
- Remote `origin` = `ssh://git@git.daubney.dev:222/matt/Scrobbler.git`.
|
||||
- Using the Gitea API with `GITEA_TOKEN` from the environment:
|
||||
- Check whether `matt/Scrobbler` exists with `GET /api/v1/repos/matt/Scrobbler`.
|
||||
- Create it with `POST /api/v1/user/repos` (private) only if it's missing.
|
||||
- Confirm that Actions are enabled on the repo.
|
||||
- **Commits:** one commit per build-order step once that step's tests pass (see the Build order section), with descriptive messages.
|
||||
- **Push:** push to `origin/main` once the CI step lands, so the workflows run. After that, push after each commit.
|
||||
|
||||
### Gitea Actions (`.gitea/workflows/`), runner label `ubuntu-latest`
|
||||
- **`ci.yml`** runs on push and PR to any branch:
|
||||
- **`lint`:** `uv sync`, `ruff check`, `ruff format --check`. Adds `ruff` as a dev dependency.
|
||||
- **`test`:** a `postgres:16` service container. Runs `flask db upgrade`, then `pytest`, which includes the OpenAPI drift test, the metrics tests and the dashboard tests.
|
||||
- **`validate-monitoring`:** `promtool check config` and `promtool check rules` via the `prom/prometheus` image.
|
||||
- **`notify`:** `needs: [lint, test, validate-monitoring]`, `if: always()`. Posts the overall result.
|
||||
- **`publish.yml`** runs on push to `main` and on `v*` tags, after the CI jobs pass (it repeats them as needed-jobs):
|
||||
- **`images`:** `docker login pkgs.daubney.dev` with `PKGS_USER`/`PKGS_PASSWORD`, then build and push two images to the ProGet **Docker feed**:
|
||||
- `pkgs.daubney.dev/<docker-feed>/scrobbler-api` (multi-stage uv build to a slim runtime running gunicorn),
|
||||
- `pkgs.daubney.dev/<docker-feed>/scrobbler-ui` (nginx + `frontend/`).
|
||||
- Both are tagged `sha-<short>` and `main`. On tags they're also tagged `<version>` and `latest`.
|
||||
- **`python-package`:** `uv build`, then `uv publish` to the ProGet **PyPI feed** (`https://pkgs.daubney.dev/pypi/<pypi-feed>/legacy`, auth `api` / `PKGS_API_KEY`). Only on `v*` tags, because PyPI versions are immutable. The project version comes from the tag.
|
||||
- **`assets`:** upload the monitoring bundle to a ProGet **asset feed** with `X-ApiKey: PKGS_API_KEY`. The bundle holds `docs/openapi.json`, `deploy/grafana/dashboards/*.json`, the Prometheus config and alerts, and `docker-compose.yml`. Destination: `https://pkgs.daubney.dev/endpoints/<asset-feed>/content/scrobbler/<version-or-sha>/`.
|
||||
- **`notify`:** `if: always()`. Posts the result, including the published image tags and version.
|
||||
- **Dockerfiles:** `docker/api.Dockerfile` and `docker/ui.Dockerfile`, which `docker-compose.yml` also uses for local builds. Compose can take `SCROBBLER_IMAGE_TAG` to pull the published images instead of building them.
|
||||
|
||||
### Notifications (ntfy on notify.daubney.dev, topic `ScrobblingService`, every run)
|
||||
- A reusable composite action `.gitea/actions/notify/action.yml` takes `status`, `title` and `message` inputs.
|
||||
- It sends `curl -u "$NTFY_USER:$NTFY_PASSWORD" https://notify.daubney.dev/ScrobblingService` with these headers:
|
||||
- `Title`: e.g. "CI ✅ main @ abc1234" or "Publish ❌ v0.2.0".
|
||||
- `Priority`: `default` on success, `high` on failure.
|
||||
- `Tags`: `white_check_mark` / `x` / `package`.
|
||||
- `Click`: the Gitea run URL (`${{ gitea.server_url }}/${{ gitea.repository }}/actions/runs/${{ gitea.run_number }}`).
|
||||
- The body carries the commit message, author, branch and job results.
|
||||
- A failed notification never fails the workflow (`continue-on-error`).
|
||||
|
||||
### Secrets & variables (set via Gitea API with `GITEA_TOKEN`, never committed)
|
||||
- Set with `PUT /api/v1/repos/matt/Scrobbler/actions/secrets/{name}` and `.../actions/variables/{name}`.
|
||||
- **Secrets:**
|
||||
- `PKGS_USER`, `PKGS_PASSWORD`, `PKGS_API_KEY`: values read from the local environment (from `.zshrc`) at set time. Never echoed.
|
||||
- `NTFY_USER` = `matt` and `NTFY_PASSWORD`: the password you gave me. It goes only into the Gitea secret. It won't be in the repo, the plan file or memory.
|
||||
- **Variables:** `PKGS_HOST=pkgs.daubney.dev`, `PKGS_DOCKER_FEED`, `PKGS_PYPI_FEED`, `PKGS_ASSET_FEED`, `NTFY_URL=https://notify.daubney.dev`, `NTFY_TOPIC=ScrobblingService`.
|
||||
|
||||
### ProGet feeds
|
||||
- During implementation, list the existing feeds with the ProGet API (`X-ApiKey: $PKGS_API_KEY`) and pick the existing Docker, PyPI and asset feeds that fit.
|
||||
- If a suitable feed doesn't exist, **I'll ask you before creating one**, because that changes your shared package server.
|
||||
|
||||
## Frontend (`frontend/`)
|
||||
- `js/api.js`:
|
||||
- Reads `API_BASE_URL` from `config.js`.
|
||||
- Stores the UI token in `localStorage`.
|
||||
- Adds the bearer header to requests.
|
||||
- Redirects to `login.html` on a 401.
|
||||
- Pages:
|
||||
- **login / register**
|
||||
- **index (dashboard):** now playing (polled every 30s), totals, recent 10, top artists/tracks with a period switcher, and a simple daily listens bar chart drawn with inline SVG, no chart library.
|
||||
- **history:** paginated.
|
||||
- **apps:** create/delete, show key and secret, and setup instructions showing the API root `<api>/2.0/`.
|
||||
- **sessions:** revoke.
|
||||
- **approve:** the desktop-flow token confirmation. Sends the user to login first if needed, then back.
|
||||
- Text from the server is always inserted with `textContent` or escaping, never raw `innerHTML`, so track names can't inject HTML.
|
||||
|
||||
## Tests (`tests/`, pytest against `TEST_DATABASE_URL`)
|
||||
- `conftest.py`: an app fixture (tables created once, truncated per test), a Flask test client, and user/app/session/UI-token fixtures plus a `signed(params, secret)` helper.
|
||||
- `test_signature.py`: known-vector check; bad or missing signature returns error 13.
|
||||
- `test_lastfm_auth.py`: mobile session success and bad password (4), token → approve (via `/api/v1`) → getSession, expired and unapproved tokens (15 and 14), and the `/api/auth/` redirect to the UI.
|
||||
- `test_scrobble.py`: single scrobble, batch of 50, ignore rules, duplicate idempotency, and now-playing set, expiry and clearing.
|
||||
- `test_lastfm_user.py`: top and recent over periods, XML vs JSON shapes.
|
||||
- `test_ui_api.py`:
|
||||
- register/login/logout,
|
||||
- 401 without a token,
|
||||
- app CRUD,
|
||||
- session revoke (the revoked key then gets error 9 on `/2.0/`),
|
||||
- stats endpoints,
|
||||
- CORS headers.
|
||||
- `test_openapi.py`:
|
||||
- `/api/openapi.json` passes `openapi-spec-validator`.
|
||||
- Every registered Flask rule under `/api/v1` and `/2.0/` has a matching path in the spec.
|
||||
- Every Last.fm handler in the registry appears in the `method` enum.
|
||||
- `/api/docs` and `/api/redoc` return 200.
|
||||
- The committed `docs/openapi.json` matches the generated spec, so a stale export fails the tests.
|
||||
- `test_metrics.py`: uses a fresh `CollectorRegistry` per test.
|
||||
- Requests increment the HTTP metrics with the right `endpoint`/`status` labels.
|
||||
- A scrobble batch with mixed valid and invalid tracks increments accepted, ignored and reason counts correctly.
|
||||
- A bad signature increments `auth_failures_total{reason="bad_signature"}` and `lastfm_errors_total{code="13"}`.
|
||||
- An unknown method or path maps to `unknown`/`unmatched`, which checks that cardinality stays bounded.
|
||||
- The metrics server output parses.
|
||||
- `test_dashboards.py`:
|
||||
- Every dashboard JSON loads and has a unique uid.
|
||||
- Every `scrobbler_*` metric referenced in panel queries or alert rules is actually defined in `metrics/__init__.py` (histograms may use their `_bucket`/`_sum`/`_count` names). This stops dashboards drifting from the code.
|
||||
- `test_pylast_compat.py`: runs the app in a threaded werkzeug server and points `pylast` at it. It gets a session, calls now-playing and scrobble, then reads recent tracks. Exactly which password param pylast sends for getMobileSession will be checked here, and both forms will be accepted if needed.
|
||||
- Frontend: no JS test framework in v1. It is verified manually in the browser (below).
|
||||
|
||||
## Build order (each step ends with passing tests + a commit)
|
||||
0. `git init`, `.gitignore`, remote and repo setup. Then `ci.yml` plus the notify action and repo secrets/variables. Push, and confirm the first CI run goes green and the ntfy message arrives, so every later commit is checked by CI.
|
||||
1. Dependencies, docker-compose, config, app factory, models, first migration.
|
||||
2. Last.fm core: signature, responses, errors, dispatcher.
|
||||
3. flask-smorest `Api` setup plus `/api/openapi.json`, `/api/docs` and `/api/redoc`. Then `services/accounts.py` and the UI auth API (`/api/v1/auth`, bearer decorator + security scheme, CORS), with schemas written alongside each route from here on.
|
||||
4. Last.fm auth methods, the `/api/auth/` redirect, and the token approval API.
|
||||
5. Scrobble and now-playing, with the service layer.
|
||||
6. Stats service, then Last.fm `user.*` methods and the `/api/v1/me/*` endpoints.
|
||||
7. Frontend pages.
|
||||
8. Last.fm OpenAPI definitions (`openapi/lastfm.py`) from the handler registry. Export `docs/openapi.json` and add `test_openapi.py`.
|
||||
9. Metrics:
|
||||
- Add the HTTP hooks and metrics server early, in step 1, so every later step can add its domain counters as it goes.
|
||||
- Finish with the DB hooks, cached collectors, gunicorn multiprocess config and `test_metrics.py`.
|
||||
10. Monitoring stack: Prometheus config and alerts, postgres-exporter, Grafana provisioning, the 4 dashboards, `test_dashboards.py`.
|
||||
11. pylast compatibility test, nginx config, README (running the API and UI, configuring clients, API docs link, monitoring).
|
||||
12. Dockerfiles and `publish.yml`: confirm the ProGet feeds, push to main and check the images and assets land. Then tag `v0.1.0` and check the wheel appears in the PyPI feed.
|
||||
|
||||
## Verification
|
||||
1. `docker compose up -d db`, then `uv sync`, then `uv run flask --app scrobbler db upgrade`.
|
||||
2. `uv run pytest`: all tests pass, including the pylast end-to-end test.
|
||||
3. Run `uv run flask --app scrobbler run` (port 5000) and `python -m http.server 8080 -d frontend`, with `CORS_ORIGINS=http://localhost:8080`. Then in the browser:
|
||||
- register and create an API app,
|
||||
- scrobble a few tracks with a small pylast script,
|
||||
- confirm the dashboard shows now-playing, recent tracks, top lists and the chart.
|
||||
4. Test the desktop auth flow: call `auth.getToken` via curl, open `http://localhost:5000/api/auth/?api_key=…&token=…`, confirm it redirects to the UI approve page and approval works, then call `auth.getSession` via curl.
|
||||
5. `curl 'http://localhost:5000/2.0/?method=user.getRecentTracks&user=<name>&api_key=<key>&format=json'` returns Last.fm-shaped JSON.
|
||||
6. Open `http://localhost:5000/api/docs`:
|
||||
- Every tag and path appears.
|
||||
- "Authorize" with a token from `/auth/login`, then run `GET /api/v1/me/recent` from Swagger UI.
|
||||
- Run `GET /2.0/?method=user.getTopArtists` from the Last.fm section.
|
||||
- `/api/redoc` renders.
|
||||
7. `docker compose --profile monitoring up` brings up db, api, ui, prometheus, grafana and postgres-exporter. Then:
|
||||
- `curl localhost:9100/metrics` shows the `scrobbler_*` series.
|
||||
- Prometheus targets page shows api and postgres-exporter as UP.
|
||||
- `promtool check config` and `promtool check rules` pass (run in the prometheus container).
|
||||
8. Run a small load script (pylast scrobbling a few hundred tracks, some deliberately invalid or badly signed, plus UI API calls). Then open Grafana at `localhost:3000`:
|
||||
- All 4 dashboards in the "Scrobbler" folder show data.
|
||||
- Latency and error panels move.
|
||||
- Ignore reasons and auth failures reflect the bad requests.
|
||||
- The alert rules are listed.
|
||||
9. CI/CD:
|
||||
- Each push shows green `ci.yml` runs in Gitea Actions, and each run posts to the `ScrobblingService` ntfy topic, including a deliberately failing test on a throwaway branch (which should arrive with high priority, then be deleted).
|
||||
- A push to main publishes both images to the ProGet Docker feed (`docker pull pkgs.daubney.dev/<feed>/scrobbler-api:main` works) and uploads the asset bundle.
|
||||
- Tag `v0.1.0` publishes the wheel to the PyPI feed (`uv pip install --index-url …` works) and version-tagged images.
|
||||
|
||||
## Out of scope for v1
|
||||
- Legacy Audioscrobbler 1.2 handshake.
|
||||
- ListenBrainz API.
|
||||
- Importing history from Last.fm.
|
||||
- Normalized artist/album tables and MusicBrainz lookups.
|
||||
- Rate limiting (code 29 is reserved).
|
||||
- A frontend build toolchain.
|
||||
@@ -1921,6 +1921,225 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/me/avatar": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"404": {
|
||||
"description": "You have no profile image",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"200": {
|
||||
"description": "Your profile image (JPEG, PNG or WebP)"
|
||||
},
|
||||
"401": {
|
||||
"description": "Not authenticated",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||
}
|
||||
},
|
||||
"summary": "Your profile image",
|
||||
"tags": [
|
||||
"Avatar"
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"put": {
|
||||
"responses": {
|
||||
"422": {
|
||||
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
|
||||
},
|
||||
"415": {
|
||||
"description": "Not a JPEG, PNG or WebP image",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"413": {
|
||||
"description": "Image too large",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Empty file",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/User"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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/AvatarUpload"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"summary": "Upload a profile image",
|
||||
"description": "Replaces your current one, whatever its source.",
|
||||
"tags": [
|
||||
"Avatar"
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"delete": {
|
||||
"responses": {
|
||||
"404": {
|
||||
"description": "You have no profile image",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
},
|
||||
"401": {
|
||||
"description": "Not authenticated",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||
}
|
||||
},
|
||||
"summary": "Remove your profile image",
|
||||
"tags": [
|
||||
"Avatar"
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/me/avatar/gravatar": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"502": {
|
||||
"description": "Gravatar couldn't be reached",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Gravatar is off, or has no image for you",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/User"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Not authenticated",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||
}
|
||||
},
|
||||
"summary": "Use your Gravatar as your profile image",
|
||||
"description": "The server fetches the image for your account email from Gravatar (sending it a hash\nof the address) and keeps a copy. Call again to refresh it. Only available when the\nserver's admin has enabled it; see `gravatar_enabled` on `/auth/me`.",
|
||||
"tags": [
|
||||
"Avatar"
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"/healthz": {
|
||||
"get": {
|
||||
"responses": {
|
||||
@@ -2721,6 +2940,44 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"/api/v1/federation/profiles/{username}/avatar": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"404": {
|
||||
"description": "No image shared under that name",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"200": {
|
||||
"description": "The profile image (JPEG, PNG or WebP)"
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/DEFAULT_ERROR"
|
||||
}
|
||||
},
|
||||
"summary": "A public profile image",
|
||||
"description": "For the web UI's profile page. Only served when the user shares and has chosen to\nshare their image.",
|
||||
"tags": [
|
||||
"Federation"
|
||||
]
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"in": "path",
|
||||
"name": "username",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"/api/v1/federation/profiles/{username}/posts/{post_uuid}": {
|
||||
"get": {
|
||||
"responses": {
|
||||
@@ -3435,6 +3692,53 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"/users/{username}/avatar": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"ActivityPub"
|
||||
],
|
||||
"summary": "Profile image",
|
||||
"description": "The user's profile image, which their actor document names as its `icon`. Only served when the user shares and has chosen to share their image.",
|
||||
"operationId": "federation_actor_avatar",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "A JPEG, PNG or WebP image",
|
||||
"content": {
|
||||
"image/*": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"format": "binary"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Unknown, or not sharing (the two are indistinguishable)"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "username",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"in": "path",
|
||||
"name": "username",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"/users/{username}/followers": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -3796,6 +4100,10 @@
|
||||
"name": "Art",
|
||||
"description": "Album art, resolved from MusicBrainz / Cover Art Archive by a background worker. You can also upload your own art, or correct a failed lookup; those only change what you see."
|
||||
},
|
||||
{
|
||||
"name": "Avatar",
|
||||
"description": "Your profile image: upload one, use your Gravatar (if this server allows it), or remove it."
|
||||
},
|
||||
{
|
||||
"name": "Health",
|
||||
"description": "Liveness for load balancers and containers"
|
||||
@@ -3931,6 +4239,35 @@
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"readOnly": true
|
||||
},
|
||||
"has_avatar": {
|
||||
"type": "boolean",
|
||||
"readOnly": true,
|
||||
"description": "Whether you have a profile image"
|
||||
},
|
||||
"avatar_source": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"none",
|
||||
"upload",
|
||||
"gravatar"
|
||||
],
|
||||
"readOnly": true,
|
||||
"description": "Where your profile image comes from"
|
||||
},
|
||||
"avatar_updated_at": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"format": "date-time",
|
||||
"readOnly": true,
|
||||
"description": "When it last changed"
|
||||
},
|
||||
"gravatar_enabled": {
|
||||
"readOnly": true,
|
||||
"type": "boolean",
|
||||
"description": "Whether this server offers Gravatar"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -4654,6 +4991,20 @@
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"AvatarUpload": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"file": {
|
||||
"description": "A JPEG, PNG or WebP image",
|
||||
"type": "string",
|
||||
"format": "binary"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"file"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"Health": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -5260,6 +5611,10 @@
|
||||
],
|
||||
"description": "`off` (default): nothing. `profile`: a \"Now playing\" field on your profile, refreshed at most every 5 minutes and cleared when you stop. `posts`: the profile field, plus a post for each track played 30+ seconds, at most one every 30 minutes, replacing the last one."
|
||||
},
|
||||
"share_avatar": {
|
||||
"type": "boolean",
|
||||
"description": "Show your profile image on your public profile and send it to other servers as your picture. Off by default; has no effect if you have no image."
|
||||
},
|
||||
"handle": {
|
||||
"type": "string",
|
||||
"readOnly": true,
|
||||
@@ -5349,6 +5704,10 @@
|
||||
],
|
||||
"description": "`off` (default): nothing. `profile`: a \"Now playing\" field on your profile, refreshed at most every 5 minutes and cleared when you stop. `posts`: the profile field, plus a post for each track played 30+ seconds, at most one every 30 minutes, replacing the last one."
|
||||
},
|
||||
"share_avatar": {
|
||||
"type": "boolean",
|
||||
"description": "Show your profile image on your public profile and send it to other servers as your picture. Off by default; has no effect if you have no image."
|
||||
},
|
||||
"handle": {
|
||||
"type": "string",
|
||||
"readOnly": true,
|
||||
@@ -5439,6 +5798,10 @@
|
||||
],
|
||||
"description": "\"Track by Artist\", or null"
|
||||
},
|
||||
"has_avatar": {
|
||||
"type": "boolean",
|
||||
"description": "Whether there's a profile image at `/profiles/{username}/avatar`"
|
||||
},
|
||||
"handle": {
|
||||
"type": "string",
|
||||
"example": "@alice@scrobble.example"
|
||||
|
||||
+20
-3
@@ -6,7 +6,8 @@ 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
|
||||
Register in the web UI, then open the account menu at the top right (your picture and
|
||||
name), 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
|
||||
@@ -47,7 +48,7 @@ scrobbler is one example; look for a plugin or a different player with 2.0 suppo
|
||||
|
||||
## Importing history
|
||||
|
||||
Open **Import** in the web UI:
|
||||
Open **Import** from the account menu:
|
||||
|
||||
- **An export file**:
|
||||
- CSV from [lastfm-to-csv](https://benjaminbenben.com/lastfm-to-csv/), no header row,
|
||||
@@ -65,10 +66,26 @@ flight. Unlike live scrobbles, imports keep plays of any age (still skipping row
|
||||
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.
|
||||
|
||||
## Your profile image
|
||||
|
||||
Open the account menu at the top right (your picture and name) and choose **Profile**, where
|
||||
you can give yourself a picture, shown next to your name. Upload a JPEG, PNG or WebP image, or remove it again.
|
||||
|
||||
If your instance's admin has allowed it, you can also **use your Gravatar**. The server
|
||||
asks Gravatar for the picture linked to your account email, sending it a hash of that
|
||||
address (never the address itself), and keeps a copy; your browser doesn't contact
|
||||
Gravatar. **Refresh Gravatar** fetches it again after you change it there. Choosing an
|
||||
upload replaces a Gravatar and vice versa.
|
||||
|
||||
Your image is private by default. If your instance shares on the fediverse, **Sharing**
|
||||
has a **Share my profile image** switch that shows it on your public profile page and
|
||||
sends it to other servers as your picture. They keep their own copies, so a change or
|
||||
removal can take a while to show up everywhere.
|
||||
|
||||
## 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
|
||||
**Sharing** appears in the account menu. 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
|
||||
|
||||
@@ -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>Profile · Scrobbled</title>
|
||||
<link rel="icon" href="favicon.ico" sizes="48x48">
|
||||
<link rel="icon" href="favicon.svg" type="image/svg+xml">
|
||||
<link rel="apple-touch-icon" href="apple-touch-icon.png">
|
||||
<link rel="manifest" href="site.webmanifest">
|
||||
<meta name="theme-color" content="#1F1C28">
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
<script src="config.js"></script>
|
||||
<script type="module" src="js/account.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header" id="site-header"></header>
|
||||
<main id="main">
|
||||
<h1 class="page-title">Profile</h1>
|
||||
<p class="lede">Your profile image, shown next to your name.</p>
|
||||
<div id="messages" aria-live="polite"></div>
|
||||
<section id="avatar-panel"></section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
+144
-6
@@ -206,13 +206,147 @@ code {
|
||||
}
|
||||
|
||||
.account {
|
||||
position: relative; /* anchors the menu */
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
align-items: baseline;
|
||||
color: var(--ink-soft);
|
||||
}
|
||||
|
||||
.account-trigger {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
padding: 0.25rem 0.5rem 0.25rem 0.25rem;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius-control);
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.account-trigger:hover,
|
||||
.account-trigger[aria-expanded="true"] {
|
||||
color: var(--ink);
|
||||
border-color: var(--rule);
|
||||
background: var(--paper-raised);
|
||||
}
|
||||
|
||||
.account-trigger[data-current] .account-name {
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
/* A three-line "hamburger" icon, drawn with two borders and a shadow-free centre bar */
|
||||
.account-icon {
|
||||
width: 1rem;
|
||||
height: 0.7rem;
|
||||
border-block: 2px solid currentColor;
|
||||
background: linear-gradient(currentColor, currentColor) center / 100% 2px no-repeat;
|
||||
}
|
||||
|
||||
.account-menu {
|
||||
position: absolute;
|
||||
top: calc(100% + 0.35rem);
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
min-width: 12rem;
|
||||
margin: 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.18);
|
||||
}
|
||||
|
||||
.account-menu[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.account-menu-item {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 0;
|
||||
border-radius: calc(var(--radius-control) - 2px);
|
||||
background: none;
|
||||
color: var(--ink-soft);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.account-menu-item:hover,
|
||||
.account-menu-item:focus-visible {
|
||||
color: var(--ink);
|
||||
background: var(--bar);
|
||||
}
|
||||
|
||||
.account-menu-item[aria-current="page"] {
|
||||
color: var(--ink);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.account-menu-end {
|
||||
margin-top: 0.35rem;
|
||||
padding-top: 0.35rem;
|
||||
border-top: 1px solid var(--rule);
|
||||
}
|
||||
|
||||
.account-avatar {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
/* A profile image: round, with the placeholder ring while there's none */
|
||||
.avatar {
|
||||
display: block;
|
||||
flex: none;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
background: var(--paper-raised);
|
||||
border: 1px solid var(--rule);
|
||||
}
|
||||
|
||||
.avatar-sm {
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
}
|
||||
|
||||
.avatar-lg {
|
||||
width: 7rem;
|
||||
height: 7rem;
|
||||
}
|
||||
|
||||
.avatar-empty {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.avatar-empty::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 32%;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--bar);
|
||||
}
|
||||
|
||||
.avatar-row {
|
||||
display: flex;
|
||||
gap: 1.5rem;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.avatar-body {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
max-width: 40rem;
|
||||
}
|
||||
|
||||
.avatar-xl {
|
||||
width: 6rem;
|
||||
height: 6rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
main {
|
||||
max-width: 1120px;
|
||||
margin: 0 auto;
|
||||
@@ -798,9 +932,13 @@ input {
|
||||
margin-inline: -8px;
|
||||
}
|
||||
|
||||
.account {
|
||||
margin-left: 0;
|
||||
width: 100%;
|
||||
/* Just the picture and the icon; the name is still the button's accessible label */
|
||||
.account-name {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.account-menu {
|
||||
min-width: min(16rem, calc(100vw - 32px));
|
||||
}
|
||||
|
||||
.keys,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { api, describeError, upload } from "./api.js";
|
||||
import { avatarImage } from "./avatar.js";
|
||||
import { errorBox, h, replace } from "./dom.js";
|
||||
import { signedInPage } from "./layout.js";
|
||||
|
||||
const root = document.getElementById("avatar-panel");
|
||||
const messages = document.getElementById("messages");
|
||||
|
||||
const SOURCES = {
|
||||
upload: "An image you uploaded.",
|
||||
gravatar: "Your Gravatar, copied to this server.",
|
||||
none: "You haven't set a profile image yet.",
|
||||
};
|
||||
|
||||
let user = await signedInPage("account.html");
|
||||
render();
|
||||
|
||||
function say(notice) {
|
||||
replace(messages, notice);
|
||||
}
|
||||
|
||||
// Runs a change, adopts the user it returns (or refetches), and redraws everything that
|
||||
// shows the image - this panel and the one in the page header.
|
||||
async function change(action, done) {
|
||||
const buttons = root.querySelectorAll("button");
|
||||
buttons.forEach((button) => (button.disabled = true));
|
||||
try {
|
||||
user = (await action()) ?? (await api("/auth/me"));
|
||||
say(h("p", { class: "notice notice-ok" }, done));
|
||||
} catch (error) {
|
||||
say(errorBox(describeError(error)));
|
||||
// The change may have half-happened, or the page was out of date: show what's true now.
|
||||
user = await api("/auth/me").catch(() => user);
|
||||
}
|
||||
render();
|
||||
const slot = document.querySelector(".account-avatar");
|
||||
if (slot) replace(slot, avatarImage(user, "avatar-sm"));
|
||||
}
|
||||
|
||||
function render() {
|
||||
const file = h("input", { type: "file", accept: "image/jpeg,image/png,image/webp", hidden: true });
|
||||
file.addEventListener("change", () => {
|
||||
if (!file.files[0]) return;
|
||||
const data = new FormData();
|
||||
data.append("file", file.files[0]);
|
||||
change(() => upload("/me/avatar", data, undefined, "PUT"), "Profile image updated.");
|
||||
});
|
||||
|
||||
const buttons = [
|
||||
h("button", { type: "button", class: "button", onclick: () => file.click() }, "Upload image"),
|
||||
user.gravatar_enabled
|
||||
? h(
|
||||
"button",
|
||||
{
|
||||
type: "button",
|
||||
class: "button button-quiet",
|
||||
onclick: () => change(() => api("/me/avatar/gravatar", { method: "POST" }), "Now using your Gravatar."),
|
||||
},
|
||||
user.avatar_source === "gravatar" ? "Refresh Gravatar" : "Use my Gravatar",
|
||||
)
|
||||
: null,
|
||||
user.has_avatar
|
||||
? h(
|
||||
"button",
|
||||
{
|
||||
type: "button",
|
||||
class: "button button-quiet",
|
||||
onclick: () => change(() => api("/me/avatar", { method: "DELETE" }), "Profile image removed."),
|
||||
},
|
||||
"Remove",
|
||||
)
|
||||
: null,
|
||||
];
|
||||
|
||||
replace(
|
||||
root,
|
||||
h(
|
||||
"div",
|
||||
{ class: "avatar-row" },
|
||||
avatarImage(user, "avatar-lg"),
|
||||
h(
|
||||
"div",
|
||||
{ class: "avatar-body" },
|
||||
h("p", {}, SOURCES[user.avatar_source] ?? SOURCES.none),
|
||||
h("p", { class: "muted" }, "JPEG, PNG or WebP. Only you see it, unless you choose to share it on your fediverse profile."),
|
||||
h("div", { class: "button-row" }, buttons, file),
|
||||
user.gravatar_enabled
|
||||
? h(
|
||||
"p",
|
||||
{ class: "muted" },
|
||||
"Using Gravatar makes this server ask Gravatar for the picture linked to your email address, sending it a hash of that address (not the address itself). Your browser never contacts Gravatar.",
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// A round profile image that starts as a placeholder ring and swaps itself for the real
|
||||
// picture once (if) it loads. `source` is either a signed-in user (their own image,
|
||||
// fetched with their token) or { path } for another public image URL.
|
||||
|
||||
import { fetchImage } from "./api.js";
|
||||
import { h } from "./dom.js";
|
||||
|
||||
export function avatarImage(user, extraClass, path = "/me/avatar") {
|
||||
const classes = extraClass ? `avatar ${extraClass}` : "avatar";
|
||||
const el = h("span", { class: `${classes} avatar-empty`, "aria-hidden": "true" });
|
||||
if (!user?.has_avatar) return el;
|
||||
fetchImage(path).then((url) => {
|
||||
if (!url) return; // miss or failed fetch: leave the placeholder
|
||||
const img = h("img", { class: classes, alt: "" });
|
||||
img.src = url;
|
||||
el.replaceWith(img);
|
||||
});
|
||||
return el;
|
||||
}
|
||||
+103
-12
@@ -1,12 +1,19 @@
|
||||
// Shared page shell: site header, navigation, sign-in guard.
|
||||
|
||||
import { api, getToken, redirectToLogin, setToken } from "./api.js";
|
||||
import { avatarImage } from "./avatar.js";
|
||||
import { h, replace } from "./dom.js";
|
||||
|
||||
const NAV = [
|
||||
["index.html", "Overview"],
|
||||
["history.html", "History"],
|
||||
["art.html", "Album art"],
|
||||
];
|
||||
|
||||
// Account pages live in the menu under the user's name. "Sharing" joins them (after
|
||||
// Profile) when the server federates.
|
||||
const MENU = [
|
||||
["account.html", "Profile"],
|
||||
["apps.html", "Apps"],
|
||||
["sessions.html", "Sessions"],
|
||||
["import.html", "Import"],
|
||||
@@ -21,15 +28,9 @@ export async function signedInPage(active) {
|
||||
const header = document.getElementById("site-header");
|
||||
replace(header, brand(), nav(active));
|
||||
const user = await api("/auth/me");
|
||||
addSharingLink(header.querySelector("nav ul"), active);
|
||||
header.append(
|
||||
h(
|
||||
"div",
|
||||
{ class: "account" },
|
||||
h("span", { class: "account-name" }, user.username),
|
||||
h("button", { type: "button", class: "link-button", onclick: signOut }, "Sign out"),
|
||||
),
|
||||
);
|
||||
const menu = accountMenu(user, active);
|
||||
header.append(menu.element);
|
||||
addSharingLink(menu.list, active);
|
||||
return user;
|
||||
}
|
||||
|
||||
@@ -61,6 +62,95 @@ function nav(active) {
|
||||
);
|
||||
}
|
||||
|
||||
// The account menu: a button showing the user's picture and name that opens a list of
|
||||
// account pages and "Sign out". Returns the element and its <ul> (for late additions).
|
||||
function accountMenu(user, active) {
|
||||
const list = h("ul", { class: "account-menu", id: "account-menu", hidden: true });
|
||||
for (const [href, label] of MENU) list.append(menuLink(href, label, active));
|
||||
list.append(
|
||||
h(
|
||||
"li",
|
||||
{ class: "account-menu-end" },
|
||||
h("button", { type: "button", class: "account-menu-item", onclick: signOut }, "Sign out"),
|
||||
),
|
||||
);
|
||||
|
||||
const trigger = h(
|
||||
"button",
|
||||
{
|
||||
type: "button",
|
||||
class: "account-trigger",
|
||||
"aria-haspopup": "true",
|
||||
"aria-expanded": "false",
|
||||
"aria-controls": "account-menu",
|
||||
"aria-label": `Account menu for ${user.username}`,
|
||||
},
|
||||
h("span", { class: "account-avatar" }, avatarImage(user, "avatar-sm")),
|
||||
h("span", { class: "account-name" }, user.username),
|
||||
h("span", { class: "account-icon", "aria-hidden": "true" }),
|
||||
);
|
||||
const element = h("div", { class: "account" }, trigger, list);
|
||||
|
||||
const items = () => [...list.querySelectorAll("a, button")];
|
||||
const setOpen = (open, focus) => {
|
||||
list.hidden = !open;
|
||||
trigger.setAttribute("aria-expanded", String(open));
|
||||
if (open && focus === "first") items()[0]?.focus();
|
||||
if (open && focus === "last") items().at(-1)?.focus();
|
||||
if (!open && focus) trigger.focus();
|
||||
};
|
||||
|
||||
trigger.addEventListener("click", () => setOpen(list.hidden));
|
||||
trigger.addEventListener("keydown", (event) => {
|
||||
if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
setOpen(true, "first");
|
||||
} else if (event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
setOpen(true, "last");
|
||||
}
|
||||
});
|
||||
list.addEventListener("keydown", (event) => {
|
||||
const all = items();
|
||||
const at = all.indexOf(document.activeElement);
|
||||
if (event.key === "Escape") {
|
||||
setOpen(false, true);
|
||||
} else if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
all[(at + 1) % all.length].focus();
|
||||
} else if (event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
all[(at - 1 + all.length) % all.length].focus();
|
||||
} else if (event.key === "Home") {
|
||||
event.preventDefault();
|
||||
all[0].focus();
|
||||
} else if (event.key === "End") {
|
||||
event.preventDefault();
|
||||
all.at(-1).focus();
|
||||
}
|
||||
});
|
||||
// Close when focus or a click lands outside the menu.
|
||||
document.addEventListener("click", (event) => {
|
||||
if (!element.contains(event.target)) setOpen(false);
|
||||
});
|
||||
element.addEventListener("focusout", (event) => {
|
||||
if (event.relatedTarget && !element.contains(event.relatedTarget)) setOpen(false);
|
||||
});
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape" && !list.hidden) setOpen(false, true);
|
||||
});
|
||||
|
||||
// Mark the trigger when the page being viewed is one of the menu's.
|
||||
if (MENU.some(([href]) => href === active) || active === SHARING) {
|
||||
trigger.setAttribute("data-current", "true");
|
||||
}
|
||||
return { element, list };
|
||||
}
|
||||
|
||||
function menuLink(href, label, active) {
|
||||
return h("li", {}, h("a", { class: "account-menu-item", href, "aria-current": href === active ? "page" : false }, label));
|
||||
}
|
||||
|
||||
async function signOut() {
|
||||
try {
|
||||
await api("/auth/logout", { method: "POST" });
|
||||
@@ -95,9 +185,10 @@ async function federationAvailable() {
|
||||
return available;
|
||||
}
|
||||
|
||||
const SHARING = "sharing.html";
|
||||
|
||||
async function addSharingLink(list, active) {
|
||||
if (!list || !(await federationAvailable())) return;
|
||||
const href = "sharing.html";
|
||||
list.append(h("li", {}, h("a", { href, "aria-current": href === active ? "page" : false }, "Sharing")));
|
||||
if (!(await federationAvailable())) return;
|
||||
list.children[0].after(menuLink(SHARING, "Sharing", active)); // right after Profile
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { api } from "./api.js";
|
||||
import { avatarImage } from "./avatar.js";
|
||||
import { errorBox, h, replace } from "./dom.js";
|
||||
import { publicPage } from "./layout.js";
|
||||
|
||||
@@ -22,6 +23,9 @@ try {
|
||||
});
|
||||
replace(
|
||||
root,
|
||||
profile.has_avatar
|
||||
? avatarImage(profile, "avatar-xl", `/federation/profiles/${encodeURIComponent(username)}/avatar`)
|
||||
: null,
|
||||
h("h1", {}, profile.display_name),
|
||||
h("div", { class: "approve-app handle" }, profile.handle),
|
||||
profile.bio ? h("p", { class: "lede profile-bio" }, profile.bio) : null,
|
||||
|
||||
@@ -16,6 +16,7 @@ const FIELDS = [
|
||||
"post_milestones",
|
||||
"timezone",
|
||||
"now_playing_mode",
|
||||
"share_avatar",
|
||||
"display_name",
|
||||
"bio",
|
||||
];
|
||||
@@ -155,6 +156,7 @@ async function save(event) {
|
||||
post_milestones: form.elements.post_milestones.checked,
|
||||
timezone: form.elements.timezone.value.trim() || "UTC",
|
||||
now_playing_mode: form.querySelector("input[name=now_playing_mode]:checked").value,
|
||||
share_avatar: form.elements.share_avatar.checked,
|
||||
display_name: form.elements.display_name.value.trim() || null,
|
||||
bio: form.elements.bio.value.trim() || null,
|
||||
};
|
||||
|
||||
@@ -114,6 +114,10 @@
|
||||
<textarea id="bio" name="bio" maxlength="500" rows="3"></textarea>
|
||||
<span class="hint">Shown on your fediverse profile. Plain text.</span>
|
||||
</div>
|
||||
<div class="choice">
|
||||
<input type="checkbox" id="share_avatar" name="share_avatar">
|
||||
<label for="share_avatar"><strong>Share my profile image</strong><span class="muted">Show the image from your <a href="account.html">profile</a> on your public profile page, and send it to other servers as your picture. Without this it stays private.</span></label>
|
||||
</div>
|
||||
<p class="muted" id="profile-link"></p>
|
||||
</fieldset>
|
||||
|
||||
|
||||
@@ -48,7 +48,18 @@ def init_app(app: Flask) -> None:
|
||||
},
|
||||
)
|
||||
|
||||
from scrobbler.api import apps, art, auth, health, imports, sessions, stats, tokens, tracks
|
||||
from scrobbler.api import (
|
||||
apps,
|
||||
art,
|
||||
auth,
|
||||
avatar,
|
||||
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")
|
||||
@@ -58,6 +69,7 @@ def init_app(app: Flask) -> None:
|
||||
api.register_blueprint(tracks.blp, url_prefix="/api/v1/me/tracks")
|
||||
api.register_blueprint(imports.blp, url_prefix="/api/v1/imports")
|
||||
api.register_blueprint(art.blp, url_prefix="/api/v1/art")
|
||||
api.register_blueprint(avatar.blp, url_prefix="/api/v1/me/avatar")
|
||||
api.register_blueprint(health.blp)
|
||||
|
||||
from scrobbler.openapi import lastfm
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
from flask import Response, current_app, g, request
|
||||
from flask_smorest import Blueprint, abort
|
||||
|
||||
from scrobbler import metrics
|
||||
from scrobbler.api.decorators import authenticated
|
||||
from scrobbler.schemas import AvatarUploadSchema, ErrorSchema, UserSchema
|
||||
from scrobbler.services import avatars
|
||||
|
||||
blp = Blueprint(
|
||||
"Avatar",
|
||||
__name__,
|
||||
description=(
|
||||
"Your profile image: upload one, use your Gravatar (if this server allows it), "
|
||||
"or remove it."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@blp.route("", methods=["GET"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, content_type="image/jpeg", description="Your profile image (JPEG, PNG or WebP)")
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="You have no profile image")
|
||||
def get_avatar():
|
||||
"""Your profile image"""
|
||||
data = avatars.read(g.user)
|
||||
if data is None:
|
||||
abort(404, code="no_avatar", message="You have no profile image")
|
||||
response = Response(data, mimetype=g.user.avatar_content_type or "image/jpeg")
|
||||
response.headers["Cache-Control"] = "private, no-cache" # revalidate: it can change
|
||||
response.add_etag()
|
||||
return response.make_conditional(request)
|
||||
|
||||
|
||||
@blp.route("", methods=["PUT"])
|
||||
@authenticated(blp)
|
||||
@blp.arguments(AvatarUploadSchema, location="files")
|
||||
@blp.response(200, UserSchema)
|
||||
@blp.alt_response(400, schema=ErrorSchema, description="Empty file")
|
||||
@blp.alt_response(413, schema=ErrorSchema, description="Image too large")
|
||||
@blp.alt_response(415, schema=ErrorSchema, description="Not a JPEG, PNG or WebP image")
|
||||
def upload_avatar(files):
|
||||
"""Upload a profile image
|
||||
|
||||
Replaces your current one, whatever its source.
|
||||
"""
|
||||
limit = current_app.config["AVATAR_UPLOAD_MAX_BYTES"]
|
||||
data = files["file"].read(limit + 1)
|
||||
if not data:
|
||||
metrics.avatar_uploads_total.labels("empty").inc()
|
||||
abort(400, code="empty_file", message="That file is empty.")
|
||||
if len(data) > limit:
|
||||
metrics.avatar_uploads_total.labels("too_large").inc()
|
||||
abort(413, code="file_too_large", message="That image is larger than this server accepts.")
|
||||
try:
|
||||
content_type = avatars.sniff_image_type(data)
|
||||
except avatars.UnsupportedImage:
|
||||
metrics.avatar_uploads_total.labels("bad_type").inc()
|
||||
abort(415, code="unsupported_image", message="Upload a JPEG, PNG or WebP image.")
|
||||
avatars.save(g.user, data, content_type, "upload")
|
||||
metrics.avatar_uploads_total.labels("ok").inc()
|
||||
metrics.avatar_upload_bytes.observe(len(data))
|
||||
return g.user
|
||||
|
||||
|
||||
@blp.route("/gravatar", methods=["POST"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, UserSchema)
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="Gravatar is off, or has no image for you")
|
||||
@blp.alt_response(502, schema=ErrorSchema, description="Gravatar couldn't be reached")
|
||||
def use_gravatar():
|
||||
"""Use your Gravatar as your profile image
|
||||
|
||||
The server fetches the image for your account email from Gravatar (sending it a hash
|
||||
of the address) and keeps a copy. Call again to refresh it. Only available when the
|
||||
server's admin has enabled it; see `gravatar_enabled` on `/auth/me`.
|
||||
"""
|
||||
try:
|
||||
avatars.use_gravatar(g.user)
|
||||
except avatars.GravatarDisabled:
|
||||
abort(404, code="gravatar_disabled", message="This server doesn't use Gravatar.")
|
||||
except avatars.GravatarMissing:
|
||||
abort(404, code="no_gravatar", message="Gravatar has no image for your email address.")
|
||||
except avatars.GravatarUnavailable:
|
||||
abort(502, code="gravatar_unavailable", message="Gravatar couldn't be reached.")
|
||||
return g.user
|
||||
|
||||
|
||||
@blp.route("", methods=["DELETE"])
|
||||
@authenticated(blp)
|
||||
@blp.response(204)
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="You have no profile image")
|
||||
def delete_avatar():
|
||||
"""Remove your profile image"""
|
||||
if not avatars.remove(g.user):
|
||||
abort(404, code="no_avatar", message="You have no profile image")
|
||||
@@ -72,6 +72,17 @@ class Config:
|
||||
ART_STORAGE_DIR = os.environ.get("ART_STORAGE_DIR", "var/album-art")
|
||||
# Largest image a user may upload as their own album art.
|
||||
ART_UPLOAD_MAX_BYTES = int(os.environ.get("ART_UPLOAD_MAX_BYTES", str(5 * 1024 * 1024)))
|
||||
# Profile images live in an "avatars" folder inside ART_STORAGE_DIR. This is the
|
||||
# largest one a user may upload.
|
||||
AVATAR_UPLOAD_MAX_BYTES = int(os.environ.get("AVATAR_UPLOAD_MAX_BYTES", str(2 * 1024 * 1024)))
|
||||
# Lets users pick their Gravatar as their profile image. Off by default: using one
|
||||
# sends a hash of the user's email address to Gravatar (from this server, not their browser).
|
||||
AVATAR_GRAVATAR_ENABLED = os.environ.get("AVATAR_GRAVATAR_ENABLED", "").lower() in (
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
)
|
||||
GRAVATAR_URL = os.environ.get("GRAVATAR_URL", "https://gravatar.com/avatar/")
|
||||
|
||||
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
|
||||
|
||||
@@ -34,6 +34,15 @@ def now_playing_field(user, settings) -> list[tuple[str, str]]:
|
||||
return [(NOW_PLAYING_FIELD, text)] if text else []
|
||||
|
||||
|
||||
def avatar_icon(urls: vocab.ActorUrls, user, settings) -> tuple[str, str] | None:
|
||||
"""The actor's picture: only if they've chosen to share one. The URL carries the
|
||||
image's age so other servers, which cache by URL, fetch a changed picture."""
|
||||
if not settings.share_avatar or not user.has_avatar:
|
||||
return None
|
||||
version = int(user.avatar_updated_at.timestamp()) if user.avatar_updated_at else 0
|
||||
return f"{urls.avatar}?v={version}", user.avatar_content_type or "image/jpeg"
|
||||
|
||||
|
||||
def build_document(urls: vocab.ActorUrls, user, settings) -> dict:
|
||||
return vocab.person(
|
||||
urls,
|
||||
@@ -46,4 +55,5 @@ def build_document(urls: vocab.ActorUrls, user, settings) -> dict:
|
||||
indexable=settings.indexable,
|
||||
published=settings.created_at.isoformat().replace("+00:00", "Z"),
|
||||
fields=now_playing_field(user, settings),
|
||||
icon=avatar_icon(urls, user, settings),
|
||||
)
|
||||
@@ -178,10 +178,28 @@ def public_profile(username):
|
||||
"now_playing": actors.now_playing_text(user)
|
||||
if settings.now_playing_mode != "off"
|
||||
else None,
|
||||
"has_avatar": settings.share_avatar and user.has_avatar,
|
||||
**{k: v for k, v in _identity(user.username).items() if k != "profile_url"},
|
||||
}
|
||||
|
||||
|
||||
@blp.route("/profiles/<string:username>/avatar", methods=["GET"])
|
||||
@blp.response(200, content_type="image/jpeg", description="The profile image (JPEG, PNG or WebP)")
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="No image shared under that name")
|
||||
def public_avatar(username):
|
||||
"""A public profile image
|
||||
|
||||
For the web UI's profile page. Only served when the user shares and has chosen to
|
||||
share their image.
|
||||
"""
|
||||
found = sharing.shared_avatar(username)
|
||||
if found is None:
|
||||
fed_metrics.lookups_total.labels(kind="avatar", result="not_found").inc()
|
||||
abort(404, code="not_found", message="No shared profile image under that name.")
|
||||
fed_metrics.lookups_total.labels(kind="avatar", result="found").inc()
|
||||
return sharing.avatar_response(*found)
|
||||
|
||||
|
||||
@blp.route("/profiles/<string:username>/posts/<string:post_uuid>", methods=["GET"])
|
||||
@blp.response(200, PublicPostSchema)
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="Not found, not public, or deleted")
|
||||
|
||||
@@ -4,7 +4,7 @@ from prometheus_client import Counter, Gauge, Histogram
|
||||
|
||||
lookups_total = Counter(
|
||||
"scrobbler_federation_lookups_total",
|
||||
"Fediverse lookups answered: WebFinger, actor, NodeInfo, profile",
|
||||
"Fediverse lookups answered: WebFinger, actor, NodeInfo, profile, avatar",
|
||||
["kind", "result"],
|
||||
)
|
||||
sharing_changes_total = Counter(
|
||||
|
||||
@@ -41,6 +41,9 @@ class FederationSettings(db.Model):
|
||||
indexable: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
display_name: Mapped[str | None] = mapped_column(String(100))
|
||||
bio: Mapped[str | None] = mapped_column(Text)
|
||||
# Offer the user's profile image to other servers (as the actor's icon) and on the
|
||||
# public profile page. Off until they say so.
|
||||
share_avatar: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
# An IANA zone name (validated with zoneinfo), used to decide when a Monday starts.
|
||||
timezone: Mapped[str] = mapped_column(String(64), default="UTC")
|
||||
post_weekly_summary: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
|
||||
@@ -130,6 +130,20 @@ _OPERATIONS = {
|
||||
"404": {"description": "Not found, not listed, or deleted"},
|
||||
},
|
||||
),
|
||||
"federation.actor_avatar": (
|
||||
"get",
|
||||
"Profile image",
|
||||
"The user's profile image, which their actor document names as its `icon`. Only "
|
||||
"served when the user shares and has chosen to share their image.",
|
||||
[_USERNAME],
|
||||
{
|
||||
"200": {
|
||||
"description": "A JPEG, PNG or WebP image",
|
||||
"content": {"image/*": {"schema": {"type": "string", "format": "binary"}}},
|
||||
},
|
||||
"404": _NOT_FOUND,
|
||||
},
|
||||
),
|
||||
"federation.followers": (
|
||||
"get",
|
||||
"Followers",
|
||||
|
||||
@@ -35,6 +35,7 @@ class ActorUrls:
|
||||
shared_inbox: str
|
||||
key_id: str
|
||||
profile_page: str
|
||||
avatar: str
|
||||
|
||||
|
||||
def actor_urls(base_url: str, username: str, profile_page: str) -> ActorUrls:
|
||||
@@ -49,6 +50,7 @@ def actor_urls(base_url: str, username: str, profile_page: str) -> ActorUrls:
|
||||
shared_inbox=f"{base_url}/inbox",
|
||||
key_id=f"{actor}#main-key",
|
||||
profile_page=profile_page,
|
||||
avatar=f"{actor}/avatar",
|
||||
)
|
||||
|
||||
|
||||
@@ -79,8 +81,10 @@ def person(
|
||||
indexable: bool,
|
||||
published: str | None = None,
|
||||
fields: list[tuple[str, str]] = (),
|
||||
icon: tuple[str, str] | None = None,
|
||||
) -> dict:
|
||||
"""A user's actor document. `fields` are (name, plain-text value) profile fields."""
|
||||
"""A user's actor document. `fields` are (name, plain-text value) profile fields;
|
||||
`icon` is the profile picture's (url, media type)."""
|
||||
doc = {
|
||||
"@context": ACTOR_CONTEXT,
|
||||
"id": urls.id,
|
||||
@@ -106,6 +110,8 @@ def person(
|
||||
}
|
||||
if published:
|
||||
doc["published"] = published
|
||||
if icon:
|
||||
doc["icon"] = {"type": "Image", "url": icon[0], "mediaType": icon[1]}
|
||||
return doc
|
||||
|
||||
|
||||
|
||||
@@ -55,6 +55,14 @@ class SharingSettingsSchema(Schema):
|
||||
)
|
||||
},
|
||||
)
|
||||
share_avatar = fields.Boolean(
|
||||
metadata={
|
||||
"description": (
|
||||
"Show your profile image on your public profile and send it to other "
|
||||
"servers as your picture. Off by default; has no effect if you have no image."
|
||||
)
|
||||
}
|
||||
)
|
||||
handle = fields.String(dump_only=True, metadata={"example": "@alice@scrobble.example"})
|
||||
actor_url = fields.String(dump_only=True)
|
||||
profile_url = fields.String(dump_only=True)
|
||||
@@ -71,6 +79,9 @@ class PublicProfileSchema(Schema):
|
||||
now_playing = fields.String(
|
||||
allow_none=True, metadata={"description": '"Track by Artist", or null'}
|
||||
)
|
||||
has_avatar = fields.Boolean(
|
||||
metadata={"description": "Whether there's a profile image at `/profiles/{username}/avatar`"}
|
||||
)
|
||||
handle = fields.String(metadata={"example": "@alice@scrobble.example"})
|
||||
actor_url = fields.String()
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
"""Per-user sharing settings: whether a user federates, and how."""
|
||||
|
||||
from flask import Response, request
|
||||
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.federation import keys
|
||||
from scrobbler.federation.models import NOW_PLAYING_MODES, VISIBILITIES, FederationSettings
|
||||
from scrobbler.federation.protocol.schedule import is_valid_timezone
|
||||
from scrobbler.services import accounts
|
||||
from scrobbler.services import accounts, avatars
|
||||
|
||||
EDITABLE = (
|
||||
"enabled",
|
||||
@@ -18,6 +20,7 @@ EDITABLE = (
|
||||
"post_weekly_summary",
|
||||
"post_milestones",
|
||||
"now_playing_mode",
|
||||
"share_avatar",
|
||||
)
|
||||
|
||||
|
||||
@@ -38,6 +41,7 @@ def settings_for(user_id: int) -> FederationSettings:
|
||||
post_weekly_summary=True,
|
||||
post_milestones=True,
|
||||
now_playing_mode="off",
|
||||
share_avatar=False,
|
||||
)
|
||||
return settings
|
||||
|
||||
@@ -81,6 +85,27 @@ def shared_user(username: str):
|
||||
return user, settings
|
||||
|
||||
|
||||
def shared_avatar(username: str):
|
||||
"""(user, image bytes) for a sharing user who has chosen to share their profile image
|
||||
and has one, else None - indistinguishable from 'no such user', like shared_user."""
|
||||
found = shared_user(username)
|
||||
if found is None:
|
||||
return None
|
||||
user, settings = found
|
||||
if not settings.share_avatar:
|
||||
return None
|
||||
data = avatars.read(user)
|
||||
return None if data is None else (user, data)
|
||||
|
||||
|
||||
def avatar_response(user, data: bytes):
|
||||
"""The public image response: cacheable by anyone, but briefly, as it can change."""
|
||||
response = Response(data, mimetype=user.avatar_content_type or "image/jpeg")
|
||||
response.headers["Cache-Control"] = "public, max-age=300"
|
||||
response.add_etag()
|
||||
return response.make_conditional(request)
|
||||
|
||||
|
||||
def sharing_count() -> int:
|
||||
return db.session.scalar(
|
||||
db.select(db.func.count()).select_from(FederationSettings).filter_by(enabled=True)
|
||||
|
||||
@@ -134,6 +134,15 @@ def actor(username: str):
|
||||
return _json(doc)
|
||||
|
||||
|
||||
@bp.get("/users/<username>/avatar")
|
||||
def actor_avatar(username: str):
|
||||
found = sharing.shared_avatar(username)
|
||||
if found is None:
|
||||
return _not_found("avatar")
|
||||
_found("avatar")
|
||||
return sharing.avatar_response(*found)
|
||||
|
||||
|
||||
def _collection(username: str, which: str, items: list | None, total: int = 0):
|
||||
found = sharing.shared_user(username)
|
||||
if found is None:
|
||||
|
||||
@@ -193,6 +193,33 @@ art_override_worker_seconds = Histogram(
|
||||
buckets=(0.25, 0.5, 1, 2.5, 5, 10, 20, 40, 80),
|
||||
)
|
||||
|
||||
# Profile images
|
||||
avatar_uploads_total = Counter(
|
||||
"scrobbler_avatar_uploads_total",
|
||||
"Profile image upload attempts: ok, empty, too_large or bad_type",
|
||||
["result"],
|
||||
)
|
||||
avatar_upload_bytes = Histogram(
|
||||
"scrobbler_avatar_upload_bytes",
|
||||
"Size of accepted profile image uploads",
|
||||
buckets=(5_000, 10_000, 25_000, 50_000, 100_000, 250_000, 500_000, 1_000_000, 2_000_000),
|
||||
)
|
||||
avatar_gravatar_fetches_total = Counter(
|
||||
"scrobbler_avatar_gravatar_fetches_total",
|
||||
"Gravatar fetches: ok, none (no Gravatar for the email), bad_type, too_large or error",
|
||||
["result"],
|
||||
)
|
||||
avatar_gravatar_seconds = Histogram(
|
||||
"scrobbler_avatar_gravatar_seconds",
|
||||
"Latency of one Gravatar fetch",
|
||||
buckets=(0.1, 0.25, 0.5, 1, 2.5, 5, 10),
|
||||
)
|
||||
avatar_actions_total = Counter(
|
||||
"scrobbler_avatar_actions_total",
|
||||
"Profile image changes: uploaded, gravatar, removed",
|
||||
["action"],
|
||||
)
|
||||
|
||||
# Database
|
||||
db_query_duration_seconds = Histogram(
|
||||
"scrobbler_db_query_duration_seconds",
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""user avatar
|
||||
|
||||
Revision ID: b3e8a5d1f720
|
||||
Revises: c7d2f08a19e4
|
||||
Create Date: 2026-10-13 09:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "b3e8a5d1f720"
|
||||
down_revision = "c7d2f08a19e4"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column(
|
||||
"users",
|
||||
sa.Column("avatar_source", sa.String(length=16), server_default="none", nullable=False),
|
||||
)
|
||||
op.add_column("users", sa.Column("avatar_content_type", sa.String(length=32), nullable=True))
|
||||
op.add_column(
|
||||
"users", sa.Column("avatar_updated_at", sa.DateTime(timezone=True), nullable=True)
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column("users", "avatar_updated_at")
|
||||
op.drop_column("users", "avatar_content_type")
|
||||
op.drop_column("users", "avatar_source")
|
||||
@@ -0,0 +1,29 @@
|
||||
"""federation share avatar
|
||||
|
||||
Revision ID: e5a91c3d7b08
|
||||
Revises: 2533b727da79
|
||||
Create Date: 2026-10-13 10:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "e5a91c3d7b08"
|
||||
down_revision = "2533b727da79"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("federation_settings", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column("share_avatar", sa.Boolean(), nullable=False, server_default=sa.false())
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("federation_settings", schema=None) as batch_op:
|
||||
batch_op.drop_column("share_avatar")
|
||||
@@ -28,9 +28,18 @@ class User(db.Model):
|
||||
email: Mapped[str] = mapped_column(String(255))
|
||||
password_hash: Mapped[str] = mapped_column(String(255))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
# The profile image: none, upload or gravatar. Any image's bytes sit on disk (see
|
||||
# services/avatars.py); these columns just say whether there is one, and what it is.
|
||||
avatar_source: Mapped[str] = mapped_column(String(16), default="none", server_default="none")
|
||||
avatar_content_type: Mapped[str | None] = mapped_column(String(32))
|
||||
avatar_updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
__table_args__ = (Index("uq_users_username_lower", func.lower(username), unique=True),)
|
||||
|
||||
@property
|
||||
def has_avatar(self) -> bool:
|
||||
return self.avatar_source != "none"
|
||||
|
||||
|
||||
class ApiApp(db.Model):
|
||||
"""A client application; scrobblers authenticate with its key and secret."""
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Marshmallow schemas for the /api/v1 JSON API. They drive both request
|
||||
validation and the generated OpenAPI document."""
|
||||
|
||||
from flask import current_app
|
||||
from flask_smorest.fields import Upload
|
||||
from marshmallow import Schema, ValidationError, fields, validate, validates_schema
|
||||
|
||||
@@ -20,6 +21,24 @@ class UserSchema(Schema):
|
||||
username = fields.String(dump_only=True, metadata={"example": "alice"})
|
||||
email = fields.String(dump_only=True, metadata={"example": "alice@example.com"})
|
||||
created_at = fields.DateTime(dump_only=True)
|
||||
has_avatar = fields.Boolean(
|
||||
dump_only=True, metadata={"description": "Whether you have a profile image"}
|
||||
)
|
||||
avatar_source = fields.String(
|
||||
dump_only=True,
|
||||
validate=validate.OneOf(["none", "upload", "gravatar"]),
|
||||
metadata={"description": "Where your profile image comes from"},
|
||||
)
|
||||
avatar_updated_at = fields.DateTime(
|
||||
dump_only=True, allow_none=True, metadata={"description": "When it last changed"}
|
||||
)
|
||||
gravatar_enabled = fields.Method(
|
||||
"_gravatar_enabled",
|
||||
metadata={"type": "boolean", "description": "Whether this server offers Gravatar"},
|
||||
)
|
||||
|
||||
def _gravatar_enabled(self, _user) -> bool:
|
||||
return bool(current_app.config["AVATAR_GRAVATAR_ENABLED"])
|
||||
|
||||
|
||||
class RegisterSchema(Schema):
|
||||
@@ -164,6 +183,10 @@ class AlbumArtUploadSchema(Schema):
|
||||
file = Upload(required=True, metadata={"description": "A JPEG, PNG or WebP image"})
|
||||
|
||||
|
||||
class AvatarUploadSchema(Schema):
|
||||
file = Upload(required=True, metadata={"description": "A JPEG, PNG or WebP image"})
|
||||
|
||||
|
||||
class AlbumArtCorrectionSchema(AlbumArtArgsSchema):
|
||||
search_artist = fields.String(
|
||||
validate=validate.Length(min=1, max=500),
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Profile images.
|
||||
|
||||
The bytes live on disk, in an "avatars" folder inside ART_STORAGE_DIR (so they share its
|
||||
volume and its backups), one file per user named by user id with no extension. The users
|
||||
row records where the image came from and its content type; that is the source of truth
|
||||
for whether there is one.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from scrobbler import metrics
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.models import User
|
||||
from scrobbler.services.art import IMAGE_TYPES, UnsupportedImage, sniff_image_type
|
||||
|
||||
__all__ = [
|
||||
"IMAGE_TYPES",
|
||||
"GravatarDisabled",
|
||||
"GravatarMissing",
|
||||
"GravatarUnavailable",
|
||||
"UnsupportedImage",
|
||||
"read",
|
||||
"remove",
|
||||
"save",
|
||||
"sniff_image_type",
|
||||
"use_gravatar",
|
||||
]
|
||||
|
||||
GRAVATAR_SIZE = 256 # px; plenty for a header icon or a profile page
|
||||
GRAVATAR_MAX_BYTES = 1024 * 1024
|
||||
GRAVATAR_TIMEOUT = 5 # seconds - this runs inside a web request
|
||||
|
||||
|
||||
class GravatarDisabled(Exception):
|
||||
"""The admin hasn't turned Gravatar on."""
|
||||
|
||||
|
||||
class GravatarMissing(Exception):
|
||||
"""Gravatar has no image for the user's email address."""
|
||||
|
||||
|
||||
class GravatarUnavailable(Exception):
|
||||
"""Gravatar couldn't be reached, or sent something unusable."""
|
||||
|
||||
|
||||
def _path(user_id: int) -> Path:
|
||||
return Path(current_app.config["ART_STORAGE_DIR"]) / "avatars" / str(user_id)
|
||||
|
||||
|
||||
def read(user: User) -> bytes | None:
|
||||
"""The user's image bytes, or None if they have none (or the file has gone missing)."""
|
||||
if not user.has_avatar:
|
||||
return None
|
||||
try:
|
||||
return _path(user.id).read_bytes()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
|
||||
|
||||
def _write(user_id: int, data: bytes) -> None:
|
||||
"""Writes via a temp file and a rename, so a reader never sees half an image."""
|
||||
path = _path(user_id)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temp = tempfile.mkstemp(dir=path.parent, prefix=f".{user_id}.")
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as file:
|
||||
file.write(data)
|
||||
os.replace(temp, path)
|
||||
except BaseException:
|
||||
Path(temp).unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def save(user: User, data: bytes, content_type: str, source: str) -> None:
|
||||
"""Make `data` the user's image. The caller has already validated it. The file is
|
||||
written first, so a failure leaves the previous image (and row) intact."""
|
||||
_write(user.id, data)
|
||||
user.avatar_source = source
|
||||
user.avatar_content_type = content_type
|
||||
user.avatar_updated_at = datetime.now(UTC)
|
||||
db.session.commit()
|
||||
metrics.avatar_actions_total.labels("uploaded" if source == "upload" else source).inc()
|
||||
|
||||
|
||||
def remove(user: User) -> bool:
|
||||
"""Drops the user's image. False if they didn't have one."""
|
||||
if not user.has_avatar:
|
||||
return False
|
||||
user.avatar_source = "none"
|
||||
user.avatar_content_type = None
|
||||
user.avatar_updated_at = datetime.now(UTC)
|
||||
db.session.commit()
|
||||
_path(user.id).unlink(missing_ok=True)
|
||||
metrics.avatar_actions_total.labels("removed").inc()
|
||||
return True
|
||||
|
||||
|
||||
def gravatar_url(email: str) -> str:
|
||||
"""Where Gravatar serves this address's image; d=404 asks for an error, not a stock
|
||||
picture, when it has none. Gravatar keys on the SHA-256 of the trimmed, lower-cased email."""
|
||||
digest = hashlib.sha256(email.strip().lower().encode()).hexdigest()
|
||||
base = current_app.config["GRAVATAR_URL"]
|
||||
return f"{base}{digest}?s={GRAVATAR_SIZE}&d=404"
|
||||
|
||||
|
||||
def _fetch_gravatar(email: str) -> bytes:
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
with urllib.request.urlopen(gravatar_url(email), timeout=GRAVATAR_TIMEOUT) as response:
|
||||
data = response.read(GRAVATAR_MAX_BYTES + 1)
|
||||
except urllib.error.HTTPError as err:
|
||||
if err.code == 404:
|
||||
metrics.avatar_gravatar_fetches_total.labels("none").inc()
|
||||
raise GravatarMissing from err
|
||||
metrics.avatar_gravatar_fetches_total.labels("error").inc()
|
||||
raise GravatarUnavailable(str(err)) from err
|
||||
except (urllib.error.URLError, TimeoutError) as err:
|
||||
metrics.avatar_gravatar_fetches_total.labels("error").inc()
|
||||
raise GravatarUnavailable(str(err)) from err
|
||||
finally:
|
||||
metrics.avatar_gravatar_seconds.observe(time.perf_counter() - start)
|
||||
if len(data) > GRAVATAR_MAX_BYTES:
|
||||
metrics.avatar_gravatar_fetches_total.labels("too_large").inc()
|
||||
raise GravatarUnavailable("image too large")
|
||||
return data
|
||||
|
||||
|
||||
def use_gravatar(user: User) -> None:
|
||||
"""Fetch the Gravatar for the user's email and make it their image (also how it's
|
||||
refreshed). Raises GravatarDisabled, GravatarMissing or GravatarUnavailable, leaving
|
||||
any current image alone. The bytes are kept on disk, so browsers never talk to Gravatar."""
|
||||
if not current_app.config["AVATAR_GRAVATAR_ENABLED"]:
|
||||
raise GravatarDisabled
|
||||
data = _fetch_gravatar(user.email)
|
||||
try:
|
||||
content_type = sniff_image_type(data)
|
||||
except UnsupportedImage as err:
|
||||
metrics.avatar_gravatar_fetches_total.labels("bad_type").inc()
|
||||
raise GravatarUnavailable("not an image") from err
|
||||
save(user, data, content_type, "gravatar")
|
||||
metrics.avatar_gravatar_fetches_total.labels("ok").inc()
|
||||
@@ -0,0 +1,245 @@
|
||||
import hashlib
|
||||
import io
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
from werkzeug.serving import make_server
|
||||
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.models import User
|
||||
from scrobbler.services.accounts import issue_ui_token
|
||||
|
||||
JPEG = b"\xff\xd8\xff\xe0fake-jpeg"
|
||||
PNG = b"\x89PNG\r\n\x1a\nxxxx"
|
||||
URL = "/api/v1/me/avatar"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def storage(app, tmp_path):
|
||||
saved = app.config["ART_STORAGE_DIR"]
|
||||
app.config["ART_STORAGE_DIR"] = str(tmp_path)
|
||||
yield tmp_path
|
||||
app.config["ART_STORAGE_DIR"] = saved
|
||||
|
||||
|
||||
def put(client, auth, data=JPEG, name="me.jpg"):
|
||||
return client.put(
|
||||
URL,
|
||||
headers=auth,
|
||||
data={"file": (io.BytesIO(data), name)},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
|
||||
|
||||
def test_endpoints_require_auth(client):
|
||||
assert client.get(URL).status_code == 401
|
||||
assert client.put(URL).status_code == 401
|
||||
assert client.delete(URL).status_code == 401
|
||||
|
||||
|
||||
def test_no_avatar_to_begin_with(client, auth, user, storage):
|
||||
assert client.get(URL, headers=auth).status_code == 404
|
||||
assert client.delete(URL, headers=auth).status_code == 404
|
||||
me = client.get("/api/v1/auth/me", headers=auth).get_json()
|
||||
assert (me["has_avatar"], me["avatar_source"], me["avatar_updated_at"]) == (False, "none", None)
|
||||
|
||||
|
||||
def test_upload_then_get_serves_the_image(client, auth, storage, metric_delta):
|
||||
ok = metric_delta("scrobbler_avatar_uploads_total", result="ok")
|
||||
size = metric_delta("scrobbler_avatar_upload_bytes_count")
|
||||
action = metric_delta("scrobbler_avatar_actions_total", action="uploaded")
|
||||
response = put(client, auth)
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert (body["has_avatar"], body["avatar_source"]) == (True, "upload")
|
||||
image = client.get(URL, headers=auth)
|
||||
assert image.status_code == 200
|
||||
assert (image.data, image.mimetype) == (JPEG, "image/jpeg")
|
||||
assert image.headers["Cache-Control"] == "private, no-cache"
|
||||
assert (ok.delta, size.delta, action.delta) == (1, 1, 1)
|
||||
assert client.get("/api/v1/auth/me", headers=auth).get_json()["has_avatar"] is True
|
||||
|
||||
|
||||
def test_uploading_again_replaces_it(client, auth, storage):
|
||||
put(client, auth)
|
||||
put(client, auth, data=PNG, name="me.png")
|
||||
image = client.get(URL, headers=auth)
|
||||
assert (image.data, image.mimetype) == (PNG, "image/png")
|
||||
assert [p.name for p in (storage / "avatars").iterdir()] == ["1"] # no stray temp files
|
||||
|
||||
|
||||
def test_supports_conditional_requests(client, auth, storage):
|
||||
put(client, auth)
|
||||
first = client.get(URL, headers=auth)
|
||||
again = client.get(URL, headers={**auth, "If-None-Match": first.headers["ETag"]})
|
||||
assert again.status_code == 304
|
||||
|
||||
|
||||
def test_delete_removes_the_image_and_file(client, auth, storage, metric_delta):
|
||||
put(client, auth)
|
||||
removed = metric_delta("scrobbler_avatar_actions_total", action="removed")
|
||||
assert client.delete(URL, headers=auth).status_code == 204
|
||||
assert client.get(URL, headers=auth).status_code == 404
|
||||
assert not (storage / "avatars" / "1").exists()
|
||||
assert client.get("/api/v1/auth/me", headers=auth).get_json()["has_avatar"] is False
|
||||
assert removed.delta == 1
|
||||
|
||||
|
||||
def test_a_missing_file_reads_as_no_avatar(client, auth, storage):
|
||||
put(client, auth)
|
||||
(storage / "avatars" / "1").unlink()
|
||||
assert client.get(URL, headers=auth).status_code == 404
|
||||
|
||||
|
||||
def test_avatars_are_per_user(client, auth, storage, make_user):
|
||||
put(client, auth)
|
||||
token = issue_ui_token(make_user(username="mallory"))
|
||||
other = {"Authorization": f"Bearer {token}"}
|
||||
assert client.get(URL, headers=other).status_code == 404
|
||||
assert db.session.scalar(db.select(User).where(User.username == "mallory")).has_avatar is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("data", "status", "result"),
|
||||
[(b"", 400, "empty"), (b"GIF89a....", 415, "bad_type"), (JPEG + b"x" * 100, 413, "too_large")],
|
||||
)
|
||||
def test_upload_rejects_bad_files(client, auth, app, storage, metric_delta, data, status, result):
|
||||
saved = app.config["AVATAR_UPLOAD_MAX_BYTES"]
|
||||
app.config["AVATAR_UPLOAD_MAX_BYTES"] = 50
|
||||
try:
|
||||
counted = metric_delta("scrobbler_avatar_uploads_total", result=result)
|
||||
assert put(client, auth, data=data).status_code == status
|
||||
assert counted.delta == 1
|
||||
assert client.get(URL, headers=auth).status_code == 404
|
||||
finally:
|
||||
app.config["AVATAR_UPLOAD_MAX_BYTES"] = saved
|
||||
|
||||
|
||||
def test_upload_requires_a_file(client, auth, storage):
|
||||
response = client.put(URL, headers=auth, data={}, content_type="multipart/form-data")
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
# --- Gravatar ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _digest(email):
|
||||
return hashlib.sha256(email.encode()).hexdigest()
|
||||
|
||||
|
||||
GRAVATAR_JPEG = b"\xff\xd8\xff\xe0gravatar-jpeg"
|
||||
_GRAVATARS = {
|
||||
_digest("alice@example.com"): ("200 OK", GRAVATAR_JPEG),
|
||||
_digest("html@example.com"): ("200 OK", b"<html>not an image</html>"),
|
||||
_digest("big@example.com"): ("200 OK", b"\xff\xd8\xff" + b"x" * (1024 * 1024)),
|
||||
_digest("boom@example.com"): ("500 Internal Server Error", b"boom"),
|
||||
}
|
||||
SEEN = []
|
||||
|
||||
|
||||
def _fake_gravatar(environ, start_response):
|
||||
SEEN.append((environ["PATH_INFO"], environ["QUERY_STRING"]))
|
||||
status, body = _GRAVATARS.get(
|
||||
environ["PATH_INFO"].rsplit("/", 1)[-1], ("404 Not Found", b"not found")
|
||||
)
|
||||
start_response(status, [("Content-Length", str(len(body)))])
|
||||
return [body]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fake_gravatar():
|
||||
server = make_server("127.0.0.1", 0, _fake_gravatar, threaded=True)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{server.server_port}/avatar/"
|
||||
server.shutdown()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gravatar(app, storage, fake_gravatar):
|
||||
keys = ("AVATAR_GRAVATAR_ENABLED", "GRAVATAR_URL")
|
||||
saved = {k: app.config[k] for k in keys}
|
||||
app.config.update(AVATAR_GRAVATAR_ENABLED=True, GRAVATAR_URL=fake_gravatar)
|
||||
SEEN.clear()
|
||||
yield
|
||||
app.config.update(saved)
|
||||
|
||||
|
||||
def use_gravatar(client, auth):
|
||||
return client.post(f"{URL}/gravatar", headers=auth)
|
||||
|
||||
|
||||
def set_email(user, email):
|
||||
user.email = email
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_gravatar_requires_auth(client):
|
||||
assert client.post(f"{URL}/gravatar").status_code == 401
|
||||
|
||||
|
||||
def test_gravatar_is_off_by_default(client, auth, user, storage, metric_delta):
|
||||
me = client.get("/api/v1/auth/me", headers=auth).get_json()
|
||||
assert me["gravatar_enabled"] is False
|
||||
response = use_gravatar(client, auth)
|
||||
assert (response.status_code, response.get_json()["error"]["code"]) == (
|
||||
404,
|
||||
"gravatar_disabled",
|
||||
)
|
||||
|
||||
|
||||
def test_gravatar_is_cached_and_served_like_an_upload(client, auth, user, gravatar, metric_delta):
|
||||
ok = metric_delta("scrobbler_avatar_gravatar_fetches_total", result="ok")
|
||||
action = metric_delta("scrobbler_avatar_actions_total", action="gravatar")
|
||||
assert client.get("/api/v1/auth/me", headers=auth).get_json()["gravatar_enabled"] is True
|
||||
response = use_gravatar(client, auth)
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["avatar_source"] == "gravatar"
|
||||
image = client.get(URL, headers=auth)
|
||||
assert (image.data, image.mimetype) == (GRAVATAR_JPEG, "image/jpeg")
|
||||
# Asked for the SHA-256 of the email at a fixed size, with a 404 rather than a stock picture.
|
||||
assert [(f"/avatar/{_digest('alice@example.com')}", "s=256&d=404")] == SEEN
|
||||
assert (ok.delta, action.delta) == (1, 1)
|
||||
|
||||
|
||||
def test_gravatar_email_is_trimmed_and_lowercased(client, auth, user, gravatar):
|
||||
set_email(user, " Alice@Example.COM ")
|
||||
assert use_gravatar(client, auth).status_code == 200
|
||||
|
||||
|
||||
def test_gravatar_replaces_an_upload_and_back(client, auth, user, gravatar):
|
||||
put(client, auth, data=PNG, name="me.png")
|
||||
use_gravatar(client, auth)
|
||||
assert client.get(URL, headers=auth).data == GRAVATAR_JPEG
|
||||
put(client, auth)
|
||||
assert client.get(URL, headers=auth).data == JPEG
|
||||
assert client.get("/api/v1/auth/me", headers=auth).get_json()["avatar_source"] == "upload"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("email", "status", "code", "result"),
|
||||
[
|
||||
("ghost@example.com", 404, "no_gravatar", "none"),
|
||||
("boom@example.com", 502, "gravatar_unavailable", "error"),
|
||||
("html@example.com", 502, "gravatar_unavailable", "bad_type"),
|
||||
("big@example.com", 502, "gravatar_unavailable", "too_large"),
|
||||
],
|
||||
)
|
||||
def test_gravatar_failures_keep_the_current_image(
|
||||
client, auth, user, gravatar, metric_delta, email, status, code, result
|
||||
):
|
||||
put(client, auth)
|
||||
set_email(user, email)
|
||||
counted = metric_delta("scrobbler_avatar_gravatar_fetches_total", result=result)
|
||||
response = use_gravatar(client, auth)
|
||||
assert (response.status_code, response.get_json()["error"]["code"]) == (status, code)
|
||||
assert counted.delta == 1
|
||||
assert client.get(URL, headers=auth).data == JPEG
|
||||
|
||||
|
||||
def test_gravatar_unreachable_is_a_502(client, auth, user, gravatar, app):
|
||||
app.config["GRAVATAR_URL"] = "http://127.0.0.1:1/avatar/"
|
||||
response = use_gravatar(client, auth)
|
||||
assert (response.status_code, response.get_json()["error"]["code"]) == (
|
||||
502,
|
||||
"gravatar_unavailable",
|
||||
)
|
||||
@@ -127,6 +127,7 @@ def test_public_profile(fed_client, sharing_user, make_user):
|
||||
"display_name": "Alice",
|
||||
"bio": "Listening.",
|
||||
"now_playing": None,
|
||||
"has_avatar": False,
|
||||
"handle": "@alice@scrobble.test",
|
||||
"actor_url": "https://scrobble.test/users/alice",
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import io
|
||||
|
||||
import pytest
|
||||
|
||||
from scrobbler.federation import sharing
|
||||
from scrobbler.services import avatars
|
||||
from scrobbler.services.accounts import issue_ui_token
|
||||
|
||||
AP = {"Accept": "application/activity+json"}
|
||||
JPEG = b"\xff\xd8\xff\xe0fake-jpeg"
|
||||
API = "/api/v1/federation/profiles/alice"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def storage(fed_app, tmp_path):
|
||||
saved = fed_app.config["ART_STORAGE_DIR"]
|
||||
fed_app.config["ART_STORAGE_DIR"] = str(tmp_path)
|
||||
yield tmp_path
|
||||
fed_app.config["ART_STORAGE_DIR"] = saved
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def avatar_user(sharing_user, storage):
|
||||
"""The sharing user, with a profile image that they haven't chosen to share yet."""
|
||||
avatars.save(sharing_user, JPEG, "image/jpeg", "upload")
|
||||
return sharing_user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def shared(avatar_user):
|
||||
sharing.update(avatar_user.id, {"share_avatar": True})
|
||||
return avatar_user
|
||||
|
||||
|
||||
def actor(fed_client):
|
||||
return fed_client.get("/users/alice", headers=AP).get_json()
|
||||
|
||||
|
||||
def test_sharing_the_avatar_is_off_by_default(fed_client, fed_ctx, user):
|
||||
auth = {"Authorization": f"Bearer {issue_ui_token(user)}"}
|
||||
settings = fed_client.get("/api/v1/federation/settings", headers=auth).get_json()
|
||||
assert settings["share_avatar"] is False
|
||||
changed = fed_client.patch(
|
||||
"/api/v1/federation/settings", json={"share_avatar": True}, headers=auth
|
||||
)
|
||||
assert changed.get_json()["share_avatar"] is True
|
||||
|
||||
|
||||
def test_nothing_is_public_until_the_user_opts_in(fed_client, avatar_user):
|
||||
assert fed_client.get(API).get_json()["has_avatar"] is False
|
||||
assert fed_client.get(f"{API}/avatar").status_code == 404
|
||||
assert fed_client.get("/users/alice/avatar").status_code == 404
|
||||
assert "icon" not in actor(fed_client)
|
||||
|
||||
|
||||
def test_opted_in_avatar_is_served_publicly(fed_client, shared, metric_delta):
|
||||
found = metric_delta("scrobbler_federation_lookups_total", kind="avatar", result="found")
|
||||
assert fed_client.get(API).get_json()["has_avatar"] is True
|
||||
for path in (f"{API}/avatar", "/users/alice/avatar"):
|
||||
response = fed_client.get(path) # no credentials
|
||||
assert (response.status_code, response.data, response.mimetype) == (
|
||||
200,
|
||||
JPEG,
|
||||
"image/jpeg",
|
||||
)
|
||||
assert response.headers["Cache-Control"] == "public, max-age=300"
|
||||
assert found.delta == 2
|
||||
tag = fed_client.get("/users/alice/avatar").headers["ETag"]
|
||||
assert fed_client.get("/users/alice/avatar", headers={"If-None-Match": tag}).status_code == 304
|
||||
|
||||
|
||||
def test_actor_gets_an_icon_that_changes_with_the_image(fed_client, shared):
|
||||
icon = actor(fed_client)["icon"]
|
||||
assert icon["type"] == "Image"
|
||||
assert icon["mediaType"] == "image/jpeg"
|
||||
version = int(shared.avatar_updated_at.timestamp())
|
||||
assert icon["url"] == f"https://scrobble.test/users/alice/avatar?v={version}"
|
||||
|
||||
|
||||
def test_no_icon_without_an_image(fed_client, sharing_user, storage):
|
||||
sharing.update(sharing_user.id, {"share_avatar": True})
|
||||
assert "icon" not in actor(fed_client)
|
||||
assert fed_client.get(API).get_json()["has_avatar"] is False
|
||||
assert fed_client.get("/users/alice/avatar").status_code == 404
|
||||
|
||||
|
||||
def test_removing_the_image_withdraws_it(fed_client, shared):
|
||||
avatars.remove(shared)
|
||||
assert fed_client.get("/users/alice/avatar").status_code == 404
|
||||
assert "icon" not in actor(fed_client)
|
||||
|
||||
|
||||
def test_not_sharing_at_all_hides_the_avatar_too(fed_client, shared, make_user):
|
||||
sharing.update(shared.id, {"enabled": False})
|
||||
assert fed_client.get(f"{API}/avatar").status_code == 404
|
||||
assert fed_client.get("/users/alice/avatar").status_code == 404
|
||||
# ...and looks the same as someone who doesn't exist.
|
||||
assert fed_client.get("/users/nobody/avatar").data == fed_client.get("/users/alice/avatar").data
|
||||
|
||||
|
||||
def test_unknown_users_have_no_avatar(fed_client, fed_ctx):
|
||||
assert fed_client.get("/api/v1/federation/profiles/nobody/avatar").status_code == 404
|
||||
|
||||
|
||||
def test_the_file_going_missing_is_a_404_not_an_error(fed_client, shared, storage):
|
||||
(storage / "avatars" / str(shared.id)).unlink()
|
||||
assert fed_client.get("/users/alice/avatar").status_code == 404
|
||||
assert "icon" in actor(fed_client) # the row still says there is one; only the fetch fails
|
||||
|
||||
|
||||
def test_upload_through_the_api_is_what_gets_shared(fed_client, fed_ctx, sharing_user, storage):
|
||||
auth = {"Authorization": f"Bearer {issue_ui_token(sharing_user)}"}
|
||||
sharing.update(sharing_user.id, {"share_avatar": True})
|
||||
uploaded = fed_client.put(
|
||||
"/api/v1/me/avatar",
|
||||
headers=auth,
|
||||
data={"file": (io.BytesIO(JPEG), "me.jpg")},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert uploaded.status_code == 200
|
||||
assert fed_client.get("/users/alice/avatar").data == JPEG
|
||||
@@ -77,6 +77,7 @@ def test_ui_routes_declare_bearer_auth(fed_spec):
|
||||
("/api/v1/auth/login", "post"),
|
||||
("/api/v1/auth/register", "post"),
|
||||
("/api/v1/federation/profiles/{username}", "get"),
|
||||
("/api/v1/federation/profiles/{username}/avatar", "get"),
|
||||
("/api/v1/federation/profiles/{username}/posts/{post_uuid}", "get"),
|
||||
}
|
||||
for path, operations in spec["paths"].items():
|
||||
|
||||
Reference in new issue
Block a user