Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7ba6360e5 | ||
|
|
8a4880d5ec | ||
|
|
b388e7112d | ||
|
|
b878523d51 | ||
|
|
016fc707d1 | ||
|
|
9243fe4d3f | ||
|
|
c55a6596d0 | ||
|
|
81e0b0cf42 | ||
|
|
6649cbbcae | ||
|
|
65ee13fa65 | ||
|
|
9e4218f11b | ||
|
|
aadb1c6def | ||
|
|
2c4c42a42b | ||
|
|
ad383b602e | ||
|
|
65cd610468 | ||
|
|
735556bf21 | ||
|
|
524b78a075 | ||
|
|
9c84a64d4e | ||
|
|
bee83cb9f3 | ||
|
|
87edaafe19 | ||
|
|
a887865f05 | ||
|
|
d0b8e1ed22 | ||
|
|
48fba1e0e2 | ||
|
|
6cd17d7586 | ||
|
|
83b27d7ba1 | ||
|
|
79193fbc8e | ||
|
|
2b984cca6e | ||
|
|
44abd70caa | ||
|
|
f106d68921 | ||
|
|
dfd2ef868b | ||
|
|
5bdeeddb0b | ||
|
|
7b169ea807 | ||
|
|
457e051828 | ||
|
|
25a7ac7a20 | ||
|
|
ae24c4a00e | ||
|
|
86bf9fd302 | ||
|
|
bef41fc2cc | ||
|
|
e1704b0b54 | ||
|
|
88b53df909 | ||
|
|
d2f457a84d | ||
|
|
50e2360d14 | ||
|
|
b307b11440 | ||
|
|
dfdb5285da | ||
|
|
df8a114a0c | ||
|
|
d90a42046e | ||
|
|
b941a17e07 | ||
|
|
9ca2ace854 | ||
|
|
9f7ada682c | ||
|
|
9883111fa1 | ||
|
|
f3d2b5d578 | ||
|
|
f04e53a972 | ||
|
|
515acae233 | ||
|
|
ba30d5cb15 | ||
|
|
9ab8bd8e03 | ||
|
|
c38e2e392a | ||
|
|
cb8f9c997e | ||
|
|
7d86bad929 | ||
|
|
e0423d04bc | ||
|
|
860d4d0f93 | ||
|
|
de1519a066 | ||
|
|
0acce9b948 | ||
|
|
d4f3607eef | ||
|
|
6fd028d108 | ||
|
|
c3a8233e73 | ||
|
|
0766c09fb3 | ||
|
|
b16ba116c4 | ||
|
|
dce90400e6 | ||
|
|
ed74a78625 | ||
|
|
ea6b10637e | ||
|
|
bc717c2a06 | ||
|
|
fefdeb90ec | ||
|
|
fe95f59fc8 | ||
|
|
b93cfea5b3 | ||
|
|
ec658a7751 | ||
|
|
a90cd14f59 | ||
|
|
142dc13fea | ||
|
|
5897e8217f | ||
|
|
f312c4b577 | ||
|
|
c1a7dd0877 | ||
|
|
d49aa72be1 | ||
|
|
52b9f0b27b | ||
|
|
a6d3fb6c93 | ||
|
|
044f25e2fd | ||
|
|
6b09e041b8 | ||
|
|
913ef67aca | ||
|
|
f21ce173b8 | ||
|
|
8d12922f6a | ||
|
|
c0b9e85519 | ||
|
|
0b10469514 | ||
|
|
ce39e8f865 | ||
|
|
e890568c54 | ||
|
|
98c65547f3 | ||
|
|
00ad8e9e6d | ||
|
|
cae97380fc | ||
|
|
eb5802f420 | ||
|
|
c79c42ee00 | ||
|
|
098eab025f | ||
|
|
59ff1bdfa0 | ||
|
|
247c94a79c | ||
|
|
5d71116613 | ||
|
|
caf1d3c2f8 | ||
|
|
373efbcb2d | ||
|
|
d2c71d50f1 |
No files matched your search
@@ -11,3 +11,4 @@ tests
|
|||||||
docs
|
docs
|
||||||
deploy/grafana
|
deploy/grafana
|
||||||
deploy/prometheus
|
deploy/prometheus
|
||||||
|
# (scripts/interop is used by the interop driver image)
|
||||||
@@ -10,15 +10,43 @@ CORS_ORIGINS=http://localhost:8080
|
|||||||
# Where Last.fm clients are redirected to approve desktop auth tokens.
|
# Where Last.fm clients are redirected to approve desktop auth tokens.
|
||||||
UI_BASE_URL=http://localhost:8080
|
UI_BASE_URL=http://localhost:8080
|
||||||
|
|
||||||
|
# Logging: level (DEBUG, INFO, WARNING, ERROR) and format ("text", or "json" for log aggregators).
|
||||||
|
LOG_LEVEL=INFO
|
||||||
|
LOG_FORMAT=text
|
||||||
|
|
||||||
# Prometheus metrics are served on a separate port.
|
# Prometheus metrics are served on a separate port.
|
||||||
METRICS_PORT=9100
|
METRICS_PORT=9100
|
||||||
|
|
||||||
# Set to allow importing history straight from Last.fm (https://www.last.fm/api/account/create).
|
# Set to allow importing history straight from Last.fm (https://www.last.fm/api/account/create).
|
||||||
LASTFM_API_KEY=
|
LASTFM_API_KEY=
|
||||||
|
|
||||||
|
# Album art (MusicBrainz + Cover Art Archive, both free and keyless — no setup required).
|
||||||
|
# MusicBrainz asks for a contact URL/email in requests; falls back to UI_BASE_URL if unset.
|
||||||
|
MUSICBRAINZ_CONTACT=
|
||||||
|
# Where downloaded art is stored. docker compose points this at a shared volume; the
|
||||||
|
# default below is for running the api/worker directly (not in Docker).
|
||||||
|
ART_STORAGE_DIR=var/album-art
|
||||||
|
# Largest image a user may upload as their own album art (bytes). Uploaded art is
|
||||||
|
# stored in ART_STORAGE_DIR too, so back that directory up.
|
||||||
|
ART_UPLOAD_MAX_BYTES=5242880
|
||||||
|
# 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)
|
# docker compose host ports (defaults shown)
|
||||||
API_PORT=5050
|
API_PORT=5050
|
||||||
UI_PORT=8080
|
UI_PORT=8080
|
||||||
PROMETHEUS_PORT=9090
|
PROMETHEUS_PORT=9090
|
||||||
GRAFANA_PORT=3000
|
GRAFANA_PORT=3000
|
||||||
GRAFANA_ADMIN_PASSWORD=admin
|
GRAFANA_ADMIN_PASSWORD=admin
|
||||||
|
|
||||||
|
# ActivityPub federation (in development; off by default). See src/scrobbler/federation/README.md.
|
||||||
|
# Use the web UI's host and origin: handles become @user@<FEDERATION_DOMAIN>.
|
||||||
|
FEDERATION_ENABLED=0
|
||||||
|
FEDERATION_DOMAIN=
|
||||||
|
FEDERATION_BASE_URL=
|
||||||
|
# 32+ characters; encrypts actors' private keys. Keep it safe and never change it.
|
||||||
|
FEDERATION_KEY_SECRET=
|
||||||
@@ -52,7 +52,7 @@ jobs:
|
|||||||
- run: uv sync --locked
|
- run: uv sync --locked
|
||||||
- name: Migrations are in sync with the models
|
- name: Migrations are in sync with the models
|
||||||
run: |
|
run: |
|
||||||
uv run flask --app scrobbler db upgrade
|
uv run flask --app scrobbler db upgrade heads
|
||||||
uv run flask --app scrobbler db check
|
uv run flask --app scrobbler db check
|
||||||
- run: uv run pytest
|
- run: uv run pytest
|
||||||
|
|
||||||
@@ -77,14 +77,30 @@ jobs:
|
|||||||
- name: Dashboards are valid JSON
|
- name: Dashboards are valid JSON
|
||||||
run: for f in deploy/grafana/dashboards/*.json; do python3 -m json.tool "$f" > /dev/null; done
|
run: for f in deploy/grafana/dashboards/*.json; do python3 -m json.tool "$f" > /dev/null; done
|
||||||
|
|
||||||
|
federation-interop:
|
||||||
|
# A real GoToSocial server follows a Scrobbled user (see scripts/interop/run.sh).
|
||||||
|
# Not for pull requests from forks: it runs containers on the runner's Docker.
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 20
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Scrobbled <-> GoToSocial
|
||||||
|
env:
|
||||||
|
# Own compose project, network and image tags, so concurrent runs can't collide
|
||||||
|
INTEROP_PROJECT: interop-${{ github.run_id }}
|
||||||
|
SCROBBLER_IMAGE_TAG: interop-${{ github.run_id }}
|
||||||
|
run: scripts/interop/run.sh
|
||||||
|
|
||||||
# ---- Publishing (main and v* tags only) -------------------------------------
|
# ---- Publishing (main and v* tags only) -------------------------------------
|
||||||
|
|
||||||
images:
|
images:
|
||||||
needs: [lint, test, validate-monitoring]
|
needs: [lint, test, validate-monitoring, federation-interop]
|
||||||
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v'))
|
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v'))
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
outputs:
|
outputs:
|
||||||
tags: ${{ steps.version.outputs.image_tags }}
|
tags: ${{ steps.version.outputs.image_tags }}
|
||||||
|
version: ${{ steps.version.outputs.version }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: https://github.com/astral-sh/setup-uv@v6
|
- uses: https://github.com/astral-sh/setup-uv@v6
|
||||||
@@ -123,7 +139,7 @@ jobs:
|
|||||||
run: docker logout "${{ vars.PKGS_HOST }}" || true
|
run: docker logout "${{ vars.PKGS_HOST }}" || true
|
||||||
|
|
||||||
assets:
|
assets:
|
||||||
needs: [lint, test, validate-monitoring]
|
needs: [lint, test, validate-monitoring, federation-interop]
|
||||||
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v'))
|
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v'))
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -147,7 +163,7 @@ jobs:
|
|||||||
done
|
done
|
||||||
|
|
||||||
python-package:
|
python-package:
|
||||||
needs: [lint, test, validate-monitoring]
|
needs: [lint, test, validate-monitoring, federation-interop]
|
||||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
|
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -163,8 +179,24 @@ jobs:
|
|||||||
--publish-url "https://${{ vars.PKGS_HOST }}/pypi/${{ vars.PKGS_PYPI_FEED }}/legacy"
|
--publish-url "https://${{ vars.PKGS_HOST }}/pypi/${{ vars.PKGS_PYPI_FEED }}/legacy"
|
||||||
--username api --password "${{ secrets.PKGS_API_KEY }}"
|
--username api --password "${{ secrets.PKGS_API_KEY }}"
|
||||||
|
|
||||||
|
trigger-deploy:
|
||||||
|
needs: [images]
|
||||||
|
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Trigger ScrobbledDeploy
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.images.outputs.version }}
|
||||||
|
TOKEN: ${{ secrets.SCROBBLEDDEPLOY_DISPATCH_TOKEN }}
|
||||||
|
run: |
|
||||||
|
curl -fsS -X POST \
|
||||||
|
-H "Authorization: token ${TOKEN}" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d "{\"ref\":\"main\",\"inputs\":{\"image_tag\":\"${VERSION}\"}}" \
|
||||||
|
"https://git.daubney.dev/api/v1/repos/matt/ScrobbledDeploy/actions/workflows/deploy.yml/dispatches"
|
||||||
|
|
||||||
notify:
|
notify:
|
||||||
needs: [lint, test, validate-monitoring, images, assets, python-package]
|
needs: [lint, test, validate-monitoring, federation-interop, images, assets, python-package, trigger-deploy]
|
||||||
if: always()
|
if: always()
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ htmlcov/
|
|||||||
|
|
||||||
# Runtime
|
# Runtime
|
||||||
prometheus_multiproc/
|
prometheus_multiproc/
|
||||||
|
var/album-art/
|
||||||
|
|
||||||
# IDEs
|
# IDEs
|
||||||
.idea/
|
.idea/
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
BSD 3-Clause License
|
||||||
|
|
||||||
|
Copyright (c) 2026, Matthew Daubney
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
1. Redistributions of source code must retain the above copyright notice, this
|
||||||
|
list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer in the documentation
|
||||||
|
and/or other materials provided with the distribution.
|
||||||
|
|
||||||
|
3. Neither the name of the copyright holder nor the names of its
|
||||||
|
contributors may be used to endorse or promote products derived from
|
||||||
|
this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||||
|
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Artwork licence
|
||||||
|
|
||||||
|
Copyright (c) 2026 Matthew Daubney. All rights reserved.
|
||||||
|
|
||||||
|
This applies to the Scrobbled logo and everything derived from it: the record and
|
||||||
|
tonearm mark, the wordmark and the icon files. In this repository that is
|
||||||
|
`frontend/img/`, `frontend/favicon.*`, `frontend/apple-touch-icon.png`,
|
||||||
|
`frontend/icon-*.png` and the mark drawn by `.brand-mark` in the web UI. The rest
|
||||||
|
of the repository is under [LICENSE](LICENSE).
|
||||||
|
|
||||||
|
## Permitted use
|
||||||
|
|
||||||
|
You may use the Scrobbled name and logo, unmodified, to refer to the Scrobbled
|
||||||
|
product. For example, in an article, review, tutorial, integration listing or
|
||||||
|
"works with Scrobbled" mention.
|
||||||
|
|
||||||
|
When you do:
|
||||||
|
|
||||||
|
- Use the files as supplied. Scaling is fine. Don't recolour, redraw, crop,
|
||||||
|
distort, animate or combine them with other marks.
|
||||||
|
- Don't use the logo in a way that suggests Scrobbled made, endorsed or
|
||||||
|
sponsors your product, service or organisation.
|
||||||
|
- Don't use the logo, or anything confusingly similar, as the name or logo of
|
||||||
|
your own product, app or business.
|
||||||
|
|
||||||
|
## Everything else
|
||||||
|
|
||||||
|
Any other use needs written permission first. That includes modifying the
|
||||||
|
artwork, selling it or merchandise bearing it, and using it as part of another
|
||||||
|
brand. To ask, contact Matthew Daubney.
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
# Scrobbler
|
# Scrobbled
|
||||||
|
|
||||||
A self-hosted music scrobbling service. It speaks the **Last.fm (Audioscrobbler 2.0) API**, so players and scrobblers that let you set a custom Last.fm server can use it unchanged. It also has a web UI for your listening history.
|
A self-hosted music scrobbling service. It speaks the **Last.fm (Audioscrobbler 2.0) API**,
|
||||||
|
so players and scrobblers that let you set a custom Last.fm server can use it unchanged.
|
||||||
|
It also has a web UI for your listening history, and optional sharing on the fediverse
|
||||||
|
(ActivityPub) — followable from Mastodon, with weekly summaries, milestones and now
|
||||||
|
playing.
|
||||||
|
|
||||||
```
|
```
|
||||||
players / scrobblers ──► API /2.0/ Last.fm-compatible
|
players / scrobblers ──► API /2.0/ Last.fm-compatible
|
||||||
@@ -9,160 +13,32 @@ web UI (static files) ──► API /api/v1/ JSON API for the UI
|
|||||||
Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
|
Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
|
||||||
```
|
```
|
||||||
|
|
||||||
- **API** (`src/scrobbler/`): Flask under gunicorn. It is API-only and serves no pages.
|
## Docs
|
||||||
- **Web UI** (`frontend/`): plain HTML, CSS and JavaScript with no build step. Host it anywhere static files can be served.
|
|
||||||
- **Docs**: OpenAPI at `/api/openapi.json`, Swagger UI at `/api/docs` and ReDoc at `/api/redoc`. A copy of the spec is committed at `docs/openapi.json`.
|
|
||||||
- **Import worker**: `flask imports worker` imports Last.fm history in the background, from export files or straight from Last.fm.
|
|
||||||
- **Monitoring**: Prometheus metrics, four provisioned Grafana dashboards, and alert rules.
|
|
||||||
|
|
||||||
## Run it
|
- **[Admin guide](docs/admin-guide.md)** — running a real instance: images,
|
||||||
|
configuration, TLS, monitoring, backups, upgrades, troubleshooting.
|
||||||
|
- **[User guide](docs/user-guide.md)** — accounts and apps, connecting a player,
|
||||||
|
importing history, sharing on the fediverse.
|
||||||
|
- **[Set up](docs/setup.md)** — working on the code: local dev environment, migrations,
|
||||||
|
tests, CI/CD.
|
||||||
|
- **API reference**: `/api/openapi.json`, Swagger UI at `/api/docs`, ReDoc at
|
||||||
|
`/api/redoc` (a copy is committed at `docs/openapi.json`).
|
||||||
|
- **Federation internals**: `src/scrobbler/federation/README.md`. Design docs for how it
|
||||||
|
was built: `docs/design/`.
|
||||||
|
|
||||||
|
## Try it
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD
|
cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD
|
||||||
docker compose up -d # db, api (:5050), worker, ui (:8080)
|
docker compose up -d # db, api (:5050), worker, ui (:8080)
|
||||||
docker compose --profile monitoring up -d # + Prometheus (:9090), Grafana (:3000)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Open http://localhost:8080, create an account, then go to **Apps** and create an app for each player.
|
Open http://localhost:8080, create an account, then go to **Apps** 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.
|
||||||
|
|
||||||
To run the published images instead of building them locally:
|
## Licence
|
||||||
|
|
||||||
```sh
|
BSD 3-Clause; see [LICENSE](LICENSE). The fonts vendored in `frontend/fonts/` are under
|
||||||
SCROBBLER_IMAGE_TAG=main docker compose up -d --no-build
|
the SIL Open Font License 1.1. The Scrobbled logo, wordmark and icons are not BSD-licensed:
|
||||||
```
|
they are all rights reserved, see [LICENSE-ARTWORK.md](LICENSE-ARTWORK.md).
|
||||||
|
|
||||||
The images are `pkgs.daubney.dev/scrobbler/scrobbler-api` and `pkgs.daubney.dev/scrobbler/scrobbler-ui`.
|
|
||||||
|
|
||||||
### Configuration
|
|
||||||
|
|
||||||
| Variable | Used by | Default | Purpose |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `DATABASE_URL` | api | local Postgres | SQLAlchemy URL (`postgresql+psycopg://…`) |
|
|
||||||
| `SECRET_KEY` | api | `dev-insecure-secret` | Flask secret |
|
|
||||||
| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated UI origins allowed to call `/api/v1` |
|
|
||||||
| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins |
|
|
||||||
| `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` |
|
|
||||||
| `METRICS_PORT` | api | `9100` | Prometheus metrics port (keep it off the public network) |
|
|
||||||
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
|
|
||||||
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
|
|
||||||
| `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) |
|
|
||||||
| `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted |
|
|
||||||
| `IMPORT_WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port |
|
|
||||||
| `API_BASE_URL` | ui image | `http://localhost:5050` | API location, written into `config.js` and the CSP |
|
|
||||||
|
|
||||||
In `docker compose` the host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`, `PROMETHEUS_PORT` and `GRAFANA_PORT`.
|
|
||||||
|
|
||||||
## Connecting a player
|
|
||||||
|
|
||||||
In the player's scrobbling settings, choose a custom or self-hosted Last.fm server and enter:
|
|
||||||
|
|
||||||
- **API URL**: `https://your-host/2.0/`
|
|
||||||
- **API key and shared secret**: from an app on the **Apps** page
|
|
||||||
- **Username and password**: your Scrobbler account
|
|
||||||
|
|
||||||
Two ways of signing in are supported:
|
|
||||||
|
|
||||||
- **Mobile**: `auth.getMobileSession` with a username and password, sent as a POST body over HTTPS.
|
|
||||||
- **Desktop**: `auth.getToken`, then the user approves at `/api/auth/` (which redirects to the web UI), then `auth.getSession`.
|
|
||||||
|
|
||||||
The legacy `authToken = md5(username + md5(password))` form is **not supported**, because checking it would mean storing unsalted password hashes. pylast's `password_hash` option uses that form. With pylast, use `SessionKeyGenerator` (the desktop flow) instead.
|
|
||||||
|
|
||||||
Supported methods:
|
|
||||||
|
|
||||||
- `auth.getMobileSession`, `auth.getToken`, `auth.getSession`
|
|
||||||
- `track.scrobble` (up to 50 per request), `track.updateNowPlaying`
|
|
||||||
- `user.getInfo`, `user.getRecentTracks`, `user.getTopArtists`, `user.getTopAlbums`, `user.getTopTracks`
|
|
||||||
|
|
||||||
`/api/docs` lists the parameters, rules and example responses for each method.
|
|
||||||
|
|
||||||
Scrobbles are ignored (not rejected) if the artist or track is empty, or if the timestamp is more than 14 days old or more than 5 minutes in the future. Sending the same scrobble again is accepted and stored once, so client retries are safe.
|
|
||||||
|
|
||||||
## Importing Last.fm history
|
|
||||||
|
|
||||||
Open **Import** in the web UI. You can import from:
|
|
||||||
|
|
||||||
- **An export file**:
|
|
||||||
- CSV from [lastfm-to-csv](https://benjaminbenben.com/lastfm-to-csv/), with no header row and artist, album, track and date columns.
|
|
||||||
- Any CSV or TSV with a header row naming artist, track and a date or Unix-time column. Comma, semicolon and tab delimiters all work.
|
|
||||||
- A JSON export of `user.getRecentTracks` pages (such as lastfm.ghan.nl's), a single `recenttracks` response, or a flat list of tracks.
|
|
||||||
- Files can be gzipped.
|
|
||||||
- **Last.fm directly**: enter a Last.fm username and the worker pages through that account's public history. This option only appears when the server has `LASTFM_API_KEY` set.
|
|
||||||
|
|
||||||
Imports run in the background in the `worker` service. The page shows progress, and an import can be cancelled.
|
|
||||||
|
|
||||||
Unlike live scrobbles, imports keep plays of any age. They still skip rows with no artist or track, and plays dated in the future. Plays already in your history are skipped, so importing again is safe.
|
|
||||||
|
|
||||||
## Develop
|
|
||||||
|
|
||||||
```sh
|
|
||||||
docker compose up -d db # Postgres with a scrobbler_test database
|
|
||||||
uv sync
|
|
||||||
uv run flask --app scrobbler db upgrade
|
|
||||||
uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS)
|
|
||||||
python -m http.server 8080 -d frontend # UI
|
|
||||||
uv run flask --app scrobbler imports worker # process imports
|
|
||||||
uv run pytest # needs TEST_DATABASE_URL (see .env.example)
|
|
||||||
uv run ruff check && uv run ruff format --check
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Migrations**: after changing `models.py`, run `uv run flask --app scrobbler db migrate -m "…"`. CI fails if the models and migrations disagree.
|
|
||||||
- **API docs**: after changing an endpoint, run `uv run flask --app scrobbler openapi write --format=json docs/openapi.json`. A test fails if the committed spec is stale. Every route has to appear in the spec, and every UI route has to declare bearer auth.
|
|
||||||
- **Demo traffic**: `uv run python scripts/generate_traffic.py --minutes 5` sends a realistic mix of scrobbles and errors, so the dashboards have something to show.
|
|
||||||
|
|
||||||
The test suite includes an end-to-end run with [pylast](https://github.com/pylast/pylast) over HTTPS and a real two-worker gunicorn run, which checks that metrics aggregate across workers.
|
|
||||||
|
|
||||||
## Monitoring
|
|
||||||
|
|
||||||
The API serves Prometheus metrics on `METRICS_PORT`, summed across gunicorn workers. All series are prefixed `scrobbler_`:
|
|
||||||
|
|
||||||
- **HTTP**: request rate, errors and latency per endpoint
|
|
||||||
- **Last.fm**: calls, errors by Last.fm error code, and authentication failures by reason
|
|
||||||
- **Scrobbles**: accepted, duplicate and ignored (with the reason), batch size, and how late scrobbles arrive
|
|
||||||
- **Database**: query latency and connection-pool use
|
|
||||||
- **Users**: registered, active, and listening now (computed from the database and cached for 60s)
|
|
||||||
|
|
||||||
Labels never contain users, keys or track names.
|
|
||||||
|
|
||||||
With the `monitoring` profile, Grafana (admin password `GRAFANA_ADMIN_PASSWORD`) has a **Scrobbler** folder with four dashboards:
|
|
||||||
|
|
||||||
- API overview
|
|
||||||
- Last.fm API
|
|
||||||
- Usage
|
|
||||||
- Database
|
|
||||||
|
|
||||||
Alert rules live in `deploy/prometheus/alerts.yml`:
|
|
||||||
|
|
||||||
- API down
|
|
||||||
- import worker down, or imports left waiting
|
|
||||||
- 5xx ratio
|
|
||||||
- p95 latency
|
|
||||||
- authentication-failure spike
|
|
||||||
- ignored-scrobble ratio
|
|
||||||
- database pool saturated
|
|
||||||
- Postgres down
|
|
||||||
|
|
||||||
They're evaluated by Prometheus and appear in Grafana. Nothing routes them anywhere yet; that needs Alertmanager.
|
|
||||||
|
|
||||||
Tests check that every metric a dashboard or alert uses actually exists.
|
|
||||||
|
|
||||||
## CI/CD (Gitea Actions)
|
|
||||||
|
|
||||||
Everything runs from `.gitea/workflows/ci.yml`:
|
|
||||||
|
|
||||||
- **Every push and PR**:
|
|
||||||
- lint
|
|
||||||
- the migrations check
|
|
||||||
- tests against Postgres
|
|
||||||
- `promtool` checks of the Prometheus config and alert rules
|
|
||||||
- **Pushes to `main` and `v*` tags**, once every check has passed:
|
|
||||||
- both images are pushed to the ProGet `scrobbler` Docker feed. `main` builds are tagged `main` and `sha-<commit>`; tags are tagged `<version>`, `latest` and `sha-<commit>`.
|
|
||||||
- the OpenAPI spec, dashboards and Prometheus config are uploaded to the `scrobbler-assets` feed under `scrobbler/<version>/` or `scrobbler/main/`.
|
|
||||||
- **`v*` tags** also publish the wheel and sdist to the `scrobbler-python` PyPI feed, as the `scrobby` distribution. The import name is `scrobbler`. (`scrobbler` on public PyPI is an unrelated project.)
|
|
||||||
- **Every run** is posted to the `ScrobblingService` topic on notify.daubney.dev.
|
|
||||||
|
|
||||||
The workflow needs these repository secrets and variables:
|
|
||||||
|
|
||||||
- **Secrets**: `PKGS_USER`, `PKGS_PASSWORD`, `PKGS_API_KEY`, `NTFY_USER`, `NTFY_PASSWORD`
|
|
||||||
- **Variables**: `PKGS_HOST`, `PKGS_DOCKER_FEED`, `PKGS_PYPI_FEED`, `PKGS_ASSET_FEED`, `NTFY_URL`, `NTFY_TOPIC`
|
|
||||||
|
|
||||||
To release, tag `vX.Y.Z` on `main` and push the tag. The tag sets the package and image version.
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"uid": "scrobbler-api-overview",
|
"uid": "scrobbler-api-overview",
|
||||||
"title": "Scrobbler: API overview",
|
"title": "Scrobbled: API overview",
|
||||||
"description": "Rate, errors and duration for every endpoint of the Scrobbler API.",
|
"description": "Rate, errors and duration for every endpoint of the Scrobbled API.",
|
||||||
"tags": [
|
"tags": [
|
||||||
"scrobbler"
|
"scrobbler"
|
||||||
],
|
],
|
||||||
@@ -57,7 +57,7 @@
|
|||||||
"scrobbler"
|
"scrobbler"
|
||||||
],
|
],
|
||||||
"asDropdown": true,
|
"asDropdown": true,
|
||||||
"title": "Scrobbler",
|
"title": "Scrobbled",
|
||||||
"includeVars": false
|
"includeVars": false
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"uid": "scrobbler-database",
|
"uid": "scrobbler-database",
|
||||||
"title": "Scrobbler: Database",
|
"title": "Scrobbled: Database",
|
||||||
"description": "Query latency and pool use from the app's side; Postgres health from postgres-exporter.",
|
"description": "Query latency and pool use from the app's side; Postgres health from postgres-exporter.",
|
||||||
"tags": [
|
"tags": [
|
||||||
"scrobbler"
|
"scrobbler"
|
||||||
@@ -28,7 +28,7 @@
|
|||||||
"scrobbler"
|
"scrobbler"
|
||||||
],
|
],
|
||||||
"asDropdown": true,
|
"asDropdown": true,
|
||||||
"title": "Scrobbler",
|
"title": "Scrobbled",
|
||||||
"includeVars": false
|
"includeVars": false
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"uid": "scrobbler-lastfm",
|
"uid": "scrobbler-lastfm",
|
||||||
"title": "Scrobbler: Last.fm API",
|
"title": "Scrobbled: Last.fm API",
|
||||||
"description": "The Last.fm-compatible /2.0/ API: which methods clients call, what fails, and what happens to scrobbles.",
|
"description": "The Last.fm-compatible /2.0/ API: which methods clients call, what fails, and what happens to scrobbles.",
|
||||||
"tags": [
|
"tags": [
|
||||||
"scrobbler"
|
"scrobbler"
|
||||||
@@ -57,7 +57,7 @@
|
|||||||
"scrobbler"
|
"scrobbler"
|
||||||
],
|
],
|
||||||
"asDropdown": true,
|
"asDropdown": true,
|
||||||
"title": "Scrobbler",
|
"title": "Scrobbled",
|
||||||
"includeVars": false
|
"includeVars": false
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"uid": "scrobbler-usage",
|
"uid": "scrobbler-usage",
|
||||||
"title": "Scrobbler: Usage",
|
"title": "Scrobbled: Usage",
|
||||||
"description": "Who is using the service and how much they're listening.",
|
"description": "Who is using the service and how much they're listening.",
|
||||||
"tags": [
|
"tags": [
|
||||||
"scrobbler"
|
"scrobbler"
|
||||||
@@ -28,7 +28,7 @@
|
|||||||
"scrobbler"
|
"scrobbler"
|
||||||
],
|
],
|
||||||
"asDropdown": true,
|
"asDropdown": true,
|
||||||
"title": "Scrobbler",
|
"title": "Scrobbled",
|
||||||
"includeVars": false
|
"includeVars": false
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -572,7 +572,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": "row",
|
"type": "row",
|
||||||
"title": "Imports",
|
"title": "Background work",
|
||||||
"id": 13,
|
"id": 13,
|
||||||
"collapsed": false,
|
"collapsed": false,
|
||||||
"gridPos": {
|
"gridPos": {
|
||||||
@@ -878,6 +878,67 @@
|
|||||||
"h": 8
|
"h": 8
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Worker tasks",
|
||||||
|
"description": "Runs of each background task that did work, and failures. A task that keeps failing is logged by the worker.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum by (task) (increase(scrobbler_worker_tasks_total{outcome=\"worked\"}[$__rate_interval]))",
|
||||||
|
"legendFormat": "{{task}}",
|
||||||
|
"refId": "A"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum by (task) (increase(scrobbler_worker_tasks_total{outcome=\"error\"}[$__rate_interval]))",
|
||||||
|
"legendFormat": "{{task}} errors",
|
||||||
|
"refId": "B"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short",
|
||||||
|
"custom": {
|
||||||
|
"lineWidth": 1,
|
||||||
|
"fillOpacity": 70,
|
||||||
|
"showPoints": "never",
|
||||||
|
"spanNulls": true,
|
||||||
|
"drawStyle": "bars"
|
||||||
|
},
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom",
|
||||||
|
"showLegend": true
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": 19,
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 38,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"type": "timeseries",
|
"type": "timeseries",
|
||||||
"title": "Import duration (p95)",
|
"title": "Import duration (p95)",
|
||||||
@@ -921,13 +982,138 @@
|
|||||||
"sort": "desc"
|
"sort": "desc"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"id": 19,
|
"id": 20,
|
||||||
"gridPos": {
|
"gridPos": {
|
||||||
"x": 12,
|
"x": 0,
|
||||||
"y": 38,
|
"y": 46,
|
||||||
"w": 12,
|
"w": 12,
|
||||||
"h": 8
|
"h": 8
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "row",
|
||||||
|
"title": "Album art",
|
||||||
|
"id": 21,
|
||||||
|
"collapsed": false,
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 54,
|
||||||
|
"w": 24,
|
||||||
|
"h": 1
|
||||||
|
},
|
||||||
|
"panels": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "stat",
|
||||||
|
"title": "Albums needing manual art",
|
||||||
|
"description": "Not found or errored in the shared cache, and not fixed by any user. See the Album Art dashboard.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "max(scrobbler_art_unresolved_albums)",
|
||||||
|
"legendFormat": "__auto",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short",
|
||||||
|
"decimals": 0,
|
||||||
|
"thresholds": {
|
||||||
|
"mode": "absolute",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"color": "text",
|
||||||
|
"value": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"reduceOptions": {
|
||||||
|
"calcs": [
|
||||||
|
"lastNotNull"
|
||||||
|
],
|
||||||
|
"fields": "",
|
||||||
|
"values": false
|
||||||
|
},
|
||||||
|
"colorMode": "value",
|
||||||
|
"graphMode": "area",
|
||||||
|
"textMode": "auto",
|
||||||
|
"justifyMode": "auto"
|
||||||
|
},
|
||||||
|
"id": 22,
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 55,
|
||||||
|
"w": 6,
|
||||||
|
"h": 5
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "stat",
|
||||||
|
"title": "Pending art corrections",
|
||||||
|
"description": "",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "max(scrobbler_art_overrides{kind=\"correction\",status=\"pending\"})",
|
||||||
|
"legendFormat": "__auto",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short",
|
||||||
|
"decimals": 0,
|
||||||
|
"thresholds": {
|
||||||
|
"mode": "absolute",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"color": "text",
|
||||||
|
"value": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"reduceOptions": {
|
||||||
|
"calcs": [
|
||||||
|
"lastNotNull"
|
||||||
|
],
|
||||||
|
"fields": "",
|
||||||
|
"values": false
|
||||||
|
},
|
||||||
|
"colorMode": "value",
|
||||||
|
"graphMode": "area",
|
||||||
|
"textMode": "auto",
|
||||||
|
"justifyMode": "auto"
|
||||||
|
},
|
||||||
|
"id": 23,
|
||||||
|
"gridPos": {
|
||||||
|
"x": 6,
|
||||||
|
"y": 55,
|
||||||
|
"w": 6,
|
||||||
|
"h": 5
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
apiVersion: 1
|
apiVersion: 1
|
||||||
providers:
|
providers:
|
||||||
- name: scrobbler
|
- name: scrobbler
|
||||||
folder: Scrobbler
|
folder: Scrobbled
|
||||||
type: file
|
type: file
|
||||||
allowUiUpdates: true
|
allowUiUpdates: true
|
||||||
options:
|
options:
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# Federation interop test: Scrobbled and a real GoToSocial server on one private network.
|
||||||
|
#
|
||||||
|
# docker compose -f docker-compose.yml -f deploy/interop/docker-compose.interop.yml up -d --build
|
||||||
|
# ...create the GoToSocial user (see scripts/interop/run.sh), then run the driver.
|
||||||
|
#
|
||||||
|
# TEST ONLY: GoToSocial runs over plain HTTP and skips TLS verification; Scrobbled is
|
||||||
|
# served over HTTPS by a Caddy proxy with a throwaway certificate, and its "insecure
|
||||||
|
# testing" switch lets it reach GoToSocial over HTTP on this private network. All on the
|
||||||
|
# reserved .test domain. Never use these settings anywhere else.
|
||||||
|
name: scrobbler-interop
|
||||||
|
|
||||||
|
x-federation: &federation
|
||||||
|
DATABASE_URL: postgresql+psycopg://scrobbler:scrobbler@db:5432/scrobbler
|
||||||
|
FEDERATION_ENABLED: "1"
|
||||||
|
FEDERATION_DOMAIN: scrobble.test
|
||||||
|
FEDERATION_BASE_URL: https://scrobble.test
|
||||||
|
FEDERATION_KEY_SECRET: interop-test-only-secret-0123456789abcdef
|
||||||
|
FEDERATION_INSECURE_TESTING: "1"
|
||||||
|
UI_BASE_URL: https://scrobble.test
|
||||||
|
|
||||||
|
# Docker picks the network's subnet, so concurrent runs can't collide on one. GoToSocial
|
||||||
|
# is therefore told to trust any private range rather than one specific /24.
|
||||||
|
networks:
|
||||||
|
fedi:
|
||||||
|
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
ports: !reset []
|
||||||
|
volumes: !reset [db-data:/var/lib/postgresql/data] # no bind mounts (CI)
|
||||||
|
networks: [fedi]
|
||||||
|
|
||||||
|
api:
|
||||||
|
environment: *federation
|
||||||
|
ports: !reset []
|
||||||
|
networks: [fedi]
|
||||||
|
|
||||||
|
worker:
|
||||||
|
environment: *federation
|
||||||
|
networks: [fedi]
|
||||||
|
|
||||||
|
ui:
|
||||||
|
environment:
|
||||||
|
API_BASE_URL: https://scrobble.test
|
||||||
|
API_INTERNAL_URL: http://api:8000
|
||||||
|
ports: !reset []
|
||||||
|
networks: [fedi]
|
||||||
|
|
||||||
|
# GoToSocial looks up remote servers over HTTPS: serve scrobble.test with TLS
|
||||||
|
# (Caddy's internal CA) in front of the UI, which forwards fediverse paths to the API.
|
||||||
|
tls:
|
||||||
|
image: caddy:2.10
|
||||||
|
command: ["caddy", "reverse-proxy", "--from", "https://scrobble.test", "--to", "http://ui:80", "--internal-certs"]
|
||||||
|
networks:
|
||||||
|
fedi:
|
||||||
|
aliases: [scrobble.test]
|
||||||
|
|
||||||
|
gotosocial:
|
||||||
|
image: superseriousbusiness/gotosocial:0.22.1
|
||||||
|
environment:
|
||||||
|
GTS_HOST: gts.test
|
||||||
|
GTS_PROTOCOL: http # local testing only
|
||||||
|
GTS_PORT: "80"
|
||||||
|
GTS_DB_TYPE: sqlite
|
||||||
|
GTS_DB_ADDRESS: /gotosocial/storage/sqlite.db
|
||||||
|
GTS_HTTP_CLIENT_ALLOW_IPS: ${INTEROP_PRIVATE_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16} # let it reach Scrobbled on this network
|
||||||
|
GTS_HTTP_CLIENT_TLS_INSECURE_SKIP_VERIFY: "true" # Caddy's throwaway certificate
|
||||||
|
GTS_TRUSTED_PROXIES: ${INTEROP_PRIVATE_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16}
|
||||||
|
GTS_ACCOUNTS_REGISTRATION_OPEN: "false"
|
||||||
|
GTS_LOG_LEVEL: ${GTS_LOG_LEVEL:-info}
|
||||||
|
sysctls:
|
||||||
|
net.ipv4.ip_unprivileged_port_start: 0 # listen on :80 as its non-root user
|
||||||
|
networks:
|
||||||
|
fedi:
|
||||||
|
aliases: [gts.test]
|
||||||
|
|
||||||
|
driver:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: deploy/interop/driver.Dockerfile
|
||||||
|
profiles: [driver]
|
||||||
|
environment:
|
||||||
|
GTS_REJECT_ENDS_FOLLOWS: ${GTS_REJECT_ENDS_FOLLOWS:-0}
|
||||||
|
networks: [fedi]
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# The interop test driver: the script baked in (CI runners can't bind-mount the workspace
|
||||||
|
# into sibling containers).
|
||||||
|
FROM python:3.13-slim
|
||||||
|
COPY scripts/interop/gotosocial_interop.py /interop/gotosocial_interop.py
|
||||||
|
CMD ["python", "/interop/gotosocial_interop.py"]
|
||||||
@@ -1,4 +1,10 @@
|
|||||||
# Rendered by the nginx image's envsubst step (API_BASE_URL comes from the environment).
|
# Rendered by the nginx image's envsubst step (API_BASE_URL comes from the environment).
|
||||||
|
|
||||||
|
# Behind a TLS proxy, keep its scheme; otherwise use ours.
|
||||||
|
map $http_x_forwarded_proto $scrobbler_forwarded_proto {
|
||||||
|
default $http_x_forwarded_proto;
|
||||||
|
"" $scheme;
|
||||||
|
}
|
||||||
server {
|
server {
|
||||||
listen 80;
|
listen 80;
|
||||||
server_name _;
|
server_name _;
|
||||||
@@ -12,11 +18,14 @@ server {
|
|||||||
try_files $uri $uri/ =404;
|
try_files $uri $uri/ =404;
|
||||||
# Files aren't fingerprinted, so always revalidate.
|
# Files aren't fingerprinted, so always revalidate.
|
||||||
add_header Cache-Control "no-cache";
|
add_header Cache-Control "no-cache";
|
||||||
add_header Content-Security-Policy "default-src 'self'; connect-src 'self' ${API_BASE_URL}; img-src 'self' data:; style-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always;
|
add_header Content-Security-Policy "default-src 'self'; connect-src 'self' ${API_BASE_URL}; img-src 'self' data: blob:; style-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always;
|
||||||
add_header X-Content-Type-Options nosniff always;
|
add_header X-Content-Type-Options nosniff always;
|
||||||
add_header Referrer-Policy same-origin always;
|
add_header Referrer-Policy same-origin always;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Fediverse paths forwarded to the API (written at start-up; empty if API_INTERNAL_URL is unset).
|
||||||
|
include /etc/nginx/scrobbler/federation.conf;
|
||||||
|
|
||||||
location /fonts/ {
|
location /fonts/ {
|
||||||
add_header Cache-Control "public, max-age=2592000, immutable";
|
add_header Cache-Control "public, max-age=2592000, immutable";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ groups:
|
|||||||
for: 2m
|
for: 2m
|
||||||
labels: {severity: critical}
|
labels: {severity: critical}
|
||||||
annotations:
|
annotations:
|
||||||
summary: Scrobbler API metrics endpoint is down
|
summary: Scrobbled API metrics endpoint is down
|
||||||
description: Prometheus hasn't been able to scrape {{ $labels.instance }} for 2 minutes.
|
description: Prometheus hasn't been able to scrape {{ $labels.instance }} for 2 minutes.
|
||||||
|
|
||||||
- alert: HighErrorRate
|
- alert: HighErrorRate
|
||||||
@@ -73,6 +73,77 @@ groups:
|
|||||||
summary: Imports have been waiting for 15 minutes with nothing running
|
summary: Imports have been waiting for 15 minutes with nothing running
|
||||||
description: The import worker is probably stopped or stuck.
|
description: The import worker is probably stopped or stuck.
|
||||||
|
|
||||||
|
- alert: FederationDeliveryBacklog
|
||||||
|
expr: max(scrobbler_federation_queue{queue="deliveries",status="pending"}) > 100
|
||||||
|
for: 30m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: Over 100 fediverse deliveries have been waiting for 30 minutes
|
||||||
|
description: Check the worker is running and outbound HTTPS works; one slow server can back up retries.
|
||||||
|
|
||||||
|
- alert: FederationInboxBacklog
|
||||||
|
expr: max(scrobbler_federation_queue{queue="inbox",status="queued"}) > 0
|
||||||
|
for: 15m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: Received fediverse activities haven't been processed for 15 minutes
|
||||||
|
description: The worker is probably stopped, or stuck on something.
|
||||||
|
|
||||||
|
- alert: FederationWeeklySummariesMissing
|
||||||
|
expr: sum(increase(scrobbler_worker_tasks_total{task="federation.weekly"}[30m])) == 0
|
||||||
|
for: 5m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: The weekly summary check hasn't run in 30 minutes
|
||||||
|
description: federation.weekly runs every 15 minutes regardless of whether anyone is due a post; the worker is probably stopped or stuck.
|
||||||
|
|
||||||
|
- alert: FederationSignatureFailures
|
||||||
|
expr: |
|
||||||
|
sum(rate(scrobbler_federation_signatures_total{direction="in",result!="ok"}[15m]))
|
||||||
|
/ sum(rate(scrobbler_federation_signatures_total{direction="in"}[15m])) > 0.2
|
||||||
|
for: 15m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: More than 20% of incoming fediverse signatures are failing
|
||||||
|
description: Check the Federation dashboard for the reason (e.g. a clock problem shows as 'expired').
|
||||||
|
|
||||||
|
- alert: AlbumArtBacklog
|
||||||
|
expr: max(scrobbler_art_oldest_pending_seconds) > 900
|
||||||
|
for: 10m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: Album art requests have been waiting over 15 minutes
|
||||||
|
description: The worker is probably stopped, or MusicBrainz / Cover Art Archive is failing.
|
||||||
|
|
||||||
|
- alert: AlbumArtUpstreamErrors
|
||||||
|
expr: |
|
||||||
|
sum by (service) (rate(scrobbler_art_upstream_errors_total[15m]))
|
||||||
|
/ sum by (service) (rate(scrobbler_art_upstream_seconds_count[15m])) > 0.5
|
||||||
|
for: 15m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: Over half of {{ $labels.service }} album art calls are failing
|
||||||
|
description: Failed lookups are cached as errors and retried later; check the upstream's status.
|
||||||
|
|
||||||
|
- alert: AlbumArtCorrectionBacklog
|
||||||
|
expr: max(scrobbler_art_override_oldest_pending_seconds) > 900
|
||||||
|
for: 10m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: A manual album art correction has been waiting over 15 minutes
|
||||||
|
description: The worker is probably stopped, or MusicBrainz / Cover Art Archive is failing.
|
||||||
|
|
||||||
|
- alert: AlbumArtUploadRejections
|
||||||
|
expr: |
|
||||||
|
sum(rate(scrobbler_art_uploads_total{result!="ok"}[30m]))
|
||||||
|
/ sum(rate(scrobbler_art_uploads_total[30m])) > 0.5
|
||||||
|
and sum(rate(scrobbler_art_uploads_total[30m])) > 0.002
|
||||||
|
for: 30m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: Most album art uploads are being rejected
|
||||||
|
description: Check the Album Art dashboard for the reason (too_large suggests ART_UPLOAD_MAX_BYTES or a proxy limit; bad_type a client sending the wrong format).
|
||||||
|
|
||||||
- alert: PostgresDown
|
- alert: PostgresDown
|
||||||
expr: pg_up == 0
|
expr: pg_up == 0
|
||||||
for: 2m
|
for: 2m
|
||||||
|
|||||||
@@ -29,33 +29,53 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
|
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
|
||||||
SECRET_KEY: ${SECRET_KEY:-change-me}
|
SECRET_KEY: ${SECRET_KEY:-change-me}
|
||||||
CORS_ORIGINS: ${UI_BASE_URL:-http://localhost:8080}
|
CORS_ORIGINS: ${CORS_ORIGINS:-http://localhost:8080}
|
||||||
UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080}
|
UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080}
|
||||||
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
||||||
FORWARDED_ALLOW_IPS: "*"
|
FORWARDED_ALLOW_IPS: "*"
|
||||||
|
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||||
|
LOG_FORMAT: ${LOG_FORMAT:-text}
|
||||||
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
||||||
|
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
|
||||||
|
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
|
||||||
|
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
|
||||||
|
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
|
||||||
|
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
||||||
|
FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-}
|
||||||
ports:
|
ports:
|
||||||
- "${API_PORT:-5050}:8000"
|
- "${API_PORT:-5050}:8000"
|
||||||
expose:
|
expose:
|
||||||
- "9100" # metrics: internal network only
|
- "9100" # metrics: internal network only
|
||||||
|
volumes:
|
||||||
|
- album-art-data:/data/album-art
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|
||||||
# Processes history imports (uploaded exports and pulls from Last.fm).
|
# Background work: history imports, and tasks registered by optional modules.
|
||||||
worker:
|
worker:
|
||||||
image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-api:${SCROBBLER_IMAGE_TAG:-local}
|
image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-api:${SCROBBLER_IMAGE_TAG:-local}
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: docker/api.Dockerfile
|
dockerfile: docker/api.Dockerfile
|
||||||
command: ["flask", "--app", "scrobbler", "imports", "worker"]
|
command: ["flask", "--app", "scrobbler", "worker"]
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
|
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
|
||||||
SECRET_KEY: ${SECRET_KEY:-change-me}
|
SECRET_KEY: ${SECRET_KEY:-change-me}
|
||||||
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
||||||
|
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
|
||||||
|
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
|
||||||
|
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
|
||||||
|
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
|
||||||
|
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
||||||
|
FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-}
|
||||||
RUN_MIGRATIONS: "0" # the api service applies them
|
RUN_MIGRATIONS: "0" # the api service applies them
|
||||||
|
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||||
|
LOG_FORMAT: ${LOG_FORMAT:-text}
|
||||||
expose:
|
expose:
|
||||||
- "9101" # metrics: internal network only
|
- "9101" # metrics: internal network only
|
||||||
|
volumes:
|
||||||
|
- album-art-data:/data/album-art
|
||||||
healthcheck:
|
healthcheck:
|
||||||
disable: true
|
disable: true
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -69,6 +89,8 @@ services:
|
|||||||
dockerfile: docker/ui.Dockerfile
|
dockerfile: docker/ui.Dockerfile
|
||||||
environment:
|
environment:
|
||||||
API_BASE_URL: ${API_BASE_URL:-http://localhost:5050}
|
API_BASE_URL: ${API_BASE_URL:-http://localhost:5050}
|
||||||
|
# Forward the fediverse paths (/.well-known/webfinger, /users/, /inbox, ...) to the API.
|
||||||
|
API_INTERNAL_URL: ${API_INTERNAL_URL:-http://api:8000}
|
||||||
ports:
|
ports:
|
||||||
- "${UI_PORT:-8080}:80"
|
- "${UI_PORT:-8080}:80"
|
||||||
|
|
||||||
@@ -113,5 +135,6 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
db-data:
|
db-data:
|
||||||
|
album-art-data:
|
||||||
prometheus-data:
|
prometheus-data:
|
||||||
grafana-data:
|
grafana-data:
|
||||||
@@ -3,6 +3,6 @@
|
|||||||
set -e
|
set -e
|
||||||
if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then
|
if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then
|
||||||
# Not under gunicorn, so don't use (or pollute) the multiprocess metrics directory.
|
# Not under gunicorn, so don't use (or pollute) the multiprocess metrics directory.
|
||||||
env -u PROMETHEUS_MULTIPROC_DIR flask --app scrobbler db upgrade
|
env -u PROMETHEUS_MULTIPROC_DIR flask --app scrobbler db upgrade heads
|
||||||
fi
|
fi
|
||||||
exec "$@"
|
exec "$@"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# Scrobbler API: gunicorn serving the Flask app, metrics on :9100.
|
# Scrobbled API: gunicorn serving the Flask app, metrics on :9100.
|
||||||
FROM ghcr.io/astral-sh/uv:0.7.21 AS uv
|
FROM ghcr.io/astral-sh/uv:0.7.21 AS uv
|
||||||
|
|
||||||
FROM python:3.13-slim AS build
|
FROM python:3.13-slim AS build
|
||||||
@@ -11,7 +11,10 @@ COPY src ./src
|
|||||||
RUN uv sync --locked --no-dev --no-editable
|
RUN uv sync --locked --no-dev --no-editable
|
||||||
|
|
||||||
FROM python:3.13-slim
|
FROM python:3.13-slim
|
||||||
|
LABEL org.opencontainers.image.licenses="BSD-3-Clause"
|
||||||
RUN useradd --system --uid 10001 --no-create-home scrobbler
|
RUN useradd --system --uid 10001 --no-create-home scrobbler
|
||||||
|
# Downloaded album art lives here, on a volume shared with the worker (which writes it).
|
||||||
|
RUN mkdir -p /data/album-art && chown scrobbler:scrobbler /data/album-art
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=build /app/.venv /app/.venv
|
COPY --from=build /app/.venv /app/.venv
|
||||||
COPY gunicorn.conf.py docker/api-entrypoint.sh ./
|
COPY gunicorn.conf.py docker/api-entrypoint.sh ./
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# Point the UI at the API: rewrite config.js from $API_BASE_URL at container start.
|
# Container start-up: point the UI at the API, and (when API_INTERNAL_URL is set)
|
||||||
|
# forward the fediverse paths on this domain to the API.
|
||||||
set -e
|
set -e
|
||||||
case "$API_BASE_URL" in
|
case "$API_BASE_URL" in
|
||||||
http://*|https://*) ;;
|
http://*|https://*) ;;
|
||||||
@@ -11,3 +12,35 @@ window.SCROBBLER_CONFIG = {
|
|||||||
apiBaseUrl: "$url",
|
apiBaseUrl: "$url",
|
||||||
};
|
};
|
||||||
JS
|
JS
|
||||||
|
|
||||||
|
mkdir -p /etc/nginx/scrobbler
|
||||||
|
if [ -z "$API_INTERNAL_URL" ]; then
|
||||||
|
: > /etc/nginx/scrobbler/federation.conf
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
case "$API_INTERNAL_URL" in
|
||||||
|
http://*|https://*) ;;
|
||||||
|
*) echo "API_INTERNAL_URL must look like http://api:8000" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
upstream=$(printf '%s' "$API_INTERNAL_URL" | sed 's#/*$##')
|
||||||
|
case "$upstream" in
|
||||||
|
*://*/*) echo "API_INTERNAL_URL must not have a path" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
# Resolve the API's name per request (not once at start-up), so the UI starts even if
|
||||||
|
# the API isn't up yet and keeps working when the API container is replaced.
|
||||||
|
nameserver=$(awk '/^nameserver/ { print $2; exit }' /etc/resolv.conf)
|
||||||
|
case "$nameserver" in *:*) nameserver="[$nameserver]" ;; esac
|
||||||
|
cat > /etc/nginx/scrobbler/federation.conf <<NGINX
|
||||||
|
# Fediverse (ActivityPub) paths live on the UI's domain; the API answers them.
|
||||||
|
location ~ ^/(\.well-known/(webfinger|nodeinfo|host-meta)\$|nodeinfo/|users/|inbox\$|actor(/|\$)) {
|
||||||
|
resolver ${nameserver:-127.0.0.11} valid=30s ipv6=off;
|
||||||
|
set \$scrobbler_api $upstream;
|
||||||
|
proxy_pass \$scrobbler_api;
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scrobbler_forwarded_proto;
|
||||||
|
proxy_set_header X-Forwarded-Host \$host;
|
||||||
|
client_max_body_size 1m;
|
||||||
|
}
|
||||||
|
NGINX
|
||||||
|
echo "forwarding fediverse paths to $upstream"
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
# Scrobbler web UI: static files served by nginx.
|
# Scrobbled web UI: static files served by nginx.
|
||||||
FROM nginx:1.29-alpine
|
FROM nginx:1.29-alpine
|
||||||
|
LABEL org.opencontainers.image.licenses="BSD-3-Clause"
|
||||||
ENV API_BASE_URL=http://localhost:5050
|
ENV API_BASE_URL=http://localhost:5050
|
||||||
COPY deploy/nginx/default.conf.template /etc/nginx/templates/default.conf.template
|
COPY deploy/nginx/default.conf.template /etc/nginx/templates/default.conf.template
|
||||||
COPY docker/ui-config.sh /docker-entrypoint.d/40-scrobbler-config.sh
|
COPY docker/ui-config.sh /docker-entrypoint.d/40-scrobbler-config.sh
|
||||||
|
|||||||
@@ -0,0 +1,285 @@
|
|||||||
|
# Admin guide
|
||||||
|
|
||||||
|
Running a real Scrobbled instance: architecture, installation, configuration, TLS,
|
||||||
|
fediverse sharing, monitoring, backups, upgrades and troubleshooting. If you're using an
|
||||||
|
instance someone else runs, see the [user guide](user-guide.md) instead. If you're
|
||||||
|
working on Scrobbled's own code, see [setup.md](setup.md).
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
players / scrobblers ──► API /2.0/ Last.fm-compatible
|
||||||
|
web UI (static files) ──► API /api/v1/ JSON API for the UI
|
||||||
|
API ──► PostgreSQL
|
||||||
|
Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
|
||||||
|
```
|
||||||
|
|
||||||
|
- **`api`**: Flask under gunicorn. API-only; it serves no HTML pages.
|
||||||
|
- **`ui`**: nginx serving the static frontend (`frontend/`, no build step).
|
||||||
|
- **`worker`**: `flask worker` — history imports, resolving and downloading album art
|
||||||
|
(MusicBrainz + Cover Art Archive), and background tasks for optional modules
|
||||||
|
(federation's deliveries, scheduled posts, and so on). This is the only service that
|
||||||
|
makes outbound calls to third-party APIs (Last.fm, MusicBrainz, Cover Art Archive, and
|
||||||
|
remote fediverse servers with federation on) — worth knowing if you're restricting
|
||||||
|
egress.
|
||||||
|
- **`db`**: PostgreSQL.
|
||||||
|
- With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`.
|
||||||
|
|
||||||
|
Everything Scrobbled needs to run is in these five services plus optional monitoring —
|
||||||
|
there's no separate cache, queue or search service to operate.
|
||||||
|
|
||||||
|
## Installing
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD
|
||||||
|
SCROBBLER_IMAGE_TAG=main docker compose up -d --no-build # or drop --no-build to build locally
|
||||||
|
```
|
||||||
|
|
||||||
|
Open `http://localhost:8080`, create an account, then go to **Apps** and create an app
|
||||||
|
for each player. Add `--profile monitoring` for Prometheus and Grafana.
|
||||||
|
|
||||||
|
Published images: `pkgs.daubney.dev/scrobbler/scrobbler-api` and
|
||||||
|
`pkgs.daubney.dev/scrobbler/scrobbler-ui`, tagged `main` (latest push to `main`),
|
||||||
|
`sha-<commit>`, and `<version>`/`latest` for tagged releases.
|
||||||
|
|
||||||
|
This is enough for evaluating Scrobbled. Before putting it in front of real users, also
|
||||||
|
read **Putting it behind TLS** below — the quick start above serves plain HTTP only.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
| Variable | Used by | Default | Purpose |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `DATABASE_URL` | api | local Postgres | SQLAlchemy URL (`postgresql+psycopg://…`) |
|
||||||
|
| `SECRET_KEY` | api | `dev-insecure-secret` | Flask secret — set a real one |
|
||||||
|
| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated origins allowed to call `/api/v1`: wherever browsers actually load the UI from |
|
||||||
|
| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins, and (with federation on) the public identity users are found under |
|
||||||
|
| `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` |
|
||||||
|
| `LOG_LEVEL` | api, worker | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR`. The worker logs each task pass that did work at `INFO` (with its duration); idle polls show at `DEBUG` |
|
||||||
|
| `LOG_FORMAT` | api, worker | `text` | `json` writes one JSON object per line (with `task` and `duration_ms` fields for worker tasks), for log aggregators |
|
||||||
|
| `METRICS_PORT` | api | `9100` | Prometheus metrics port — keep it off the public network |
|
||||||
|
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
|
||||||
|
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
|
||||||
|
| `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) |
|
||||||
|
| `MUSICBRAINZ_CONTACT` | api, worker | `UI_BASE_URL` | Contact URL/email sent to MusicBrainz for album art lookups (no key needed, but they ask for one) |
|
||||||
|
| `ART_STORAGE_DIR` | api, worker | `var/album-art` | Where downloaded album art is stored; the worker writes it, the api serves it — both need access to the same directory (`docker compose` mounts a shared volume there) |
|
||||||
|
| `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 |
|
||||||
|
| `API_BASE_URL` | ui image | `http://localhost:5050` | Where the browser reaches the API — written into `config.js` and the CSP |
|
||||||
|
|
||||||
|
In `docker compose`, host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`,
|
||||||
|
`PROMETHEUS_PORT` and `GRAFANA_PORT`.
|
||||||
|
|
||||||
|
`CORS_ORIGINS` and `UI_BASE_URL` answer different questions and can differ: the first is
|
||||||
|
*which browser origins may call the JSON API*, the second is *where the public identity
|
||||||
|
and sign-in redirects point*. Don't assume setting one sets the other —
|
||||||
|
`docker-compose.yml` passes them through independently, and forgetting to set
|
||||||
|
`CORS_ORIGINS` to your real public origin is the single most common cause of "the UI
|
||||||
|
can't reach the API" once you're off `localhost` (see Troubleshooting).
|
||||||
|
|
||||||
|
### Fediverse sharing (optional)
|
||||||
|
|
||||||
|
Off unless the server enables it, and then off for each user until they turn it on:
|
||||||
|
|
||||||
|
1. Set on the **api** and **worker**:
|
||||||
|
- `FEDERATION_ENABLED=1`
|
||||||
|
- `FEDERATION_DOMAIN`: the UI's host, e.g. `scrobble.example`
|
||||||
|
- `FEDERATION_BASE_URL`: the UI's origin, e.g. `https://scrobble.example`
|
||||||
|
- `FEDERATION_KEY_SECRET`: 32+ random characters
|
||||||
|
2. Give the **ui** container `API_INTERNAL_URL` (compose sets `http://api:8000`). It
|
||||||
|
forwards these paths to the API: `/.well-known/webfinger`, `/.well-known/nodeinfo`,
|
||||||
|
`/.well-known/host-meta`, `/nodeinfo/`, `/users/`, `/inbox` and `/actor`.
|
||||||
|
3. Serve the UI over **real HTTPS** on that domain — other fediverse servers only talk to
|
||||||
|
HTTPS, and won't accept a self-signed certificate.
|
||||||
|
|
||||||
|
Handles and actor URLs **can't change once anyone follows a user**, so choose the domain
|
||||||
|
carefully before enabling this in production.
|
||||||
|
|
||||||
|
`FEDERATION_KEY_SECRET` encrypts every user's signing key. **Back it up, and never
|
||||||
|
change it**: losing it means users' keys can't be read, and followers would have to
|
||||||
|
follow again.
|
||||||
|
|
||||||
|
Optional: `FEDERATION_BLOCKED_DOMAINS` (comma-separated, subdomains included),
|
||||||
|
`FEDERATION_DELIVERY_CONCURRENCY` (default 4), `FEDERATION_SIGNATURE_SCHEMES` (default
|
||||||
|
`draft-cavage,rfc9421`). The `worker` service must be running — it delivers outgoing
|
||||||
|
activities and processes incoming ones.
|
||||||
|
|
||||||
|
Once it's on, tell your users: they still need to opt in themselves under **Sharing** in
|
||||||
|
the web UI — see the [user guide](user-guide.md#sharing-on-the-fediverse).
|
||||||
|
|
||||||
|
## Putting it behind TLS
|
||||||
|
|
||||||
|
Scrobbled itself only speaks plain HTTP; something in front of it needs to terminate
|
||||||
|
TLS. Any reverse proxy works — nginx, Caddy, or a tunnel like Cloudflare Tunnel for
|
||||||
|
testing without a public IP (see `docs/design/activitypub-phase4.md` for how the
|
||||||
|
project's own manual federation test used one).
|
||||||
|
|
||||||
|
Caddy, proxying everything to the `ui` container (which itself forwards the fediverse
|
||||||
|
paths to `api`), gets you a certificate automatically with no extra steps:
|
||||||
|
|
||||||
|
```
|
||||||
|
scrobble.example {
|
||||||
|
reverse_proxy localhost:8080
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
nginx with certbot, doing the same job:
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name scrobble.example;
|
||||||
|
location / { return 301 https://$host$request_uri; }
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name scrobble.example;
|
||||||
|
ssl_certificate /etc/letsencrypt/live/scrobble.example/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/scrobble.example/privkey.pem;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://localhost:8080;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Proto https;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
certbot --nginx -d scrobble.example
|
||||||
|
```
|
||||||
|
|
||||||
|
Point `UI_BASE_URL`/`FEDERATION_BASE_URL`/`FEDERATION_DOMAIN` at that same public
|
||||||
|
`https://scrobble.example` origin. The API (`API_PORT`, default 5050) doesn't need its
|
||||||
|
own public hostname unless you want browsers to reach it directly instead of through the
|
||||||
|
UI's proxy — set `API_BASE_URL` accordingly either way, since the browser calls it
|
||||||
|
directly for `/api/v1`, and make sure `CORS_ORIGINS` includes `https://scrobble.example`
|
||||||
|
regardless of which layout you pick.
|
||||||
|
|
||||||
|
## Monitoring
|
||||||
|
|
||||||
|
The API serves Prometheus metrics on `METRICS_PORT`, summed across gunicorn workers. All
|
||||||
|
series are prefixed `scrobbler_`: HTTP request rate/errors/latency, Last.fm calls and
|
||||||
|
auth failures, scrobble outcomes, database query latency and pool use, and gauges for
|
||||||
|
registered/active/currently-listening users. Labels never contain usernames, API keys or
|
||||||
|
track names.
|
||||||
|
|
||||||
|
With `--profile monitoring`, Grafana (`GRAFANA_ADMIN_PASSWORD`) provisions a
|
||||||
|
**Scrobbled** folder with dashboards for API overview, Last.fm API, usage, database and
|
||||||
|
(with federation on) federation. Alert rules live in `deploy/prometheus/alerts.yml` —
|
||||||
|
evaluated by Prometheus and visible in Grafana, but nothing routes them anywhere without
|
||||||
|
Alertmanager.
|
||||||
|
|
||||||
|
## Backups and restore
|
||||||
|
|
||||||
|
Back up, at minimum:
|
||||||
|
|
||||||
|
- The Postgres database (all scrobble history, accounts, federation state).
|
||||||
|
- `FEDERATION_KEY_SECRET`, if federation is on — it's the only thing that can decrypt
|
||||||
|
stored signing keys, and it's never derivable from the database alone.
|
||||||
|
- Your `.env` (or equivalent secrets store), so `SECRET_KEY` and the rest survive a
|
||||||
|
rebuild without inventing new ones.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose exec db pg_dump -U scrobbler scrobbler | gzip > backup-$(date +%F).sql.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
To restore onto a fresh `db` volume:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
gunzip -c backup-2026-01-01.sql.gz | docker compose exec -T db psql -U scrobbler scrobbler
|
||||||
|
```
|
||||||
|
|
||||||
|
Restoring an older dump with federation on will leave followers pointed at posts that no
|
||||||
|
longer exist and profile data that's gone stale — expected after any point-in-time
|
||||||
|
restore, not a sign anything's broken.
|
||||||
|
|
||||||
|
The `album-art-data` volume holds two kinds of file. Cover art the worker downloaded is a
|
||||||
|
disposable cache — it's simply re-downloaded the next time it's requested. Images users
|
||||||
|
**upload** (and the art from their manual corrections) live under `user/` in the same
|
||||||
|
volume and can't be re-created, so include the volume in your backups. The database rows
|
||||||
|
that point at them are in `user_album_art`; restore the two together.
|
||||||
|
|
||||||
|
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
|
||||||
|
docker compose pull # or set SCROBBLER_IMAGE_TAG to a specific version
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
Migrations run automatically on API container start (`RUN_MIGRATIONS=1`, the default).
|
||||||
|
Take a database backup first for anything beyond a patch version — check
|
||||||
|
`docs/design/` and the Gitea release notes for the version you're jumping to if it spans
|
||||||
|
a major version.
|
||||||
|
|
||||||
|
## Releases
|
||||||
|
|
||||||
|
Gitea Actions (`.gitea/workflows/ci.yml`) builds and publishes on every push to `main`
|
||||||
|
and on `v*` tags, once lint, tests and the Prometheus config checks all pass:
|
||||||
|
|
||||||
|
- Both images push to the ProGet `scrobbler` Docker feed.
|
||||||
|
- The OpenAPI spec, dashboards and Prometheus config upload to the `scrobbler-assets`
|
||||||
|
feed.
|
||||||
|
- `v*` tags also publish the wheel/sdist to the `scrobbler-python` PyPI feed (as
|
||||||
|
`scrobby`; `scrobbler` on public PyPI is an unrelated project).
|
||||||
|
|
||||||
|
To release: tag `vX.Y.Z` on `main` and push the tag. That tag sets both the package and
|
||||||
|
image version. See [setup.md](setup.md) for the secrets/variables the workflow needs and
|
||||||
|
how to run it locally before tagging.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
**The web UI loads but can't reach the API ("Can't reach the Scrobbled API at …" or
|
||||||
|
requests failing silently).** Almost always `CORS_ORIGINS` on the `api` service not
|
||||||
|
listing the exact origin the browser loads the UI from (scheme and host both have to
|
||||||
|
match — `https://scrobble.example` is not the same origin as `http://scrobble.example`
|
||||||
|
or `www.scrobble.example`). Check with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -i -X OPTIONS https://scrobble.example/api/v1/auth/me \
|
||||||
|
-H "Origin: https://scrobble.example" -H "Access-Control-Request-Method: GET"
|
||||||
|
```
|
||||||
|
|
||||||
|
A missing `access-control-allow-origin` header in the response confirms it. This is
|
||||||
|
separate from `UI_BASE_URL` — setting one does not set the other.
|
||||||
|
|
||||||
|
**Federation looks enabled but the "Sharing" page/nav link doesn't appear for a user.**
|
||||||
|
First confirm federation is actually on server-side, independent of what any log line
|
||||||
|
says (gunicorn drops `log.info` by default unless something configures logging):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -o /dev/null -w '%{http_code}\n' https://scrobble.example/actor # 200 = federation is on
|
||||||
|
```
|
||||||
|
|
||||||
|
If that's `200`, the server is fine and the problem is client-side: the web UI caches
|
||||||
|
whether federation is available in the browser's `sessionStorage` for the tab, and
|
||||||
|
caches static JS in the ordinary browser cache. Ask the user to hard-refresh
|
||||||
|
(Ctrl/Cmd+Shift+R) or try a private window — if it works there, it's a stale cache, not
|
||||||
|
a server problem.
|
||||||
|
|
||||||
|
**A fediverse profile 404s from a specific remote server (e.g. mastodon.social) right
|
||||||
|
after you enable sharing, even though WebFinger looks correct from curl.** Large
|
||||||
|
instances cache a *negative* WebFinger lookup for a while. Confirm the server's own
|
||||||
|
response is correct first:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -H 'Accept: application/jrd+json' \
|
||||||
|
'https://scrobble.example/.well-known/webfinger?resource=acct:name@scrobble.example'
|
||||||
|
```
|
||||||
|
|
||||||
|
If that's correct, the fix is time (or trying a smaller/different instance to confirm
|
||||||
|
it's not a Scrobbled-side problem) — there's nothing to change on the server.
|
||||||
|
|
||||||
|
**A legacy scrobbler client (e.g. VLC's built-in scrobbler) fails to connect at all.**
|
||||||
|
Scrobbled implements the Last.fm 2.0 API only, not the legacy 1.2 Audioscrobbler
|
||||||
|
handshake (`hs=true&p=1.2&...`). Clients that only speak 1.2 can't be pointed at
|
||||||
|
Scrobbled regardless of configuration — point users at a client with 2.0 support
|
||||||
|
instead.
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# ActivityPub phase 0: groundwork
|
||||||
|
|
||||||
|
**Status: done** on `feature/activitypub`:
|
||||||
|
|
||||||
|
| Commit | Steps |
|
||||||
|
|---|---|
|
||||||
|
| `59ff1bd` | events |
|
||||||
|
| `098eab0` | worker |
|
||||||
|
| `c79c42e` | module and migrations |
|
||||||
|
| `eb5802f` | boundary tests |
|
||||||
|
|
||||||
|
This implements phase 0 of [activitypub.md](activitypub.md): the seams that federation will plug into. There's **no user-visible change**. All existing tests must keep passing, and the app behaves exactly as before with federation off, which is the default.
|
||||||
|
|
||||||
|
## 1. Domain events: `scrobbler/events.py`
|
||||||
|
|
||||||
|
Blinker signals in a `scrobbler` namespace. They're sent **after** the relevant commit, so receivers only ever see stored data.
|
||||||
|
|
||||||
|
| Signal | Sender | Keyword arguments | Sent from |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `scrobbles_stored` | the `User` | `scrobbles: list[TrackInput]` (newly stored only), `source: "scrobble" \| "import"` | `services.scrobbles.submit_scrobbles`, and `services.imports.store_chunk` via the job loop |
|
||||||
|
| `now_playing_changed` | the `User` | `track: TrackInput \| None` (`None` means stopped or cleared) | `update_now_playing`, and clearing when the same track is scrobbled |
|
||||||
|
| `import_finished` | the `User` | `job: ImportJob` | `services.imports`, when a job completes, fails or is cancelled |
|
||||||
|
|
||||||
|
- Duplicates and ignored scrobbles aren't included, so listeners never see a play twice.
|
||||||
|
- A receiver that raises is logged and swallowed. A broken listener must never fail a scrobble.
|
||||||
|
|
||||||
|
## 2. Generic worker: `scrobbler/worker.py`
|
||||||
|
|
||||||
|
- **A task registry.**
|
||||||
|
- `register_task(name, fn)` for work queues. `fn()` returns `True` if it did something, and the worker loops straight away while there's work.
|
||||||
|
- `register_periodic(name, every, fn)` for scheduled jobs.
|
||||||
|
- **Imports move onto it.** `services.imports` registers:
|
||||||
|
- `imports` (claim and process one job)
|
||||||
|
- `imports.requeue_stalled` (every 60s, and once at start-up)
|
||||||
|
- **CLI.** A new `flask worker` command.
|
||||||
|
- `flask imports worker` stays as an alias, so existing deployments keep working.
|
||||||
|
- `docker-compose.yml` switches to `flask worker`.
|
||||||
|
- **Metric.** `scrobbler_worker_tasks_total{task,outcome}`, where outcome is `worked` or `error`, plus a panel on the Usage dashboard.
|
||||||
|
- **Isolation.** A task that raises is logged and counted, and the worker keeps going, so one module's bug can't stop another's work.
|
||||||
|
|
||||||
|
## 3. Empty federation module: `scrobbler/federation/`
|
||||||
|
|
||||||
|
- `__init__.py` holds `init_app(app)`, the only entry point, which `create_app()` calls. With `FEDERATION_ENABLED` off (the default) it returns without registering anything.
|
||||||
|
- `config.py` holds `FEDERATION_ENABLED`, `FEDERATION_DOMAIN` and `FEDERATION_BASE_URL`, and validates them. Enabling federation without a domain and an HTTPS base URL fails at start-up with a clear message.
|
||||||
|
- `protocol/__init__.py` states the purity rule; it's otherwise empty.
|
||||||
|
- `README.md` inside the package states the boundary rules and how to add migrations.
|
||||||
|
|
||||||
|
## 4. Alembic branches
|
||||||
|
|
||||||
|
- Label the existing core history `core` by adding `branch_labels = ("core",)` to the initial revision.
|
||||||
|
- Add a federation root revision:
|
||||||
|
- revision ID `federation_0001`
|
||||||
|
- `branch_labels = ("federation",)`
|
||||||
|
- `depends_on` the core revision that creates `users`
|
||||||
|
- no tables yet
|
||||||
|
- **Everything that runs `db upgrade` now upgrades `heads`**: the API entrypoint, CI, the test fixtures and the README.
|
||||||
|
- New core migrations use `flask db migrate --head core@head`; federation ones use `--head federation@head`.
|
||||||
|
|
||||||
|
## 5. Boundary tests: `tests/test_federation_boundary.py`
|
||||||
|
|
||||||
|
Static checks (using `ast`) over `src/scrobbler`:
|
||||||
|
|
||||||
|
1. Nothing outside `scrobbler.federation` imports it, except `scrobbler/__init__.py`.
|
||||||
|
2. `scrobbler.federation.protocol` imports nothing from `flask*`, `sqlalchemy`, `werkzeug` or `scrobbler`, apart from itself.
|
||||||
|
3. The rest of `scrobbler.federation` imports only these parts of the core:
|
||||||
|
- `scrobbler.events`
|
||||||
|
- `scrobbler.extensions`
|
||||||
|
- `scrobbler.worker`
|
||||||
|
- `scrobbler.services`
|
||||||
|
- `scrobbler.api.decorators`
|
||||||
|
- `scrobbler.schemas`
|
||||||
|
|
||||||
|
So no core models, and no core metrics.
|
||||||
|
|
||||||
|
Runtime checks:
|
||||||
|
|
||||||
|
4. With federation off: no routes from federation blueprints, no signal receivers defined in `scrobbler.federation`, and no worker tasks named `federation.*`.
|
||||||
|
5. With federation on but misconfigured, `create_app` raises a clear error. Correctly configured, it starts.
|
||||||
|
|
||||||
|
## 6. Tests for the seams
|
||||||
|
|
||||||
|
- **Events**: a scrobble batch sends only the newly stored plays; now-playing sends on start and on clear; a finished import sends `import_finished`; a failing receiver doesn't break scrobbling.
|
||||||
|
- **Worker**: registered tasks run, the loop keeps running while there's work, periodic tasks keep to their interval, and a failing task is counted but doesn't stop the others.
|
||||||
|
- **Migrations**: `heads` upgrades both branches, `db check` passes, and the federation branch is independent (it can be downgraded on its own).
|
||||||
|
|
||||||
|
## 7. Docs and CI
|
||||||
|
|
||||||
|
- README: `flask worker`, `db upgrade heads`, and the two-branch migration workflow.
|
||||||
|
- CI: upgrade `heads` before `db check`.
|
||||||
|
- Commit after each numbered section once its tests pass.
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
# ActivityPub phase 1: discoverable profile
|
||||||
|
|
||||||
|
**Status: done** on `feature/activitypub` (`98c6554` … `913ef67`). The manual check with a real Mastodon account through a tunnel (`cloudflared`) is also done: WebFinger, the actor and the key all resolved correctly from mastodon.social and activitypub.academy.
|
||||||
|
|
||||||
|
This implements phase 1 of [activitypub.md](activitypub.md). Handles and actor URLs are on the **UI's domain**, and posts are **followers only by default** (a per-user setting).
|
||||||
|
|
||||||
|
**Outcome:** once an operator enables federation, a user can switch on sharing, and searching `@alice@<UI host>` from Mastodon finds their profile. Following needs phase 2 (the inbox and deliveries). Until then the actor advertises `manuallyApprovesFollowers: true`, so a follow shows as a pending request rather than failing silently. With federation off, nothing changes.
|
||||||
|
|
||||||
|
Everything below lives in `scrobbler.federation` unless it says otherwise, and the boundary tests keep holding.
|
||||||
|
|
||||||
|
## 1. Data and keys
|
||||||
|
|
||||||
|
- **New dependency**: `cryptography` (Apache-2.0 or BSD).
|
||||||
|
- **Migration on the `federation` branch** (`flask db migrate --head federation@head`), adding two tables:
|
||||||
|
- `federation_settings`, keyed by user:
|
||||||
|
- `enabled` (false)
|
||||||
|
- `visibility`: `followers` (the default), `unlisted` or `public`
|
||||||
|
- `manually_approves_followers` (false)
|
||||||
|
- `discoverable` and `indexable` (both false)
|
||||||
|
- `display_name`, `bio`
|
||||||
|
- `created_at` and `updated_at`
|
||||||
|
- `federation_keys`:
|
||||||
|
- a user ID, which is null for the instance actor
|
||||||
|
- the public key PEM
|
||||||
|
- the private key PEM encrypted with Fernet
|
||||||
|
- `created_at`
|
||||||
|
- `keys.py`:
|
||||||
|
- An RSA-2048 key pair is created the first time a user enables sharing. The instance actor's pair is created on first use.
|
||||||
|
- Private keys are encrypted with a key derived by HKDF-SHA256 from **`FEDERATION_KEY_SECRET`**. That setting becomes required when federation is on, and is validated at start-up.
|
||||||
|
- Keys are never regenerated, because followers pin them.
|
||||||
|
|
||||||
|
## 2. Protocol (pure: `federation/protocol/`)
|
||||||
|
|
||||||
|
- `media.py`: the ActivityPub content types (`application/activity+json`, and `application/ld+json` with the ActivityStreams profile), plus a check for whether a request's `Accept` header wants ActivityPub.
|
||||||
|
- `vocab.py`, which builds dicts with `@context`:
|
||||||
|
- `person()`: `id`, `preferredUsername`, `name`, `summary`, `url`, `inbox`, `outbox`, `followers`, `following`, `endpoints.sharedInbox`, `publicKey`, `manuallyApprovesFollowers`, `discoverable`, `indexable`
|
||||||
|
- `application()` for the instance actor
|
||||||
|
- `ordered_collection()`
|
||||||
|
- `webfinger.py`: parses `acct:user@domain` resources (case-insensitive, trimmed, rejecting other domains) and builds the JRD: `subject`, `aliases`, a `self` link and a `profile-page` link.
|
||||||
|
- `nodeinfo.py`: the discovery document and the NodeInfo 2.1 document.
|
||||||
|
- `hostmeta.py`: the XRD for `/.well-known/host-meta`, which points at WebFinger.
|
||||||
|
|
||||||
|
These are unit-tested against the documented Mastodon shapes and examples from the WebFinger RFC.
|
||||||
|
|
||||||
|
## 3. ActivityPub endpoints (`federation/web.py`)
|
||||||
|
|
||||||
|
| Path | Response |
|
||||||
|
|---|---|
|
||||||
|
| `GET /.well-known/webfinger?resource=acct:u@DOMAIN` | JRD for users who opted in. **404 for unknown or non-opted users, with an identical body.** 400 for a malformed or foreign resource. |
|
||||||
|
| `GET /.well-known/host-meta` | XRD pointing at WebFinger |
|
||||||
|
| `GET /.well-known/nodeinfo`, `GET /nodeinfo/2.1` | Software `scrobbler`, the version, `activitypub`, and the count of users who opted in |
|
||||||
|
| `GET /users/<u>` | Actor JSON when the request asks for ActivityPub; otherwise a **302 to the UI profile page**; 404 if not opted in |
|
||||||
|
| `GET /users/<u>/outbox`, `/followers`, `/following` | Empty collections with `totalItems` (filled in phases 2 and 3) |
|
||||||
|
| `POST /users/<u>/inbox`, `POST /inbox` | 202 and discard, for now (phase 2 handles it) |
|
||||||
|
| `GET /actor` | The instance actor (an `Application`), used later for signed fetches |
|
||||||
|
|
||||||
|
- All IDs and URLs are built from `FEDERATION_BASE_URL`, never from the request, so a proxy misconfiguration can't produce wrong IDs.
|
||||||
|
- Responses are cacheable: `Cache-Control: max-age=300` on the actor and WebFinger.
|
||||||
|
- CORS stays unchanged: remote servers don't send CORS requests.
|
||||||
|
|
||||||
|
## 4. UI-facing API (`federation/api.py`, `/api/v1/federation/*`, documented in OpenAPI)
|
||||||
|
|
||||||
|
- **`GET` and `PUT /settings`** (bearer auth):
|
||||||
|
- Returns `enabled`, `visibility`, `manually_approves_followers`, `discoverable`, `indexable`, `display_name`, `bio`, the read-only `handle` and `profile_url`, and `followers` (0 until phase 2).
|
||||||
|
- A 404 means the server doesn't federate, and the UI hides the Sharing page.
|
||||||
|
- **`GET /profiles/<username>`** is **public** (no auth). It returns the profile shown on the UI profile page, for opted-in users only, and 404 otherwise.
|
||||||
|
- **Registration**: federation registers its smorest blueprint on the core's `Api` object. This means allowing `scrobbler.api` itself (the `Api` instance) in the boundary test's list of permitted imports, alongside `scrobbler.api.decorators`.
|
||||||
|
|
||||||
|
## 5. Web UI (in `frontend/`, not the Python module)
|
||||||
|
|
||||||
|
- **`sharing.html`**, shown in the nav only when `/federation/settings` exists:
|
||||||
|
- A **Share my listening on the fediverse** switch, showing the handle and the warning that it's permanent.
|
||||||
|
- A **Who can see posts** choice: *Followers only* (default), *Unlisted* or *Public*. Its help text says to turn on manual approval for real privacy.
|
||||||
|
- **Approve followers manually**, **List my profile in directories** (`discoverable`) and **Allow search engines** (`indexable`).
|
||||||
|
- Display name and bio.
|
||||||
|
- **`profile.html?u=<username>`**: a public page with no login needed, where browsers opening an actor URL land.
|
||||||
|
- It shows the display name, handle, bio and how to follow ("search for `@alice@host` in your fediverse app"), with a copy button.
|
||||||
|
- It uses the existing styles, including the dot-matrix display for the handle.
|
||||||
|
|
||||||
|
## 6. Proxying from the UI domain (`deploy/nginx/default.conf.template`)
|
||||||
|
|
||||||
|
- Forward these paths to `${API_INTERNAL_URL}` (default `http://api:8000`, set in the UI image):
|
||||||
|
- `/.well-known/webfinger`, `/.well-known/nodeinfo`, `/.well-known/host-meta`
|
||||||
|
- `/nodeinfo/`, `/users/`, `/inbox`, `/actor`
|
||||||
|
- Pass `Host`, `X-Forwarded-For` and `X-Forwarded-Proto` through. The proto comes from an outer TLS proxy when there is one.
|
||||||
|
- The API trusts the UI proxy via `FORWARDED_ALLOW_IPS`.
|
||||||
|
- No changes to the UI's CSP: these are server-to-server requests.
|
||||||
|
- Compose adds the federation settings to `api` and `worker`, and `API_INTERNAL_URL` to `ui`.
|
||||||
|
|
||||||
|
## 7. Metrics and dashboard
|
||||||
|
|
||||||
|
- `federation/metrics.py` holds federation's own metrics:
|
||||||
|
- `scrobbler_federation_lookups_total{kind,result}`, where kind is `webfinger`, `actor`, `nodeinfo` or `profile`, and result is `found` or `not_found`
|
||||||
|
- `scrobbler_federation_sharing_changes_total{change}`, for `enabled` and `disabled`
|
||||||
|
- Request rate and latency come free from the existing HTTP metrics (endpoint label `federation.*`).
|
||||||
|
- A new **Federation** Grafana dashboard: lookups by kind and result, sharing changes, and federation endpoint latency. Phases 2 and 3 add delivery and inbox panels.
|
||||||
|
|
||||||
|
## 8. Tests
|
||||||
|
|
||||||
|
- **Protocol**: WebFinger parsing, including other domains, mixed case and garbage; JRD, actor and NodeInfo shapes; `Accept` negotiation.
|
||||||
|
- **Keys**: encryption round trip, the wrong secret failing, and keys staying stable across enable and disable.
|
||||||
|
- **Endpoints**, against a second session app with federation on, sharing the same database:
|
||||||
|
- opted-in users vs 404
|
||||||
|
- identical 404s for unknown and non-opted users
|
||||||
|
- the browser redirect to the profile page
|
||||||
|
- IDs built from config
|
||||||
|
- the 202 inbox stub
|
||||||
|
- **Settings API**: defaults (followers only, not discoverable), validation, and the public profile endpoint.
|
||||||
|
- **Still holding**: boundary tests, federation off meaning nothing is registered, and the OpenAPI drift test.
|
||||||
|
- **Manual pass**: Mastodon needs a public HTTPS domain. A tunnel (for example `cloudflared`) to a local stack, then searching the handle from a Mastodon account, confirms the profile and key resolve. GoToSocial in CI comes with phase 2.
|
||||||
|
|
||||||
|
## 9. Docs
|
||||||
|
|
||||||
|
- The federation README gains the proxy paths and `FEDERATION_KEY_SECRET`.
|
||||||
|
- The main README gets a "Sharing on the fediverse" section.
|
||||||
|
- The OpenAPI export is regenerated.
|
||||||
|
|
||||||
|
Commit after each numbered section once its tests pass.
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
# ActivityPub phase 2: followers
|
||||||
|
|
||||||
|
**Status: done** on `feature/activitypub` (`a6d3fb6` … `fe95f59`). The GoToSocial interop test passes locally and in CI. The manual pass with a real Mastodon account through a tunnel is also done: follow, unfollow, manual approval, and block/unblock all worked correctly.
|
||||||
|
|
||||||
|
Where this differed from the plan:
|
||||||
|
|
||||||
|
- **httpcore instead of httpx.** httpcore is the transport layer underneath httpx, and it publicly supports the custom network backend that connecting to a pre-checked address needs.
|
||||||
|
- **No in-process test with two Scrobbled instances.** Scrobbled can't initiate follows yet, so one instance has nothing to send the other. Scripted remote accounts over real HTTP cover the same paths, and GoToSocial is the real second server.
|
||||||
|
- **Undo of a Block.** Unblocking needed it: GoToSocial otherwise keeps the block.
|
||||||
|
|
||||||
|
This implements phase 2 of [activitypub.md](activitypub.md), building on [phase 1](activitypub-phase1.md).
|
||||||
|
|
||||||
|
**Outcome:** people on Mastodon, GoToSocial and similar servers can follow a user who shares. Follows are accepted automatically, or wait for the user's approval if they've turned it on. The user sees their followers and can approve, decline, remove or block them. Scrobbled signs everything it sends and checks the signature on everything it receives. Posts come in phase 3; this phase makes the relationship work end to end.
|
||||||
|
|
||||||
|
Everything below is inside `scrobbler.federation`, and the boundary tests keep holding. Federation off still means nothing is registered.
|
||||||
|
|
||||||
|
## 1. HTTP signatures (pure: `protocol/signatures/`)
|
||||||
|
|
||||||
|
- **`base.py`**:
|
||||||
|
- A `SignedRequest` value (method, URL, headers, body).
|
||||||
|
- A `SignatureScheme` interface with `sign(request, key_id, private_key)` and `verify(request, public_key_for) -> VerifiedSignature` (the key ID used and the scheme).
|
||||||
|
- `SignatureError` carries a machine-readable reason: `missing`, `malformed`, `expired`, `digest_mismatch`, `bad_signature` or `unsupported`.
|
||||||
|
- A registry keyed by scheme name.
|
||||||
|
- **`draft_cavage.py`**:
|
||||||
|
- **Signing** (the header shapes are in [Mastodon's security spec](https://docs.joinmastodon.org/spec/security/)):
|
||||||
|
- `Signature: keyId="…",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="…"`
|
||||||
|
- `Digest: SHA-256=<base64>` for POSTs
|
||||||
|
- `(request-target)` is the lowercase method plus path and query.
|
||||||
|
- **Verification**:
|
||||||
|
- accepts `rsa-sha256` and `hs2019`, which means RSA when the key is RSA
|
||||||
|
- for POSTs, requires `(request-target)`, `host`, `date` and `digest` to be signed
|
||||||
|
- `Date` within ±12 hours
|
||||||
|
- the digest must match the body
|
||||||
|
- **`rfc9421.py`**:
|
||||||
|
- **Signing**: `Signature-Input: sig1=("@method" "@target-uri" "content-digest");created=…;keyid="…";alg="rsa-v1_5-sha256"`, with `Signature: sig1=:…:` and `Content-Digest: sha-256=:<base64>:`.
|
||||||
|
- **Verification**:
|
||||||
|
- one signature
|
||||||
|
- `created` required and within the allowed skew
|
||||||
|
- `@method` and `@target-uri` covered, and `content-digest` too when there's a body
|
||||||
|
- A minimal parser for the RFC 8941 structured fields these headers use: inner lists, parameters and byte sequences.
|
||||||
|
- **Order**:
|
||||||
|
- Outgoing: `FEDERATION_SIGNATURE_SCHEMES` (default `draft-cavage,rfc9421`) sets the order schemes are tried. The first is used, and the next is tried only if a server answers 401, the same "double-knocking" Mastodon 4.7 does.
|
||||||
|
- Incoming: whichever scheme is present is verified.
|
||||||
|
- **Tests**:
|
||||||
|
- the published test vectors (draft-cavage appendix C; RFC 9421 appendix B for `rsa-v1_5-sha256`)
|
||||||
|
- sign-then-verify round trips for both schemes
|
||||||
|
- tampered body, method, path, date and headers
|
||||||
|
- expired and future dates, missing components, and a wrong key
|
||||||
|
|
||||||
|
## 2. Safe outbound HTTP and remote actors
|
||||||
|
|
||||||
|
- **New dependency**: `httpx` (BSD-3-Clause), for pooled clients, timeouts and response streaming.
|
||||||
|
- **`net.py`**, the only way federation code talks to other servers:
|
||||||
|
- **HTTPS only**.
|
||||||
|
- **SSRF protection**: a host's addresses are resolved once; the request is refused if any is loopback, private, link-local, multicast or otherwise reserved; and the connection goes to the checked address, using the original host name for SNI and `Host`. So a DNS change mid-request can't redirect it.
|
||||||
|
- At most 3 redirects, each checked the same way.
|
||||||
|
- Response bodies are capped at 1 MB.
|
||||||
|
- Timeouts: 10s to connect and 20s to read.
|
||||||
|
- A `User-Agent` of `Scrobbled/<version> (+<base url>)`.
|
||||||
|
- `signed_get(url, as_actor)`, which signs with the instance actor by default so "authorized fetch" servers answer; and `signed_post(inbox, activity, as_user)`.
|
||||||
|
- **`FEDERATION_INSECURE_TESTING=1`** is **for automated tests only**. It allows `http://` and private addresses. It's refused unless the domain ends in `.test` (a reserved top-level domain) and logs a warning every minute while on. It exists so CI can federate with GoToSocial on a private Docker network.
|
||||||
|
- **`remote.py`**: the remote-actor cache.
|
||||||
|
- `get_actor(uri, refresh=False)` fetches, validates and stores: the ID must equal the URI it was fetched from, the host must match, it must have an `inbox`, and `publicKey.owner` must equal the actor ID.
|
||||||
|
- `key_for(key_id)` maps a key ID (`…#main-key`, or a separate key document) to its owner and PEM.
|
||||||
|
- An actor is refreshed after 24 hours, or once immediately when a signature fails, in case the key was rotated.
|
||||||
|
|
||||||
|
## 3. Data (migration on the `federation` branch)
|
||||||
|
|
||||||
|
| Table | Holds |
|
||||||
|
|---|---|
|
||||||
|
| `federation_remote_actors` | URI, inbox, shared inbox, `preferredUsername`, host, display name, public key ID and PEM, `fetched_at`, `gone` |
|
||||||
|
| `federation_followers` | User, remote actor, state (`pending` or `accepted`), the Follow activity's ID and JSON, created and accepted times. Unique per user and actor. |
|
||||||
|
| `federation_blocks` | User and remote actor, or a whole domain. Operator domain blocks come from `FEDERATION_BLOCKED_DOMAINS`, not this table. |
|
||||||
|
| `federation_inbox` | Received deliveries: raw headers (a fixed allow-list), body, the inbox path, `received_at`, status (`queued`, `processed`, `rejected` or `failed`), reason, and the activity ID (unique, for deduplication). Pruned after 30 days. |
|
||||||
|
| `federation_activities` | Activities we send: UUID, user, type, JSON, and `created_at`. Dereferenceable at `/activities/<uuid>` when public, so it can be the outbox's source in phase 3. |
|
||||||
|
| `federation_deliveries` | Activity × inbox: status (`pending`, `delivered`, `failed` or `abandoned`), `attempts`, `next_attempt_at`, the last status code and error |
|
||||||
|
|
||||||
|
## 4. Inbox intake (`web.py`) and processing (a worker task)
|
||||||
|
|
||||||
|
- **Intake stays network-free.** `POST /inbox` and `POST /users/<u>/inbox` check the size (256 KB), the content type and that the JSON has `type`, `actor` and `id`, then store the delivery and answer **202**.
|
||||||
|
- Deliveries from blocked domains are refused with 403.
|
||||||
|
- Repeated activity IDs are acknowledged but not stored again.
|
||||||
|
- The UI's nginx rate-limits the inbox paths per client IP (`limit_req`), as a first defence.
|
||||||
|
- **The `federation.inbox` worker task** processes queued deliveries, oldest first:
|
||||||
|
1. **Check the signature** with the scheme present, fetching the key through `remote.key_for`.
|
||||||
|
- On failure, it refreshes the actor once and retries.
|
||||||
|
- Then it rejects with a reason, which is counted in metrics.
|
||||||
|
2. **Check it's who they say.** The signing key's owner must equal the activity's `actor`, and the activity ID's host must equal the actor's host.
|
||||||
|
3. **Dispatch** to a handler registered by activity type:
|
||||||
|
|
||||||
|
| Activity | Handling |
|
||||||
|
|---|---|
|
||||||
|
| `Follow` (object = a sharing user) | Store the follower. If manual approval is on, keep it `pending`; otherwise mark it `accepted` and queue an `Accept`. If already accepted (a repeat Follow), queue an `Accept` again. |
|
||||||
|
| `Undo` of a `Follow` | Remove the follower. The Undo must come from the same actor as the Follow. |
|
||||||
|
| `Delete` of an actor | Remove it from every user's followers and mark the cached actor gone. |
|
||||||
|
| `Update` of a `Person` or `Service` | Refresh the cached actor. |
|
||||||
|
| `Accept` or `Reject` | Recorded; nothing to do until we follow people. |
|
||||||
|
| `Like`, `Announce`, `Create` | Recorded for metrics only. |
|
||||||
|
| Anything else | Recorded as unsupported. |
|
||||||
|
|
||||||
|
- **A delivery that errors unexpectedly** is retried twice and then marked `failed` with the error. The worker never stops over it.
|
||||||
|
|
||||||
|
## 5. Sending: activities and deliveries
|
||||||
|
|
||||||
|
- `activities.py` builds and stores our activities:
|
||||||
|
- **`Accept(Follow)`**: the object is the original Follow, embedded.
|
||||||
|
- **`Reject(Follow)`**: used both to decline a request and to remove an existing follower. Mastodon drops the relationship on either.
|
||||||
|
- **`Block`**: sent when a user blocks a follower.
|
||||||
|
- **Fan-out** turns an activity into delivery rows, one per distinct inbox. Replies to a Follow go to the follower's own inbox.
|
||||||
|
- **The `federation.deliver` worker task**:
|
||||||
|
- Sends pending deliveries whose time has come, with signed POSTs through `net.signed_post`, trying the next scheme on a 401.
|
||||||
|
- **Retries**: 1m, 5m, 30m, 2h, 6h, then every 12h, **abandoning after 2 days**.
|
||||||
|
- No retry after a 4xx, except 401, 408 and 429.
|
||||||
|
- **410 Gone** from an actor's inbox removes that follower.
|
||||||
|
- It runs several deliveries at once (a bounded thread pool, default 4) and processes at most 50 per pass, so the worker stays responsive.
|
||||||
|
- **Actor changes**:
|
||||||
|
- The actor now reflects the user's real `manually_approves_followers` setting; phase 1 always said true.
|
||||||
|
- The followers collection's `totalItems` is the accepted-follower count.
|
||||||
|
- **Turning sharing off** queues a `Reject` for every follower, then removes them.
|
||||||
|
|
||||||
|
## 6. Managing followers (API and UI)
|
||||||
|
|
||||||
|
- **API** (bearer auth, under `/api/v1/federation`, documented in OpenAPI):
|
||||||
|
- `GET /followers?state=accepted|pending`, returning handle, display name, actor URL, server and since when.
|
||||||
|
- `POST /followers/{id}/approve`, which sends `Accept`.
|
||||||
|
- `POST /followers/{id}/decline` and `POST /followers/{id}/remove`, which send `Reject`.
|
||||||
|
- `POST /followers/{id}/block`, which sends `Block` and remembers it.
|
||||||
|
- `GET /blocks` and `DELETE /blocks/{id}` to see and undo blocks. Unblocking doesn't restore the follow.
|
||||||
|
- The settings response gains accepted and pending follower counts.
|
||||||
|
- **UI**:
|
||||||
|
- A new `followers.html` shows requests (Approve / Decline) above followers (Remove / Block, each with a confirm step), and blocked accounts at the bottom.
|
||||||
|
- Remote names are shown **as plain text only**; no remote HTML or images in this phase.
|
||||||
|
- The Sharing page shows the follower count and links to the Followers page.
|
||||||
|
- The "following arrives later" note goes.
|
||||||
|
|
||||||
|
## 7. Configuration
|
||||||
|
|
||||||
|
| Variable | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `FEDERATION_SIGNATURE_SCHEMES` | Outgoing order; default `draft-cavage,rfc9421` |
|
||||||
|
| `FEDERATION_BLOCKED_DOMAINS` | Comma-separated domains (subdomains included) whose deliveries are refused and whose follows are rejected |
|
||||||
|
| `FEDERATION_DELIVERY_CONCURRENCY` | Parallel deliveries in the worker (default 4) |
|
||||||
|
| `FEDERATION_INSECURE_TESTING` | Tests only; see §2 |
|
||||||
|
|
||||||
|
## 8. Metrics, dashboard and alerts
|
||||||
|
|
||||||
|
- **Metrics**:
|
||||||
|
- `scrobbler_federation_inbox_activities_total{type,result}`, where result is `processed`, `rejected`, `duplicate`, `blocked` or `failed`
|
||||||
|
- `scrobbler_federation_signatures_total{direction,scheme,result}`, where result is `ok` or a `SignatureError` reason
|
||||||
|
- `scrobbler_federation_deliveries_total{result}`: `delivered`, `retry`, `abandoned`, `gone`
|
||||||
|
- `scrobbler_federation_delivery_seconds` (a histogram)
|
||||||
|
- `scrobbler_federation_queue{queue,status}`, a gauge set by the worker for the inbox and delivery queues
|
||||||
|
- `scrobbler_federation_followers{state}`, a gauge set by the worker
|
||||||
|
- **Federation dashboard** gains:
|
||||||
|
- inbox activity by type and result
|
||||||
|
- signature failures by reason
|
||||||
|
- delivery outcomes and latency
|
||||||
|
- queue depths
|
||||||
|
- follower totals
|
||||||
|
- **Alerts**:
|
||||||
|
- `FederationDeliveryBacklog`: more than 100 pending deliveries for 30 minutes
|
||||||
|
- `FederationInboxBacklog`: queued inbox items for 15 minutes
|
||||||
|
- `FederationSignatureFailures`: more than 20% of incoming signatures failing for 15 minutes
|
||||||
|
|
||||||
|
## 9. Tests
|
||||||
|
|
||||||
|
- **Unit tests**:
|
||||||
|
- signatures (§1)
|
||||||
|
- the SSRF guard: private and reserved IPs, `http`, redirects to private addresses, the oversized-body cap and timeouts
|
||||||
|
- remote-actor validation: ID mismatch, key owner mismatch, a missing inbox
|
||||||
|
- each inbox handler
|
||||||
|
- the retry schedule and 4xx/410 handling
|
||||||
|
- addressing
|
||||||
|
- **In-process federation**: two federation-enabled apps with different `.test` domains serving each other over real HTTP in the test process, with insecure testing on. Scripted remote actors cover the full path: follow → signature check → Accept delivered and verified by the "remote" → Undo. Also covered:
|
||||||
|
- manual approval
|
||||||
|
- decline, remove and block
|
||||||
|
- repeat Follow
|
||||||
|
- bad signatures rejected with the right reason
|
||||||
|
- a blocked domain
|
||||||
|
- turning sharing off
|
||||||
|
- **A real peer in CI**: a new `federation-interop` job runs Scrobbled (API, worker and UI) and a GoToSocial container on one Docker network. The hosts are `scrobble.test` and `gts.test`, over HTTP, with each side's test-only settings. A script:
|
||||||
|
1. creates a GoToSocial user with its admin CLI,
|
||||||
|
2. gets a user token by driving GoToSocial's sign-in and OAuth screens with plain HTTP (this part gets a short spike first, since GoToSocial has no password grant),
|
||||||
|
3. follows `@alice@scrobble.test`, and checks it's accepted,
|
||||||
|
4. unfollows, and checks it's gone,
|
||||||
|
5. with manual approval on, checks the request waits until approved through Scrobbled's API.
|
||||||
|
|
||||||
|
The job posts to ntfy like every other job. It doesn't run on pull requests from forks.
|
||||||
|
- **Manual pass before merging**: follow and unfollow from a real Mastodon account through a tunnel.
|
||||||
|
|
||||||
|
## 10. Docs
|
||||||
|
|
||||||
|
- Update the README and the federation README: following now works, the new settings, and the operator domain blocks.
|
||||||
|
- Regenerate the OpenAPI export.
|
||||||
|
- Mark this plan done.
|
||||||
|
|
||||||
|
## Order of work (a commit per step once its tests pass)
|
||||||
|
|
||||||
|
1. Signatures, pure, with test vectors
|
||||||
|
2. `net.py` and the remote-actor cache
|
||||||
|
3. Tables and migration
|
||||||
|
4. Inbox intake and processing, with handlers
|
||||||
|
5. Outgoing activities and the delivery task
|
||||||
|
6. Follower management API and UI; the actor reflects the approval setting; turning sharing off
|
||||||
|
7. Metrics, dashboard and alerts
|
||||||
|
8. In-process federation tests, and the GoToSocial CI job
|
||||||
|
9. Docs
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- **Licences**:
|
||||||
|
- `httpx` is BSD-3-Clause and `cryptography` is Apache-2.0/BSD.
|
||||||
|
- GoToSocial is AGPL, but it runs only as a separate container in CI to test against. Nothing of it is linked into, or shipped with, Scrobbled, so it has no effect on Scrobbled's licence.
|
||||||
|
- **Scale**: this is the biggest phase, and signatures plus safe outbound HTTP are where the risk lies. They come first and have the most thorough tests.
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
# ActivityPub phase 3: posts
|
||||||
|
|
||||||
|
**Status: done** on `feature/activitypub` (`bc717c2` … `860d4d0`). The GoToSocial interop test now covers posts too: a weekly summary reaches a follower's home timeline as `private` with the expected content, and disappears from it when deleted. The manual pass with a real Mastodon account through a tunnel (done alongside phase 4's, see its notes) confirmed a forced weekly summary posted and deleted correctly there too.
|
||||||
|
|
||||||
|
Where this differed from the plan:
|
||||||
|
|
||||||
|
- **A top-10 entry needs a real top 10 first.** With fewer than `TOP_N` distinct artists, every first play of a new artist would trivially "enter the top 10" — caught by a test that used the real (unpatched) thresholds instead of always overriding them down for speed. Nothing is posted until a user actually has that many distinct artists.
|
||||||
|
- **`post_now()` is a separate path from the normal check.** `flask federation post-weekly --now` and the Sharing page's preview both need the week still *in progress*, not the last one whose Monday-09:00 gate has passed; they share the posting logic (`_post_for_window`) with the normal `check_and_post`, but compute a different window.
|
||||||
|
- **The Note's `url` needed the username, not just the post's id.** `post.html` (the UI page a browser lands on) has no other way to know whose post to look up; caught while wiring up the UI, not by a test written against the plan.
|
||||||
|
|
||||||
|
This implements phase 3 of [activitypub.md](activitypub.md): **weekly summaries** and **milestones**. Now playing is phase 4. It builds on [phase 2](activitypub-phase2.md): followers, signed delivery and retries.
|
||||||
|
|
||||||
|
**Outcome:**
|
||||||
|
|
||||||
|
- A user who shares gets two kinds of post, delivered to their followers: a summary of the past week, every Monday morning in their own time zone, and occasional milestone posts.
|
||||||
|
- Posts are **followers only by default**, following the user's visibility setting.
|
||||||
|
- Each kind can be switched off, and any post can be deleted. Turning sharing off deletes the posts from followers' servers.
|
||||||
|
- Existing history never produces posts retroactively.
|
||||||
|
|
||||||
|
Everything is in `scrobbler.federation` except one small addition to the core stats service (§1), and the boundary tests keep holding.
|
||||||
|
|
||||||
|
## 1. Core: stats over a date range
|
||||||
|
|
||||||
|
- `services.stats` gains top artists, top tracks and play counts for an explicit window (`start`, `end`). Today it only knows the rolling periods (`7day` and so on).
|
||||||
|
- The existing functions keep working, re-expressed on top of the window version. This is a core change and is tested like one. Federation uses it through the public service, as the boundary rules require.
|
||||||
|
|
||||||
|
## 2. Settings and data (migration on the `federation` branch)
|
||||||
|
|
||||||
|
- **`federation_settings` gains:**
|
||||||
|
- `timezone`: an IANA name such as `Europe/London`, validated with `zoneinfo`. The Sharing page fills it in from the browser the first time.
|
||||||
|
- `post_weekly_summary`: default on.
|
||||||
|
- `post_milestones`: default on.
|
||||||
|
- **`federation_posts`**, one row per post:
|
||||||
|
- user, `kind` (`weekly` or `milestone`)
|
||||||
|
- `key`, unique per user, e.g. `weekly:2026-W39` or `milestone:scrobbles:10000`
|
||||||
|
- the Note's UUID, the visibility it was sent with, plain-text and HTML content
|
||||||
|
- `created_at`, and `deleted_at` (a tombstone)
|
||||||
|
|
||||||
|
The unique key makes posting **idempotent**: a worker restart or a repeated check can never post twice.
|
||||||
|
- **`federation_milestone_marks`**: user plus key, with `posted` true or false. It records thresholds already passed, including ones deliberately *not* posted (see §5).
|
||||||
|
- **`federation_pending_checks`**: user, `since`, `reason`. It's a small queue, filled by event receivers (§5), so receivers never do real work inside a scrobble request.
|
||||||
|
|
||||||
|
## 3. Vocabulary (pure: `protocol/vocab.py`)
|
||||||
|
|
||||||
|
- **`note(...)`**: a `Note` with:
|
||||||
|
- `id`, `attributedTo`, `content` (HTML) plus `contentMap` (`{"en": …}`)
|
||||||
|
- `published`, `url` (the UI post page)
|
||||||
|
- `to` and `cc` from the visibility setting
|
||||||
|
- `tag` (`Hashtag` objects: `#Scrobbled`, and `#NowPlaying` in phase 4)
|
||||||
|
- `sensitive: false`
|
||||||
|
- **`create(...)`**: `Create` wrapping the Note, with the same addressing.
|
||||||
|
- **`delete(...)`**: `Delete` whose object is a `Tombstone` of the Note (the same shape Mastodon sends).
|
||||||
|
- **`ordered_collection_page(...)`**, used for outbox paging.
|
||||||
|
- **Addressing** comes from one function (`protocol/addressing.py`), unit-tested for each visibility:
|
||||||
|
- followers only: `to` followers, no `cc`
|
||||||
|
- unlisted: `to` followers, `cc` Public
|
||||||
|
- public: `to` Public, `cc` followers
|
||||||
|
- The HTML uses only tags Mastodon keeps (`p`, `br`, `strong`, `em`, `ol`, `li`), and every artist and track name is escaped. A formatting test covers awkward names (`<script>`, `&`, emoji, right-to-left text).
|
||||||
|
|
||||||
|
## 4. Publishing core (`federation/publishing/`)
|
||||||
|
|
||||||
|
- **`base.py`**: `publish(user, kind, key, text, html)`:
|
||||||
|
1. Refuse if the key already exists, or if the user has stopped sharing.
|
||||||
|
2. Store the post.
|
||||||
|
3. Build `Create(Note)` with the user's current visibility, and store it as an activity, marked public when the visibility isn't followers only.
|
||||||
|
4. Fan out one delivery per **distinct shared inbox** of the accepted followers (their own inbox when they have no shared one).
|
||||||
|
|
||||||
|
Everything happens in one transaction; the existing delivery task sends it.
|
||||||
|
- **Post kinds are plug-ins.** `weekly.py` and `milestones.py` each register a kind with its settings flag, and phase 4's now playing will slot in the same way.
|
||||||
|
- **`delete_post(user, post)`**: sends `Delete(Tombstone)` to the same inboxes, marks the post deleted, and keeps the row so the key can't be reused.
|
||||||
|
- **Turning sharing off** now sends `Delete` for every live post *before* the Rejects (phase 2), in the same fan-out. The farewell actor (phase 2) stays up until those are delivered too.
|
||||||
|
|
||||||
|
## 5. The two kinds
|
||||||
|
|
||||||
|
**Weekly summary** (`publishing/weekly.py`, worker task `federation.weekly`, every 15 minutes):
|
||||||
|
|
||||||
|
- For each sharing user with summaries on:
|
||||||
|
- once it's past **Monday 09:00 in their time zone**,
|
||||||
|
- if `weekly:<ISO year-week of the week just ended>` doesn't exist yet,
|
||||||
|
- build the summary from **Monday 00:00 to Sunday 24:00 local time** (correct across daylight-saving changes, since the boundaries are computed in their zone and converted to UTC).
|
||||||
|
- **Skipped** if the week had no plays; a `skipped` mark is kept so it isn't reconsidered.
|
||||||
|
- **Catch-up:** only the most recent week is posted. A worker that was down for three weeks posts one summary, not three.
|
||||||
|
- Example text (plain text shown; the HTML version has the same content):
|
||||||
|
|
||||||
|
> **My week in music: 312 plays**
|
||||||
|
> Top artists: 1. Radiohead (48) 2. Björk (31) 3. Portishead (22)
|
||||||
|
> Most played: *Reckoner* by Radiohead (12 plays)
|
||||||
|
> #Scrobbled
|
||||||
|
|
||||||
|
**Milestones** (`publishing/milestones.py`, worker task `federation.milestones`):
|
||||||
|
|
||||||
|
- **Rules:**
|
||||||
|
- **Scrobble count**: 1,000, 5,000 and 10,000, then every 25,000.
|
||||||
|
- **An artist's plays**: 100 and 500 (and 1,000).
|
||||||
|
- **All-time top 10**: an artist enters it for the first time.
|
||||||
|
- **Detection is cheap and off the request path.**
|
||||||
|
- The `scrobbles_stored` receiver (live scrobbles only, `source="scrobble"`) just upserts a pending check for the user.
|
||||||
|
- The worker task then compares current totals with the marks and posts at most **one milestone per check**, the most notable, so a single batch can't spam followers.
|
||||||
|
- **No retroactive posts:**
|
||||||
|
- When a user **turns sharing on**, every threshold they've already passed is marked `posted=false`.
|
||||||
|
- When an **import finishes** (`import_finished`), the same happens: imported history moves the baseline silently. Imported plays therefore never trigger milestone posts, even if a live scrobble crosses a line soon after.
|
||||||
|
- Example: *"10,000 plays on Scrobbled 🎉"* or *"Björk just joined my all-time top 10 (at #7)"*.
|
||||||
|
|
||||||
|
## 6. Endpoints (served on the UI domain, documented in OpenAPI)
|
||||||
|
|
||||||
|
- **`GET /users/<u>/outbox`**: now paged, as an `OrderedCollection` with `first`, and `OrderedCollectionPage`s of 20, newest first.
|
||||||
|
- It holds the user's **public and unlisted** `Create`s only.
|
||||||
|
- Followers-only posts are never listed, since this is unauthenticated.
|
||||||
|
- **`GET /users/<u>/posts/<uuid>`**: the Note, for public and unlisted posts. Followers-only and deleted posts return 404 for now; Mastodon receives them by delivery, and signed fetches by followers can come later.
|
||||||
|
- `/activities/<uuid>` already serves public `Create`s.
|
||||||
|
- A browser (no ActivityPub `Accept`) is redirected to the UI post page.
|
||||||
|
- **`/api/v1/federation`**, bearer auth:
|
||||||
|
- `GET /posts`: the user's posts, newest first, with kind, text, visibility, created and deleted.
|
||||||
|
- `DELETE /posts/{id}`: sends `Delete` and tombstones the post.
|
||||||
|
- `GET /preview/weekly`: renders what the next weekly summary would say, from the current partial week, without posting.
|
||||||
|
- The settings gain `timezone`, `post_weekly_summary` and `post_milestones`.
|
||||||
|
|
||||||
|
## 7. Web UI
|
||||||
|
|
||||||
|
- **Sharing page**, a new **What to post** section:
|
||||||
|
- on/off switches for **Weekly summary** and **Milestones**
|
||||||
|
- a **time zone** picker (defaulting to the browser's), with "Summaries are posted on Monday mornings in this time zone"
|
||||||
|
- **Preview this week's summary**, which shows the text it would post now
|
||||||
|
- **A Posts list** (on the Followers page, or its own page if it's long): recent posts with their visibility and a **Delete** button behind a confirmation. Deleted posts are shown struck through for a while.
|
||||||
|
- **`post.html?id=…`**: a public page for a post, where browsers land from a Note URL. It shows the text for public and unlisted posts, and "only visible to followers" otherwise.
|
||||||
|
|
||||||
|
## 8. Metrics, dashboard and alerts
|
||||||
|
|
||||||
|
- **Metrics:**
|
||||||
|
- `scrobbler_federation_posts_total{kind,visibility}`
|
||||||
|
- `scrobbler_federation_post_deletions_total{reason}`, where reason is `user` or `sharing_off`
|
||||||
|
- `scrobbler_federation_milestone_checks_total{result}`: `posted`, `none`, `baseline`
|
||||||
|
- `scrobbler_federation_weekly_total{result}`: `posted`, `skipped_empty`, `disabled`
|
||||||
|
- **Federation dashboard, new "Posts" row:** posts by kind, deletions, weekly results, milestone checks, and the delivery fan-out size per post (a histogram).
|
||||||
|
- **Alert**, `FederationWeeklySummariesMissing`: on a Monday after 12:00 UTC, no `weekly` results at all in the last 6 hours even though users are sharing. That means the task isn't running. It's evaluated only on Mondays, so it can't fire on quiet days.
|
||||||
|
|
||||||
|
## 9. Tests
|
||||||
|
|
||||||
|
- **Stats window (core):** week boundaries, the rolling periods still behaving as before.
|
||||||
|
- **Vocabulary and addressing:** Note, Create and Delete shapes; each visibility's `to`/`cc`; HTML escaping of hostile names.
|
||||||
|
- **Weekly scheduling:**
|
||||||
|
- Monday 08:59 vs 09:00 in several zones (`Pacific/Auckland`, `America/Los_Angeles`, `Europe/London` across a DST change)
|
||||||
|
- ISO weeks at a year boundary
|
||||||
|
- an empty week skipped
|
||||||
|
- posting twice impossible
|
||||||
|
- three missed weeks give one post
|
||||||
|
- summaries switched off
|
||||||
|
- **Milestones:**
|
||||||
|
- each rule
|
||||||
|
- one post per check
|
||||||
|
- live scrobbles only
|
||||||
|
- the import baseline and the enable-sharing baseline (no retroactive posts)
|
||||||
|
- idempotence
|
||||||
|
- **Fan-out:** accepted followers only, one delivery per shared inbox, pending followers excluded.
|
||||||
|
- **Outbox and Note endpoints:** paging, only public and unlisted listed, followers-only and deleted Notes 404, the browser redirect.
|
||||||
|
- **Deleting:** a single post, and all posts plus Rejects when sharing is turned off, with the farewell actor serving until delivered.
|
||||||
|
- **Interop (GoToSocial):**
|
||||||
|
- a new admin command `flask federation post-weekly --user <name> --now` (for operators too) posts immediately
|
||||||
|
- the driver checks the post reaches the GoToSocial follower's home timeline with visibility `private` (followers only) and the expected text
|
||||||
|
- then deletes it and checks it's gone there too
|
||||||
|
|
||||||
|
## 10. Docs
|
||||||
|
|
||||||
|
- README: what gets posted, and the settings.
|
||||||
|
- Federation README: the publishing plug-ins.
|
||||||
|
- Regenerate the OpenAPI export.
|
||||||
|
- Mark this plan done.
|
||||||
|
|
||||||
|
## Order of work (a commit per step once its tests pass)
|
||||||
|
|
||||||
|
1. Core stats windows
|
||||||
|
2. Settings columns, posts, marks and pending-checks tables
|
||||||
|
3. Vocabulary and addressing
|
||||||
|
4. Publishing core (publish, fan-out, delete) and deleting posts when sharing is turned off
|
||||||
|
5. Weekly summary task
|
||||||
|
6. Milestones (receivers, task, baselines)
|
||||||
|
7. Outbox paging and Note endpoints
|
||||||
|
8. API and web UI
|
||||||
|
9. Metrics, dashboard and alert
|
||||||
|
10. Admin command and interop checks
|
||||||
|
11. Docs
|
||||||
|
|
||||||
|
## Defaults I've chosen (easy to change)
|
||||||
|
|
||||||
|
| Choice | Default |
|
||||||
|
|---|---|
|
||||||
|
| When weekly summaries post | Monday 09:00 in the user's time zone, for the Monday–Sunday just ended |
|
||||||
|
| Milestone thresholds | Plays: 1k, 5k, 10k, then every 25k. An artist's plays: 100, 500, 1k. New artist in the all-time top 10 |
|
||||||
|
| Posts per milestone check | At most one (the most notable) |
|
||||||
|
| Post language | English only for now (`contentMap.en`) |
|
||||||
|
| Hashtag | `#Scrobbled` on every post |
|
||||||
|
| Deleting individual posts | Allowed, from the web UI |
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
# ActivityPub phase 4: now playing
|
||||||
|
|
||||||
|
**Status: done** on `feature/activitypub` (`7d86bad` … `9883111`, plus a `docker-compose.yml` fix from the manual pass below). The GoToSocial interop test now covers now playing too: turning it on updates the "Now playing" field GoToSocial has cached for the profile, via the periodic `Update(Person)` push - not just a fresh fetch showing the live truth, which was already covered by the actor route's own tests.
|
||||||
|
|
||||||
|
The manual pass with a real Mastodon account through a tunnel (the last standing gap after every phase) is also done now, covering phases 1-4 together: WebFinger, actor and follow/unfollow/approve/block against mastodon.social and activitypub.academy over a `cloudflared` tunnel, a forced weekly summary posting and deleting correctly, and the now-playing profile field appearing, clearing, and respecting the 5-minute push throttle.
|
||||||
|
|
||||||
|
Where this differed from the plan:
|
||||||
|
|
||||||
|
- **The now-playing key had to be hashed, not raw.** `artist\x1ftrack\x1fstarted_at` was going straight into `federation_posts.key` (`VARCHAR(64)`), which real track and artist names routinely overflow. Caught by the first Postgres-backed test that used a real track name, not by anything in the plan itself.
|
||||||
|
- **`now_playing_field()` needed its own privacy gate.** It read core's `now_playing` table (populated for every user regardless of federation settings) without checking `now_playing_mode` itself, so a user who'd never turned the feature on at all would still leak what they were listening to if a caller forgot to gate it externally. Found while designing the periodic push task, not by a test written against the plan - the existing tests happened to never combine "something playing" with "mode off". Fixed by moving the gate inside `now_playing_field()` itself, so there's exactly one place that can get this wrong.
|
||||||
|
- **`docker-compose.yml` hardcoded the API's `CORS_ORIGINS` to `UI_BASE_URL`.** Found during the manual pass: pointing `UI_BASE_URL` at the tunnel host (needed for federation's own identity) silently changed which browser origins the API accepted, blocking the operator's own `localhost:8080` UI from calling it at all - an `.env` `CORS_ORIGINS` setting had no effect, since the compose file never referenced it. Fixed by making `CORS_ORIGINS` its own variable, defaulting the same as before.
|
||||||
|
- **`TestConfig` wasn't isolating `UI_BASE_URL`/`CORS_ORIGINS` either.** The same local `.env` change broke six tests that assert on `http://localhost:8080` URLs, the same way an earlier session found `FEDERATION_ENABLED`/`LASTFM_API_KEY` leaking from a developer's `.env` into the test run. Pinned alongside them.
|
||||||
|
|
||||||
|
This implements phase 4 of [activitypub.md](activitypub.md): **now playing**, the last of the "still open" decisions there. It builds on [phase 3](activitypub-phase3.md): publishing, delivery and the web UI for posts.
|
||||||
|
|
||||||
|
Chosen (of the doc's three options): **profile field, plus opt-in posts** — the profile field is what a user gets as soon as they turn now playing on at all; posts are a further, separate opt-in on top of that, matching the doc's own "profile field mode, then optional posts" framing.
|
||||||
|
|
||||||
|
**Outcome:**
|
||||||
|
|
||||||
|
- A sharing user can turn now playing on. While something is genuinely playing, their fediverse profile shows a "Now playing: *Track* by Artist" field, refreshed automatically and cleared a few minutes after playback stops.
|
||||||
|
- If they also opt into posts, each track they play for at least 30 seconds gets a post to their followers (at most one every 30 minutes), with the previous now-playing post deleted when a new one goes out — so at most one exists at a time.
|
||||||
|
- Nothing here is retroactive or history-based: it only ever reflects what's playing *right now*, so there's no baseline/import concern like milestones has.
|
||||||
|
|
||||||
|
Everything is in `scrobbler.federation`, using the core's existing `services.scrobbles.get_now_playing()` (no core changes needed this time), and the boundary tests keep holding.
|
||||||
|
|
||||||
|
## 1. Settings and data (migration on the `federation` branch)
|
||||||
|
|
||||||
|
- **`federation_settings` gains `now_playing_mode`**: `off` (default), `profile`, or `posts`. Validated the same way `visibility` is.
|
||||||
|
- **`federation_now_playing`**, one row per user, the state of what Scrobbled has last told the fediverse (as opposed to `now_playing` in core, which is what's actually playing):
|
||||||
|
- `profile_key` (nullable) and `profile_updated_at` (nullable): what the last `Update(Person)` said, and when it was sent
|
||||||
|
- `post_key` (nullable) and `post_posted_at` (nullable): the key of the last now-playing post, and when
|
||||||
|
|
||||||
|
A "key" is `artist\x1ftrack\x1fstarted_at` — including `started_at` means playing the same track again later is a genuinely new now-playing moment, not a stale repeat, and it's what `federation_posts.key` uses too (so posting is idempotent through the same unique-constraint mechanism phase 3 already has, no new machinery needed).
|
||||||
|
|
||||||
|
## 2. Vocabulary (pure: `protocol/vocab.py`)
|
||||||
|
|
||||||
|
- **`update(activity_id, actor_id, actor_object)`**: wraps a document as an `Update`, addressed the same way `undo()` already does (mirrors its shape).
|
||||||
|
- **`person(...)` already takes `fields`** (phase 1): a "Now playing" field is just one more `(name, value)` pair, `"Track by Artist"`.
|
||||||
|
- Now-playing posts reuse the existing `note()`/`create()` builders from phase 3, tagged `#NowPlaying` in addition to `#Scrobbled` (already anticipated in the phase 3 plan's vocabulary notes).
|
||||||
|
|
||||||
|
## 3. Live actor vs. pushed updates
|
||||||
|
|
||||||
|
Two different questions, answered two different ways:
|
||||||
|
|
||||||
|
- **`GET /users/<u>` (a pull)** always reflects the truth *right now*: it reads `get_now_playing()` directly and adds the field only while something unexpired is playing. No throttling — a fresh fetch should never lie.
|
||||||
|
- **`Update(Person)` (a push)**, telling already-following servers proactively so they don't have to poll, is throttled to **once every 5 minutes** (`federation_now_playing.profile_updated_at`). A server that fetches in between sees the live truth anyway via the pull path above; the push is purely so it doesn't have to.
|
||||||
|
|
||||||
|
This split means a fast-changing "now playing" never spams followers' inboxes, while the profile itself is never stale to a server that asks.
|
||||||
|
|
||||||
|
## 4. `publishing/now_playing.py`
|
||||||
|
|
||||||
|
A periodic worker task (`federation.now_playing`, every 30 seconds — well under both throttle windows, so they stay the binding constraint) checks every sharing user with `now_playing_mode != "off"`:
|
||||||
|
|
||||||
|
1. Read `get_now_playing(user)` (core service; federation reaches it through `scrobbler.services.scrobbles`, already inside the public surface) and compute `current_key` (`None` if nothing's playing or it's expired).
|
||||||
|
2. **Profile** (mode `profile` or `posts`): if `current_key != federation_now_playing.profile_key` and at least 5 minutes have passed since `profile_updated_at` (or it's never been sent), build the actor document with (or without) the now-playing field and send `Update(Person)` to accepted followers' inboxes. Update the stored key and timestamp either way the check runs, so a change that arrives mid-throttle isn't retried every 30 seconds — only reconsidered once the throttle clears.
|
||||||
|
3. **Posts** (mode `posts` only): if `current_key` is set, has been playing for **at least 30 seconds**, differs from `federation_now_playing.post_key`, and at least 30 minutes have passed since `post_posted_at` (or never posted): publish a `now_playing` post (through the same `publishing.publish()` as weekly/milestones — idempotent on `now_playing:<key>`), then delete the previous now-playing post if one exists, and update the stored key and timestamp.
|
||||||
|
|
||||||
|
No event receiver, no pending-checks queue: unlike milestones, now playing doesn't need to react within a scrobble request, and the throttle windows (5 and 30 minutes) are so much longer than a 30-second poll that a periodic scan (the same shape as `weekly.check_all`) is simplest and cheapest.
|
||||||
|
|
||||||
|
## 5. Endpoints
|
||||||
|
|
||||||
|
- **`GET /users/<u>`**: gains the live now-playing field (§3). No new endpoint.
|
||||||
|
- **`GET /users/<u>/outbox`, `GET /users/<u>/posts/<uuid>`, `/api/v1/federation/posts`, `DELETE /posts/{id}`**: unchanged — `now_playing` posts are just another `kind` in `federation_posts`, so they already show up everywhere phase 3's post endpoints look.
|
||||||
|
- **`/api/v1/federation/settings`**: gains `now_playing_mode`.
|
||||||
|
|
||||||
|
## 6. Web UI
|
||||||
|
|
||||||
|
- **Sharing page**, a new **Now playing** section: off / profile field / profile field + posts, as a single choice (matching the settings column), with a one-line explanation of the 5-minute and 30-minute throttles.
|
||||||
|
- **Posts page**: `now_playing` posts show there like any other kind (already handled generically).
|
||||||
|
- **Profile page**: shows the "Now playing" field when the profile response includes it (the public profile API already returns arbitrary settings-derived fields; this adds one, read from the same live path as the actor document).
|
||||||
|
|
||||||
|
## 7. Metrics, dashboard
|
||||||
|
|
||||||
|
- `scrobbler_federation_profile_updates_total{result}`: `sent` or `throttled`. (Posts already get `scrobbler_federation_posts_total{kind="now_playing",visibility}` for free, phase 3's existing metric.)
|
||||||
|
- Federation dashboard: a panel on the existing "Posts" row for profile updates/min, and the `kind="now_playing"` series already shows up in the existing posts-by-kind panel without changes.
|
||||||
|
|
||||||
|
## 8. Tests
|
||||||
|
|
||||||
|
- **Vocabulary**: `update()` shape.
|
||||||
|
- **Actor document**: the live now-playing field appears while playing, is absent once expired, absent when off.
|
||||||
|
- **`now_playing.py`**:
|
||||||
|
- profile update sent on a genuine change, throttled within 5 minutes, cleared when playback stops
|
||||||
|
- post sent only after 30 seconds played, throttled within 30 minutes, previous post deleted when a new one goes out
|
||||||
|
- `profile` mode never posts; `off` mode does nothing at all
|
||||||
|
- idempotence (the same key never posted twice, matching phase 3's pattern)
|
||||||
|
- **Settings API**: `now_playing_mode` validation and round-trip.
|
||||||
|
- **Interop (GoToSocial)**: extends the existing driver — now playing is turned on, a track is set as playing, and the test confirms GoToSocial's resolved account shows the "Now playing" field after the next `Update(Person)`; posts aren't re-tested here since they go through the same publish/delivery path phase 3 already covers end to end.
|
||||||
|
|
||||||
|
## 9. Docs
|
||||||
|
|
||||||
|
- README: the now-playing section, its modes and throttles.
|
||||||
|
- Federation README: `now_playing.py` added to the publishing plug-ins list.
|
||||||
|
- Regenerate the OpenAPI export.
|
||||||
|
- Mark this plan done.
|
||||||
|
|
||||||
|
## Order of work (a commit per step once its tests pass)
|
||||||
|
|
||||||
|
1. Settings column and `federation_now_playing` table
|
||||||
|
2. Vocabulary (`update()`) and the live actor now-playing field
|
||||||
|
3. `publishing/now_playing.py` and its worker task
|
||||||
|
4. Settings API and schema
|
||||||
|
5. Web UI (Sharing page section, profile page field)
|
||||||
|
6. Metrics and dashboard
|
||||||
|
7. Interop check
|
||||||
|
8. Docs
|
||||||
|
|
||||||
|
## Defaults I've chosen (easy to change)
|
||||||
|
|
||||||
|
| Choice | Default |
|
||||||
|
|---|---|
|
||||||
|
| Now playing | Off by default, per user |
|
||||||
|
| Profile push throttle | 5 minutes |
|
||||||
|
| Post throttle | 30 minutes |
|
||||||
|
| Minimum played before a post | 30 seconds |
|
||||||
|
| Deleting the previous now-playing post | Always, when a new one goes out |
|
||||||
|
| Worker poll interval | 30 seconds |
|
||||||
|
| Hashtags | `#Scrobbled` and `#NowPlaying` |
|
||||||
@@ -0,0 +1,403 @@
|
|||||||
|
# ActivityPub federation: design proposal
|
||||||
|
|
||||||
|
Status: **proposal, for review.** Nothing here is built yet. The decisions still open are listed at the end.
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
Let a user turn their Scrobbled account into a fediverse account, for example `@alice@scrobble.example`, that people on Mastodon, GoToSocial, Misskey and similar servers can follow. Followers see three kinds of post:
|
||||||
|
|
||||||
|
- a **weekly listening summary**
|
||||||
|
- **milestones** (for example "10,000th scrobble")
|
||||||
|
- **what the user is playing now**
|
||||||
|
|
||||||
|
The first version is **outbound only**: Scrobbled publishes, and it accepts and manages followers. Following other people and showing their listening in the UI is a possible later phase (see [Later](#later-following-and-listen-activities)). The data model is designed so it can be added without rework.
|
||||||
|
|
||||||
|
Federation is **off for everyone until they turn it on**. Until then a user can't be found by WebFinger and nothing about them is published.
|
||||||
|
|
||||||
|
**Decided:** we write the protocol layer ourselves, on `cryptography` plus the Flask, SQLAlchemy and worker setup we already have (about 1,500 lines, in the four phases below). Scrobbled is BSD-licensed, and the ready-made Python library is AGPL (see [Build or buy](#build-or-buy)).
|
||||||
|
|
||||||
|
All of it lives in **one self-contained package, `scrobbler.federation`**, behind a narrow interface. It can then be changed, replaced or switched off without touching the rest of the app, and changes to the specs (signature schemes, vocabulary, FEPs) stay inside it. See [Module structure](#module-structure).
|
||||||
|
|
||||||
|
## What users get
|
||||||
|
|
||||||
|
- **Settings → Sharing**, a new UI page:
|
||||||
|
- A **Share my listening on the fediverse** switch. It shows the handle (`@alice@scrobble.example`) and warns that the handle can't change once people follow it.
|
||||||
|
- Choose what to post:
|
||||||
|
- **Weekly summary**: on by default once sharing is on.
|
||||||
|
- **Milestones**: on by default.
|
||||||
|
- **Now playing**: off by default, with two ways to show it. See [Now playing](#now-playing).
|
||||||
|
- **Who can see posts**: *Followers only* (**the default**), *Unlisted* (anyone who visits the profile, but kept out of public timelines), or *Public*. The help text explains that followers-only is only as private as who can follow: with automatic approval anyone can follow and then see posts, so for real privacy it suggests turning on **Approve followers manually**.
|
||||||
|
- **Approve followers manually** (off by default).
|
||||||
|
- Profile fields: display name, bio, avatar. The avatar defaults to a generated cover-art-style tile.
|
||||||
|
- **Followers**: a list of remote followers, with *Remove*. There are *Approve* and *Decline* buttons when manual approval is on.
|
||||||
|
- **Turning sharing off** deletes the published posts from followers' servers (`Delete` activities) and removes the followers. The account goes back to being unreachable. Keys are kept, so turning it on again keeps the same identity. Remote servers may still cache the old profile.
|
||||||
|
|
||||||
|
## How it fits the current system
|
||||||
|
|
||||||
|
```
|
||||||
|
Mastodon, GoToSocial, … Scrobbled
|
||||||
|
────────────────────────────────────────────────────────────────────────────
|
||||||
|
GET /.well-known/webfinger?resource=acct:… ─► API (only for opted-in users)
|
||||||
|
GET /users/alice (Accept: activity+json) ─► API actor document
|
||||||
|
POST /users/alice/inbox or /inbox ─► API verify signature, record, 202
|
||||||
|
│ Follow → follower (+ Accept queued)
|
||||||
|
▼
|
||||||
|
Postgres ◄── worker (`flask worker`)
|
||||||
|
│ • delivers queued activities (signed POSTs)
|
||||||
|
◄──────────── POST {follower shared inbox} ──────┘ • weekly summaries, milestones, now playing
|
||||||
|
```
|
||||||
|
|
||||||
|
- The **API** serves everything a remote server fetches: WebFinger, NodeInfo, actors, outboxes and inboxes. The inbox only validates and records; it never makes outbound calls itself.
|
||||||
|
- The **worker** (today's import worker, generalised to `flask worker`) does all outbound work: `Accept`s, post deliveries, retries, and the scheduled weekly and milestone posts. It uses the same claim-with-`SKIP LOCKED` pattern as imports.
|
||||||
|
- The **UI** gains the Sharing and Followers pages, which call new `/api/v1/federation/*` endpoints.
|
||||||
|
|
||||||
|
## Module structure
|
||||||
|
|
||||||
|
Everything to do with ActivityPub lives in `src/scrobbler/federation/`. The rest of Scrobbled knows only two things about it: how to switch it on, and a handful of domain events. Replacing the implementation (with another library, or a rewrite when the specs move on) means replacing this package; nothing else changes.
|
||||||
|
|
||||||
|
```
|
||||||
|
src/scrobbler/
|
||||||
|
events.py # core → anyone: blinker signals (scrobbles_stored, now_playing_changed, …)
|
||||||
|
worker.py # generic worker: runs tasks registered by any module
|
||||||
|
federation/
|
||||||
|
__init__.py # init_app(app): the ONLY entry point. No-op unless FEDERATION_ENABLED
|
||||||
|
config.py # FEDERATION_* settings and their validation
|
||||||
|
protocol/ # pure ActivityPub: no Flask, no SQLAlchemy, no scrobbler imports
|
||||||
|
vocab.py # JSON-LD builders: Person, Note, Create, Accept, Update, Delete, collections
|
||||||
|
addressing.py # visibility → to/cc
|
||||||
|
webfinger.py # JRD documents, acct: parsing
|
||||||
|
nodeinfo.py
|
||||||
|
signatures/
|
||||||
|
base.py # Signer / Verifier interfaces, SignedRequest value object
|
||||||
|
draft_cavage.py # one module per scheme; add/remove schemes here
|
||||||
|
rfc9421.py
|
||||||
|
net.py # SSRF-safe HTTP client; signed GET/POST using protocol.signatures
|
||||||
|
models.py # federation_* tables (own migrations, see below)
|
||||||
|
keys.py # key generation, encryption at rest, rotation
|
||||||
|
inbox.py # activity-type → handler registry (like the Last.fm method registry)
|
||||||
|
delivery.py # queue, retries, shared-inbox fan-out (a worker task)
|
||||||
|
publishing/ # what gets posted; each kind is a plug-in
|
||||||
|
summary.py # weekly summary
|
||||||
|
milestones.py
|
||||||
|
now_playing.py
|
||||||
|
subscribers.py # connects core events to publishing
|
||||||
|
web.py # Flask blueprint: webfinger, nodeinfo, actor, inbox, outbox, collections
|
||||||
|
api.py # /api/v1/federation/* (settings, followers) for the UI
|
||||||
|
metrics.py # federation's own Prometheus metrics
|
||||||
|
```
|
||||||
|
|
||||||
|
**Rules that keep the boundary clean:**
|
||||||
|
|
||||||
|
1. **The core never imports `scrobbler.federation`.** The only exception is `create_app()`, which calls `federation.init_app(app)`.
|
||||||
|
- Core code tells the outside world what happened by sending **domain events** from `scrobbler/events.py`:
|
||||||
|
- `scrobbles_stored(user, scrobbles, source)`
|
||||||
|
- `now_playing_changed(user, track or None)`
|
||||||
|
- `import_finished(user, job)`
|
||||||
|
- `user_deleted(user)`
|
||||||
|
- These are blinker signals; blinker is already a Flask dependency. Federation subscribes to them; with federation off, nothing listens.
|
||||||
|
- Imports can pass `source="import"`, which is how milestones know to ignore imported history.
|
||||||
|
2. **Federation reads core data only through core services** (`services.stats`, `services.accounts`), never by querying core tables directly. So core schema changes don't break it.
|
||||||
|
3. **`federation.protocol` is pure.** It has no Flask, SQLAlchemy or `scrobbler` imports: just dicts, dataclasses and `cryptography`.
|
||||||
|
- This is where spec changes land. A new signature scheme is a new module under `signatures/`. A vocabulary change is a builder in `vocab.py`.
|
||||||
|
- It's tested with spec test vectors and recorded requests alone.
|
||||||
|
4. **Pluggable pieces go through registries**, not `if` chains:
|
||||||
|
- **Signature schemes.** `FEDERATION_SIGNATURE_SCHEMES=draft-cavage,rfc9421` sets which schemes are accepted and the order they're tried when sending. Dropping draft-cavage one day would be a config change followed by deleting a module.
|
||||||
|
- **Inbox activity handlers**: activity type → handler, the same pattern as the Last.fm method registry.
|
||||||
|
- **Post kinds**: summary, milestones and now playing each register as a publisher.
|
||||||
|
5. **Federation owns its data.** Its tables are all prefixed `federation_` and have foreign keys to `users` only.
|
||||||
|
- Its migrations live in their own Alembic branch (`migrations/versions/federation_*`, `branch_labels=("federation",)`), so they can be dropped or rewritten without touching the core migration history.
|
||||||
|
- Removing the module means dropping its branch, which drops its tables.
|
||||||
|
6. **Work in the background goes through a generic task runner.** Today's import worker becomes `scrobbler/worker.py`, which runs tasks registered by modules: imports register theirs, and federation registers delivery and scheduled posting. The worker doesn't know what ActivityPub is.
|
||||||
|
7. **Enforced by tests.** A boundary test walks every module's imports and fails if:
|
||||||
|
- anything outside `scrobbler.federation` imports it (apart from `create_app`),
|
||||||
|
- `federation.protocol` imports Flask, SQLAlchemy or `scrobbler`, or
|
||||||
|
- federation code imports core models directly.
|
||||||
|
|
||||||
|
There's also a test that the whole app works with `FEDERATION_ENABLED=0`: no routes registered, no signal receivers, no tables touched.
|
||||||
|
|
||||||
|
**Switching it off:** with `FEDERATION_ENABLED=0` (the default until an operator sets up a domain), `init_app` registers nothing. There are no routes, no subscribers and no worker tasks, and the app behaves exactly as it does today.
|
||||||
|
|
||||||
|
## Protocol pieces
|
||||||
|
|
||||||
|
### Identity and domains
|
||||||
|
|
||||||
|
**Decided: the UI's domain**, which is the name users already know. Two settings configure it:
|
||||||
|
|
||||||
|
- `FEDERATION_DOMAIN`: the handle's domain, as in `@alice@<FEDERATION_DOMAIN>`. This is the UI's host.
|
||||||
|
- `FEDERATION_BASE_URL`: where the actor documents live, as in `https://<host>/users/alice`. It's also the UI's origin, so actor links, profile links and the handle all show one domain, and the API hostname stays an internal detail.
|
||||||
|
|
||||||
|
The UI's nginx **forwards the ActivityPub paths to the API**:
|
||||||
|
|
||||||
|
- `/.well-known/webfinger`, `/.well-known/nodeinfo`, `/.well-known/host-meta`
|
||||||
|
- `/nodeinfo/`, `/users/`, `/inbox`, `/actor`
|
||||||
|
|
||||||
|
All other paths are the static UI, as now. None of these paths collide with the UI's pages. The proxy passes `Host` and `X-Forwarded-*` through, and the API must trust them (`FORWARDED_ALLOW_IPS`), so that signature checks, which cover the request target and host, see the URL the remote server actually signed.
|
||||||
|
|
||||||
|
A browser opening an actor URL (`/users/alice` without an ActivityPub `Accept` header) gets a redirect from the API to the UI's profile page.
|
||||||
|
|
||||||
|
The two settings are kept separate even though they're usually the same host: the design still allows handles on one domain and actors on another, should that ever be needed. Mastodon supports that split through WebFinger's `self` link.
|
||||||
|
|
||||||
|
**Both values become permanent once anyone follows**: actor IDs are how other servers identify the account. Renaming a user or moving domains later needs the `Move` flow and `alsoKnownAs` (see [Later](#later-following-and-listen-activities)). So we should:
|
||||||
|
|
||||||
|
- stop users renaming themselves once they've enabled sharing, and
|
||||||
|
- refuse to start if the domain settings change while followers exist, unless an explicit migration flag is set.
|
||||||
|
|
||||||
|
### WebFinger (RFC 7033)
|
||||||
|
|
||||||
|
- `GET /.well-known/webfinger?resource=acct:alice@domain` returns `subject` plus two links:
|
||||||
|
- a `self` link of type `application/activity+json` pointing to the actor
|
||||||
|
- a `profile-page` link to the UI
|
||||||
|
- It returns **404** for unknown users and for users who haven't opted in. The response is identical in both cases, so the endpoint can't be used to list accounts.
|
||||||
|
- It's required: Mastodon resolves `@user@domain` through it.
|
||||||
|
|
||||||
|
### Actor (`Person`)
|
||||||
|
|
||||||
|
`GET /users/{username}` with `Accept: application/activity+json` or `application/ld+json; profile="https://www.w3.org/ns/activitystreams"` returns the actor document. Its fields:
|
||||||
|
|
||||||
|
- `id`, `type: Person`, `preferredUsername`, `name`, `summary`, `url` (the UI profile), `icon`
|
||||||
|
- `inbox`, `outbox`, `followers`, `following`, and `endpoints.sharedInbox`
|
||||||
|
- `publicKey`: `{id: …#main-key, owner, publicKeyPem}`
|
||||||
|
- `manuallyApprovesFollowers`, and `discoverable` and `indexable`. The last two are **false** by default and are settings the user can change.
|
||||||
|
- `attachment`: `PropertyValue` profile fields, for example "Scrobbles: 12,345". This is also where [now playing](#now-playing) can live.
|
||||||
|
|
||||||
|
A browser (a non-ActivityPub `Accept` header) is redirected to the UI profile page.
|
||||||
|
|
||||||
|
### Keys and signatures
|
||||||
|
|
||||||
|
- **One RSA-2048 key pair per federated user.** Mastodon's draft-signature path requires RSA.
|
||||||
|
- Private keys are **encrypted at rest** with a Fernet key derived from `FEDERATION_KEY_SECRET` (Mastodon 4.7 does the same).
|
||||||
|
- Ed25519 keys ([FEP-521a](https://codeberg.org/fediverse/fep/src/branch/main/fep/521a/fep-521a.md)) can be added later without breaking anything.
|
||||||
|
- **Outgoing**: sign with the draft-cavage HTTP Signatures scheme, still the most widely accepted.
|
||||||
|
- Signed headers: `(request-target) host date digest`, using `rsa-sha256`.
|
||||||
|
- The body digest goes in `Digest: SHA-256=…`.
|
||||||
|
- **Incoming**: verify both **draft-cavage** and **RFC 9421** (`Signature-Input`/`Signature`, which covers `@method`, `@target-uri` and `Content-Digest`).
|
||||||
|
- Mastodon 4.5+ accepts RFC 9421.
|
||||||
|
- Mastodon 4.7 *sends* RFC 9421 when a draft-signed request fails ("double-knocking"). Accepting both avoids needless failures.
|
||||||
|
- **Verification rules**:
|
||||||
|
- `Date` within ±12 hours.
|
||||||
|
- The digest must match the body.
|
||||||
|
- Fetch the `keyId` document and confirm its `owner` is the activity's `actor`.
|
||||||
|
- Cache remote keys, and re-fetch once on failure in case the key was rotated.
|
||||||
|
- Ignore Linked Data Signatures; Mastodon itself advises against implementing them.
|
||||||
|
- **Signed GETs**: some servers use "authorized fetch" (secure mode), which requires signed GETs. We always sign our fetches of remote actors, using an instance actor (`/actor`, type `Application`), so fetching works everywhere.
|
||||||
|
|
||||||
|
The signing code is small and well specified. Test vectors come from the specs and from recorded Mastodon and GoToSocial requests.
|
||||||
|
|
||||||
|
### Inbox
|
||||||
|
|
||||||
|
- `POST /users/{u}/inbox` and a shared `POST /inbox`. Limits: 256 KB body, and JSON-LD content types only.
|
||||||
|
- Once the signature is verified, an activity is **recorded and answered with 202**. Processing is quick and does no network I/O. Activity IDs are deduplicated.
|
||||||
|
|
||||||
|
| Activity | Handling |
|
||||||
|
|---|---|
|
||||||
|
| `Follow` (object = our actor) | Store the follower: `accepted`, or `pending` if manual approval is on. Queue an `Accept` (or wait for the user to decide). |
|
||||||
|
| `Undo` → `Follow` | Remove the follower. |
|
||||||
|
| `Delete` (actor) | Remove the follower and drop the cached actor. |
|
||||||
|
| `Update` (Person) | Refresh the cached actor, which may have a new shared inbox or key. |
|
||||||
|
| `Like`, `Announce`, `Create` (replies) | Recorded for metrics only; not shown in v1. |
|
||||||
|
| Anything else | Accepted and ignored. |
|
||||||
|
|
||||||
|
- **Blocks**:
|
||||||
|
- A user can block a remote account, which also removes it as a follower.
|
||||||
|
- An admin can block a whole domain with `FEDERATION_BLOCKED_DOMAINS`. Blocked senders get 403, and their `Follow`s are rejected.
|
||||||
|
|
||||||
|
### Collections
|
||||||
|
|
||||||
|
- `outbox`: an `OrderedCollection`, paged, holding the user's public and unlisted `Create` activities, newest first.
|
||||||
|
- `followers`: shows `totalItems` only. Items are hidden, as Mastodon does by default.
|
||||||
|
- `following`: an empty collection in v1.
|
||||||
|
|
||||||
|
### NodeInfo 2.1
|
||||||
|
|
||||||
|
Serve `/.well-known/nodeinfo` and `/nodeinfo/2.1`, giving the software name `scrobbler`, the version, protocols `["activitypub"]`, and user counts (opted-in users only). Fediverse tooling and statistics sites read it, and it's cheap.
|
||||||
|
|
||||||
|
### Delivery
|
||||||
|
|
||||||
|
- Every outgoing activity is saved, then turned into **delivery rows**: one per distinct inbox, using each follower's shared inbox where it has one.
|
||||||
|
- The worker delivers them with signed POSTs. Timeouts are 10s to connect and 20s to read.
|
||||||
|
- **Retries**: failures are retried with exponential backoff (1m, 5m, 30m, 2h, 6h, then every 12h) for up to **2 days**. After that the delivery is dropped and the peer marked unhealthy.
|
||||||
|
- 410 Gone and permanent 4xx responses aren't retried.
|
||||||
|
- 410 Gone for an actor removes it as a follower.
|
||||||
|
- **Outbound fetches are protected against SSRF**: HTTPS only, no private or loopback addresses (checked after DNS resolution), a 1 MB response limit, and at most 3 redirects.
|
||||||
|
|
||||||
|
## What gets posted
|
||||||
|
|
||||||
|
Posts are `Note` objects inside `Create` activities: Mastodon shows `Note` as a normal status, while other types are squashed into a title and link. The HTML uses only tags Mastodon keeps (`p`, `a`, `br`, `strong`, `em`, `ul`, `ol`, `li`), and all track and artist text is escaped. Each post also gets hashtags (`#NowPlaying`, `#Scrobbled`) as `Hashtag` tags. Visibility follows the user's setting, which defaults to **followers only**:
|
||||||
|
|
||||||
|
| Setting | `to` | `cc` |
|
||||||
|
|---|---|---|
|
||||||
|
| Followers only (default) | followers | *(none)* |
|
||||||
|
| Unlisted | followers | `as:Public` |
|
||||||
|
| Public | `as:Public` | followers |
|
||||||
|
|
||||||
|
What followers-only means in practice:
|
||||||
|
|
||||||
|
- Posts go only to followers' servers, which show them only to followers.
|
||||||
|
- They don't appear in the public outbox or on the profile for anyone else.
|
||||||
|
- They can't be boosted.
|
||||||
|
- Changing the setting affects new posts only: already-published posts keep the visibility they were sent with.
|
||||||
|
|
||||||
|
### Weekly summary
|
||||||
|
|
||||||
|
- The worker posts one per opted-in user, on Monday at 09:00 in the user's time zone. Users don't have a time zone yet, so the Sharing page adds one, defaulting to the browser's.
|
||||||
|
- Posting is idempotent: there's one summary per user per ISO week, so a worker restart doesn't post twice.
|
||||||
|
- Weeks with no plays are skipped.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
> **This week: 312 scrobbles**
|
||||||
|
> Top artists: 1. Radiohead (48) 2. Björk (31) 3. Portishead (22)
|
||||||
|
> Top track: *Reckoner* by Radiohead (12 plays)
|
||||||
|
> #Scrobbled
|
||||||
|
|
||||||
|
### Milestones
|
||||||
|
|
||||||
|
These are checked after each scrobble batch and each import, and each one is posted at most once:
|
||||||
|
|
||||||
|
- **Scrobble counts**: the 1,000th, 5,000th and 10,000th scrobble, then every 25,000.
|
||||||
|
- **Artist plays**: an artist's 100th or 500th play.
|
||||||
|
- **All-time top 10**: a new artist enters it.
|
||||||
|
|
||||||
|
History imports never produce milestone posts: importing 50,000 old plays shouldn't set off a burst of them. Milestones only start counting after the import.
|
||||||
|
|
||||||
|
### Now playing
|
||||||
|
|
||||||
|
A new post for every track would flood followers' timelines. There are two options:
|
||||||
|
|
||||||
|
1. **Profile field (recommended default)**: a "Now playing: *Reckoner* by Radiohead" field on the profile. The field is updated with an `Update(Person)` when the track changes, at most once every 5 minutes, and cleared when playback stops. Nothing appears in timelines; followers see it on the profile. This option is cheap and quiet.
|
||||||
|
2. **Posts (opt-in)**: a `Note` when a track starts, at most one every 30 minutes, and only for tracks played for at least 30 seconds.
|
||||||
|
- It uses the user's visibility setting (followers only by default).
|
||||||
|
- Optionally, the previous now-playing post is deleted when the next one goes out, so only one exists at a time.
|
||||||
|
|
||||||
|
## Build or buy
|
||||||
|
|
||||||
|
| | Write it ourselves (recommended) | Pubby (Python) | Fedify (TypeScript) sidecar |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Fits the codebase | Same Flask, SQLAlchemy, worker, metrics and OpenAPI patterns | Flask adapter and SQLAlchemy storage | A second language and service |
|
||||||
|
| Signatures | Draft-cavage and RFC 9421 (we write both) | HTTP Signatures (built in) | Draft, RFC 9421, FEP-8b32 |
|
||||||
|
| **Licence** | Ours | **AGPL-3.0-or-later**: offering the service over a network brings AGPL obligations for the whole app | MIT |
|
||||||
|
| Maturity | New code, but the scope is narrow | Active, but young (0.3.x, one maintainer) | The most complete framework |
|
||||||
|
| Effort | About 1,500 lines, mostly signatures, inbox and delivery | Less code, but we'd adapt its storage and flow to ours | A new service to run and monitor |
|
||||||
|
|
||||||
|
**Decided: write it ourselves.** Scrobbled is BSD-3-Clause licensed. Using Pubby inside the app would make the running program subject to the AGPL, which defeats the point of a permissive licence. Fedify is excellent, but it would split the backend across two languages. The protocol surface we need is small (four activity types in and three out), so writing it ourselves is the least total cost. It also keeps ActivityPub on the same metrics, dashboards and tests as everything else, and it can all live in the one replaceable module described above.
|
||||||
|
|
||||||
|
New dependency: `cryptography` (Apache-2.0 or BSD), for keys and signatures.
|
||||||
|
|
||||||
|
## Data model
|
||||||
|
|
||||||
|
All of these are federation's own tables, prefixed `federation_` and managed in its own Alembic branch (the names below leave the prefix off, except the first). The only link to the core schema is a foreign key to `users`.
|
||||||
|
|
||||||
|
| Table | Holds |
|
||||||
|
|---|---|
|
||||||
|
| `federation_settings` | Per user: `enabled`, visibility, which post types, now-playing mode, manual approval, discoverable and indexable, time zone, display name, bio, avatar |
|
||||||
|
| `actor_keys` | Per user, plus one instance actor: public key PEM, encrypted private key, created and rotated times |
|
||||||
|
| `remote_actors` | Cache: actor URI, inbox, shared inbox, key ID and PEM, handle, display name, `fetched_at`, health |
|
||||||
|
| `followers` | Local user ↔ remote actor, with state (`pending`, `accepted`), the Follow activity ID, and when |
|
||||||
|
| `blocks` | Per-user remote-actor blocks, plus admin domain blocks |
|
||||||
|
| `outbox_activities` | Our activities (ID, type, JSON, visibility, published). They are the source for the outbox collection and for deliveries |
|
||||||
|
| `deliveries` | Activity × target inbox: `attempts`, `next_attempt_at`, `status`, `last_error` |
|
||||||
|
| `inbox_activities` | Received activity IDs (for deduplication), type, actor, and outcome. Pruned after 30 days |
|
||||||
|
| `posted_milestones` / `weekly_posts` | One row per posted milestone or week, which keeps posting idempotent |
|
||||||
|
|
||||||
|
## Security and privacy
|
||||||
|
|
||||||
|
- **Opt-in.** Nothing about a user is published or discoverable until they turn sharing on. Existing listening history is never posted retroactively: summaries start from the next week, and milestones from the next scrobble.
|
||||||
|
- **Nothing that allows tracking**: we publish aggregates and choices the user made explicitly, never raw scrobble timestamps. Now-playing is throttled and can be switched off.
|
||||||
|
- **The inbox is the new attack surface**:
|
||||||
|
- signature checks before any processing
|
||||||
|
- body size limits
|
||||||
|
- rate limits per remote host
|
||||||
|
- activity deduplication
|
||||||
|
- the SSRF-hardened fetcher described above
|
||||||
|
- no HTML from remote servers is ever rendered in v1
|
||||||
|
- **Followers can be removed or blocked**, and admins can block whole domains.
|
||||||
|
- **Private keys are encrypted at rest**, with `FEDERATION_KEY_SECRET` kept separate from `SECRET_KEY`.
|
||||||
|
|
||||||
|
## Observability
|
||||||
|
|
||||||
|
Everything goes on the existing Prometheus and Grafana setup:
|
||||||
|
|
||||||
|
- **Metrics**:
|
||||||
|
- `scrobbler_federation_inbox_activities_total{type,result}`
|
||||||
|
- `scrobbler_federation_signature_failures_total{scheme,reason}`
|
||||||
|
- `scrobbler_federation_deliveries_total{result}`
|
||||||
|
- `scrobbler_federation_delivery_queue{status}`
|
||||||
|
- `scrobbler_federation_followers`
|
||||||
|
- `scrobbler_federation_posts_total{kind}`
|
||||||
|
- **Dashboard**: a new **Federation** dashboard.
|
||||||
|
- **Alerts**: the delivery queue growing for 30 minutes, and signature failures spiking.
|
||||||
|
|
||||||
|
## Testing and interoperability
|
||||||
|
|
||||||
|
- **Unit tests**:
|
||||||
|
- signing and verification against spec test vectors and recorded requests
|
||||||
|
- WebFinger, actor and collection shapes
|
||||||
|
- inbox state transitions
|
||||||
|
- delivery retry schedule
|
||||||
|
- visibility addressing
|
||||||
|
- **In-process federation**: two Scrobbled instances in one test process following each other.
|
||||||
|
- **A real peer in CI**: a [GoToSocial](https://gotosocial.org) container, which is a single binary with SQLite. It follows a Scrobbled user and we assert that it receives the `Accept` and the posts. That's much lighter than running Mastodon in CI.
|
||||||
|
- **Manual pass before release** (done, over a `cloudflared` tunnel - see [phase 4](activitypub-phase4.md)):
|
||||||
|
- follow from a real Mastodon account
|
||||||
|
- check the profile, posts, profile-field updates and unfollowing
|
||||||
|
- check with [verify.funfedi.dev](https://verify.funfedi.dev/) or the [ActivityPub Academy](https://activitypub.academy/)
|
||||||
|
|
||||||
|
## Phases
|
||||||
|
|
||||||
|
Each phase can be released on its own, with its migration, docs, OpenAPI updates, metrics and tests.
|
||||||
|
|
||||||
|
0. **Groundwork**, with no user-visible change:
|
||||||
|
- `scrobbler/events.py`, and the core sending its events
|
||||||
|
- the generic `scrobbler/worker.py`, with imports moved onto it
|
||||||
|
- the empty `scrobbler.federation` package with `init_app`
|
||||||
|
- its Alembic branch
|
||||||
|
- the boundary tests
|
||||||
|
|
||||||
|
This lands first so every later phase is built inside the boundary from day one.
|
||||||
|
1. **Discoverable profile.** Settings, keys, WebFinger, the actor, NodeInfo and the Sharing page. A user can turn sharing on and be found from Mastodon, but can't be followed yet.
|
||||||
|
2. **Followers.** Inbox, signature verification (both schemes), the delivery queue with retries and signing, `Accept`, removing and blocking followers, the Followers page, and the GoToSocial CI test.
|
||||||
|
3. **Posts.** The outbox, weekly summaries, milestones, and deleting posts when sharing is turned off. Adds the Federation dashboard and alerts.
|
||||||
|
4. **Now playing.** The profile-field mode, then optional posts. See [phase 4](activitypub-phase4.md).
|
||||||
|
|
||||||
|
## Later: following and `Listen` activities
|
||||||
|
|
||||||
|
This is the "profiles plus friends' listening" option, deliberately left out of v1:
|
||||||
|
|
||||||
|
- Users follow other Scrobbled users, or any actor that publishes listens, and see a friends feed in the UI.
|
||||||
|
- **Wire format**: ActivityStreams has a `Listen` activity type. Funkwhale already federates `Listen` activities whose object is a `Track`. We'd send the same thing to followers on Scrobbled and Funkwhale servers only. Mastodon ignores activity types it doesn't know, and a stream of `Listen`s isn't something people want in their timelines anyway.
|
||||||
|
- **Changes needed**: an outbound `Follow` flow, storing received listens, a feed UI, and moderation of incoming content.
|
||||||
|
- **Account migration** (`Move` and `alsoKnownAs`) would come with this, so users can change handle or domain without losing followers.
|
||||||
|
|
||||||
|
## Decisions for you
|
||||||
|
|
||||||
|
Settled so far: **build it ourselves** (the project is BSD-3-Clause), inside **one replaceable module**.
|
||||||
|
|
||||||
|
Also settled:
|
||||||
|
|
||||||
|
- **Domain: the UI's.** Handles and actor URLs are both on the UI host, and the UI's nginx forwards the ActivityPub paths to the API.
|
||||||
|
- **Visibility: followers only by default**, and each user can change it on their Sharing settings.
|
||||||
|
- **Now playing: the profile field, plus opt-in posts** (phase 4) — not just the recommended default, both.
|
||||||
|
|
||||||
|
Still open:
|
||||||
|
|
||||||
|
1. **Does it need an admin?** Phase 2 assumes domain blocks set in configuration. A real moderation UI (reports, per-domain policies) would be a separate piece of work.
|
||||||
|
|
||||||
|
## Sources
|
||||||
|
|
||||||
|
- [Mastodon ActivityPub spec](https://docs.joinmastodon.org/spec/activitypub/): object rendering, supported activities, actor properties, visibility addressing, allowed HTML
|
||||||
|
- [Mastodon security spec](https://docs.joinmastodon.org/spec/security/): draft-cavage requirements, RFC 9421 accepted from 4.5, 12-hour clock skew, LD Signatures not advised
|
||||||
|
- [Mastodon 4.7 release notes](https://blog.joinmastodon.org/2026/08/mastodon-4.7/): RFC 9421 fallback when sending, FEP-521a keys (RSA, Ed25519, ML-DSA-44), FEP-8b32, encrypted private keys
|
||||||
|
- [Mastodon WebFinger spec](https://docs.joinmastodon.org/spec/webfinger/)
|
||||||
|
- [SocialHub: RFC 9421 HTTP signatures in 2026](https://socialhub.activitypub.rocks/t/rfc-9421-http-signatures-in-2026/8427)
|
||||||
|
- [Funkwhale federation docs](https://docs.funkwhale.audio/develop/developer/federation/index.html): the `Listen` activity with a `Track` object
|
||||||
|
- [Pubby on PyPI](https://pypi.org/project/pubby/): features and AGPL-3.0-or-later licence
|
||||||
|
|
||||||
|
## Lessons from interop testing (phase 2)
|
||||||
|
|
||||||
|
Testing against a real GoToSocial server changed a few details:
|
||||||
|
|
||||||
|
- **Key IDs come in three shapes.** A fragment of the actor (`<actor>#main-key`, used by Mastodon), a path that serves the actor document (`<actor>/main-key`, used by GoToSocial), or a separate key document with an `owner`. All three are resolved.
|
||||||
|
- **Rejects reference the Follow by ID rather than embedding it.** Some servers match an embedded Follow by the pair of accounts. A late Reject of an old Follow would then cancel a newer request between the same two accounts.
|
||||||
|
- **An Undo only removes the Follow it names.** Deliveries race, so an Undo of an older Follow can arrive after a newer one.
|
||||||
|
- **Unblocking sends an Undo of the Block**, so the other server lets the person follow again.
|
||||||
|
- **Actors publish a `featured` collection** (empty for now). Mastodon and GoToSocial fetch it.
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# Working on Scrobbled
|
||||||
|
|
||||||
|
Setting up a local development environment. For running a real instance, see the
|
||||||
|
[admin guide](admin-guide.md). For what the service does, see the
|
||||||
|
[user guide](user-guide.md).
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- [uv](https://docs.astral.sh/uv/) for Python dependencies
|
||||||
|
- Docker, for Postgres (and optionally the full stack)
|
||||||
|
|
||||||
|
## Get running
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose up -d db # Postgres, with a scrobbler_test database too
|
||||||
|
uv sync
|
||||||
|
uv run flask --app scrobbler db upgrade heads
|
||||||
|
uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS)
|
||||||
|
python -m http.server 8080 -d frontend # UI
|
||||||
|
uv run flask --app scrobbler worker # background work: imports, federation deliveries, …
|
||||||
|
```
|
||||||
|
|
||||||
|
`TEST_DATABASE_URL` (see `.env.example`) points the test suite at `scrobbler_test`.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
uv run pytest
|
||||||
|
uv run ruff check && uv run ruff format --check
|
||||||
|
```
|
||||||
|
|
||||||
|
The test suite includes an end-to-end run with [pylast](https://github.com/pylast/pylast)
|
||||||
|
over HTTPS and a real two-worker gunicorn run, checking that metrics aggregate across
|
||||||
|
workers. `TestConfig` pins every setting a developer might have in their own `.env`
|
||||||
|
(`FEDERATION_ENABLED`, `LASTFM_API_KEY`, `UI_BASE_URL`, `CORS_ORIGINS`, …) so a local
|
||||||
|
`.env` used for manual testing can never change what the test suite exercises — if you
|
||||||
|
add a new setting that a test might reasonably assert an exact value for, pin it there
|
||||||
|
too rather than relying on its default.
|
||||||
|
|
||||||
|
## Migrations
|
||||||
|
|
||||||
|
Two Alembic branches, `core` and `federation`, so federation's tables can be changed or
|
||||||
|
dropped without touching core ones:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
uv run flask --app scrobbler db migrate --head core@head -m "…" # core models
|
||||||
|
uv run flask --app scrobbler db migrate --head federation@head -m "…" # federation models
|
||||||
|
uv run flask --app scrobbler db upgrade heads # apply both
|
||||||
|
```
|
||||||
|
|
||||||
|
CI fails if the models and migrations disagree. See
|
||||||
|
`src/scrobbler/federation/README.md` for more on the federation branch specifically
|
||||||
|
(it also enforces that federation stays an optional, replaceable module — an
|
||||||
|
AST-based boundary test checks what it's allowed to import).
|
||||||
|
|
||||||
|
## API docs
|
||||||
|
|
||||||
|
After changing an endpoint:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
uv run python -m scrobbler.openapi.export docs/openapi.json
|
||||||
|
```
|
||||||
|
|
||||||
|
It documents the API with every optional module (federation included) switched on. A
|
||||||
|
test fails if the committed spec is stale, if any route is missing from it, or if any UI
|
||||||
|
route is missing its bearer-auth declaration.
|
||||||
|
|
||||||
|
## Useful scripts
|
||||||
|
|
||||||
|
- `uv run python scripts/generate_traffic.py --minutes 5` — sends a realistic mix of
|
||||||
|
scrobbles and errors, so the Grafana dashboards have something to show.
|
||||||
|
- `scripts/interop/run.sh` — runs Scrobbled against a real GoToSocial server on a private
|
||||||
|
network and checks the whole federation follow/post/now-playing life cycle end to end.
|
||||||
|
CI runs this on every push; run it locally the same way before changing anything in
|
||||||
|
`scrobbler.federation`.
|
||||||
|
|
||||||
|
## Manual fediverse test
|
||||||
|
|
||||||
|
The interop test above proves the protocol works against one real server on a private
|
||||||
|
network. It can't prove WebFinger resolves from the public internet, or that a real
|
||||||
|
Mastodon instance renders things sensibly. Before merging federation changes that touch
|
||||||
|
anything user-visible, do a manual pass with a real account through a tunnel
|
||||||
|
(`cloudflared tunnel --url http://localhost:8080` needs no account for a quick HTTPS
|
||||||
|
URL) — see `docs/design/activitypub-phase4.md` for what was checked and two real bugs
|
||||||
|
that manual pass caught that no automated test had.
|
||||||
|
|
||||||
|
## CI/CD
|
||||||
|
|
||||||
|
Everything runs from `.gitea/workflows/ci.yml`:
|
||||||
|
|
||||||
|
- **Every push and PR**: lint, the migrations-vs-models check, tests against Postgres,
|
||||||
|
and `promtool` checks of the Prometheus config and alert rules.
|
||||||
|
- **Pushes to `main` and tags**, once those all pass: images and assets publish (see
|
||||||
|
[admin guide](admin-guide.md#releases)).
|
||||||
|
- **Every run** posts to the `ScrobblingService` topic on notify.daubney.dev.
|
||||||
|
|
||||||
|
Repository secrets: `PKGS_USER`, `PKGS_PASSWORD`, `PKGS_API_KEY`, `NTFY_USER`,
|
||||||
|
`NTFY_PASSWORD`. Variables: `PKGS_HOST`, `PKGS_DOCKER_FEED`, `PKGS_PYPI_FEED`,
|
||||||
|
`PKGS_ASSET_FEED`, `NTFY_URL`, `NTFY_TOPIC`.
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- Keep the web UI (`frontend/`) entirely outside the API stack: Flask serves JSON only,
|
||||||
|
never HTML.
|
||||||
|
- Every endpoint needs an OpenAPI entry and Prometheus metrics; every new dashboard
|
||||||
|
metric needs a Grafana panel (or an existing one it plausibly extends).
|
||||||
|
- Commit at logical checkpoints through a piece of work, not only at the end.
|
||||||
|
- BSD-3-Clause licensed; avoid GPL/AGPL dependencies.
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
# User guide
|
||||||
|
|
||||||
|
What Scrobbled does once you're signed in: connecting a player, importing your old
|
||||||
|
history, and sharing your listening on the fediverse. If you're setting up or running an
|
||||||
|
instance rather than using one, see the [admin guide](admin-guide.md) instead.
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
Register in the web UI, then go to **Apps** and create one app per player or scrobbler
|
||||||
|
client you use — each gets its own API key and shared secret, and can be revoked on its
|
||||||
|
own from the **Sessions** page without affecting the others. If a friend runs your
|
||||||
|
instance, ask them for its address; that's the only thing you need from them to get
|
||||||
|
going.
|
||||||
|
|
||||||
|
## Connecting a player
|
||||||
|
|
||||||
|
In the player's scrobbling settings, choose a custom or self-hosted Last.fm server:
|
||||||
|
|
||||||
|
- **API URL**: `https://your-host/2.0/`
|
||||||
|
- **API key and shared secret**: from an app on the **Apps** page
|
||||||
|
- **Username and password**: your Scrobbled account
|
||||||
|
|
||||||
|
Two sign-in flows are supported, and most players use one or the other automatically:
|
||||||
|
|
||||||
|
- **Mobile**: you enter your username and password directly in the player.
|
||||||
|
- **Desktop**: the player opens a browser page for you to approve, then signs itself in
|
||||||
|
— no password ever passed to the player.
|
||||||
|
|
||||||
|
A sign-in method that hashes your password before sending it (sometimes offered as a
|
||||||
|
"stored password" or "password hash" option, e.g. pylast's `password_hash`) isn't
|
||||||
|
supported — use the plain username/password or desktop-approval flow instead.
|
||||||
|
|
||||||
|
Supported methods, if your player lets you check: `auth.getMobileSession`,
|
||||||
|
`auth.getToken`, `auth.getSession`, `track.scrobble` (up to 50 per request),
|
||||||
|
`track.updateNowPlaying`, `user.getInfo`, `user.getRecentTracks`, `user.getTopArtists`,
|
||||||
|
`user.getTopAlbums`, `user.getTopTracks`. `/api/docs` on your instance has the full
|
||||||
|
parameters and example responses for each, if you're curious or debugging a client.
|
||||||
|
|
||||||
|
A play is silently skipped (not rejected as an error) if the artist or track name is
|
||||||
|
empty, or its timestamp is more than 14 days old or more than 5 minutes in the future.
|
||||||
|
Sending the same play twice — a common side effect of a player retrying after a network
|
||||||
|
blip — is accepted both times but only stored once, so retries are always safe.
|
||||||
|
|
||||||
|
**A legacy scrobbler that speaks the old 1.2 "handshake" protocol (rather than 2.0) won't
|
||||||
|
work here** — this is a client limitation, not a setting to fix. VLC's built-in
|
||||||
|
scrobbler is one example; look for a plugin or a different player with 2.0 support.
|
||||||
|
|
||||||
|
## Importing history
|
||||||
|
|
||||||
|
Open **Import** in the web UI:
|
||||||
|
|
||||||
|
- **An export file**:
|
||||||
|
- CSV from [lastfm-to-csv](https://benjaminbenben.com/lastfm-to-csv/), no header row,
|
||||||
|
artist/album/track/date columns.
|
||||||
|
- Any CSV or TSV with a header row naming artist, track and a date or Unix-time
|
||||||
|
column. Comma, semicolon and tab delimiters all work.
|
||||||
|
- A JSON export of `user.getRecentTracks` pages (such as lastfm.ghan.nl's), a single
|
||||||
|
`recenttracks` response, or a flat list of tracks.
|
||||||
|
- Files can be gzipped.
|
||||||
|
- **Last.fm directly**: enter a Last.fm username and the import runs against that
|
||||||
|
account's public history. Only appears if your instance's admin has set this up.
|
||||||
|
|
||||||
|
Imports run in the background — the page shows progress and you can cancel one in
|
||||||
|
flight. Unlike live scrobbles, imports keep plays of any age (still skipping rows with no
|
||||||
|
artist or track, or plays dated in the future). Plays already in your history are
|
||||||
|
skipped, so importing the same export again, or importing overlapping exports, is safe.
|
||||||
|
|
||||||
|
## Your profile image
|
||||||
|
|
||||||
|
Click your name in the page header to open **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
|
||||||
|
`@name@<your instance's host>` from Mastodon and other fediverse apps.
|
||||||
|
|
||||||
|
- Follows are accepted automatically, or wait for your approval if you turn that on
|
||||||
|
under **Followers and discovery**.
|
||||||
|
- **Followers** lists requests, followers and blocked accounts, with approve, decline,
|
||||||
|
remove, block and unblock.
|
||||||
|
|
||||||
|
Once someone follows you, **Sharing**'s **What to post** section controls what they see:
|
||||||
|
|
||||||
|
- **Weekly summary**: your play count and top artist(s), posted once a week (Monday
|
||||||
|
09:00 in your own time zone, for the week that just ended). A live preview shows what
|
||||||
|
it would say so far.
|
||||||
|
- **Milestones**: total scrobbles, an artist's plays, and a new entry into your all-time
|
||||||
|
top 10 — each posted once, the first time you reach it. History already on file when
|
||||||
|
you turn sharing on, or added by an import, is never posted about retroactively.
|
||||||
|
|
||||||
|
Both are on by default and can be switched off independently. Posts use the same
|
||||||
|
visibility as your profile (followers only by default, or unlisted/public); **Posts**
|
||||||
|
lists your own posts, each with a delete button.
|
||||||
|
|
||||||
|
**Now playing** is a separate, three-way choice:
|
||||||
|
|
||||||
|
- **Off** (default): nothing shown or posted.
|
||||||
|
- **Show on my profile**: a "Now playing: *Track* by Artist" field on your profile,
|
||||||
|
refreshed at most every 5 minutes while something's playing and cleared a few minutes
|
||||||
|
after it stops.
|
||||||
|
- **Show on my profile and post**: the profile field, plus a post for each track played
|
||||||
|
30 seconds or more, at most one every 30 minutes, with the previous now-playing post
|
||||||
|
deleted once the new one is confirmed published.
|
||||||
|
|
||||||
|
**Your handle can't change once anyone follows you** — if you get to choose the
|
||||||
|
instance's domain yourself, or you're choosing which instance to join, bear that in mind
|
||||||
|
before you start sharing.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
**I turned Sharing on but can't see it in the menu.** Try a hard refresh
|
||||||
|
(Ctrl/Cmd+Shift+R) or a private/incognito window. The menu remembers whether sharing is
|
||||||
|
available for the length of a browser tab, so it can lag behind a setting your admin just
|
||||||
|
changed.
|
||||||
|
|
||||||
|
**My profile 404s on a big instance like mastodon.social right after I start sharing.**
|
||||||
|
Some servers cache a "not found" for a little while after they first look you up. Give it
|
||||||
|
an hour, or try searching from a smaller instance to confirm your handle really works.
|
||||||
|
|
||||||
|
**A change I made under Sharing doesn't seem to have taken effect.** Make sure you
|
||||||
|
clicked **Save sharing settings** at the bottom of the page — ticking a box alone doesn't
|
||||||
|
save it.
|
||||||
@@ -0,0 +1,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>
|
||||||
|
After Width: | Height: | Size: 16 KiB |
@@ -3,8 +3,12 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Allow access · Scrobbler</title>
|
<title>Allow access · Scrobbled</title>
|
||||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
|
<link rel="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">
|
<link rel="stylesheet" href="css/style.css">
|
||||||
<script src="config.js"></script>
|
<script src="config.js"></script>
|
||||||
<script type="module" src="js/approve.js"></script>
|
<script type="module" src="js/approve.js"></script>
|
||||||
|
|||||||
@@ -3,8 +3,12 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Apps · Scrobbler</title>
|
<title>Apps · Scrobbled</title>
|
||||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
|
<link rel="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">
|
<link rel="stylesheet" href="css/style.css">
|
||||||
<script src="config.js"></script>
|
<script src="config.js"></script>
|
||||||
<script type="module" src="js/apps.js"></script>
|
<script type="module" src="js/apps.js"></script>
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Album art · 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/art-failures.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="site-header" id="site-header"></header>
|
||||||
|
<main id="main">
|
||||||
|
<h1 class="page-title">Album art</h1>
|
||||||
|
<p class="lede" id="art-summary">Albums you've scrobbled that have no cover art.</p>
|
||||||
|
<div id="messages" aria-live="polite"></div>
|
||||||
|
<ul class="rows art-rows" id="albums"></ul>
|
||||||
|
<nav class="pager" aria-label="Pages" id="pager"></nav>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// Where the Scrobbler API lives. The UI container rewrites this file from the
|
// Where the Scrobbled API lives. The UI container rewrites this file from the
|
||||||
// API_BASE_URL environment variable at start-up; edit it by hand otherwise.
|
// API_BASE_URL environment variable at start-up; edit it by hand otherwise.
|
||||||
window.SCROBBLER_CONFIG = {
|
window.SCROBBLER_CONFIG = {
|
||||||
apiBaseUrl: "http://localhost:5050",
|
apiBaseUrl: "http://localhost:5050",
|
||||||
|
|||||||
@@ -152,18 +152,32 @@ code {
|
|||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.6rem;
|
gap: 0.6rem;
|
||||||
font-weight: 700;
|
|
||||||
font-size: var(--step-1);
|
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* A small round "power" lamp */
|
/* The Scrobbled mark: a record with the tonearm resting on it */
|
||||||
.brand-mark {
|
.brand-mark {
|
||||||
width: 0.7rem;
|
width: 2rem;
|
||||||
height: 0.7rem;
|
height: 2rem;
|
||||||
border-radius: 50%;
|
background: url("../img/scrobbled-mark-simple.svg") center / contain no-repeat;
|
||||||
background: var(--glow);
|
}
|
||||||
box-shadow: 0 0 0 3px var(--panel), 0 0 10px 1px color-mix(in srgb, var(--glow) 60%, transparent);
|
|
||||||
|
/* The outlined wordmark; the name is in the link's visually-hidden text. The "b" is
|
||||||
|
lime on dark and violet on light, so there is one file per theme. */
|
||||||
|
.brand-word {
|
||||||
|
width: 5.3rem;
|
||||||
|
height: 1.4rem;
|
||||||
|
background: url("../img/scrobbled-wordmark-on-light.svg") center / contain no-repeat;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme="light"]) .brand-word {
|
||||||
|
background-image: url("../img/scrobbled-wordmark-on-dark.svg");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
:root[data-theme="dark"] .brand-word {
|
||||||
|
background-image: url("../img/scrobbled-wordmark-on-dark.svg");
|
||||||
}
|
}
|
||||||
|
|
||||||
.site-header nav ul {
|
.site-header nav ul {
|
||||||
@@ -195,10 +209,76 @@ code {
|
|||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
align-items: baseline;
|
align-items: center;
|
||||||
color: var(--ink-soft);
|
color: var(--ink-soft);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.account-link {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
align-items: center;
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.account-link:hover .account-name {
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
|
||||||
|
.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 {
|
main {
|
||||||
max-width: 1120px;
|
max-width: 1120px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
@@ -582,6 +662,16 @@ input {
|
|||||||
background: var(--slate);
|
background: var(--slate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.ranking a.name {
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ranking a.name:hover,
|
||||||
|
.ranking a.name:focus-visible {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
/* ---- Listening log -------------------------------------------------------- */
|
/* ---- Listening log -------------------------------------------------------- */
|
||||||
.log {
|
.log {
|
||||||
list-style: none;
|
list-style: none;
|
||||||
@@ -615,6 +705,22 @@ input {
|
|||||||
color: var(--ink-soft);
|
color: var(--ink-soft);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Stack the track above a muted artist line and make the cell a link, like .ranking rows */
|
||||||
|
.log-stacked .by {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-stacked li a {
|
||||||
|
display: block;
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-stacked li a:hover,
|
||||||
|
.log-stacked li a:focus-visible {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
.log-day {
|
.log-day {
|
||||||
margin: 2rem 0 0.25rem;
|
margin: 2rem 0 0.25rem;
|
||||||
font-size: var(--step-0);
|
font-size: var(--step-0);
|
||||||
@@ -844,3 +950,303 @@ input {
|
|||||||
transition: width 0.4s ease-out;
|
transition: width 0.4s ease-out;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---- Sharing & profile ---------------------------------------------------- */
|
||||||
|
.sharing {
|
||||||
|
max-width: 44rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.share-switch {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
font-size: var(--step-1);
|
||||||
|
font-weight: 650;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.share-switch input {
|
||||||
|
width: 1.4rem;
|
||||||
|
height: 1.4rem;
|
||||||
|
accent-color: var(--ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
.handle-panel {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.handle {
|
||||||
|
font-size: clamp(1.1rem, 4vw, var(--step-2));
|
||||||
|
margin: 0.4rem 0 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.handle-panel .notice {
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.choices {
|
||||||
|
border: 0;
|
||||||
|
border-top: 1px solid var(--rule);
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
padding: 1.25rem 0 0;
|
||||||
|
min-inline-size: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.choices legend {
|
||||||
|
font-weight: 650;
|
||||||
|
font-size: var(--step-1);
|
||||||
|
padding: 0 0.5rem 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.choice {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.75rem;
|
||||||
|
align-items: flex-start;
|
||||||
|
margin-bottom: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.choice input {
|
||||||
|
margin-top: 0.3rem;
|
||||||
|
accent-color: var(--ink);
|
||||||
|
}
|
||||||
|
|
||||||
|
.choice label {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.choice label .muted {
|
||||||
|
font-size: var(--step--1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.choices .hint {
|
||||||
|
color: var(--ink-soft);
|
||||||
|
font-size: var(--step--1);
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-box {
|
||||||
|
padding: 1rem 1.25rem;
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
background: var(--paper-raised);
|
||||||
|
border: 1px solid var(--rule);
|
||||||
|
margin: 0.75rem 0 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-box p {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-box p:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field textarea {
|
||||||
|
min-height: 5rem;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border: 1px solid var(--rule);
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
background: var(--paper-raised);
|
||||||
|
font: inherit;
|
||||||
|
color: inherit;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field textarea:focus-visible {
|
||||||
|
border-color: var(--focus);
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-bio {
|
||||||
|
white-space: pre-line;
|
||||||
|
}
|
||||||
|
|
||||||
|
.now-playing {
|
||||||
|
padding: 0.6rem 1rem;
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
border-left: 4px solid var(--glow);
|
||||||
|
background: var(--paper-raised);
|
||||||
|
margin: 0.75rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-follow {
|
||||||
|
margin: 2rem 0 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.save-row {
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.follower-summary {
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-off .button-row {
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- Song lookup ------------------------------------------------------------ */
|
||||||
|
.song-search {
|
||||||
|
position: relative;
|
||||||
|
max-width: 28rem;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-search .field {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 10;
|
||||||
|
inset-inline: 0;
|
||||||
|
top: 100%;
|
||||||
|
margin: 0.25rem 0 0;
|
||||||
|
padding: 0.35rem;
|
||||||
|
list-style: none;
|
||||||
|
background: var(--paper-raised);
|
||||||
|
border: 1px solid var(--rule);
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
box-shadow: 0 8px 24px rgb(0 0 0 / 0.12);
|
||||||
|
max-height: 18rem;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results li {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results a {
|
||||||
|
display: block;
|
||||||
|
padding: 0.5rem 0.6rem;
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results a:hover,
|
||||||
|
.search-results a:focus-visible {
|
||||||
|
background: var(--panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results .by {
|
||||||
|
display: block;
|
||||||
|
color: var(--ink-soft);
|
||||||
|
font-size: var(--step--1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-results .empty {
|
||||||
|
padding: 0.5rem 0.6rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-meta {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
|
||||||
|
gap: 1rem 2rem;
|
||||||
|
margin: 1.25rem 0 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-meta div {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-meta dt {
|
||||||
|
font-size: var(--step--1);
|
||||||
|
color: var(--ink-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-meta dd {
|
||||||
|
margin: 0;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The song page's glowing display gets an art thumbnail alongside its text, when there's one */
|
||||||
|
.display-with-art {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.display-with-art .display-body {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.display-art {
|
||||||
|
width: 4.5rem;
|
||||||
|
height: 4.5rem;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- Album art ---------------------------------------------------------------- */
|
||||||
|
.art-thumb {
|
||||||
|
display: block;
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
object-fit: cover;
|
||||||
|
background: var(--paper-raised);
|
||||||
|
border: 1px solid var(--rule);
|
||||||
|
}
|
||||||
|
|
||||||
|
.art-thumb-empty {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* No artwork: a plain ring, echoing the record in .brand-mark */
|
||||||
|
.art-thumb-empty::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: 32%;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 2px solid var(--bar);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Most played > Albums: a thumbnail column ahead of the rank */
|
||||||
|
.ranking-art li {
|
||||||
|
grid-template-columns: 2.25rem 2rem minmax(0, 1fr) auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ranking-art .art-thumb {
|
||||||
|
width: 2.25rem;
|
||||||
|
height: 2.25rem;
|
||||||
|
align-self: center; /* .ranking li aligns its other cells to baseline, which suits text, not art */
|
||||||
|
}
|
||||||
|
|
||||||
|
.ranking-art .meter {
|
||||||
|
left: 5.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Recently played / History: a thumbnail column ahead of the time */
|
||||||
|
.log-art li {
|
||||||
|
grid-template-columns: 2.25rem 8rem minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-art.log-clock li {
|
||||||
|
grid-template-columns: 2.25rem 3.5rem minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-art .art-thumb {
|
||||||
|
width: 2.25rem;
|
||||||
|
height: 2.25rem;
|
||||||
|
align-self: center; /* .log li items default to stretch/start, which suits text, not art */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- Album art: fixing missing art ---------------------------------------------- */
|
||||||
|
.art-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 4rem minmax(0, 1fr);
|
||||||
|
gap: 1rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.art-thumb-lg {
|
||||||
|
width: 4rem;
|
||||||
|
height: 4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.art-row-body .muted {
|
||||||
|
margin: 0.35rem 0 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.art-correction {
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 4.7 KiB |
@@ -0,0 +1,7 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-6 8 196 196" width="512" height="512"><circle cx="88" cy="112" r="76" fill="#15131A" stroke="#F4F1EA" stroke-width="9"/>
|
||||||
|
<circle cx="88" cy="112" r="28" fill="#8B6CFF"/>
|
||||||
|
<path d="M168 32 L144 78" fill="none" stroke="#000000" stroke-width="14" stroke-linecap="round"/>
|
||||||
|
<circle cx="168" cy="32" r="14" fill="#F4F1EA" stroke="#000000" stroke-width="2.4"/>
|
||||||
|
<path d="M168 32 L144 78" fill="none" stroke="#F4F1EA" stroke-width="10" stroke-linecap="round"/>
|
||||||
|
<path d="M144 78 L126 108 L114 96" fill="none" stroke="#C8F560" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 639 B |
@@ -0,0 +1,36 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Followers · 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/followers.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="site-header" id="site-header"></header>
|
||||||
|
<main id="main">
|
||||||
|
<h1 class="page-title">Followers</h1>
|
||||||
|
<p class="lede">People on the fediverse who follow your listening. <a href="sharing.html">Sharing settings</a></p>
|
||||||
|
<div id="messages"></div>
|
||||||
|
<section aria-labelledby="requests-title" id="requests-section" hidden>
|
||||||
|
<h2 id="requests-title" class="section-head">Follow requests</h2>
|
||||||
|
<ul class="rows" id="requests"></ul>
|
||||||
|
</section>
|
||||||
|
<section aria-labelledby="followers-title">
|
||||||
|
<h2 id="followers-title" class="section-head">Followers</h2>
|
||||||
|
<ul class="rows" id="followers"></ul>
|
||||||
|
</section>
|
||||||
|
<section aria-labelledby="blocks-title" id="blocks-section" hidden>
|
||||||
|
<h2 id="blocks-title" class="section-head">Blocked</h2>
|
||||||
|
<ul class="rows" id="blocks"></ul>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -3,8 +3,12 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>History · Scrobbler</title>
|
<title>History · Scrobbled</title>
|
||||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
|
<link rel="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">
|
<link rel="stylesheet" href="css/style.css">
|
||||||
<script src="config.js"></script>
|
<script src="config.js"></script>
|
||||||
<script type="module" src="js/history.js"></script>
|
<script type="module" src="js/history.js"></script>
|
||||||
|
|||||||
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 35 KiB |
@@ -0,0 +1,7 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-6 8 196 196" width="512" height="512"><circle cx="88" cy="112" r="76" fill="#15131A" stroke="#F4F1EA" stroke-width="9"/>
|
||||||
|
<circle cx="88" cy="112" r="28" fill="#8B6CFF"/>
|
||||||
|
<path d="M168 32 L144 78" fill="none" stroke="#000000" stroke-width="14" stroke-linecap="round"/>
|
||||||
|
<circle cx="168" cy="32" r="14" fill="#F4F1EA" stroke="#000000" stroke-width="2.4"/>
|
||||||
|
<path d="M168 32 L144 78" fill="none" stroke="#F4F1EA" stroke-width="10" stroke-linecap="round"/>
|
||||||
|
<path d="M144 78 L126 108 L114 96" fill="none" stroke="#C8F560" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 639 B |
@@ -0,0 +1,10 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-6 8 196 196" width="512" height="512"><circle cx="88" cy="112" r="78" fill="#15131A" stroke="#F4F1EA" stroke-width="5"/>
|
||||||
|
<circle cx="88" cy="112" r="60" fill="none" stroke="#F4F1EA" stroke-width="2" stroke-opacity="0.4"/>
|
||||||
|
<circle cx="88" cy="112" r="46" fill="none" stroke="#F4F1EA" stroke-width="2" stroke-opacity="0.28"/>
|
||||||
|
<circle cx="88" cy="112" r="24" fill="#8B6CFF"/>
|
||||||
|
<circle cx="88" cy="112" r="4" fill="#15131A"/>
|
||||||
|
<path d="M168 32 L144 78" fill="none" stroke="#000000" stroke-width="9" stroke-linecap="round"/>
|
||||||
|
<circle cx="168" cy="32" r="12" fill="#F4F1EA" stroke="#000000" stroke-width="1.6"/>
|
||||||
|
<path d="M168 32 L144 78" fill="none" stroke="#F4F1EA" stroke-width="7" stroke-linecap="round"/>
|
||||||
|
<path d="M144 78 L128 108 L119 99" fill="none" stroke="#C8F560" stroke-width="11" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 888 B |
@@ -0,0 +1,11 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-35.0 -111.0 554.7 146.0" width="555" height="146" role="img" aria-label="scrobbled">
|
||||||
|
<path d="M27.8 1.4Q22.5 1.4 18.2 0.45Q13.9 -0.5 10.7 -2.3Q7.5 -4.1 5.45 -6.65Q3.4 -9.2 2.6 -12.3L14.6 -17.6Q15.3 -15.9 17.05 -14.15Q18.8 -12.4 21.75 -11.3Q24.7 -10.2 28.9 -10.2Q32.9 -10.2 35.15 -11.35Q37.4 -12.5 37.4 -14.7Q37.4 -16.3 36.15 -17.25Q34.9 -18.2 32.4 -18.95Q29.9 -19.7 26.2 -20.4Q22.4 -21.2 18.5 -22.25Q14.6 -23.3 11.2 -25.15Q7.8 -27 5.75 -30.05Q3.7 -33.1 3.7 -37.8Q3.7 -42.7 6.3 -46.35Q8.9 -50 14.05 -52.1Q19.2 -54.2 26.6 -54.2Q33.2 -54.2 38.2 -52.5Q43.2 -50.8 46.55 -47.65Q49.9 -44.5 51.2 -40.1L38.3 -35.5Q37.8 -37.7 36.25 -39.3Q34.7 -40.9 32.35 -41.75Q30 -42.6 26.8 -42.6Q22.9 -42.6 20.75 -41.4Q18.6 -40.2 18.6 -38.2Q18.6 -36.6 20.05 -35.55Q21.5 -34.5 24.2 -33.8Q26.9 -33.1 30.6 -32.3Q34.5 -31.5 38.35 -30.45Q42.2 -29.4 45.35 -27.65Q48.5 -25.9 50.35 -23.05Q52.2 -20.2 52.2 -15.7Q52.2 -10.4 49.4 -6.55Q46.6 -2.7 41.15 -0.65Q35.7 1.4 27.8 1.4Z" fill="#F4F1EA"/>
|
||||||
|
<path d="M84.6 1.4Q77.8 1.4 72.6 -0.5Q67.4 -2.4 63.9 -5.95Q60.4 -9.5 58.55 -14.5Q56.7 -19.5 56.7 -25.7Q56.7 -32.1 58.55 -37.3Q60.4 -42.5 63.9 -46.3Q67.4 -50.1 72.5 -52.15Q77.6 -54.2 84.2 -54.2Q90.8 -54.2 95.6 -52.1Q100.4 -50 103.45 -46.2Q106.5 -42.4 107.6 -37.4L92.7 -32.4Q92.4 -35.7 91.1 -37.8Q89.8 -39.9 87.75 -40.85Q85.7 -41.8 83.3 -41.8Q80.8 -41.8 78.9 -40.8Q77 -39.8 75.7 -37.8Q74.4 -35.8 73.7 -32.95Q73 -30.1 73 -26.4Q73 -21.1 74.35 -17.55Q75.7 -14 78.35 -12.2Q81 -10.4 84.8 -10.4Q88.7 -10.4 90.9 -12Q93.1 -13.6 94.1 -15.95Q95.1 -18.3 95.3 -20.6L109.3 -17.5Q108.9 -13.8 107.35 -10.35Q105.8 -6.9 102.8 -4.25Q99.8 -1.6 95.35 -0.1Q90.9 1.4 84.6 1.4Z" fill="#F4F1EA"/>
|
||||||
|
<path d="M114.8 0V-24.5V-52.8H128L128.3 -34.9H130.3Q131 -41.9 132.95 -46.05Q134.9 -50.2 138.55 -52.1Q142.2 -54 147.6 -54Q148.4 -54 149.4 -53.95Q150.4 -53.9 151.7 -53.7L151.1 -36.5Q149.5 -37.3 147.65 -37.55Q145.8 -37.8 144.4 -37.8Q140.5 -37.8 137.65 -36.3Q134.8 -34.8 133.15 -31.7Q131.5 -28.6 131 -23.9V0Z" fill="#F4F1EA"/>
|
||||||
|
<path d="M181.7 1.4Q173.7 1.4 167.55 -1.7Q161.4 -4.8 157.9 -11Q154.4 -17.2 154.4 -26.5Q154.4 -35.8 157.9 -41.95Q161.4 -48.1 167.6 -51.15Q173.8 -54.2 181.8 -54.2Q189.8 -54.2 196 -51.1Q202.2 -48 205.7 -41.85Q209.2 -35.7 209.2 -26.4Q209.2 -16.9 205.6 -10.7Q202 -4.5 195.75 -1.55Q189.5 1.4 181.7 1.4ZM182.2 -10.3Q185.8 -10.3 188.2 -11.95Q190.6 -13.6 191.8 -17Q193 -20.4 193 -25.4Q193 -30.7 191.7 -34.35Q190.4 -38 187.85 -39.95Q185.3 -41.9 181.3 -41.9Q177.9 -41.9 175.45 -40.25Q173 -38.6 171.8 -35.2Q170.6 -31.8 170.6 -26.7Q170.6 -18.5 173.65 -14.4Q176.7 -10.3 182.2 -10.3Z" fill="#F4F1EA"/>
|
||||||
|
<path d="M250 1.4Q245 1.4 241.25 -0.5Q237.5 -2.4 235.15 -6.2Q232.8 -10 232 -15.6H230.1L229.8 0H216.6V-25.9V-72H232.7V-54.5Q232.7 -52.1 232.35 -49.45Q232 -46.8 231.45 -43.9Q230.9 -41 230.3 -37.7H232.6Q234 -43.1 236.3 -46.7Q238.6 -50.3 242.05 -52.15Q245.5 -54 250.2 -54Q256.8 -54 261.65 -50.6Q266.5 -47.2 269.2 -40.95Q271.9 -34.7 271.9 -26Q271.9 -17.6 269.25 -11.45Q266.6 -5.3 261.7 -1.95Q256.8 1.4 250 1.4ZM244 -11.6Q247.3 -11.6 249.8 -13.45Q252.3 -15.3 253.65 -18.65Q255 -22 255 -26.5Q255 -31.1 253.7 -34.35Q252.4 -37.6 250.05 -39.4Q247.7 -41.2 244.4 -41.2Q242.2 -41.2 240.35 -40.4Q238.5 -39.6 237.1 -38.2Q235.7 -36.8 234.7 -35.05Q233.7 -33.3 233.2 -31.35Q232.7 -29.4 232.7 -27.5V-25.4Q232.7 -23.3 233.3 -20.9Q233.9 -18.5 235.25 -16.4Q236.6 -14.3 238.75 -12.95Q240.9 -11.6 244 -11.6Z" fill="#C8F560"/>
|
||||||
|
<path d="M312.8 1.4Q307.8 1.4 304.05 -0.5Q300.3 -2.4 297.95 -6.2Q295.6 -10 294.8 -15.6H292.9L292.6 0H279.4V-25.9V-72H295.5V-54.5Q295.5 -52.1 295.15 -49.45Q294.8 -46.8 294.25 -43.9Q293.7 -41 293.1 -37.7H295.4Q296.8 -43.1 299.1 -46.7Q301.4 -50.3 304.85 -52.15Q308.3 -54 313 -54Q319.6 -54 324.45 -50.6Q329.3 -47.2 332 -40.95Q334.7 -34.7 334.7 -26Q334.7 -17.6 332.05 -11.45Q329.4 -5.3 324.5 -1.95Q319.6 1.4 312.8 1.4ZM306.8 -11.6Q310.1 -11.6 312.6 -13.45Q315.1 -15.3 316.45 -18.65Q317.8 -22 317.8 -26.5Q317.8 -31.1 316.5 -34.35Q315.2 -37.6 312.85 -39.4Q310.5 -41.2 307.2 -41.2Q305 -41.2 303.15 -40.4Q301.3 -39.6 299.9 -38.2Q298.5 -36.8 297.5 -35.05Q296.5 -33.3 296 -31.35Q295.5 -29.4 295.5 -27.5V-25.4Q295.5 -23.3 296.1 -20.9Q296.7 -18.5 298.05 -16.4Q299.4 -14.3 301.55 -12.95Q303.7 -11.6 306.8 -11.6Z" fill="#F4F1EA"/>
|
||||||
|
<path d="M342.2 0V-72H358V0Z" fill="#F4F1EA"/>
|
||||||
|
<path d="M393.6 1.4Q387 1.4 381.8 -0.35Q376.6 -2.1 372.95 -5.5Q369.3 -8.9 367.4 -13.9Q365.5 -18.9 365.5 -25.4Q365.5 -31.7 367.35 -37Q369.2 -42.3 372.65 -46.15Q376.1 -50 381.15 -52.1Q386.2 -54.2 392.5 -54.2Q398.9 -54.2 403.75 -52.15Q408.6 -50.1 411.75 -46.1Q414.9 -42.1 416.4 -36.35Q417.9 -30.6 417.4 -23.2L376.1 -22.9V-31.3L408.2 -31.6L402.5 -27.7Q403.2 -32.7 401.9 -35.85Q400.6 -39 398.1 -40.45Q395.6 -41.9 392.7 -41.9Q389.2 -41.9 386.55 -40Q383.9 -38.1 382.4 -34.5Q380.9 -30.9 380.9 -25.7Q380.9 -17.5 384.45 -13.8Q388 -10.1 393.5 -10.1Q396.2 -10.1 398 -10.85Q399.8 -11.6 400.95 -12.75Q402.1 -13.9 402.75 -15.3Q403.4 -16.7 403.8 -18L417.8 -15Q417 -11.3 415.25 -8.3Q413.5 -5.3 410.55 -3.1Q407.6 -0.9 403.45 0.25Q399.3 1.4 393.6 1.4Z" fill="#F4F1EA"/>
|
||||||
|
<path d="M445.3 1.4Q438.7 1.4 433.75 -1.95Q428.8 -5.3 426 -11.55Q423.2 -17.8 423.2 -26.5Q423.2 -34.5 425.6 -40.7Q428 -46.9 432.75 -50.45Q437.5 -54 444.5 -54Q449.5 -54 452.95 -52.2Q456.4 -50.4 458.7 -46.8Q461 -43.2 462.4 -37.7H464.9Q464.2 -41.1 463.6 -44.15Q463 -47.2 462.65 -49.85Q462.3 -52.5 462.3 -54.5V-72H478.5V-25.8V0H465.3L465.1 -15.6H462.9Q461.8 -9.6 459.45 -5.85Q457.1 -2.1 453.55 -0.35Q450 1.4 445.3 1.4ZM451.1 -11.6Q454.2 -11.6 456.35 -12.95Q458.5 -14.3 459.8 -16.4Q461.1 -18.5 461.7 -20.9Q462.3 -23.3 462.3 -25.4V-27.5Q462.3 -29.4 461.8 -31.3Q461.3 -33.2 460.35 -35Q459.4 -36.8 458 -38.2Q456.6 -39.6 454.75 -40.4Q452.9 -41.2 450.7 -41.2Q447.4 -41.2 445.05 -39.4Q442.7 -37.6 441.45 -34.3Q440.2 -31 440.2 -26.5Q440.2 -22 441.5 -18.65Q442.8 -15.3 445.3 -13.45Q447.8 -11.6 451.1 -11.6Z" fill="#F4F1EA"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 5.7 KiB |
@@ -0,0 +1,11 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-35.0 -111.0 554.7 146.0" width="555" height="146" role="img" aria-label="scrobbled">
|
||||||
|
<path d="M27.8 1.4Q22.5 1.4 18.2 0.45Q13.9 -0.5 10.7 -2.3Q7.5 -4.1 5.45 -6.65Q3.4 -9.2 2.6 -12.3L14.6 -17.6Q15.3 -15.9 17.05 -14.15Q18.8 -12.4 21.75 -11.3Q24.7 -10.2 28.9 -10.2Q32.9 -10.2 35.15 -11.35Q37.4 -12.5 37.4 -14.7Q37.4 -16.3 36.15 -17.25Q34.9 -18.2 32.4 -18.95Q29.9 -19.7 26.2 -20.4Q22.4 -21.2 18.5 -22.25Q14.6 -23.3 11.2 -25.15Q7.8 -27 5.75 -30.05Q3.7 -33.1 3.7 -37.8Q3.7 -42.7 6.3 -46.35Q8.9 -50 14.05 -52.1Q19.2 -54.2 26.6 -54.2Q33.2 -54.2 38.2 -52.5Q43.2 -50.8 46.55 -47.65Q49.9 -44.5 51.2 -40.1L38.3 -35.5Q37.8 -37.7 36.25 -39.3Q34.7 -40.9 32.35 -41.75Q30 -42.6 26.8 -42.6Q22.9 -42.6 20.75 -41.4Q18.6 -40.2 18.6 -38.2Q18.6 -36.6 20.05 -35.55Q21.5 -34.5 24.2 -33.8Q26.9 -33.1 30.6 -32.3Q34.5 -31.5 38.35 -30.45Q42.2 -29.4 45.35 -27.65Q48.5 -25.9 50.35 -23.05Q52.2 -20.2 52.2 -15.7Q52.2 -10.4 49.4 -6.55Q46.6 -2.7 41.15 -0.65Q35.7 1.4 27.8 1.4Z" fill="#15131A"/>
|
||||||
|
<path d="M84.6 1.4Q77.8 1.4 72.6 -0.5Q67.4 -2.4 63.9 -5.95Q60.4 -9.5 58.55 -14.5Q56.7 -19.5 56.7 -25.7Q56.7 -32.1 58.55 -37.3Q60.4 -42.5 63.9 -46.3Q67.4 -50.1 72.5 -52.15Q77.6 -54.2 84.2 -54.2Q90.8 -54.2 95.6 -52.1Q100.4 -50 103.45 -46.2Q106.5 -42.4 107.6 -37.4L92.7 -32.4Q92.4 -35.7 91.1 -37.8Q89.8 -39.9 87.75 -40.85Q85.7 -41.8 83.3 -41.8Q80.8 -41.8 78.9 -40.8Q77 -39.8 75.7 -37.8Q74.4 -35.8 73.7 -32.95Q73 -30.1 73 -26.4Q73 -21.1 74.35 -17.55Q75.7 -14 78.35 -12.2Q81 -10.4 84.8 -10.4Q88.7 -10.4 90.9 -12Q93.1 -13.6 94.1 -15.95Q95.1 -18.3 95.3 -20.6L109.3 -17.5Q108.9 -13.8 107.35 -10.35Q105.8 -6.9 102.8 -4.25Q99.8 -1.6 95.35 -0.1Q90.9 1.4 84.6 1.4Z" fill="#15131A"/>
|
||||||
|
<path d="M114.8 0V-24.5V-52.8H128L128.3 -34.9H130.3Q131 -41.9 132.95 -46.05Q134.9 -50.2 138.55 -52.1Q142.2 -54 147.6 -54Q148.4 -54 149.4 -53.95Q150.4 -53.9 151.7 -53.7L151.1 -36.5Q149.5 -37.3 147.65 -37.55Q145.8 -37.8 144.4 -37.8Q140.5 -37.8 137.65 -36.3Q134.8 -34.8 133.15 -31.7Q131.5 -28.6 131 -23.9V0Z" fill="#15131A"/>
|
||||||
|
<path d="M181.7 1.4Q173.7 1.4 167.55 -1.7Q161.4 -4.8 157.9 -11Q154.4 -17.2 154.4 -26.5Q154.4 -35.8 157.9 -41.95Q161.4 -48.1 167.6 -51.15Q173.8 -54.2 181.8 -54.2Q189.8 -54.2 196 -51.1Q202.2 -48 205.7 -41.85Q209.2 -35.7 209.2 -26.4Q209.2 -16.9 205.6 -10.7Q202 -4.5 195.75 -1.55Q189.5 1.4 181.7 1.4ZM182.2 -10.3Q185.8 -10.3 188.2 -11.95Q190.6 -13.6 191.8 -17Q193 -20.4 193 -25.4Q193 -30.7 191.7 -34.35Q190.4 -38 187.85 -39.95Q185.3 -41.9 181.3 -41.9Q177.9 -41.9 175.45 -40.25Q173 -38.6 171.8 -35.2Q170.6 -31.8 170.6 -26.7Q170.6 -18.5 173.65 -14.4Q176.7 -10.3 182.2 -10.3Z" fill="#15131A"/>
|
||||||
|
<path d="M250 1.4Q245 1.4 241.25 -0.5Q237.5 -2.4 235.15 -6.2Q232.8 -10 232 -15.6H230.1L229.8 0H216.6V-25.9V-72H232.7V-54.5Q232.7 -52.1 232.35 -49.45Q232 -46.8 231.45 -43.9Q230.9 -41 230.3 -37.7H232.6Q234 -43.1 236.3 -46.7Q238.6 -50.3 242.05 -52.15Q245.5 -54 250.2 -54Q256.8 -54 261.65 -50.6Q266.5 -47.2 269.2 -40.95Q271.9 -34.7 271.9 -26Q271.9 -17.6 269.25 -11.45Q266.6 -5.3 261.7 -1.95Q256.8 1.4 250 1.4ZM244 -11.6Q247.3 -11.6 249.8 -13.45Q252.3 -15.3 253.65 -18.65Q255 -22 255 -26.5Q255 -31.1 253.7 -34.35Q252.4 -37.6 250.05 -39.4Q247.7 -41.2 244.4 -41.2Q242.2 -41.2 240.35 -40.4Q238.5 -39.6 237.1 -38.2Q235.7 -36.8 234.7 -35.05Q233.7 -33.3 233.2 -31.35Q232.7 -29.4 232.7 -27.5V-25.4Q232.7 -23.3 233.3 -20.9Q233.9 -18.5 235.25 -16.4Q236.6 -14.3 238.75 -12.95Q240.9 -11.6 244 -11.6Z" fill="#8B6CFF"/>
|
||||||
|
<path d="M312.8 1.4Q307.8 1.4 304.05 -0.5Q300.3 -2.4 297.95 -6.2Q295.6 -10 294.8 -15.6H292.9L292.6 0H279.4V-25.9V-72H295.5V-54.5Q295.5 -52.1 295.15 -49.45Q294.8 -46.8 294.25 -43.9Q293.7 -41 293.1 -37.7H295.4Q296.8 -43.1 299.1 -46.7Q301.4 -50.3 304.85 -52.15Q308.3 -54 313 -54Q319.6 -54 324.45 -50.6Q329.3 -47.2 332 -40.95Q334.7 -34.7 334.7 -26Q334.7 -17.6 332.05 -11.45Q329.4 -5.3 324.5 -1.95Q319.6 1.4 312.8 1.4ZM306.8 -11.6Q310.1 -11.6 312.6 -13.45Q315.1 -15.3 316.45 -18.65Q317.8 -22 317.8 -26.5Q317.8 -31.1 316.5 -34.35Q315.2 -37.6 312.85 -39.4Q310.5 -41.2 307.2 -41.2Q305 -41.2 303.15 -40.4Q301.3 -39.6 299.9 -38.2Q298.5 -36.8 297.5 -35.05Q296.5 -33.3 296 -31.35Q295.5 -29.4 295.5 -27.5V-25.4Q295.5 -23.3 296.1 -20.9Q296.7 -18.5 298.05 -16.4Q299.4 -14.3 301.55 -12.95Q303.7 -11.6 306.8 -11.6Z" fill="#15131A"/>
|
||||||
|
<path d="M342.2 0V-72H358V0Z" fill="#15131A"/>
|
||||||
|
<path d="M393.6 1.4Q387 1.4 381.8 -0.35Q376.6 -2.1 372.95 -5.5Q369.3 -8.9 367.4 -13.9Q365.5 -18.9 365.5 -25.4Q365.5 -31.7 367.35 -37Q369.2 -42.3 372.65 -46.15Q376.1 -50 381.15 -52.1Q386.2 -54.2 392.5 -54.2Q398.9 -54.2 403.75 -52.15Q408.6 -50.1 411.75 -46.1Q414.9 -42.1 416.4 -36.35Q417.9 -30.6 417.4 -23.2L376.1 -22.9V-31.3L408.2 -31.6L402.5 -27.7Q403.2 -32.7 401.9 -35.85Q400.6 -39 398.1 -40.45Q395.6 -41.9 392.7 -41.9Q389.2 -41.9 386.55 -40Q383.9 -38.1 382.4 -34.5Q380.9 -30.9 380.9 -25.7Q380.9 -17.5 384.45 -13.8Q388 -10.1 393.5 -10.1Q396.2 -10.1 398 -10.85Q399.8 -11.6 400.95 -12.75Q402.1 -13.9 402.75 -15.3Q403.4 -16.7 403.8 -18L417.8 -15Q417 -11.3 415.25 -8.3Q413.5 -5.3 410.55 -3.1Q407.6 -0.9 403.45 0.25Q399.3 1.4 393.6 1.4Z" fill="#15131A"/>
|
||||||
|
<path d="M445.3 1.4Q438.7 1.4 433.75 -1.95Q428.8 -5.3 426 -11.55Q423.2 -17.8 423.2 -26.5Q423.2 -34.5 425.6 -40.7Q428 -46.9 432.75 -50.45Q437.5 -54 444.5 -54Q449.5 -54 452.95 -52.2Q456.4 -50.4 458.7 -46.8Q461 -43.2 462.4 -37.7H464.9Q464.2 -41.1 463.6 -44.15Q463 -47.2 462.65 -49.85Q462.3 -52.5 462.3 -54.5V-72H478.5V-25.8V0H465.3L465.1 -15.6H462.9Q461.8 -9.6 459.45 -5.85Q457.1 -2.1 453.55 -0.35Q450 1.4 445.3 1.4ZM451.1 -11.6Q454.2 -11.6 456.35 -12.95Q458.5 -14.3 459.8 -16.4Q461.1 -18.5 461.7 -20.9Q462.3 -23.3 462.3 -25.4V-27.5Q462.3 -29.4 461.8 -31.3Q461.3 -33.2 460.35 -35Q459.4 -36.8 458 -38.2Q456.6 -39.6 454.75 -40.4Q452.9 -41.2 450.7 -41.2Q447.4 -41.2 445.05 -39.4Q442.7 -37.6 441.45 -34.3Q440.2 -31 440.2 -26.5Q440.2 -22 441.5 -18.65Q442.8 -15.3 445.3 -13.45Q447.8 -11.6 451.1 -11.6Z" fill="#15131A"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 5.7 KiB |
@@ -3,8 +3,12 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Import · Scrobbler</title>
|
<title>Import · Scrobbled</title>
|
||||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
|
<link rel="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">
|
<link rel="stylesheet" href="css/style.css">
|
||||||
<script src="config.js"></script>
|
<script src="config.js"></script>
|
||||||
<script type="module" src="js/import.js"></script>
|
<script type="module" src="js/import.js"></script>
|
||||||
|
|||||||
@@ -3,8 +3,12 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Overview · Scrobbler</title>
|
<title>Overview · Scrobbled</title>
|
||||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
|
<link rel="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">
|
<link rel="stylesheet" href="css/style.css">
|
||||||
<script src="config.js"></script>
|
<script src="config.js"></script>
|
||||||
<script type="module" src="js/dashboard.js"></script>
|
<script type="module" src="js/dashboard.js"></script>
|
||||||
@@ -14,6 +18,14 @@
|
|||||||
<main id="main">
|
<main id="main">
|
||||||
<h1 class="visually-hidden">Overview</h1>
|
<h1 class="visually-hidden">Overview</h1>
|
||||||
<div id="panel" class="panel" aria-live="polite"></div>
|
<div id="panel" class="panel" aria-live="polite"></div>
|
||||||
|
<section aria-labelledby="song-search-title" class="song-search">
|
||||||
|
<h2 id="song-search-title" class="visually-hidden">Find a song</h2>
|
||||||
|
<div class="field">
|
||||||
|
<label for="song-search">Find a song</label>
|
||||||
|
<input id="song-search" type="search" autocomplete="off" placeholder="Search your scrobbles…">
|
||||||
|
</div>
|
||||||
|
<ul class="search-results" id="song-search-results" hidden></ul>
|
||||||
|
</section>
|
||||||
<section aria-labelledby="charts-title">
|
<section aria-labelledby="charts-title">
|
||||||
<div class="section-head">
|
<div class="section-head">
|
||||||
<h2 id="charts-title">Most played</h2>
|
<h2 id="charts-title">Most played</h2>
|
||||||
@@ -23,6 +35,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="charts">
|
<div class="charts">
|
||||||
<div><h3 class="muted">Artists</h3><ol class="ranking" id="top-artists"></ol></div>
|
<div><h3 class="muted">Artists</h3><ol class="ranking" id="top-artists"></ol></div>
|
||||||
|
<div><h3 class="muted">Albums</h3><ol class="ranking ranking-art" id="top-albums"></ol></div>
|
||||||
<div><h3 class="muted">Tracks</h3><ol class="ranking" id="top-tracks"></ol></div>
|
<div><h3 class="muted">Tracks</h3><ol class="ranking" id="top-tracks"></ol></div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -31,7 +44,7 @@
|
|||||||
<h2 id="recent-title">Recently played</h2>
|
<h2 id="recent-title">Recently played</h2>
|
||||||
<a href="history.html">Full history</a>
|
<a href="history.html">Full history</a>
|
||||||
</div>
|
</div>
|
||||||
<ol class="log" id="recent"></ol>
|
<ol class="log log-stacked log-art" id="recent"></ol>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
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)));
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// Thin client for the Scrobbler /api/v1 JSON API.
|
// Thin client for the Scrobbled /api/v1 JSON API.
|
||||||
|
|
||||||
const TOKEN_KEY = "scrobbler.token";
|
const TOKEN_KEY = "scrobbler.token";
|
||||||
|
|
||||||
@@ -40,6 +40,29 @@ export function redirectToLogin() {
|
|||||||
location.href = `login.html?next=${encodeURIComponent(safeNext(here + location.search))}`;
|
location.href = `login.html?next=${encodeURIComponent(safeNext(here + location.search))}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fetches a binary resource (e.g. album art) with the same bearer-auth transport as api(),
|
||||||
|
// returning a blob: object URL, or null on any failure (including a 404 "no art" response) -
|
||||||
|
// the caller treats "missing" and "couldn't fetch" the same way: show a placeholder.
|
||||||
|
export async function fetchImage(path) {
|
||||||
|
const headers = {};
|
||||||
|
const token = getToken();
|
||||||
|
if (token) headers.Authorization = `Bearer ${token}`;
|
||||||
|
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await fetch(`${apiBase}/api/v1${path}`, { headers });
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (response.status === 401) {
|
||||||
|
setToken(null);
|
||||||
|
redirectToLogin();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!response.ok) return null;
|
||||||
|
return URL.createObjectURL(await response.blob());
|
||||||
|
}
|
||||||
|
|
||||||
export async function api(path, { method = "GET", body, auth = true } = {}) {
|
export async function api(path, { method = "GET", body, auth = true } = {}) {
|
||||||
const headers = {};
|
const headers = {};
|
||||||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||||
@@ -54,7 +77,7 @@ export async function api(path, { method = "GET", body, auth = true } = {}) {
|
|||||||
body: body === undefined ? undefined : JSON.stringify(body),
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
throw new ApiError(0, "network", `Can't reach the Scrobbler API at ${apiBase}. Check that it's running.`);
|
throw new ApiError(0, "network", `Can't reach the Scrobbled API at ${apiBase}. Check that it's running.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response.status === 401 && auth) {
|
if (response.status === 401 && auth) {
|
||||||
@@ -79,7 +102,7 @@ export async function api(path, { method = "GET", body, auth = true } = {}) {
|
|||||||
|
|
||||||
// Turn webargs validation details into a single readable sentence.
|
// Turn webargs validation details into a single readable sentence.
|
||||||
export function describeError(error) {
|
export function describeError(error) {
|
||||||
const fields = error.details?.json ?? error.details?.query;
|
const fields = error.details?.json ?? error.details?.query ?? error.details?.files;
|
||||||
if (fields) {
|
if (fields) {
|
||||||
return Object.entries(fields)
|
return Object.entries(fields)
|
||||||
.map(([field, messages]) => `${field}: ${[].concat(messages).join(" ")}`)
|
.map(([field, messages]) => `${field}: ${[].concat(messages).join(" ")}`)
|
||||||
@@ -89,17 +112,17 @@ export function describeError(error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Multipart upload with progress (fetch can't report upload progress).
|
// Multipart upload with progress (fetch can't report upload progress).
|
||||||
export function upload(path, formData, onProgress) {
|
export function upload(path, formData, onProgress, method = "POST") {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const xhr = new XMLHttpRequest();
|
const xhr = new XMLHttpRequest();
|
||||||
xhr.open("POST", `${apiBase}/api/v1${path}`);
|
xhr.open(method, `${apiBase}/api/v1${path}`);
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
|
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
|
||||||
xhr.upload.addEventListener("progress", (event) => {
|
xhr.upload.addEventListener("progress", (event) => {
|
||||||
if (event.lengthComputable) onProgress?.(event.loaded / event.total);
|
if (event.lengthComputable) onProgress?.(event.loaded / event.total);
|
||||||
});
|
});
|
||||||
xhr.addEventListener("error", () =>
|
xhr.addEventListener("error", () =>
|
||||||
reject(new ApiError(0, "network", `Can't reach the Scrobbler API at ${apiBase}. Check that it's running.`)),
|
reject(new ApiError(0, "network", `Can't reach the Scrobbled API at ${apiBase}. Check that it's running.`)),
|
||||||
);
|
);
|
||||||
xhr.addEventListener("load", () => {
|
xhr.addEventListener("load", () => {
|
||||||
let data = null;
|
let data = null;
|
||||||
|
|||||||
@@ -113,7 +113,7 @@ function renderSetup() {
|
|||||||
h("dt", {}, "Username"),
|
h("dt", {}, "Username"),
|
||||||
h("dd", {}, h("code", {}, user.username)),
|
h("dd", {}, h("code", {}, user.username)),
|
||||||
h("dt", {}, "Password"),
|
h("dt", {}, "Password"),
|
||||||
h("dd", {}, "Your Scrobbler password"),
|
h("dd", {}, "Your Scrobbled password"),
|
||||||
h("dt", {}, "Key and secret"),
|
h("dt", {}, "Key and secret"),
|
||||||
h("dd", {}, "From one of the apps above"),
|
h("dd", {}, "From one of the apps above"),
|
||||||
h("dt", {}, "API reference"),
|
h("dt", {}, "API reference"),
|
||||||
|
|||||||
@@ -0,0 +1,178 @@
|
|||||||
|
import { api, describeError, upload } from "./api.js";
|
||||||
|
import { artThumb, forgetArt } from "./art.js";
|
||||||
|
import { errorBox, h, num, replace } from "./dom.js";
|
||||||
|
import { signedInPage } from "./layout.js";
|
||||||
|
|
||||||
|
const PER_PAGE = 25;
|
||||||
|
const list = document.getElementById("albums");
|
||||||
|
const messages = document.getElementById("messages");
|
||||||
|
const pager = document.getElementById("pager");
|
||||||
|
const page = Math.max(1, Number.parseInt(new URLSearchParams(location.search).get("page"), 10) || 1);
|
||||||
|
|
||||||
|
await signedInPage("art.html");
|
||||||
|
await refresh();
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
try {
|
||||||
|
render(await api(`/art/failures?page=${page}&limit=${PER_PAGE}`));
|
||||||
|
} catch (error) {
|
||||||
|
replace(list, h("li", {}, errorBox(error.message)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(result) {
|
||||||
|
document.getElementById("art-summary").textContent = result.total
|
||||||
|
? `${num(result.total)} of your albums have no cover art, most-played first. Upload a picture, retry the lookup, or correct what it searches for.`
|
||||||
|
: "Every album you've scrobbled has cover art, or is still being looked up.";
|
||||||
|
if (!result.items.length) {
|
||||||
|
replace(list);
|
||||||
|
} else {
|
||||||
|
replace(list, result.items.map(albumRow));
|
||||||
|
}
|
||||||
|
replace(
|
||||||
|
pager,
|
||||||
|
result.page > 1 ? h("a", { class: "button button-quiet", href: `?page=${result.page - 1}` }, "Previous") : h("span"),
|
||||||
|
result.page < result.total_pages
|
||||||
|
? h("a", { class: "button button-quiet", href: `?page=${result.page + 1}` }, "Next")
|
||||||
|
: h("span"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusText(item) {
|
||||||
|
const own = item.override;
|
||||||
|
if (own?.status === "pending") return "Your correction is waiting to be looked up.";
|
||||||
|
if (own?.status === "error") {
|
||||||
|
return own.error_code === "NotFound"
|
||||||
|
? "Your correction didn't find any art."
|
||||||
|
: `Your correction failed (${own.error_code ?? "unknown error"}).`;
|
||||||
|
}
|
||||||
|
if (item.status === "error") return `The lookup failed (${item.error_code ?? "unknown error"}). It will be tried again.`;
|
||||||
|
if (item.status === "not_found") return "No cover art was found for this album.";
|
||||||
|
return "Waiting to be looked up.";
|
||||||
|
}
|
||||||
|
|
||||||
|
function say(notice) {
|
||||||
|
replace(messages, notice);
|
||||||
|
}
|
||||||
|
|
||||||
|
function albumRow(item) {
|
||||||
|
const { artist, album } = item;
|
||||||
|
const query = `artist=${encodeURIComponent(artist)}&album=${encodeURIComponent(album)}`;
|
||||||
|
const fileInput = h("input", { type: "file", accept: "image/jpeg,image/png,image/webp", hidden: true });
|
||||||
|
const correction = correctionForm(item, query);
|
||||||
|
const buttons = h("div", { class: "button-row" });
|
||||||
|
const busy = (on) => buttons.querySelectorAll("button").forEach((b) => (b.disabled = on));
|
||||||
|
|
||||||
|
async function act(work, done) {
|
||||||
|
busy(true);
|
||||||
|
replace(messages);
|
||||||
|
try {
|
||||||
|
await work();
|
||||||
|
say(h("p", { class: "notice notice-ok", role: "status" }, done));
|
||||||
|
forgetArt(artist, album);
|
||||||
|
await refresh();
|
||||||
|
} catch (error) {
|
||||||
|
say(errorBox(describeError(error)));
|
||||||
|
} finally {
|
||||||
|
busy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fileInput.addEventListener("change", () => {
|
||||||
|
const file = fileInput.files[0];
|
||||||
|
if (!file) return;
|
||||||
|
const data = new FormData();
|
||||||
|
data.append("file", file);
|
||||||
|
act(() => upload(`/art/album?${query}`, data), `Uploaded art for ${album}.`);
|
||||||
|
fileInput.value = "";
|
||||||
|
});
|
||||||
|
|
||||||
|
replace(
|
||||||
|
buttons,
|
||||||
|
h("button", { type: "button", class: "button", onclick: () => fileInput.click() }, "Upload art"),
|
||||||
|
h(
|
||||||
|
"button",
|
||||||
|
{
|
||||||
|
type: "button",
|
||||||
|
class: "button button-quiet",
|
||||||
|
onclick: () => act(() => api(`/art/album/retry?${query}`, { method: "POST" }), `Looking up ${album} again.`),
|
||||||
|
},
|
||||||
|
"Retry lookup",
|
||||||
|
),
|
||||||
|
h(
|
||||||
|
"button",
|
||||||
|
{ type: "button", class: "button button-quiet", onclick: () => (correction.hidden = !correction.hidden) },
|
||||||
|
"Correct search",
|
||||||
|
),
|
||||||
|
item.override
|
||||||
|
? h(
|
||||||
|
"button",
|
||||||
|
{
|
||||||
|
type: "button",
|
||||||
|
class: "button button-quiet",
|
||||||
|
onclick: () => act(() => api(`/art/album?${query}`, { method: "DELETE" }), `Removed your correction for ${album}.`),
|
||||||
|
},
|
||||||
|
"Remove mine",
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
correction.addEventListener("submit", (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const body = { artist, album };
|
||||||
|
const { search_artist, search_album, release_group_mbid, release_mbid } = correction.elements;
|
||||||
|
if (search_artist.value.trim()) body.search_artist = search_artist.value.trim();
|
||||||
|
if (search_album.value.trim()) body.search_album = search_album.value.trim();
|
||||||
|
if (release_group_mbid.value.trim()) body.release_group_mbid = release_group_mbid.value.trim();
|
||||||
|
if (release_mbid.value.trim()) body.release_mbid = release_mbid.value.trim();
|
||||||
|
act(() => api("/art/album/correction", { method: "PUT", body }), `Queued a corrected lookup for ${album}.`);
|
||||||
|
});
|
||||||
|
|
||||||
|
return h(
|
||||||
|
"li",
|
||||||
|
{ class: "art-row" },
|
||||||
|
artThumb(artist, album, "art-thumb-lg"),
|
||||||
|
h(
|
||||||
|
"div",
|
||||||
|
{ class: "art-row-body" },
|
||||||
|
h("span", { class: "row-title" }, album),
|
||||||
|
h("span", { class: "by" }, ` by ${artist}`),
|
||||||
|
h("p", { class: "muted" }, `${num(item.scrobbles)} ${item.scrobbles === 1 ? "scrobble" : "scrobbles"} · ${statusText(item)}`),
|
||||||
|
buttons,
|
||||||
|
fileInput,
|
||||||
|
correction,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function correctionForm(item, query) {
|
||||||
|
const own = item.override ?? {};
|
||||||
|
const field = (name, label, value, hint, extra = {}) =>
|
||||||
|
h(
|
||||||
|
"div",
|
||||||
|
{ class: "field" },
|
||||||
|
h("label", { for: `${name}-${query}` }, label),
|
||||||
|
h("input", { id: `${name}-${query}`, name, type: "text", value: value ?? "", autocomplete: "off", ...extra }),
|
||||||
|
hint ? h("p", { class: "hint" }, hint) : null,
|
||||||
|
);
|
||||||
|
return h(
|
||||||
|
"form",
|
||||||
|
{ class: "stacked-form art-correction", hidden: true },
|
||||||
|
field("search_artist", "Search for artist", own.search_artist ?? item.artist),
|
||||||
|
field("search_album", "Search for album", own.search_album ?? item.album),
|
||||||
|
field(
|
||||||
|
"release_group_mbid",
|
||||||
|
"MusicBrainz release-group ID (optional)",
|
||||||
|
own.release_group_mbid,
|
||||||
|
"If you know it, paste the ID from the album's MusicBrainz page. It skips the search.",
|
||||||
|
{ placeholder: "00000000-0000-0000-0000-000000000000", pattern: "[0-9a-fA-F-]{36}" },
|
||||||
|
),
|
||||||
|
field(
|
||||||
|
"release_mbid",
|
||||||
|
"MusicBrainz release ID (optional)",
|
||||||
|
own.release_mbid,
|
||||||
|
"Or a specific release's ID, if that's the one you have. Use either this or the release-group ID.",
|
||||||
|
{ placeholder: "00000000-0000-0000-0000-000000000000", pattern: "[0-9a-fA-F-]{36}" },
|
||||||
|
),
|
||||||
|
h("button", { type: "submit", class: "button" }, "Look it up"),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// A small thumbnail that starts as a placeholder and swaps itself for the real album art
|
||||||
|
// once (if) it resolves. Shared by every list/page that shows art.
|
||||||
|
|
||||||
|
import { fetchImage } from "./api.js";
|
||||||
|
import { h } from "./dom.js";
|
||||||
|
|
||||||
|
const cache = new Map(); // dedupes repeat/concurrent lookups for the same album within a page
|
||||||
|
|
||||||
|
const keyFor = (artist, album) => `${artist.toLowerCase()}␟${album.toLowerCase()}`;
|
||||||
|
|
||||||
|
// Forget a looked-up album (after the user uploads or corrects its art) so the next
|
||||||
|
// artThumb() for it asks the server again instead of reusing the stale answer.
|
||||||
|
export function forgetArt(artist, album) {
|
||||||
|
cache.delete(keyFor(artist, album));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function artThumb(artist, album, extraClass) {
|
||||||
|
const classes = extraClass ? `art-thumb ${extraClass}` : "art-thumb";
|
||||||
|
const el = h("div", { class: `${classes} art-thumb-empty` });
|
||||||
|
if (!album) return el; // nothing to look up
|
||||||
|
|
||||||
|
const key = keyFor(artist, album);
|
||||||
|
if (!cache.has(key)) {
|
||||||
|
cache.set(
|
||||||
|
key,
|
||||||
|
fetchImage(`/art/album?artist=${encodeURIComponent(artist)}&album=${encodeURIComponent(album)}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
cache.get(key).then((url) => {
|
||||||
|
if (!url) return; // miss or failed fetch: leave the placeholder
|
||||||
|
// Not revoked: the same URL is shared by every thumbnail for this album on the page
|
||||||
|
// (see `cache` above), and this is a full-page-reload site, so the browser releases it
|
||||||
|
// on navigation anyway.
|
||||||
|
const img = h("img", { class: classes, alt: "", loading: "lazy" });
|
||||||
|
img.src = url;
|
||||||
|
el.replaceWith(img);
|
||||||
|
});
|
||||||
|
return el;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import { api } from "./api.js";
|
import { api } from "./api.js";
|
||||||
import { errorBox, formatDate, formatDuration, h, num, replace, timeAgo } from "./dom.js";
|
import { artThumb } from "./art.js";
|
||||||
|
import { errorBox, formatDuration, h, num, replace, timeAgo } from "./dom.js";
|
||||||
import { signedInPage } from "./layout.js";
|
import { signedInPage } from "./layout.js";
|
||||||
|
import { spectrum } from "./spectrum.js";
|
||||||
|
|
||||||
const PERIODS = [
|
const PERIODS = [
|
||||||
["7day", "7 days"],
|
["7day", "7 days"],
|
||||||
@@ -9,7 +11,6 @@ const PERIODS = [
|
|||||||
["overall", "All time"],
|
["overall", "All time"],
|
||||||
];
|
];
|
||||||
const PERIOD_KEY = "scrobbler.period";
|
const PERIOD_KEY = "scrobbler.period";
|
||||||
const SEGMENTS = 10; // lit segments per spectrum column at the busiest day
|
|
||||||
const NOW_PLAYING_POLL_MS = 30_000;
|
const NOW_PLAYING_POLL_MS = 30_000;
|
||||||
|
|
||||||
const panel = document.getElementById("panel");
|
const panel = document.getElementById("panel");
|
||||||
@@ -19,6 +20,7 @@ let progressTimer;
|
|||||||
|
|
||||||
await signedInPage("index.html");
|
await signedInPage("index.html");
|
||||||
renderPeriodSelector();
|
renderPeriodSelector();
|
||||||
|
initSongSearch();
|
||||||
await Promise.all([loadPanel(), loadTop(currentPeriod()), loadRecent()]).catch(showError);
|
await Promise.all([loadPanel(), loadTop(currentPeriod()), loadRecent()]).catch(showError);
|
||||||
setInterval(() => refreshDisplay().catch(() => {}), NOW_PLAYING_POLL_MS);
|
setInterval(() => refreshDisplay().catch(() => {}), NOW_PLAYING_POLL_MS);
|
||||||
|
|
||||||
@@ -117,55 +119,6 @@ function readouts(summary) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Daily plays for the last 30 days, drawn as a segmented level meter.
|
|
||||||
function spectrum(counts) {
|
|
||||||
const NS = "http://www.w3.org/2000/svg";
|
|
||||||
const width = 1000;
|
|
||||||
const height = 96;
|
|
||||||
const gap = 4;
|
|
||||||
const max = Math.max(1, ...counts.map((c) => c.count));
|
|
||||||
const columnWidth = width / counts.length;
|
|
||||||
const segmentHeight = height / SEGMENTS;
|
|
||||||
const total = counts.reduce((sum, c) => sum + c.count, 0);
|
|
||||||
|
|
||||||
const svg = document.createElementNS(NS, "svg");
|
|
||||||
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
|
|
||||||
svg.setAttribute("preserveAspectRatio", "none");
|
|
||||||
svg.setAttribute("role", "img");
|
|
||||||
svg.setAttribute("aria-label", `Plays per day over the last ${counts.length} days: ${num(total)} in total`);
|
|
||||||
|
|
||||||
counts.forEach((day, i) => {
|
|
||||||
const lit = day.count ? Math.max(1, Math.round((day.count / max) * SEGMENTS)) : 0;
|
|
||||||
const group = document.createElementNS(NS, "g");
|
|
||||||
const title = document.createElementNS(NS, "title");
|
|
||||||
title.textContent = `${formatDate(day.start)}: ${num(day.count)} ${day.count === 1 ? "play" : "plays"}`;
|
|
||||||
group.append(title);
|
|
||||||
for (let s = 0; s < SEGMENTS; s++) {
|
|
||||||
const rect = document.createElementNS(NS, "rect");
|
|
||||||
rect.setAttribute("x", i * columnWidth + gap / 2);
|
|
||||||
rect.setAttribute("y", height - (s + 1) * segmentHeight + 1.5);
|
|
||||||
rect.setAttribute("width", columnWidth - gap);
|
|
||||||
rect.setAttribute("height", segmentHeight - 3);
|
|
||||||
rect.setAttribute("class", s < lit ? "seg-on" : "seg-off");
|
|
||||||
group.append(rect);
|
|
||||||
}
|
|
||||||
svg.append(group);
|
|
||||||
});
|
|
||||||
|
|
||||||
return h(
|
|
||||||
"div",
|
|
||||||
{ class: "spectrum" },
|
|
||||||
svg,
|
|
||||||
h(
|
|
||||||
"div",
|
|
||||||
{ class: "spectrum-axis" },
|
|
||||||
h("span", {}, formatDate(counts[0].start)),
|
|
||||||
h("span", {}, `${num(total)} plays in 30 days`),
|
|
||||||
h("span", {}, "Today"),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Most played ------------------------------------------------------------
|
// ---- Most played ------------------------------------------------------------
|
||||||
|
|
||||||
function currentPeriod() {
|
function currentPeriod() {
|
||||||
@@ -199,39 +152,103 @@ function renderPeriodSelector() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadTop(period) {
|
async function loadTop(period) {
|
||||||
const [artists, tracks] = await Promise.all([
|
const [artists, albums, tracks] = await Promise.all([
|
||||||
api(`/me/top/artists?period=${period}&limit=10`),
|
api(`/me/top/artists?period=${period}&limit=10`),
|
||||||
|
api(`/me/top/albums?period=${period}&limit=10`),
|
||||||
api(`/me/top/tracks?period=${period}&limit=10`),
|
api(`/me/top/tracks?period=${period}&limit=10`),
|
||||||
]);
|
]);
|
||||||
renderRanking(document.getElementById("top-artists"), artists.items, false);
|
renderRanking(document.getElementById("top-artists"), artists.items, false);
|
||||||
renderRanking(document.getElementById("top-tracks"), tracks.items, true);
|
renderRanking(document.getElementById("top-albums"), albums.items, true, false, true);
|
||||||
|
renderRanking(document.getElementById("top-tracks"), tracks.items, true, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderRanking(list, items, withArtist) {
|
function renderRanking(list, items, withArtist, linkToSong = false, withArt = false) {
|
||||||
if (!items.length) {
|
if (!items.length) {
|
||||||
replace(list, h("li", { class: "empty" }, "No plays in this period."));
|
replace(list, h("li", { class: "empty" }, "No plays in this period."));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const max = items[0].playcount;
|
const max = items[0].playcount;
|
||||||
|
const meterOffset = withArt ? "5.75rem" : "2.75rem";
|
||||||
replace(
|
replace(
|
||||||
list,
|
list,
|
||||||
items.map((item) =>
|
items.map((item) => {
|
||||||
h(
|
const by = withArtist ? h("span", { class: "by" }, item.artist) : null;
|
||||||
|
const name = linkToSong
|
||||||
|
? h("a", { class: "name", href: songHref(item.artist, item.name) }, item.name, by)
|
||||||
|
: h("span", { class: "name" }, item.name, by);
|
||||||
|
return h(
|
||||||
"li",
|
"li",
|
||||||
{},
|
{},
|
||||||
|
withArt ? artThumb(item.artist, item.name) : null,
|
||||||
h("span", { class: "rank" }, item.rank),
|
h("span", { class: "rank" }, item.rank),
|
||||||
h("span", { class: "name" }, item.name, withArtist ? h("span", { class: "by" }, item.artist) : null),
|
name,
|
||||||
h("span", { class: "plays" }, num(item.playcount)),
|
h("span", { class: "plays" }, num(item.playcount)),
|
||||||
h("span", {
|
h("span", {
|
||||||
class: "meter",
|
class: "meter",
|
||||||
"aria-hidden": "true",
|
"aria-hidden": "true",
|
||||||
style: `width: calc((100% - 2.75rem) * ${item.playcount / max})`,
|
style: `width: calc((100% - ${meterOffset}) * ${item.playcount / max})`,
|
||||||
}),
|
}),
|
||||||
),
|
);
|
||||||
),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function songHref(artist, track) {
|
||||||
|
return `song.html?artist=${encodeURIComponent(artist)}&track=${encodeURIComponent(track)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Song search --------------------------------------------------------------
|
||||||
|
|
||||||
|
function initSongSearch() {
|
||||||
|
const input = document.getElementById("song-search");
|
||||||
|
const results = document.getElementById("song-search-results");
|
||||||
|
let debounce;
|
||||||
|
let hideTimer;
|
||||||
|
|
||||||
|
input.addEventListener("input", () => {
|
||||||
|
clearTimeout(debounce);
|
||||||
|
const q = input.value.trim();
|
||||||
|
if (q.length < 2) {
|
||||||
|
results.hidden = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
debounce = setTimeout(() => runSearch(q), 250);
|
||||||
|
});
|
||||||
|
input.addEventListener("focus", () => {
|
||||||
|
if (results.childElementCount) results.hidden = false;
|
||||||
|
});
|
||||||
|
input.addEventListener("blur", () => {
|
||||||
|
hideTimer = setTimeout(() => (results.hidden = true), 150);
|
||||||
|
});
|
||||||
|
// Keep focus on mousedown so the subsequent click still lands on the result.
|
||||||
|
results.addEventListener("mousedown", (event) => event.preventDefault());
|
||||||
|
|
||||||
|
async function runSearch(q) {
|
||||||
|
let matches;
|
||||||
|
try {
|
||||||
|
matches = await api(`/me/tracks/search?q=${encodeURIComponent(q)}&limit=10`);
|
||||||
|
} catch {
|
||||||
|
return; // a flaky search box isn't worth surfacing an error for
|
||||||
|
}
|
||||||
|
clearTimeout(hideTimer);
|
||||||
|
if (!matches.length) {
|
||||||
|
replace(results, h("li", { class: "empty" }, "No matches."));
|
||||||
|
} else {
|
||||||
|
replace(
|
||||||
|
results,
|
||||||
|
matches.map((m) =>
|
||||||
|
h(
|
||||||
|
"li",
|
||||||
|
{},
|
||||||
|
h("a", { href: songHref(m.artist, m.track) }, m.track, h("span", { class: "by" }, m.artist)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
results.hidden = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---- Recently played ----------------------------------------------------------
|
// ---- Recently played ----------------------------------------------------------
|
||||||
|
|
||||||
async function loadRecent() {
|
async function loadRecent() {
|
||||||
@@ -247,8 +264,14 @@ async function loadRecent() {
|
|||||||
h(
|
h(
|
||||||
"li",
|
"li",
|
||||||
{},
|
{},
|
||||||
|
artThumb(s.album_artist || s.artist, s.album),
|
||||||
h("time", { datetime: s.played_at, title: new Date(s.played_at).toLocaleString() }, timeAgo(s.played_at)),
|
h("time", { datetime: s.played_at, title: new Date(s.played_at).toLocaleString() }, timeAgo(s.played_at)),
|
||||||
h("span", {}, h("span", { class: "track" }, s.track), h("span", { class: "by" }, ` by ${s.artist}`)),
|
h(
|
||||||
|
"a",
|
||||||
|
{ href: songHref(s.artist, s.track) },
|
||||||
|
h("span", { class: "track" }, s.track),
|
||||||
|
h("span", { class: "by" }, s.artist),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import { api } from "./api.js";
|
||||||
|
import { errorBox, formatDate, h, replace, timeAgo } from "./dom.js";
|
||||||
|
import { signedInPage } from "./layout.js";
|
||||||
|
|
||||||
|
const messages = document.getElementById("messages");
|
||||||
|
|
||||||
|
await signedInPage("sharing.html");
|
||||||
|
await refresh();
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
let followers, blocks;
|
||||||
|
try {
|
||||||
|
[followers, blocks] = await Promise.all([api("/federation/followers"), api("/federation/blocks")]);
|
||||||
|
} catch (error) {
|
||||||
|
replace(
|
||||||
|
messages,
|
||||||
|
error.status === 404
|
||||||
|
? h("p", { class: "notice" }, "This server doesn't share to the fediverse.")
|
||||||
|
: errorBox(error.message),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const requests = followers.filter((f) => f.state === "pending");
|
||||||
|
const accepted = followers.filter((f) => f.state === "accepted");
|
||||||
|
|
||||||
|
document.getElementById("requests-section").hidden = requests.length === 0;
|
||||||
|
replace(document.getElementById("requests"), requests.map(requestRow));
|
||||||
|
replace(
|
||||||
|
document.getElementById("followers"),
|
||||||
|
accepted.length
|
||||||
|
? accepted.map(followerRow)
|
||||||
|
: h("li", { class: "empty" }, "No followers yet. People can follow you by searching for your handle."),
|
||||||
|
);
|
||||||
|
document.getElementById("blocks-section").hidden = blocks.length === 0;
|
||||||
|
replace(document.getElementById("blocks"), blocks.map(blockRow));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remote names and handles are shown as plain text only.
|
||||||
|
function who(person) {
|
||||||
|
return h(
|
||||||
|
"span",
|
||||||
|
{},
|
||||||
|
h("span", { class: "row-title" }, person.display_name || person.handle),
|
||||||
|
person.display_name ? h("span", { class: "muted" }, ` ${person.handle}`) : null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function act(path, done) {
|
||||||
|
try {
|
||||||
|
await api(path, { method: "POST" });
|
||||||
|
replace(messages, h("p", { class: "notice notice-ok", role: "status" }, done));
|
||||||
|
} catch (error) {
|
||||||
|
replace(messages, errorBox(error.message));
|
||||||
|
}
|
||||||
|
await refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestRow(follower) {
|
||||||
|
return h(
|
||||||
|
"li",
|
||||||
|
{},
|
||||||
|
h(
|
||||||
|
"div",
|
||||||
|
{ class: "row-head" },
|
||||||
|
who(follower),
|
||||||
|
h(
|
||||||
|
"div",
|
||||||
|
{ class: "confirm" },
|
||||||
|
h(
|
||||||
|
"button",
|
||||||
|
{ type: "button", class: "button", onclick: () => act(`/federation/followers/${follower.id}/approve`, `${follower.handle} now follows you.`) },
|
||||||
|
"Approve",
|
||||||
|
),
|
||||||
|
h(
|
||||||
|
"button",
|
||||||
|
{ type: "button", class: "button button-quiet", onclick: () => act(`/federation/followers/${follower.id}/decline`, `Declined ${follower.handle}.`) },
|
||||||
|
"Decline",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
h("p", { class: "muted", title: formatDate(follower.since) }, `Asked ${timeAgo(follower.since)}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function followerRow(follower) {
|
||||||
|
const actions = h("div", { class: "confirm" });
|
||||||
|
const reset = () =>
|
||||||
|
replace(
|
||||||
|
actions,
|
||||||
|
h("button", { type: "button", class: "button button-quiet", onclick: askRemove }, "Remove"),
|
||||||
|
h("button", { type: "button", class: "button button-quiet", onclick: askBlock }, "Block"),
|
||||||
|
);
|
||||||
|
const confirm = (question, label, path, done) =>
|
||||||
|
replace(
|
||||||
|
actions,
|
||||||
|
h("span", { class: "muted" }, question),
|
||||||
|
h("button", { type: "button", class: "button button-danger", onclick: () => act(path, done) }, label),
|
||||||
|
h("button", { type: "button", class: "button button-quiet", onclick: reset }, "Cancel"),
|
||||||
|
);
|
||||||
|
const askRemove = () =>
|
||||||
|
confirm(
|
||||||
|
"They can follow you again later.",
|
||||||
|
"Remove follower",
|
||||||
|
`/federation/followers/${follower.id}/remove`,
|
||||||
|
`Removed ${follower.handle}.`,
|
||||||
|
);
|
||||||
|
const askBlock = () =>
|
||||||
|
confirm(
|
||||||
|
"They're removed and can't follow you again.",
|
||||||
|
"Block",
|
||||||
|
`/federation/followers/${follower.id}/block`,
|
||||||
|
`Blocked ${follower.handle}.`,
|
||||||
|
);
|
||||||
|
reset();
|
||||||
|
return h(
|
||||||
|
"li",
|
||||||
|
{},
|
||||||
|
h("div", { class: "row-head" }, who(follower), actions),
|
||||||
|
h("p", { class: "muted", title: formatDate(follower.since) }, `Following since ${timeAgo(follower.since)}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function blockRow(block) {
|
||||||
|
const unblock = async () => {
|
||||||
|
try {
|
||||||
|
await api(`/federation/blocks/${block.id}`, { method: "DELETE" });
|
||||||
|
replace(messages, h("p", { class: "notice notice-ok", role: "status" }, `Unblocked ${block.handle}.`));
|
||||||
|
} catch (error) {
|
||||||
|
replace(messages, errorBox(error.message));
|
||||||
|
}
|
||||||
|
await refresh();
|
||||||
|
};
|
||||||
|
return h(
|
||||||
|
"li",
|
||||||
|
{},
|
||||||
|
h(
|
||||||
|
"div",
|
||||||
|
{ class: "row-head" },
|
||||||
|
who(block),
|
||||||
|
h("button", { type: "button", class: "button button-quiet", onclick: unblock }, "Unblock"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { api } from "./api.js";
|
import { api } from "./api.js";
|
||||||
|
import { artThumb } from "./art.js";
|
||||||
import { errorBox, formatDay, formatTime, h, num, replace } from "./dom.js";
|
import { errorBox, formatDay, formatTime, h, num, replace } from "./dom.js";
|
||||||
import { signedInPage } from "./layout.js";
|
import { signedInPage } from "./layout.js";
|
||||||
|
|
||||||
@@ -38,11 +39,12 @@ function render(result) {
|
|||||||
h("h2", { class: "log-day" }, formatDay(scrobbles[0].played_at)),
|
h("h2", { class: "log-day" }, formatDay(scrobbles[0].played_at)),
|
||||||
h(
|
h(
|
||||||
"ol",
|
"ol",
|
||||||
{ class: "log log-clock" },
|
{ class: "log log-clock log-art" },
|
||||||
scrobbles.map((s) =>
|
scrobbles.map((s) =>
|
||||||
h(
|
h(
|
||||||
"li",
|
"li",
|
||||||
{},
|
{},
|
||||||
|
artThumb(s.album_artist || s.artist, s.album),
|
||||||
h("time", { datetime: s.played_at }, formatTime(s.played_at)),
|
h("time", { datetime: s.played_at }, formatTime(s.played_at)),
|
||||||
h(
|
h(
|
||||||
"span",
|
"span",
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
// Shared page shell: site header, navigation, sign-in guard.
|
// Shared page shell: site header, navigation, sign-in guard.
|
||||||
|
|
||||||
import { api, getToken, redirectToLogin, setToken } from "./api.js";
|
import { api, getToken, redirectToLogin, setToken } from "./api.js";
|
||||||
|
import { avatarImage } from "./avatar.js";
|
||||||
import { h, replace } from "./dom.js";
|
import { h, replace } from "./dom.js";
|
||||||
|
|
||||||
const NAV = [
|
const NAV = [
|
||||||
["index.html", "Overview"],
|
["index.html", "Overview"],
|
||||||
["history.html", "History"],
|
["history.html", "History"],
|
||||||
|
["art.html", "Album art"],
|
||||||
["apps.html", "Apps"],
|
["apps.html", "Apps"],
|
||||||
["sessions.html", "Sessions"],
|
["sessions.html", "Sessions"],
|
||||||
["import.html", "Import"],
|
["import.html", "Import"],
|
||||||
@@ -20,11 +22,17 @@ export async function signedInPage(active) {
|
|||||||
const header = document.getElementById("site-header");
|
const header = document.getElementById("site-header");
|
||||||
replace(header, brand(), nav(active));
|
replace(header, brand(), nav(active));
|
||||||
const user = await api("/auth/me");
|
const user = await api("/auth/me");
|
||||||
|
addSharingLink(header.querySelector("nav ul"), active);
|
||||||
header.append(
|
header.append(
|
||||||
h(
|
h(
|
||||||
"div",
|
"div",
|
||||||
{ class: "account" },
|
{ class: "account" },
|
||||||
h("span", { class: "account-name" }, user.username),
|
h(
|
||||||
|
"a",
|
||||||
|
{ class: "account-link", href: "account.html", title: "Your profile image" },
|
||||||
|
h("span", { class: "account-avatar" }, avatarImage(user, "avatar-sm")),
|
||||||
|
h("span", { class: "account-name" }, user.username),
|
||||||
|
),
|
||||||
h("button", { type: "button", class: "link-button", onclick: signOut }, "Sign out"),
|
h("button", { type: "button", class: "link-button", onclick: signOut }, "Sign out"),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -36,7 +44,13 @@ export function publicPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function brand() {
|
function brand() {
|
||||||
return h("a", { class: "brand", href: "index.html" }, h("span", { class: "brand-mark", "aria-hidden": "true" }), "Scrobbler");
|
return h(
|
||||||
|
"a",
|
||||||
|
{ class: "brand", href: "index.html" },
|
||||||
|
h("span", { class: "brand-mark", "aria-hidden": "true" }),
|
||||||
|
h("span", { class: "brand-word", "aria-hidden": "true" }),
|
||||||
|
h("span", { class: "visually-hidden" }, "Scrobbled"),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function nav(active) {
|
function nav(active) {
|
||||||
@@ -61,3 +75,35 @@ async function signOut() {
|
|||||||
location.href = "login.html";
|
location.href = "login.html";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// "Sharing" only appears when the server federates. Remembered per tab.
|
||||||
|
const FEDERATION_KEY = "scrobbler.federation";
|
||||||
|
|
||||||
|
async function federationAvailable() {
|
||||||
|
try {
|
||||||
|
const cached = sessionStorage.getItem(FEDERATION_KEY);
|
||||||
|
if (cached !== null) return cached === "1";
|
||||||
|
} catch {
|
||||||
|
// Storage unavailable: just ask.
|
||||||
|
}
|
||||||
|
let available = false;
|
||||||
|
try {
|
||||||
|
await api("/federation/settings");
|
||||||
|
available = true;
|
||||||
|
} catch {
|
||||||
|
available = false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(FEDERATION_KEY, available ? "1" : "0");
|
||||||
|
} catch {
|
||||||
|
// Not remembered; asked again next page.
|
||||||
|
}
|
||||||
|
return available;
|
||||||
|
}
|
||||||
|
|
||||||
|
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")));
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { api } from "./api.js";
|
||||||
|
import { errorBox, formatDate, h, replace } from "./dom.js";
|
||||||
|
import { publicPage } from "./layout.js";
|
||||||
|
|
||||||
|
const root = document.getElementById("post");
|
||||||
|
const params = new URLSearchParams(location.search);
|
||||||
|
const username = params.get("u") ?? "";
|
||||||
|
const postId = params.get("id") ?? "";
|
||||||
|
|
||||||
|
// A public page: never sends visitors to sign in.
|
||||||
|
publicPage();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const post = await api(
|
||||||
|
`/federation/profiles/${encodeURIComponent(username)}/posts/${encodeURIComponent(postId)}`,
|
||||||
|
{ auth: false },
|
||||||
|
);
|
||||||
|
document.title = `${post.display_name} · Scrobbled`;
|
||||||
|
replace(
|
||||||
|
root,
|
||||||
|
h(
|
||||||
|
"p",
|
||||||
|
{ class: "muted" },
|
||||||
|
h("a", { href: post.profile_url }, post.display_name),
|
||||||
|
` · ${post.handle}`,
|
||||||
|
),
|
||||||
|
h("p", { style: "white-space: pre-line" }, post.text),
|
||||||
|
h("p", { class: "muted", title: formatDate(post.created_at) }, `Posted ${formatDate(post.created_at)}`),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
replace(
|
||||||
|
root,
|
||||||
|
error.status === 404
|
||||||
|
? [
|
||||||
|
h("h1", {}, "No post here"),
|
||||||
|
h("p", { class: "lede" }, "This post doesn't exist, isn't public, or has been deleted."),
|
||||||
|
]
|
||||||
|
: errorBox(error.message),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { api } from "./api.js";
|
||||||
|
import { errorBox, formatDate, h, replace, timeAgo } from "./dom.js";
|
||||||
|
import { signedInPage } from "./layout.js";
|
||||||
|
|
||||||
|
const messages = document.getElementById("messages");
|
||||||
|
const KIND_LABEL = { weekly: "Weekly summary", milestone: "Milestone" };
|
||||||
|
const VISIBILITY_LABEL = { followers: "Followers only", unlisted: "Unlisted", public: "Public" };
|
||||||
|
|
||||||
|
await signedInPage("sharing.html");
|
||||||
|
await refresh();
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
let posts;
|
||||||
|
try {
|
||||||
|
posts = await api("/federation/posts");
|
||||||
|
} catch (error) {
|
||||||
|
replace(
|
||||||
|
messages,
|
||||||
|
error.status === 404
|
||||||
|
? h("p", { class: "notice" }, "This server doesn't share to the fediverse.")
|
||||||
|
: errorBox(error.message),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
replace(
|
||||||
|
document.getElementById("posts"),
|
||||||
|
posts.length
|
||||||
|
? posts.map(postRow)
|
||||||
|
: h(
|
||||||
|
"li",
|
||||||
|
{ class: "empty" },
|
||||||
|
"Nothing posted yet. Weekly summaries and milestones appear here once you're sharing.",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function postRow(post) {
|
||||||
|
const actions = h("div", { class: "confirm" });
|
||||||
|
const reset = () =>
|
||||||
|
replace(
|
||||||
|
actions,
|
||||||
|
post.deleted_at
|
||||||
|
? null
|
||||||
|
: h("button", { type: "button", class: "button button-quiet", onclick: askDelete }, "Delete"),
|
||||||
|
);
|
||||||
|
const askDelete = () =>
|
||||||
|
replace(
|
||||||
|
actions,
|
||||||
|
h("span", { class: "muted" }, "Delivered followers keep a copy; this only removes it from their timeline."),
|
||||||
|
h("button", { type: "button", class: "button button-danger", onclick: doDelete }, "Delete post"),
|
||||||
|
h("button", { type: "button", class: "button button-quiet", onclick: reset }, "Cancel"),
|
||||||
|
);
|
||||||
|
const doDelete = async () => {
|
||||||
|
try {
|
||||||
|
await api(`/federation/posts/${post.id}`, { method: "DELETE" });
|
||||||
|
replace(messages, h("p", { class: "notice notice-ok", role: "status" }, "Post deleted."));
|
||||||
|
} catch (error) {
|
||||||
|
replace(messages, errorBox(error.message));
|
||||||
|
}
|
||||||
|
await refresh();
|
||||||
|
};
|
||||||
|
reset();
|
||||||
|
return h(
|
||||||
|
"li",
|
||||||
|
{},
|
||||||
|
h(
|
||||||
|
"div",
|
||||||
|
{ class: "row-head" },
|
||||||
|
h("span", { class: "row-title" }, KIND_LABEL[post.kind] ?? post.kind),
|
||||||
|
actions,
|
||||||
|
),
|
||||||
|
h("p", { style: "white-space: pre-line" }, post.text),
|
||||||
|
h(
|
||||||
|
"p",
|
||||||
|
{ class: "muted", title: formatDate(post.created_at) },
|
||||||
|
`${VISIBILITY_LABEL[post.visibility] ?? post.visibility} · Posted ${timeAgo(post.created_at)}`,
|
||||||
|
post.deleted_at ? ` · Deleted ${timeAgo(post.deleted_at)}` : null,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { api } from "./api.js";
|
||||||
|
import { avatarImage } from "./avatar.js";
|
||||||
|
import { errorBox, h, replace } from "./dom.js";
|
||||||
|
import { publicPage } from "./layout.js";
|
||||||
|
|
||||||
|
const root = document.getElementById("profile");
|
||||||
|
const username = new URLSearchParams(location.search).get("u") ?? "";
|
||||||
|
|
||||||
|
// A public page: never sends visitors to sign in.
|
||||||
|
publicPage();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const profile = await api(`/federation/profiles/${encodeURIComponent(username)}`, { auth: false });
|
||||||
|
document.title = `${profile.display_name} · Scrobbled`;
|
||||||
|
const copy = h("button", { type: "button", class: "button button-quiet" }, "Copy handle");
|
||||||
|
copy.addEventListener("click", async () => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(profile.handle);
|
||||||
|
copy.textContent = "Copied";
|
||||||
|
} catch {
|
||||||
|
copy.textContent = "Select and copy it above";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
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,
|
||||||
|
profile.now_playing
|
||||||
|
? h("p", { class: "now-playing" }, "Now playing: ", h("strong", {}, profile.now_playing))
|
||||||
|
: null,
|
||||||
|
h("h2", { class: "profile-follow" }, "Follow from the fediverse"),
|
||||||
|
h(
|
||||||
|
"p",
|
||||||
|
{ class: "muted" },
|
||||||
|
"Search for the handle above in Mastodon or any other fediverse app, then follow.",
|
||||||
|
),
|
||||||
|
h("div", { class: "button-row" }, copy),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
replace(
|
||||||
|
root,
|
||||||
|
error.status === 404
|
||||||
|
? [h("h1", {}, "No profile here"), h("p", { class: "lede" }, "No one on this server shares their listening under that name.")]
|
||||||
|
: errorBox(error.message),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
import { api, describeError } from "./api.js";
|
||||||
|
import { errorBox, h, num, replace } from "./dom.js";
|
||||||
|
import { signedInPage } from "./layout.js";
|
||||||
|
|
||||||
|
const form = document.getElementById("sharing");
|
||||||
|
const messages = document.getElementById("messages");
|
||||||
|
const handlePanel = document.getElementById("handle-panel");
|
||||||
|
const RADIO_GROUPS = ["visibility", "now_playing_mode"];
|
||||||
|
const FIELDS = [
|
||||||
|
"enabled",
|
||||||
|
"visibility",
|
||||||
|
"manually_approves_followers",
|
||||||
|
"discoverable",
|
||||||
|
"indexable",
|
||||||
|
"post_weekly_summary",
|
||||||
|
"post_milestones",
|
||||||
|
"timezone",
|
||||||
|
"now_playing_mode",
|
||||||
|
"share_avatar",
|
||||||
|
"display_name",
|
||||||
|
"bio",
|
||||||
|
];
|
||||||
|
|
||||||
|
fillTimezoneChoices();
|
||||||
|
await signedInPage("sharing.html");
|
||||||
|
|
||||||
|
let settings;
|
||||||
|
try {
|
||||||
|
settings = await api("/federation/settings");
|
||||||
|
} catch (error) {
|
||||||
|
replace(
|
||||||
|
messages,
|
||||||
|
error.status === 404
|
||||||
|
? h("p", { class: "notice" }, "This server doesn't share to the fediverse. Ask whoever runs it to turn it on.")
|
||||||
|
: errorBox(error.message),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (settings) {
|
||||||
|
fill(settings);
|
||||||
|
form.hidden = false;
|
||||||
|
form.elements.enabled.addEventListener("change", () => showHandle(form.elements.enabled.checked));
|
||||||
|
form.addEventListener("submit", save);
|
||||||
|
document.getElementById("preview-weekly").addEventListener("click", previewWeekly);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Free text (validated server-side), with autocomplete from the browser's own IANA list
|
||||||
|
// when it can supply one; a picker where that's available, a plain field otherwise.
|
||||||
|
function fillTimezoneChoices() {
|
||||||
|
if (typeof Intl.supportedValuesOf !== "function") return;
|
||||||
|
const datalist = document.getElementById("timezones");
|
||||||
|
replace(datalist, Intl.supportedValuesOf("timeZone").map((zone) => h("option", { value: zone })));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function previewWeekly() {
|
||||||
|
const box = document.getElementById("weekly-preview");
|
||||||
|
const button = document.getElementById("preview-weekly");
|
||||||
|
button.disabled = true;
|
||||||
|
try {
|
||||||
|
const preview = await api("/federation/preview/weekly");
|
||||||
|
replace(
|
||||||
|
box,
|
||||||
|
h("p", { class: "muted" }, "What this week's summary would say so far:"),
|
||||||
|
h("p", { style: "white-space: pre-line" }, preview.text),
|
||||||
|
);
|
||||||
|
box.hidden = false;
|
||||||
|
} catch (error) {
|
||||||
|
replace(messages, errorBox(error.message));
|
||||||
|
} finally {
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fill(values) {
|
||||||
|
for (const name of FIELDS) {
|
||||||
|
if (RADIO_GROUPS.includes(name)) {
|
||||||
|
form.querySelector(`input[name=${name}][value="${values[name]}"]`).checked = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const field = form.elements[name];
|
||||||
|
if (field.type === "checkbox") {
|
||||||
|
field.checked = Boolean(values[name]);
|
||||||
|
} else {
|
||||||
|
field.value = values[name] ?? "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.getElementById("handle").textContent = values.handle;
|
||||||
|
const summary = document.getElementById("follower-summary");
|
||||||
|
const parts = [`${num(values.followers)} ${values.followers === 1 ? "follower" : "followers"}`];
|
||||||
|
if (values.pending_followers) parts.push(`${num(values.pending_followers)} waiting for approval`);
|
||||||
|
replace(summary, parts.join(", "), ". ", h("a", { href: "followers.html" }, "See followers"));
|
||||||
|
replace(
|
||||||
|
document.getElementById("profile-link"),
|
||||||
|
"Your public profile page: ",
|
||||||
|
h("a", { href: values.profile_url }, values.profile_url.replace(/^https?:\/\//, "")),
|
||||||
|
);
|
||||||
|
showHandle(values.enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
function showHandle(on) {
|
||||||
|
handlePanel.hidden = !on;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Turning sharing off removes every follower, so it's confirmed first.
|
||||||
|
function confirmTurningOff(followerCount) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const box = document.getElementById("confirm-off");
|
||||||
|
const done = (answer) => {
|
||||||
|
box.hidden = true;
|
||||||
|
resolve(answer);
|
||||||
|
};
|
||||||
|
replace(
|
||||||
|
box,
|
||||||
|
h(
|
||||||
|
"p",
|
||||||
|
{},
|
||||||
|
`Turning sharing off removes your ${num(followerCount)} ${followerCount === 1 ? "follower" : "followers"}. `,
|
||||||
|
"Each is told, and they'd have to follow you again if you turn it back on.",
|
||||||
|
),
|
||||||
|
h(
|
||||||
|
"div",
|
||||||
|
{ class: "button-row" },
|
||||||
|
h("button", { type: "button", class: "button button-danger", onclick: () => done(true) }, "Turn off sharing"),
|
||||||
|
h(
|
||||||
|
"button",
|
||||||
|
{
|
||||||
|
type: "button",
|
||||||
|
class: "button button-quiet",
|
||||||
|
onclick: () => {
|
||||||
|
form.elements.enabled.checked = true;
|
||||||
|
showHandle(true);
|
||||||
|
done(false);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"Keep sharing",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
box.hidden = false;
|
||||||
|
box.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
const turningOff = settings.enabled && !form.elements.enabled.checked;
|
||||||
|
if (turningOff && settings.followers > 0 && !(await confirmTurningOff(settings.followers))) return;
|
||||||
|
const button = form.querySelector("button[type=submit]");
|
||||||
|
const changes = {
|
||||||
|
enabled: form.elements.enabled.checked,
|
||||||
|
visibility: form.querySelector("input[name=visibility]:checked").value,
|
||||||
|
manually_approves_followers: form.elements.manually_approves_followers.checked,
|
||||||
|
discoverable: form.elements.discoverable.checked,
|
||||||
|
indexable: form.elements.indexable.checked,
|
||||||
|
post_weekly_summary: form.elements.post_weekly_summary.checked,
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
const status = document.getElementById("save-status");
|
||||||
|
button.disabled = true;
|
||||||
|
status.textContent = "Saving";
|
||||||
|
replace(messages);
|
||||||
|
try {
|
||||||
|
const saved = await api("/federation/settings", { method: "PATCH", body: changes });
|
||||||
|
settings = saved;
|
||||||
|
fill(saved);
|
||||||
|
status.textContent = saved.enabled
|
||||||
|
? `Saved. You're sharing as ${saved.handle}.`
|
||||||
|
: "Saved. Sharing is off, and your followers have been told.";
|
||||||
|
} catch (error) {
|
||||||
|
status.textContent = "";
|
||||||
|
replace(messages, errorBox(describeError(error)));
|
||||||
|
messages.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||||
|
} finally {
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import { api } from "./api.js";
|
||||||
|
import { artThumb } from "./art.js";
|
||||||
|
import { errorBox, formatDate, formatDay, formatDuration, formatTime, h, num, replace } from "./dom.js";
|
||||||
|
import { signedInPage } from "./layout.js";
|
||||||
|
import { spectrum } from "./spectrum.js";
|
||||||
|
|
||||||
|
const PER_PAGE = 50;
|
||||||
|
const panel = document.getElementById("panel");
|
||||||
|
const meta = document.getElementById("song-meta");
|
||||||
|
const history = document.getElementById("song-history");
|
||||||
|
const pager = document.getElementById("pager");
|
||||||
|
|
||||||
|
await signedInPage(null); // a permalink, not a top-level nav section
|
||||||
|
|
||||||
|
const params = new URLSearchParams(location.search);
|
||||||
|
const artist = params.get("artist") ?? "";
|
||||||
|
const track = params.get("track") ?? "";
|
||||||
|
const page = Math.max(1, Number.parseInt(params.get("page"), 10) || 1);
|
||||||
|
|
||||||
|
if (!artist || !track) {
|
||||||
|
replace(panel, h("p", { class: "notice" }, "Use the search box on the dashboard to find a song."));
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const result = await api(
|
||||||
|
`/me/tracks?artist=${encodeURIComponent(artist)}&track=${encodeURIComponent(track)}&page=${page}&limit=${PER_PAGE}`,
|
||||||
|
);
|
||||||
|
render(result);
|
||||||
|
} catch (error) {
|
||||||
|
replace(
|
||||||
|
panel,
|
||||||
|
error.status === 404
|
||||||
|
? h("p", { class: "notice" }, `You've never scrobbled "${track}" by ${artist}.`)
|
||||||
|
: errorBox(error.message),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(result) {
|
||||||
|
document.title = `${result.track} · Scrobbled`;
|
||||||
|
const m = result.metadata;
|
||||||
|
|
||||||
|
const body = h(
|
||||||
|
"div",
|
||||||
|
{ class: "display-body" },
|
||||||
|
h("p", { class: "display-status" }, "Now viewing"),
|
||||||
|
h("p", { class: "display-track" }, result.track),
|
||||||
|
h(
|
||||||
|
"p",
|
||||||
|
{ class: "display-meta" },
|
||||||
|
h("strong", {}, result.artist),
|
||||||
|
m.album ? [" from ", h("strong", {}, m.album)] : null,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const display = m.album
|
||||||
|
? h("div", { class: "display display-with-art" }, artThumb(m.album_artist || result.artist, m.album, "display-art"), body)
|
||||||
|
: h("div", { class: "display" }, body);
|
||||||
|
replace(panel, display, readouts(m), spectrum(result.counts, `Plays of ${result.track}`, "90 days"));
|
||||||
|
|
||||||
|
const row = (label, value) =>
|
||||||
|
value === null || value === undefined ? null : h("div", {}, h("dt", {}, label), h("dd", {}, value));
|
||||||
|
replace(
|
||||||
|
meta,
|
||||||
|
row("Album artist", m.album_artist),
|
||||||
|
row("Track number", m.track_number),
|
||||||
|
row("Duration", m.duration ? formatDuration(m.duration) : null),
|
||||||
|
row("MusicBrainz ID", m.mbid),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!result.items.length) {
|
||||||
|
replace(history, h("p", { class: "empty" }, "Nothing here yet."));
|
||||||
|
} else {
|
||||||
|
// Group by local calendar day, same as the full history page.
|
||||||
|
const days = new Map();
|
||||||
|
for (const scrobble of result.items) {
|
||||||
|
const key = new Date(scrobble.played_at).toDateString();
|
||||||
|
if (!days.has(key)) days.set(key, []);
|
||||||
|
days.get(key).push(scrobble);
|
||||||
|
}
|
||||||
|
replace(
|
||||||
|
history,
|
||||||
|
[...days.values()].map((scrobbles) => [
|
||||||
|
h("h3", { class: "log-day" }, formatDay(scrobbles[0].played_at)),
|
||||||
|
h(
|
||||||
|
"ol",
|
||||||
|
{ class: "log log-clock" },
|
||||||
|
scrobbles.map((s) =>
|
||||||
|
h(
|
||||||
|
"li",
|
||||||
|
{},
|
||||||
|
h("time", { datetime: s.played_at }, formatTime(s.played_at)),
|
||||||
|
s.album ? h("span", { class: "by" }, `from ${s.album}`) : h("span"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const link = (p) => `?artist=${encodeURIComponent(artist)}&track=${encodeURIComponent(track)}&page=${p}`;
|
||||||
|
replace(
|
||||||
|
pager,
|
||||||
|
result.page > 1 ? h("a", { class: "button button-quiet", href: link(result.page - 1) }, "Newer") : h("span"),
|
||||||
|
result.page < result.total_pages
|
||||||
|
? h("a", { class: "button button-quiet", href: link(result.page + 1) }, "Older")
|
||||||
|
: h("span"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readouts(m) {
|
||||||
|
const item = (value, label) => h("div", {}, h("dt", {}, label), h("dd", {}, value));
|
||||||
|
return h(
|
||||||
|
"dl",
|
||||||
|
{ class: "readouts" },
|
||||||
|
item(num(m.playcount), "plays"),
|
||||||
|
item(formatDate(m.first_played_at), "first played"),
|
||||||
|
item(formatDate(m.last_played_at), "last played"),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// A segmented level meter: daily play counts drawn as columns of lit/unlit segments,
|
||||||
|
// like a hi-fi spectrum analyser. Shared by the dashboard (30 days, all plays) and the
|
||||||
|
// song page (90 days, one track).
|
||||||
|
|
||||||
|
import { formatDate, h, num } from "./dom.js";
|
||||||
|
|
||||||
|
const SEGMENTS = 10; // lit segments per column at the busiest day
|
||||||
|
|
||||||
|
export function spectrum(counts, subject = "Plays", windowLabel = "30 days") {
|
||||||
|
const NS = "http://www.w3.org/2000/svg";
|
||||||
|
const width = 1000;
|
||||||
|
const height = 96;
|
||||||
|
const gap = 4;
|
||||||
|
const max = Math.max(1, ...counts.map((c) => c.count));
|
||||||
|
const columnWidth = width / counts.length;
|
||||||
|
const segmentHeight = height / SEGMENTS;
|
||||||
|
const total = counts.reduce((sum, c) => sum + c.count, 0);
|
||||||
|
|
||||||
|
const svg = document.createElementNS(NS, "svg");
|
||||||
|
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
|
||||||
|
svg.setAttribute("preserveAspectRatio", "none");
|
||||||
|
svg.setAttribute("role", "img");
|
||||||
|
svg.setAttribute("aria-label", `${subject} per day over the last ${counts.length} days: ${num(total)} in total`);
|
||||||
|
|
||||||
|
counts.forEach((day, i) => {
|
||||||
|
const lit = day.count ? Math.max(1, Math.round((day.count / max) * SEGMENTS)) : 0;
|
||||||
|
const group = document.createElementNS(NS, "g");
|
||||||
|
const title = document.createElementNS(NS, "title");
|
||||||
|
title.textContent = `${formatDate(day.start)}: ${num(day.count)} ${day.count === 1 ? "play" : "plays"}`;
|
||||||
|
group.append(title);
|
||||||
|
for (let s = 0; s < SEGMENTS; s++) {
|
||||||
|
const rect = document.createElementNS(NS, "rect");
|
||||||
|
rect.setAttribute("x", i * columnWidth + gap / 2);
|
||||||
|
rect.setAttribute("y", height - (s + 1) * segmentHeight + 1.5);
|
||||||
|
rect.setAttribute("width", columnWidth - gap);
|
||||||
|
rect.setAttribute("height", segmentHeight - 3);
|
||||||
|
rect.setAttribute("class", s < lit ? "seg-on" : "seg-off");
|
||||||
|
group.append(rect);
|
||||||
|
}
|
||||||
|
svg.append(group);
|
||||||
|
});
|
||||||
|
|
||||||
|
return h(
|
||||||
|
"div",
|
||||||
|
{ class: "spectrum" },
|
||||||
|
svg,
|
||||||
|
h(
|
||||||
|
"div",
|
||||||
|
{ class: "spectrum-axis" },
|
||||||
|
h("span", {}, formatDate(counts[0].start)),
|
||||||
|
h("span", {}, `${num(total)} ${subject.toLowerCase()} in ${windowLabel}`),
|
||||||
|
h("span", {}, "Today"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,8 +3,12 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Sign in · Scrobbler</title>
|
<title>Sign in · Scrobbled</title>
|
||||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
|
<link rel="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">
|
<link rel="stylesheet" href="css/style.css">
|
||||||
<script src="config.js"></script>
|
<script src="config.js"></script>
|
||||||
<script type="module" src="js/login.js"></script>
|
<script type="module" src="js/login.js"></script>
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Post · 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/post.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="site-header" id="site-header"></header>
|
||||||
|
<main id="main">
|
||||||
|
<div class="auth" id="post" aria-live="polite"></div>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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>Posts · 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/posts.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="site-header" id="site-header"></header>
|
||||||
|
<main id="main">
|
||||||
|
<h1 class="page-title">Posts</h1>
|
||||||
|
<p class="lede">Weekly summaries and milestones sent to the fediverse. <a href="sharing.html">Sharing settings</a></p>
|
||||||
|
<div id="messages"></div>
|
||||||
|
<ul class="rows" id="posts"></ul>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>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/profile.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="site-header" id="site-header"></header>
|
||||||
|
<main id="main">
|
||||||
|
<div class="auth profile" id="profile" aria-live="polite"></div>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -3,8 +3,12 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Create an account · Scrobbler</title>
|
<title>Create an account · Scrobbled</title>
|
||||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
|
<link rel="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">
|
<link rel="stylesheet" href="css/style.css">
|
||||||
<script src="config.js"></script>
|
<script src="config.js"></script>
|
||||||
<script type="module" src="js/register.js"></script>
|
<script type="module" src="js/register.js"></script>
|
||||||
|
|||||||
@@ -3,8 +3,12 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Sessions · Scrobbler</title>
|
<title>Sessions · Scrobbled</title>
|
||||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
|
<link rel="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">
|
<link rel="stylesheet" href="css/style.css">
|
||||||
<script src="config.js"></script>
|
<script src="config.js"></script>
|
||||||
<script type="module" src="js/sessions.js"></script>
|
<script type="module" src="js/sessions.js"></script>
|
||||||
@@ -13,7 +17,7 @@
|
|||||||
<header class="site-header" id="site-header"></header>
|
<header class="site-header" id="site-header"></header>
|
||||||
<main id="main">
|
<main id="main">
|
||||||
<h1 class="page-title">Sessions</h1>
|
<h1 class="page-title">Sessions</h1>
|
||||||
<p class="lede">Players you've signed in to Scrobbler. Revoking one signs it out straight away; it has to sign in again before it can scrobble.</p>
|
<p class="lede">Players you've signed in to Scrobbled. Revoking one signs it out straight away; it has to sign in again before it can scrobble.</p>
|
||||||
<div id="messages"></div>
|
<div id="messages"></div>
|
||||||
<ul class="rows" id="sessions"></ul>
|
<ul class="rows" id="sessions"></ul>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Sharing · 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/sharing.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="site-header" id="site-header"></header>
|
||||||
|
<main id="main">
|
||||||
|
<h1 class="page-title">Sharing</h1>
|
||||||
|
<p class="lede">Let people on Mastodon and other fediverse apps follow your listening.</p>
|
||||||
|
<div id="messages"></div>
|
||||||
|
<form id="sharing" class="sharing" hidden>
|
||||||
|
<div class="share-switch">
|
||||||
|
<input type="checkbox" id="enabled" name="enabled" role="switch">
|
||||||
|
<label for="enabled">Share my listening on the fediverse</label>
|
||||||
|
</div>
|
||||||
|
<div class="handle-panel" id="handle-panel" hidden>
|
||||||
|
<p class="display-status">Your fediverse handle</p>
|
||||||
|
<p class="approve-app handle" id="handle"></p>
|
||||||
|
<p class="muted">People can follow you by searching for this in their app. It can't be changed once people follow you.</p>
|
||||||
|
<p class="follower-summary" id="follower-summary"></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<fieldset class="choices">
|
||||||
|
<legend>Who can see posts</legend>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="radio" id="vis-followers" name="visibility" value="followers">
|
||||||
|
<label for="vis-followers"><strong>Only your followers</strong><span class="muted">Posts go to followers and nowhere else.</span></label>
|
||||||
|
</div>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="radio" id="vis-unlisted" name="visibility" value="unlisted">
|
||||||
|
<label for="vis-unlisted"><strong>Anyone who visits your profile</strong><span class="muted">Kept out of public timelines.</span></label>
|
||||||
|
</div>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="radio" id="vis-public" name="visibility" value="public">
|
||||||
|
<label for="vis-public"><strong>Everyone</strong><span class="muted">Including public timelines and search.</span></label>
|
||||||
|
</div>
|
||||||
|
<p class="hint">"Only your followers" is only as private as who can follow you. To choose who sees your posts, turn on <em>Approve followers</em> below.</p>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset class="choices">
|
||||||
|
<legend>Followers and discovery</legend>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="checkbox" id="manually_approves_followers" name="manually_approves_followers">
|
||||||
|
<label for="manually_approves_followers"><strong>Approve followers</strong><span class="muted">New followers need your OK.</span></label>
|
||||||
|
</div>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="checkbox" id="discoverable" name="discoverable">
|
||||||
|
<label for="discoverable"><strong>List me in directories</strong><span class="muted">Fediverse apps may suggest your profile to others.</span></label>
|
||||||
|
</div>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="checkbox" id="indexable" name="indexable">
|
||||||
|
<label for="indexable"><strong>Allow search</strong><span class="muted">Your public posts may be found by full-text search.</span></label>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset class="choices">
|
||||||
|
<legend>What to post</legend>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="checkbox" id="post_weekly_summary" name="post_weekly_summary">
|
||||||
|
<label for="post_weekly_summary"><strong>Weekly summary</strong><span class="muted">Your play count and top artist, once a week.</span></label>
|
||||||
|
</div>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="checkbox" id="post_milestones" name="post_milestones">
|
||||||
|
<label for="post_milestones"><strong>Milestones</strong><span class="muted">Scrobble-count, artist-plays and top-10 milestones as you reach them.</span></label>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="timezone">Time zone</label>
|
||||||
|
<input id="timezone" name="timezone" list="timezones" autocomplete="off">
|
||||||
|
<datalist id="timezones"></datalist>
|
||||||
|
<span class="hint">Decides when your week ends for the weekly summary.</span>
|
||||||
|
</div>
|
||||||
|
<div class="button-row">
|
||||||
|
<button class="button button-quiet" type="button" id="preview-weekly">Preview this week's summary</button>
|
||||||
|
</div>
|
||||||
|
<div class="preview-box" id="weekly-preview" hidden></div>
|
||||||
|
<p class="muted"><a href="posts.html">See your posts</a></p>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset class="choices">
|
||||||
|
<legend>Now playing</legend>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="radio" id="np-off" name="now_playing_mode" value="off">
|
||||||
|
<label for="np-off"><strong>Off</strong><span class="muted">Nothing shown or posted.</span></label>
|
||||||
|
</div>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="radio" id="np-profile" name="now_playing_mode" value="profile">
|
||||||
|
<label for="np-profile"><strong>Show on my profile</strong><span class="muted">A "Now playing" field, refreshed every few minutes and cleared when you stop.</span></label>
|
||||||
|
</div>
|
||||||
|
<div class="choice">
|
||||||
|
<input type="radio" id="np-posts" name="now_playing_mode" value="posts">
|
||||||
|
<label for="np-posts"><strong>Show on my profile and post</strong><span class="muted">The profile field, plus a post for each track played 30+ seconds, replacing the last one, at most every 30 minutes.</span></label>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset class="choices">
|
||||||
|
<legend>Profile</legend>
|
||||||
|
<div class="field">
|
||||||
|
<label for="display_name">Display name</label>
|
||||||
|
<input id="display_name" name="display_name" maxlength="100" autocomplete="off">
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="bio">Bio</label>
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<div class="notice notice-error confirm-off" id="confirm-off" role="alertdialog" aria-live="assertive" hidden></div>
|
||||||
|
<div class="button-row save-row">
|
||||||
|
<button class="button" type="submit">Save sharing settings</button>
|
||||||
|
<span class="muted" id="save-status" role="status"></span>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"name": "Scrobbled",
|
||||||
|
"short_name": "Scrobbled",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"src": "icon-192.png",
|
||||||
|
"sizes": "192x192",
|
||||||
|
"type": "image/png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "icon-512.png",
|
||||||
|
"sizes": "512x512",
|
||||||
|
"type": "image/png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "icon-maskable-512.png",
|
||||||
|
"sizes": "512x512",
|
||||||
|
"type": "image/png",
|
||||||
|
"purpose": "maskable"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"theme_color": "#1F1C28",
|
||||||
|
"background_color": "#1F1C28",
|
||||||
|
"display": "standalone"
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Song · 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/song.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="site-header" id="site-header"></header>
|
||||||
|
<main id="main">
|
||||||
|
<h1 class="visually-hidden">Song</h1>
|
||||||
|
<div id="panel" class="panel" aria-live="polite"></div>
|
||||||
|
<dl class="song-meta" id="song-meta"></dl>
|
||||||
|
<section aria-labelledby="song-history-title">
|
||||||
|
<h2 id="song-history-title">History</h2>
|
||||||
|
<div id="song-history"></div>
|
||||||
|
<nav class="pager" aria-label="Pages" id="pager"></nav>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -11,7 +11,19 @@ wsgi_app = "scrobbler:create_app()"
|
|||||||
bind = os.environ.get("BIND", "0.0.0.0:8000")
|
bind = os.environ.get("BIND", "0.0.0.0:8000")
|
||||||
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
|
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
|
||||||
accesslog = "-"
|
accesslog = "-"
|
||||||
|
loglevel = os.environ.get("LOG_LEVEL", "INFO").lower()
|
||||||
forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")
|
forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")
|
||||||
|
# gunicorn 26's control socket lives in $HOME, which the container user doesn't have.
|
||||||
|
control_socket_disable = True
|
||||||
|
|
||||||
|
|
||||||
|
def post_fork(server, worker):
|
||||||
|
# Gunicorn's own messages go through the app's handler too, so the format is uniform.
|
||||||
|
import logging
|
||||||
|
|
||||||
|
gunicorn_error = logging.getLogger("gunicorn.error")
|
||||||
|
gunicorn_error.handlers.clear()
|
||||||
|
gunicorn_error.propagate = True
|
||||||
|
|
||||||
|
|
||||||
def on_starting(server):
|
def on_starting(server):
|
||||||
|
|||||||
@@ -3,14 +3,18 @@ name = "scrobby"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
description = "Self-hosted, Last.fm-compatible music scrobbling service"
|
description = "Self-hosted, Last.fm-compatible music scrobbling service"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
|
license = "BSD-3-Clause"
|
||||||
|
license-files = ["LICENSE"]
|
||||||
requires-python = ">=3.13"
|
requires-python = ">=3.13"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"cryptography>=50.0.1",
|
||||||
"flask>=3.1.3",
|
"flask>=3.1.3",
|
||||||
"flask-cors>=6.0.5",
|
"flask-cors>=6.0.5",
|
||||||
"flask-migrate>=4.1.0",
|
"flask-migrate>=4.1.0",
|
||||||
"flask-smorest>=0.47.0",
|
"flask-smorest>=0.47.0",
|
||||||
"flask-sqlalchemy>=3.1.1",
|
"flask-sqlalchemy>=3.1.1",
|
||||||
"gunicorn>=26.2.0",
|
"gunicorn>=26.2.0",
|
||||||
|
"httpcore>=1.0.9",
|
||||||
"prometheus-client>=0.26.0",
|
"prometheus-client>=0.26.0",
|
||||||
"psycopg[binary]>=3.3.6",
|
"psycopg[binary]>=3.3.6",
|
||||||
"python-dotenv>=1.2.3",
|
"python-dotenv>=1.2.3",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Send realistic traffic to a running Scrobbler, e.g. to see the Grafana dashboards move.
|
"""Send realistic traffic to a running Scrobbled, e.g. to see the Grafana dashboards move.
|
||||||
|
|
||||||
uv run python scripts/generate_traffic.py --api http://localhost:5050 --minutes 5
|
uv run python scripts/generate_traffic.py --api http://localhost:5050 --minutes 5
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# docker compose for the federation interop stack (Scrobbled + GoToSocial).
|
||||||
|
set -euo pipefail
|
||||||
|
root="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||||
|
# INTEROP_PROJECT (with a distinct SCROBBLER_IMAGE_TAG) lets concurrent runs (e.g. in CI) stay apart.
|
||||||
|
exec docker compose -p "${INTEROP_PROJECT:-scrobbler-interop}" \
|
||||||
|
-f "$root/docker-compose.yml" -f "$root/deploy/interop/docker-compose.interop.yml" "$@"
|
||||||
@@ -0,0 +1,437 @@
|
|||||||
|
"""Federation interop test: a real GoToSocial account follows a Scrobbled user.
|
||||||
|
|
||||||
|
Runs inside the interop compose network (see deploy/interop/). Standard library only.
|
||||||
|
Exits non-zero, with a description, on the first thing that doesn't work.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import html
|
||||||
|
import http.cookiejar
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
GTS = "http://gts.test"
|
||||||
|
SCROBBLER_API = "http://api:8000/api/v1"
|
||||||
|
GTS_EMAIL = os.environ.get("GTS_EMAIL", "gtsuser@gts.test")
|
||||||
|
GTS_PASSWORD = os.environ.get("GTS_PASSWORD", "Interop-Test-Password-1")
|
||||||
|
OOB = "urn:ietf:wg:oauth:2.0:oob"
|
||||||
|
|
||||||
|
|
||||||
|
def step(message: str) -> None:
|
||||||
|
print(f"==> {message}", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, *args, **kwargs):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class Browser:
|
||||||
|
"""Just enough of a browser to sign in and authorize an OAuth app."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.jar = http.cookiejar.CookieJar()
|
||||||
|
self.opener = urllib.request.build_opener(
|
||||||
|
urllib.request.HTTPCookieProcessor(self.jar), NoRedirect()
|
||||||
|
)
|
||||||
|
|
||||||
|
def request(self, method, url, form=None):
|
||||||
|
data = urllib.parse.urlencode(form).encode() if form is not None else None
|
||||||
|
req = urllib.request.Request(url, data=data, method=method)
|
||||||
|
if data is not None:
|
||||||
|
req.add_header("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
try:
|
||||||
|
with self.opener.open(req, timeout=20) as response:
|
||||||
|
return response.status, dict(response.headers), response.read().decode()
|
||||||
|
except urllib.error.HTTPError as err: # includes 3xx, since we don't follow them
|
||||||
|
return err.code, dict(err.headers), err.read().decode()
|
||||||
|
|
||||||
|
|
||||||
|
def api(method, url, token=None, body=None, form=None):
|
||||||
|
headers = {"Accept": "application/json"}
|
||||||
|
data = None
|
||||||
|
if body is not None:
|
||||||
|
data, headers["Content-Type"] = json.dumps(body).encode(), "application/json"
|
||||||
|
elif form is not None:
|
||||||
|
data, headers["Content-Type"] = (
|
||||||
|
urllib.parse.urlencode(form).encode(),
|
||||||
|
"application/x-www-form-urlencoded",
|
||||||
|
)
|
||||||
|
if token:
|
||||||
|
headers["Authorization"] = f"Bearer {token}"
|
||||||
|
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=20) as response:
|
||||||
|
raw = response.read()
|
||||||
|
return response.status, json.loads(raw) if raw else None
|
||||||
|
except urllib.error.HTTPError as err:
|
||||||
|
raw = err.read()
|
||||||
|
try:
|
||||||
|
return err.code, json.loads(raw)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return err.code, raw.decode(errors="replace")[:500]
|
||||||
|
|
||||||
|
|
||||||
|
def fail(message: str):
|
||||||
|
print(f"FAILED: {message}", flush=True)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
def gotosocial_token() -> str:
|
||||||
|
"""Sign in to GoToSocial's web UI and authorize an app (it has no password grant)."""
|
||||||
|
status, app = api(
|
||||||
|
"POST",
|
||||||
|
f"{GTS}/api/v1/apps",
|
||||||
|
form={
|
||||||
|
"client_name": "scrobbler-interop",
|
||||||
|
"redirect_uris": OOB,
|
||||||
|
"scopes": "read write follow",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if status != 200:
|
||||||
|
fail(f"creating a GoToSocial app: {status} {app}")
|
||||||
|
browser = Browser()
|
||||||
|
authorize = f"{GTS}/oauth/authorize?" + urllib.parse.urlencode(
|
||||||
|
{
|
||||||
|
"response_type": "code",
|
||||||
|
"client_id": app["client_id"],
|
||||||
|
"redirect_uri": OOB,
|
||||||
|
"scope": "read write follow",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
status, headers, body = browser.request("GET", authorize)
|
||||||
|
print(f" authorize -> {status} {headers.get('Location', '')}")
|
||||||
|
status, headers, body = browser.request(
|
||||||
|
"POST", f"{GTS}/auth/sign_in", {"username": GTS_EMAIL, "password": GTS_PASSWORD}
|
||||||
|
)
|
||||||
|
print(f" sign in -> {status} {headers.get('Location', '')}")
|
||||||
|
if status not in (302, 303):
|
||||||
|
fail(f"sign-in didn't redirect: {status} {body[:300]}")
|
||||||
|
location = urllib.parse.urljoin(GTS, headers.get("Location", "/oauth/authorize"))
|
||||||
|
status, headers, body = browser.request("GET", location)
|
||||||
|
print(f" authorize page -> {status} {headers.get('Location', '')}")
|
||||||
|
if status == 200:
|
||||||
|
# The consent page: submit its form (with any hidden fields it has)
|
||||||
|
fields = dict(re.findall(r'<input[^>]*name="([^"]+)"[^>]*value="([^"]*)"', body))
|
||||||
|
action = re.search(r'<form[^>]*action="([^"]+)"', body)
|
||||||
|
target = urllib.parse.urljoin(
|
||||||
|
GTS, html.unescape(action.group(1)) if action else "/oauth/authorize"
|
||||||
|
)
|
||||||
|
status, headers, body = browser.request(
|
||||||
|
"POST", target, {k: html.unescape(v) for k, v in fields.items()}
|
||||||
|
)
|
||||||
|
print(f" consent -> {status} {headers.get('Location', '')}")
|
||||||
|
location = headers.get("Location", "")
|
||||||
|
code = urllib.parse.parse_qs(urllib.parse.urlsplit(location).query).get("code", [None])[0]
|
||||||
|
if code is None and status in (302, 303):
|
||||||
|
# Out-of-band: the code is shown on the page we're sent to
|
||||||
|
status, headers, body = browser.request("GET", urllib.parse.urljoin(GTS, location))
|
||||||
|
match = re.search(r"<code>([^<]+)</code>", body) or re.search(
|
||||||
|
r'value="([A-Za-z0-9_-]{20,})"', body
|
||||||
|
)
|
||||||
|
code = match.group(1) if match else None
|
||||||
|
if not code:
|
||||||
|
fail(f"no authorization code (last response {status}: {body[:300]})")
|
||||||
|
status, token = api(
|
||||||
|
"POST",
|
||||||
|
f"{GTS}/oauth/token",
|
||||||
|
form={
|
||||||
|
"grant_type": "authorization_code",
|
||||||
|
"code": code,
|
||||||
|
"client_id": app["client_id"],
|
||||||
|
"client_secret": app["client_secret"],
|
||||||
|
"redirect_uri": OOB,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if status != 200:
|
||||||
|
fail(f"exchanging the code: {status} {token}")
|
||||||
|
return token["access_token"]
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for(description, check, timeout=60):
|
||||||
|
"""Poll `check()` until it returns something truthy."""
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
result = check()
|
||||||
|
if result:
|
||||||
|
return result
|
||||||
|
time.sleep(1)
|
||||||
|
fail(f"timed out waiting for: {description}")
|
||||||
|
|
||||||
|
|
||||||
|
class Scrobbled:
|
||||||
|
def __init__(self, username="alice", password="interop-password-1"):
|
||||||
|
status, body = api(
|
||||||
|
"POST",
|
||||||
|
f"{SCROBBLER_API}/auth/register",
|
||||||
|
body={
|
||||||
|
"username": username,
|
||||||
|
"email": f"{username}@scrobble.test",
|
||||||
|
"password": password,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if status == 409:
|
||||||
|
status, body = api(
|
||||||
|
"POST",
|
||||||
|
f"{SCROBBLER_API}/auth/login",
|
||||||
|
body={
|
||||||
|
"username": username,
|
||||||
|
"password": password,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if status not in (200, 201):
|
||||||
|
fail(f"signing in to Scrobbled: {status} {body}")
|
||||||
|
self.token = body["token"]
|
||||||
|
|
||||||
|
def settings(self, **changes):
|
||||||
|
status, body = api(
|
||||||
|
"PATCH", f"{SCROBBLER_API}/federation/settings", self.token, body=changes
|
||||||
|
)
|
||||||
|
if status != 200:
|
||||||
|
fail(f"changing Scrobbled settings: {status} {body}")
|
||||||
|
return body
|
||||||
|
|
||||||
|
def followers(self, state=None):
|
||||||
|
query = f"?state={state}" if state else ""
|
||||||
|
status, body = api("GET", f"{SCROBBLER_API}/federation/followers{query}", self.token)
|
||||||
|
if status != 200:
|
||||||
|
fail(f"listing followers: {status} {body}")
|
||||||
|
return body
|
||||||
|
|
||||||
|
def act(self, follower_id, action):
|
||||||
|
status, body = api(
|
||||||
|
"POST", f"{SCROBBLER_API}/federation/followers/{follower_id}/{action}", self.token
|
||||||
|
)
|
||||||
|
if status not in (200, 204):
|
||||||
|
fail(f"{action} follower: {status} {body}")
|
||||||
|
|
||||||
|
def posts(self):
|
||||||
|
status, body = api("GET", f"{SCROBBLER_API}/federation/posts", self.token)
|
||||||
|
if status != 200:
|
||||||
|
fail(f"listing posts: {status} {body}")
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
|
class GoToSocial:
|
||||||
|
def __init__(self, token):
|
||||||
|
self.token = token
|
||||||
|
|
||||||
|
def resolve(self, handle):
|
||||||
|
status, body = api(
|
||||||
|
"GET",
|
||||||
|
f"{GTS}/api/v2/search?"
|
||||||
|
+ urllib.parse.urlencode({"q": handle, "resolve": "true", "type": "accounts"}),
|
||||||
|
self.token,
|
||||||
|
)
|
||||||
|
if status != 200 or not body.get("accounts"):
|
||||||
|
fail(f"GoToSocial couldn't find {handle}: {status} {body}")
|
||||||
|
return body["accounts"][0]
|
||||||
|
|
||||||
|
def follow(self, account_id):
|
||||||
|
status, body = api(
|
||||||
|
"POST", f"{GTS}/api/v1/accounts/{account_id}/follow", self.token, body={}
|
||||||
|
)
|
||||||
|
if status != 200:
|
||||||
|
fail(f"following: {status} {body}")
|
||||||
|
return body
|
||||||
|
|
||||||
|
def unfollow(self, account_id):
|
||||||
|
status, body = api(
|
||||||
|
"POST", f"{GTS}/api/v1/accounts/{account_id}/unfollow", self.token, body={}
|
||||||
|
)
|
||||||
|
if status != 200:
|
||||||
|
fail(f"unfollowing: {status} {body}")
|
||||||
|
|
||||||
|
def relationship(self, account_id):
|
||||||
|
status, body = api(
|
||||||
|
"GET", f"{GTS}/api/v1/accounts/relationships?id[]={account_id}", self.token
|
||||||
|
)
|
||||||
|
if status != 200 or not body:
|
||||||
|
fail(f"relationship: {status} {body}")
|
||||||
|
return body[0]
|
||||||
|
|
||||||
|
def home_timeline(self):
|
||||||
|
status, body = api("GET", f"{GTS}/api/v1/timelines/home", self.token)
|
||||||
|
if status != 200:
|
||||||
|
fail(f"home timeline: {status} {body}")
|
||||||
|
return body
|
||||||
|
|
||||||
|
def account(self, account_id):
|
||||||
|
"""The account as GoToSocial currently has it stored - not a fresh remote fetch
|
||||||
|
like resolve()'s ?resolve=true search, so this shows whether a proactive
|
||||||
|
Update(Person) actually reached and updated their cached copy."""
|
||||||
|
status, body = api("GET", f"{GTS}/api/v1/accounts/{account_id}", self.token)
|
||||||
|
if status != 200:
|
||||||
|
fail(f"account lookup: {status} {body}")
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
step("Getting a GoToSocial access token")
|
||||||
|
gts = GoToSocial(gotosocial_token())
|
||||||
|
|
||||||
|
step("Alice starts sharing on Scrobbled")
|
||||||
|
alice = Scrobbled()
|
||||||
|
alice.settings(
|
||||||
|
enabled=True,
|
||||||
|
display_name="Alice Interop",
|
||||||
|
bio="Testing federation.",
|
||||||
|
manually_approves_followers=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
step("GoToSocial finds @alice@scrobble.test (WebFinger, actor, key)")
|
||||||
|
account = gts.resolve("@alice@scrobble.test")
|
||||||
|
print(f" found {account['acct']} ({account['display_name']!r})")
|
||||||
|
if account["display_name"] != "Alice Interop":
|
||||||
|
fail(f"unexpected display name {account['display_name']!r}")
|
||||||
|
account_id = account["id"]
|
||||||
|
|
||||||
|
step("Follow: GoToSocial sees it accepted (our signed Accept verified)")
|
||||||
|
gts.follow(account_id)
|
||||||
|
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
|
||||||
|
followers = wait_for("Scrobbled to list the follower", lambda: alice.followers("accepted"))
|
||||||
|
print(f" Scrobbled follower: {followers[0]['handle']}")
|
||||||
|
if followers[0]["handle"] != "@gtsuser@gts.test":
|
||||||
|
fail(f"unexpected follower {followers[0]['handle']}")
|
||||||
|
|
||||||
|
step("Unfollow: Scrobbled drops the follower (their signed Undo verified)")
|
||||||
|
gts.unfollow(account_id)
|
||||||
|
wait_for("Scrobbled to drop the follower", lambda: not alice.followers())
|
||||||
|
|
||||||
|
step("Manual approval: the follow waits as a request")
|
||||||
|
alice.settings(manually_approves_followers=True)
|
||||||
|
gts.follow(account_id)
|
||||||
|
wait_for(
|
||||||
|
"GoToSocial to show a pending request", lambda: gts.relationship(account_id)["requested"]
|
||||||
|
)
|
||||||
|
pending = wait_for("Scrobbled to list the request", lambda: alice.followers("pending"))
|
||||||
|
if gts.relationship(account_id)["following"]:
|
||||||
|
fail("following before being approved")
|
||||||
|
|
||||||
|
step("Approve: GoToSocial sees it accepted")
|
||||||
|
alice.act(pending[0]["id"], "approve")
|
||||||
|
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
|
||||||
|
|
||||||
|
step("Remove the follower: Scrobbled drops them and sends a Reject")
|
||||||
|
alice.act(alice.followers()[0]["id"], "remove")
|
||||||
|
if alice.followers():
|
||||||
|
fail("the follower is still listed after removal")
|
||||||
|
# GoToSocial 0.22.1 only applies a Reject to *pending* follow requests (its
|
||||||
|
# federatingdb/reject.go has a TODO for accepted follows; fixed on its main branch).
|
||||||
|
# Mastodon, and the ActivityPub consensus, drop the follow. Until a GoToSocial
|
||||||
|
# release includes the fix, their side is checked only when asked to.
|
||||||
|
if os.environ.get("GTS_REJECT_ENDS_FOLLOWS") == "1":
|
||||||
|
wait_for(
|
||||||
|
"GoToSocial to stop following", lambda: not gts.relationship(account_id)["following"]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
print(" (skipping GoToSocial's side: its 0.22.1 ignores Reject for accepted follows)")
|
||||||
|
gts.unfollow(account_id) # tidy up their side for the next step
|
||||||
|
wait_for(
|
||||||
|
"GoToSocial to not be following", lambda: not gts.relationship(account_id)["following"]
|
||||||
|
)
|
||||||
|
|
||||||
|
step("Block a follower: GoToSocial drops the follow (it honours Block)")
|
||||||
|
gts.follow(account_id)
|
||||||
|
pending = wait_for("Scrobbled to list the request", lambda: alice.followers("pending"))
|
||||||
|
alice.act(pending[0]["id"], "approve")
|
||||||
|
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
|
||||||
|
alice.act(alice.followers()[0]["id"], "block")
|
||||||
|
wait_for("GoToSocial to stop following", lambda: not gts.relationship(account_id)["following"])
|
||||||
|
status, blocks = api("GET", f"{SCROBBLER_API}/federation/blocks", alice.token)
|
||||||
|
if status != 200 or [b["handle"] for b in blocks] != ["@gtsuser@gts.test"]:
|
||||||
|
fail(f"the block isn't listed: {status} {blocks}")
|
||||||
|
wait_for("GoToSocial to see the block", lambda: gts.relationship(account_id)["blocked_by"])
|
||||||
|
|
||||||
|
step("Unblock: GoToSocial sees the Undo of the Block")
|
||||||
|
status, _ = api("DELETE", f"{SCROBBLER_API}/federation/blocks/{blocks[0]['id']}", alice.token)
|
||||||
|
if status != 204:
|
||||||
|
fail(f"unblocking: {status}")
|
||||||
|
wait_for(
|
||||||
|
"GoToSocial to see the unblock", lambda: not gts.relationship(account_id)["blocked_by"]
|
||||||
|
)
|
||||||
|
|
||||||
|
step("Decline a request: GoToSocial's request is withdrawn")
|
||||||
|
gts.follow(account_id)
|
||||||
|
pending = wait_for("Scrobbled to list the request", lambda: alice.followers("pending"))
|
||||||
|
alice.act(pending[0]["id"], "decline")
|
||||||
|
wait_for(
|
||||||
|
"GoToSocial's request to go away",
|
||||||
|
lambda: (
|
||||||
|
not gts.relationship(account_id)["requested"]
|
||||||
|
and not gts.relationship(account_id)["following"]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
step("Re-follow: left in place for the post check (run.sh's second driver pass)")
|
||||||
|
alice.settings(manually_approves_followers=False)
|
||||||
|
gts.follow(account_id)
|
||||||
|
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
|
||||||
|
|
||||||
|
step("All interop checks passed")
|
||||||
|
|
||||||
|
|
||||||
|
def check_posts():
|
||||||
|
"""Second phase, run by run.sh after it triggers `flask federation post-weekly
|
||||||
|
--now` directly in the api container (this container has no docker access to do that
|
||||||
|
itself). Checks the post reaches the already-following GoToSocial account's home
|
||||||
|
timeline as a private (followers-only) status with the expected text, then deletes
|
||||||
|
it and checks it disappears there too. Also turns now playing on and checks the
|
||||||
|
profile field GoToSocial has cached is updated by the periodic push."""
|
||||||
|
step("Getting a GoToSocial access token")
|
||||||
|
gts = GoToSocial(gotosocial_token())
|
||||||
|
alice = Scrobbled() # register-or-login: the same account main() set up
|
||||||
|
account = gts.resolve("@alice@scrobble.test")
|
||||||
|
account_id = account["id"]
|
||||||
|
if not gts.relationship(account_id)["following"]:
|
||||||
|
fail("GoToSocial isn't following alice; run the main interop flow first")
|
||||||
|
|
||||||
|
step("Alice turns now playing on (run.sh already seeded a now-playing track)")
|
||||||
|
alice.settings(now_playing_mode="profile")
|
||||||
|
|
||||||
|
step("The weekly summary reaches GoToSocial's home timeline")
|
||||||
|
posted = wait_for(
|
||||||
|
"the weekly summary in GoToSocial's home timeline",
|
||||||
|
lambda: next(
|
||||||
|
(s for s in gts.home_timeline() if s["account"]["acct"] == "alice@scrobble.test"),
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if posted["visibility"] != "private":
|
||||||
|
fail(f"expected private (followers-only) visibility, got {posted['visibility']!r}")
|
||||||
|
if "My week in music" not in posted["content"]:
|
||||||
|
fail(f"unexpected content: {posted['content']!r}")
|
||||||
|
print(f" {posted['visibility']} post: {posted['content'][:80]!r}")
|
||||||
|
|
||||||
|
step("Deleting the post removes it from GoToSocial too")
|
||||||
|
[post, *_] = alice.posts()
|
||||||
|
status, body = api("DELETE", f"{SCROBBLER_API}/federation/posts/{post['id']}", alice.token)
|
||||||
|
if status != 204:
|
||||||
|
fail(f"deleting the post: {status} {body}")
|
||||||
|
wait_for(
|
||||||
|
"the post to disappear from GoToSocial's home timeline",
|
||||||
|
lambda: not any(s["id"] == posted["id"] for s in gts.home_timeline()),
|
||||||
|
)
|
||||||
|
|
||||||
|
step("The now-playing field reaches GoToSocial's cached copy of the profile")
|
||||||
|
field = wait_for(
|
||||||
|
"a Now playing field on GoToSocial's cached account",
|
||||||
|
lambda: next(
|
||||||
|
(f for f in gts.account(account_id)["fields"] if f["name"] == "Now playing"), None
|
||||||
|
),
|
||||||
|
timeout=90, # the push is throttled and only checked every 30s
|
||||||
|
)
|
||||||
|
if "Interop Now Playing" not in field["value"]:
|
||||||
|
fail(f"unexpected now-playing field: {field['value']!r}")
|
||||||
|
print(f" Now playing: {field['value']!r}")
|
||||||
|
|
||||||
|
step("All post interop checks passed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
check_posts() if "--check-posts" in sys.argv[1:] else main()
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Run the GoToSocial federation interop test end to end, then tear everything down.
|
||||||
|
# Usage: scripts/interop/run.sh [--keep] (--keep leaves the stack running afterwards)
|
||||||
|
set -uo pipefail
|
||||||
|
here="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
compose="$here/compose.sh"
|
||||||
|
keep=0; [ "${1:-}" = "--keep" ] && keep=1
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
[ "$keep" = 1 ] && return 0
|
||||||
|
"$compose" down -v --remove-orphans --rmi local >/dev/null 2>&1
|
||||||
|
# Per-run api/ui images (tagged with SCROBBLER_IMAGE_TAG) would otherwise pile up
|
||||||
|
[ -n "${SCROBBLER_IMAGE_TAG:-}" ] && "$compose" config --images 2>/dev/null \
|
||||||
|
| grep ":${SCROBBLER_IMAGE_TAG}$" | xargs -r docker rmi >/dev/null 2>&1
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
|
||||||
|
"$compose" down -v --remove-orphans >/dev/null 2>&1
|
||||||
|
echo "==> Building and starting Scrobbled + GoToSocial"
|
||||||
|
"$compose" up -d --build --wait db api ui worker tls gotosocial || { "$compose" ps; exit 1; }
|
||||||
|
|
||||||
|
echo "==> Waiting for GoToSocial"
|
||||||
|
for _ in $(seq 1 60); do
|
||||||
|
"$compose" exec -T gotosocial wget -qO- http://127.0.0.1/api/v1/instance >/dev/null 2>&1 && break
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "==> Creating the GoToSocial test user"
|
||||||
|
"$compose" exec -T gotosocial /gotosocial/gotosocial admin account create \
|
||||||
|
--username gtsuser --email gtsuser@gts.test --password 'Interop-Test-Password-1' >/dev/null
|
||||||
|
"$compose" exec -T gotosocial /gotosocial/gotosocial admin account confirm --username gtsuser >/dev/null
|
||||||
|
|
||||||
|
diagnose() {
|
||||||
|
echo "==> Scrobbled federation state"
|
||||||
|
"$compose" exec -T db psql -U scrobbler -d scrobbler -c \
|
||||||
|
"select activity_type, status, reason, attempts from federation_inbox order by id" -c \
|
||||||
|
"select a.activity_type, d.status, d.attempts, d.last_status, left(d.last_error, 200) as error
|
||||||
|
from federation_deliveries d join federation_activities a on a.id = d.activity_id order by d.id"
|
||||||
|
echo "==> Recent logs"
|
||||||
|
"$compose" logs --tail 200 worker gotosocial | grep -v "api/v1/accounts/relationships" | tail -40
|
||||||
|
}
|
||||||
|
|
||||||
|
"$compose" build driver >/dev/null
|
||||||
|
"$compose" run --rm driver
|
||||||
|
status=$?
|
||||||
|
if [ $status -ne 0 ]; then
|
||||||
|
diagnose
|
||||||
|
exit $status
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> Alice scrobbles something, for the weekly summary to have content, and is playing something now"
|
||||||
|
"$compose" exec -T api python3 -c "
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from scrobbler import create_app
|
||||||
|
from scrobbler.config import Config
|
||||||
|
from scrobbler.extensions import db
|
||||||
|
from scrobbler.models import Scrobble, User
|
||||||
|
from scrobbler.services.scrobbles import TrackInput, update_now_playing
|
||||||
|
|
||||||
|
app = create_app(Config)
|
||||||
|
with app.app_context():
|
||||||
|
user = db.session.scalar(db.select(User).filter_by(username='alice'))
|
||||||
|
db.session.add(Scrobble(user_id=user.id, artist='Interop Artist', track='Interop Track', played_at=datetime.now(UTC)))
|
||||||
|
db.session.commit()
|
||||||
|
update_now_playing(user, TrackInput(artist='Interop Artist', track='Interop Now Playing'))
|
||||||
|
"
|
||||||
|
|
||||||
|
echo "==> Posting alice's weekly summary immediately"
|
||||||
|
"$compose" exec -T api flask --app scrobbler federation post-weekly --user alice --now
|
||||||
|
|
||||||
|
echo "==> Checking the post reaches GoToSocial, then is removed there when deleted"
|
||||||
|
"$compose" run --rm driver python /interop/gotosocial_interop.py --check-posts
|
||||||
|
status=$?
|
||||||
|
if [ $status -ne 0 ]; then
|
||||||
|
diagnose
|
||||||
|
fi
|
||||||
|
exit $status
|
||||||
@@ -19,6 +19,10 @@ def create_app(config_object=None):
|
|||||||
app = Flask(__name__, static_folder=None) # API only: the UI is hosted separately
|
app = Flask(__name__, static_folder=None) # API only: the UI is hosted separately
|
||||||
app.config.from_object(config_object or Config)
|
app.config.from_object(config_object or Config)
|
||||||
|
|
||||||
|
from scrobbler.logsetup import configure_logging
|
||||||
|
|
||||||
|
configure_logging(app.config["LOG_LEVEL"], app.config["LOG_FORMAT"])
|
||||||
|
|
||||||
db.init_app(app)
|
db.init_app(app)
|
||||||
migrate.init_app(app, db, directory=_migrations_dir())
|
migrate.init_app(app, db, directory=_migrations_dir())
|
||||||
http_metrics.init_app(app)
|
http_metrics.init_app(app)
|
||||||
@@ -30,6 +34,10 @@ def create_app(config_object=None):
|
|||||||
|
|
||||||
app.register_blueprint(lastfm_bp)
|
app.register_blueprint(lastfm_bp)
|
||||||
api.init_app(app)
|
api.init_app(app)
|
||||||
|
|
||||||
|
from scrobbler import federation # the only place the core touches federation
|
||||||
|
|
||||||
|
federation.init_app(app)
|
||||||
CORS(
|
CORS(
|
||||||
app,
|
app,
|
||||||
resources={r"/api/v1/*": {"origins": app.config["CORS_ORIGINS"]}},
|
resources={r"/api/v1/*": {"origins": app.config["CORS_ORIGINS"]}},
|
||||||
@@ -37,9 +45,14 @@ def create_app(config_object=None):
|
|||||||
max_age=600,
|
max_age=600,
|
||||||
)
|
)
|
||||||
|
|
||||||
from scrobbler.cli import imports_cli
|
from scrobbler.cli import imports_cli, worker_command
|
||||||
|
from scrobbler.services import art as art_service
|
||||||
|
from scrobbler.services import imports as import_service
|
||||||
|
|
||||||
|
app.cli.add_command(worker_command)
|
||||||
app.cli.add_command(imports_cli)
|
app.cli.add_command(imports_cli)
|
||||||
|
import_service.register_worker_tasks(app)
|
||||||
|
art_service.register_worker_tasks(app)
|
||||||
|
|
||||||
from scrobbler.metrics import db as db_metrics
|
from scrobbler.metrics import db as db_metrics
|
||||||
|
|
||||||
|
|||||||
@@ -29,11 +29,16 @@ class ScrobblerApi(Api):
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
api = ScrobblerApi()
|
def get_api(app: Flask) -> ScrobblerApi:
|
||||||
|
"""This app's Api (for registering blueprints and documenting paths)."""
|
||||||
|
return app.extensions["scrobbler_api"]
|
||||||
|
|
||||||
|
|
||||||
def init_app(app: Flask) -> None:
|
def init_app(app: Flask) -> None:
|
||||||
api.init_app(app)
|
# One Api per app: its OpenAPI spec is per app too, so apps with different
|
||||||
|
# optional modules enabled (e.g. in tests) never share a spec.
|
||||||
|
api = ScrobblerApi(app)
|
||||||
|
app.extensions["scrobbler_api"] = api
|
||||||
api.spec.components.security_scheme(
|
api.spec.components.security_scheme(
|
||||||
"bearerAuth",
|
"bearerAuth",
|
||||||
{
|
{
|
||||||
@@ -43,14 +48,28 @@ def init_app(app: Flask) -> None:
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
from scrobbler.api import apps, auth, health, imports, sessions, stats, tokens
|
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(auth.blp, url_prefix="/api/v1/auth")
|
||||||
api.register_blueprint(apps.blp, url_prefix="/api/v1/apps")
|
api.register_blueprint(apps.blp, url_prefix="/api/v1/apps")
|
||||||
api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions")
|
api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions")
|
||||||
api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens")
|
api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens")
|
||||||
api.register_blueprint(stats.blp, url_prefix="/api/v1/me")
|
api.register_blueprint(stats.blp, url_prefix="/api/v1/me")
|
||||||
|
api.register_blueprint(tracks.blp, url_prefix="/api/v1/me/tracks")
|
||||||
api.register_blueprint(imports.blp, url_prefix="/api/v1/imports")
|
api.register_blueprint(imports.blp, url_prefix="/api/v1/imports")
|
||||||
|
api.register_blueprint(art.blp, url_prefix="/api/v1/art")
|
||||||
|
api.register_blueprint(avatar.blp, url_prefix="/api/v1/me/avatar")
|
||||||
api.register_blueprint(health.blp)
|
api.register_blueprint(health.blp)
|
||||||
|
|
||||||
from scrobbler.openapi import lastfm
|
from scrobbler.openapi import lastfm
|
||||||
|
|||||||
@@ -0,0 +1,178 @@
|
|||||||
|
import math
|
||||||
|
|
||||||
|
from flask import Response, current_app, g, request
|
||||||
|
from flask_smorest import Blueprint, abort
|
||||||
|
|
||||||
|
from scrobbler import metrics
|
||||||
|
from scrobbler.api.decorators import authenticated
|
||||||
|
from scrobbler.schemas import (
|
||||||
|
AlbumArtArgsSchema,
|
||||||
|
AlbumArtCorrectionSchema,
|
||||||
|
AlbumArtFailuresPageSchema,
|
||||||
|
AlbumArtOverrideSchema,
|
||||||
|
AlbumArtUploadSchema,
|
||||||
|
ErrorSchema,
|
||||||
|
PageArgsSchema,
|
||||||
|
)
|
||||||
|
from scrobbler.services import art
|
||||||
|
|
||||||
|
blp = Blueprint(
|
||||||
|
"Art",
|
||||||
|
__name__,
|
||||||
|
description=(
|
||||||
|
"Album art, resolved from MusicBrainz / Cover Art Archive by a background worker. "
|
||||||
|
"You can also upload your own art, or correct a failed lookup; those only change "
|
||||||
|
"what you see."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/album", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(AlbumArtArgsSchema, location="query")
|
||||||
|
@blp.response(
|
||||||
|
200, content_type="image/jpeg", description="The album's cover art (JPEG, PNG or WebP)"
|
||||||
|
)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="No cover art available yet")
|
||||||
|
def album_art(args):
|
||||||
|
"""An album's cover art
|
||||||
|
|
||||||
|
Your own uploaded or corrected art comes first. Otherwise it's served from a local
|
||||||
|
cache that a background worker task keeps filled; this endpoint never makes a live
|
||||||
|
MusicBrainz/Cover Art Archive call, so it can't be slowed down by one. An album seen
|
||||||
|
for the first time returns 404 until the worker resolves it, typically within a few
|
||||||
|
seconds - cache this response client-side and retry later.
|
||||||
|
"""
|
||||||
|
own = art.get_override(g.user.id, args["artist"], args["album"])
|
||||||
|
if own is not None and own.status == "found":
|
||||||
|
data = art.read_override_file(own)
|
||||||
|
if data is not None:
|
||||||
|
metrics.art_requests_total.labels("override").inc()
|
||||||
|
response = Response(data, mimetype=own.content_type or "image/jpeg")
|
||||||
|
response.headers["Cache-Control"] = "private, no-cache" # revalidate: it can change
|
||||||
|
response.add_etag()
|
||||||
|
return response.make_conditional(request)
|
||||||
|
|
||||||
|
row = art.get_cached(args["artist"], args["album"])
|
||||||
|
if row is None:
|
||||||
|
art.want(args["artist"], args["album"])
|
||||||
|
metrics.art_requests_total.labels("queued").inc()
|
||||||
|
abort(404, code="no_album_art", message="Not resolved yet")
|
||||||
|
image = art.read_file(row.id) if row.status == "found" else None
|
||||||
|
if image is None:
|
||||||
|
if row.status == "found":
|
||||||
|
art.requeue(row) # resolved before, but the file is missing - ask again
|
||||||
|
result = "file_missing"
|
||||||
|
else:
|
||||||
|
result = "pending" if row.status == "pending" else "unavailable"
|
||||||
|
metrics.art_requests_total.labels(result).inc()
|
||||||
|
abort(404, code="no_album_art", message="No cover art found for this album")
|
||||||
|
metrics.art_requests_total.labels("served").inc()
|
||||||
|
response = Response(image, mimetype="image/jpeg")
|
||||||
|
response.headers["Cache-Control"] = "private, max-age=604800" # 7 days; art rarely changes
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/album", methods=["POST"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(AlbumArtUploadSchema, location="files")
|
||||||
|
@blp.arguments(AlbumArtArgsSchema, location="query")
|
||||||
|
@blp.response(201, AlbumArtOverrideSchema)
|
||||||
|
@blp.alt_response(400, schema=ErrorSchema, description="Empty file")
|
||||||
|
@blp.alt_response(413, schema=ErrorSchema, description="Image too large")
|
||||||
|
@blp.alt_response(415, schema=ErrorSchema, description="Not a JPEG, PNG or WebP image")
|
||||||
|
def upload_art(files, args):
|
||||||
|
"""Upload your own art for an album
|
||||||
|
|
||||||
|
Replaces any earlier upload or correction of yours for this album. Only you see it.
|
||||||
|
"""
|
||||||
|
limit = current_app.config["ART_UPLOAD_MAX_BYTES"]
|
||||||
|
data = files["file"].read(limit + 1)
|
||||||
|
if not data:
|
||||||
|
metrics.art_uploads_total.labels("empty").inc()
|
||||||
|
abort(400, code="empty_file", message="That file is empty.")
|
||||||
|
if len(data) > limit:
|
||||||
|
metrics.art_uploads_total.labels("too_large").inc()
|
||||||
|
abort(413, code="file_too_large", message="That image is larger than this server accepts.")
|
||||||
|
try:
|
||||||
|
content_type = art.sniff_image_type(data)
|
||||||
|
except art.UnsupportedImage:
|
||||||
|
metrics.art_uploads_total.labels("bad_type").inc()
|
||||||
|
abort(415, code="unsupported_image", message="Upload a JPEG, PNG or WebP image.")
|
||||||
|
art.save_upload(g.user.id, args["artist"], args["album"], data, content_type)
|
||||||
|
metrics.art_uploads_total.labels("ok").inc()
|
||||||
|
metrics.art_upload_bytes.observe(len(data))
|
||||||
|
return art.get_override(g.user.id, args["artist"], args["album"])
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/album", methods=["DELETE"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(AlbumArtArgsSchema, location="query")
|
||||||
|
@blp.response(204)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="You have no art of your own for this album")
|
||||||
|
def delete_override(args):
|
||||||
|
"""Remove your own art for an album
|
||||||
|
|
||||||
|
The album goes back to the shared lookup result, if there is one.
|
||||||
|
"""
|
||||||
|
if not art.delete_override(g.user.id, args["artist"], args["album"]):
|
||||||
|
abort(404, code="not_found", message="You have no art of your own for this album")
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/album/correction", methods=["PUT"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(AlbumArtCorrectionSchema)
|
||||||
|
@blp.response(202, AlbumArtOverrideSchema)
|
||||||
|
def correct_art(body):
|
||||||
|
"""Correct a failed lookup
|
||||||
|
|
||||||
|
Queues a new lookup with different search text, or straight from a MusicBrainz
|
||||||
|
release-group or release ID. The background worker resolves it; poll the failures list, or just
|
||||||
|
fetch the art later. Replaces any earlier upload or correction of yours.
|
||||||
|
"""
|
||||||
|
mbid = body.get("release_group_mbid")
|
||||||
|
release_mbid = body.get("release_mbid")
|
||||||
|
art.request_correction(
|
||||||
|
g.user.id,
|
||||||
|
body["artist"],
|
||||||
|
body["album"],
|
||||||
|
body.get("search_artist"),
|
||||||
|
body.get("search_album"),
|
||||||
|
str(mbid) if mbid else None,
|
||||||
|
str(release_mbid) if release_mbid else None,
|
||||||
|
)
|
||||||
|
return art.get_override(g.user.id, body["artist"], body["album"])
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/album/retry", methods=["POST"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(AlbumArtArgsSchema, location="query")
|
||||||
|
@blp.response(202)
|
||||||
|
@blp.alt_response(409, schema=ErrorSchema, description="Nothing to retry")
|
||||||
|
def retry_art(args):
|
||||||
|
"""Look an album up again
|
||||||
|
|
||||||
|
Re-queues the shared lookup for an album whose search found nothing or failed.
|
||||||
|
"""
|
||||||
|
if not art.retry(args["artist"], args["album"]):
|
||||||
|
abort(409, code="nothing_to_retry", message="This album's art is found or already queued")
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/failures", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(PageArgsSchema, location="query")
|
||||||
|
@blp.response(200, AlbumArtFailuresPageSchema)
|
||||||
|
def failures(args):
|
||||||
|
"""Albums of yours without art
|
||||||
|
|
||||||
|
Albums you've scrobbled whose lookup found nothing or failed, plus ones where your
|
||||||
|
own correction didn't work, most-scrobbled first. Albums you've fixed drop off.
|
||||||
|
"""
|
||||||
|
items, total = art.list_failures(g.user.id, args["page"], args["limit"])
|
||||||
|
return {
|
||||||
|
"items": items,
|
||||||
|
"page": args["page"],
|
||||||
|
"per_page": args["limit"],
|
||||||
|
"total": total,
|
||||||
|
"total_pages": math.ceil(total / args["limit"]),
|
||||||
|
}
|
||||||
@@ -0,0 +1,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")
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
from flask import g
|
||||||
|
from flask_smorest import Blueprint, abort
|
||||||
|
|
||||||
|
from scrobbler.api.decorators import authenticated
|
||||||
|
from scrobbler.schemas import (
|
||||||
|
ErrorSchema,
|
||||||
|
TrackDetailArgsSchema,
|
||||||
|
TrackDetailSchema,
|
||||||
|
TrackSearchArgsSchema,
|
||||||
|
TrackSearchResultSchema,
|
||||||
|
)
|
||||||
|
from scrobbler.services import stats
|
||||||
|
|
||||||
|
blp = Blueprint("Tracks", __name__, description="Look up a specific song's history and metadata")
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/search", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(TrackSearchArgsSchema, location="query")
|
||||||
|
@blp.response(200, TrackSearchResultSchema(many=True))
|
||||||
|
def search(args):
|
||||||
|
"""Find a song by track or artist name"""
|
||||||
|
return stats.track_search(g.user, args["q"], args["limit"])
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(TrackDetailArgsSchema, location="query")
|
||||||
|
@blp.response(200, TrackDetailSchema)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="You've never scrobbled this song")
|
||||||
|
def detail(args):
|
||||||
|
"""A song's play history and recorded metadata"""
|
||||||
|
metadata = stats.track_metadata(g.user, args["artist"], args["track"])
|
||||||
|
if metadata is None:
|
||||||
|
abort(404, code="not_found", message="You've never scrobbled this song")
|
||||||
|
history = stats.recent(
|
||||||
|
g.user,
|
||||||
|
page=args["page"],
|
||||||
|
per_page=args["limit"],
|
||||||
|
artist=args["artist"],
|
||||||
|
track=args["track"],
|
||||||
|
)
|
||||||
|
counts = stats.listen_counts(
|
||||||
|
g.user, period="3month", bucket="day", artist=args["artist"], track=args["track"]
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"artist": metadata.artist,
|
||||||
|
"track": metadata.track,
|
||||||
|
"metadata": metadata,
|
||||||
|
"items": history.items,
|
||||||
|
"counts": counts,
|
||||||
|
"page": history.page,
|
||||||
|
"per_page": history.per_page,
|
||||||
|
"total": history.total,
|
||||||
|
"total_pages": history.total_pages,
|
||||||
|
}
|
||||||
@@ -2,22 +2,43 @@ import logging
|
|||||||
|
|
||||||
import click
|
import click
|
||||||
from flask import current_app
|
from flask import current_app
|
||||||
from flask.cli import AppGroup
|
from flask.cli import AppGroup, with_appcontext
|
||||||
|
|
||||||
|
|
||||||
|
def _run_worker(once: bool, poll: float, serve_metrics: bool) -> None:
|
||||||
|
from scrobbler import worker
|
||||||
|
|
||||||
|
if serve_metrics:
|
||||||
|
from scrobbler.metrics.server import start_metrics_server
|
||||||
|
|
||||||
|
start_metrics_server(current_app.config["WORKER_METRICS_PORT"])
|
||||||
|
logging.getLogger(__name__).info("worker tasks: %s", ", ".join(worker.registered()))
|
||||||
|
worker.run(poll_seconds=poll, once=once)
|
||||||
|
|
||||||
|
|
||||||
|
def _worker_options(fn):
|
||||||
|
fn = click.option(
|
||||||
|
"--metrics/--no-metrics", "serve_metrics", default=True, help="Serve Prometheus metrics."
|
||||||
|
)(fn)
|
||||||
|
fn = click.option(
|
||||||
|
"--poll", default=2.0, show_default=True, help="Seconds between checks when idle."
|
||||||
|
)(fn)
|
||||||
|
return click.option("--once", is_flag=True, help="Do all waiting work, then exit.")(fn)
|
||||||
|
|
||||||
|
|
||||||
|
@click.command("worker")
|
||||||
|
@_worker_options
|
||||||
|
@with_appcontext
|
||||||
|
def worker_command(once: bool, poll: float, serve_metrics: bool) -> None:
|
||||||
|
"""Run background work: imports, and tasks registered by optional modules."""
|
||||||
|
_run_worker(once, poll, serve_metrics)
|
||||||
|
|
||||||
|
|
||||||
imports_cli = AppGroup("imports", help="History imports.")
|
imports_cli = AppGroup("imports", help="History imports.")
|
||||||
|
|
||||||
|
|
||||||
@imports_cli.command("worker")
|
@imports_cli.command("worker")
|
||||||
@click.option("--once", is_flag=True, help="Process waiting jobs, then exit.")
|
@_worker_options
|
||||||
@click.option("--poll", default=2.0, show_default=True, help="Seconds between checks when idle.")
|
def imports_worker(once: bool, poll: float, serve_metrics: bool) -> None:
|
||||||
@click.option("--metrics/--no-metrics", default=True, help="Serve Prometheus metrics.")
|
"""Alias for `flask worker` (kept for existing deployments)."""
|
||||||
def worker(once: bool, poll: float, metrics: bool) -> None:
|
_run_worker(once, poll, serve_metrics)
|
||||||
"""Process import jobs: uploaded Last.fm exports and pulls from Last.fm."""
|
|
||||||
from scrobbler.services.imports import run_worker
|
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
||||||
if metrics:
|
|
||||||
from scrobbler.metrics.server import start_metrics_server
|
|
||||||
|
|
||||||
start_metrics_server(current_app.config["IMPORT_WORKER_METRICS_PORT"])
|
|
||||||
run_worker(poll_seconds=poll, once=once)
|
|
||||||
@@ -20,13 +20,16 @@ class Config:
|
|||||||
CORS_ORIGINS = _csv(os.environ.get("CORS_ORIGINS", "http://localhost:8080"))
|
CORS_ORIGINS = _csv(os.environ.get("CORS_ORIGINS", "http://localhost:8080"))
|
||||||
UI_BASE_URL = os.environ.get("UI_BASE_URL", "http://localhost:8080").rstrip("/")
|
UI_BASE_URL = os.environ.get("UI_BASE_URL", "http://localhost:8080").rstrip("/")
|
||||||
|
|
||||||
|
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
|
||||||
|
LOG_FORMAT = os.environ.get("LOG_FORMAT", "text").lower() # "text" or "json"
|
||||||
|
|
||||||
METRICS_PORT = int(os.environ.get("METRICS_PORT", "9100"))
|
METRICS_PORT = int(os.environ.get("METRICS_PORT", "9100"))
|
||||||
# Start the metrics HTTP server from create_app (dev server). Under gunicorn the
|
# Start the metrics HTTP server from create_app (dev server). Under gunicorn the
|
||||||
# server is started by gunicorn.conf.py instead, so this stays off there.
|
# server is started by gunicorn.conf.py instead, so this stays off there.
|
||||||
START_METRICS_SERVER = os.environ.get("START_METRICS_SERVER", "0") == "1"
|
START_METRICS_SERVER = os.environ.get("START_METRICS_SERVER", "0") == "1"
|
||||||
|
|
||||||
# OpenAPI document and docs (flask-smorest)
|
# OpenAPI document and docs (flask-smorest)
|
||||||
API_TITLE = "Scrobbler API"
|
API_TITLE = "Scrobbled API"
|
||||||
API_VERSION = "v1"
|
API_VERSION = "v1"
|
||||||
OPENAPI_VERSION = "3.1.0"
|
OPENAPI_VERSION = "3.1.0"
|
||||||
OPENAPI_URL_PREFIX = "/api"
|
OPENAPI_URL_PREFIX = "/api"
|
||||||
@@ -54,9 +57,39 @@ class Config:
|
|||||||
LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY", "")
|
LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY", "")
|
||||||
LASTFM_API_URL = os.environ.get("LASTFM_API_URL", "https://ws.audioscrobbler.com/2.0/")
|
LASTFM_API_URL = os.environ.get("LASTFM_API_URL", "https://ws.audioscrobbler.com/2.0/")
|
||||||
LASTFM_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25"))
|
LASTFM_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25"))
|
||||||
|
|
||||||
|
# Album art: MusicBrainz release-group search + Cover Art Archive, both free and keyless.
|
||||||
|
MUSICBRAINZ_API_URL = os.environ.get("MUSICBRAINZ_API_URL", "https://musicbrainz.org/ws/2/")
|
||||||
|
COVERART_API_URL = os.environ.get("COVERART_API_URL", "https://coverartarchive.org/")
|
||||||
|
# MusicBrainz requires a descriptive contact in the User-Agent or it throttles/blocks us.
|
||||||
|
MUSICBRAINZ_CONTACT = os.environ.get("MUSICBRAINZ_CONTACT", "") or UI_BASE_URL
|
||||||
|
MUSICBRAINZ_REQUEST_INTERVAL = float(os.environ.get("MUSICBRAINZ_REQUEST_INTERVAL", "1.0"))
|
||||||
|
MUSICBRAINZ_RETRIES = int(os.environ.get("MUSICBRAINZ_RETRIES", "2"))
|
||||||
|
ART_NOT_FOUND_RETRY_DAYS = int(os.environ.get("ART_NOT_FOUND_RETRY_DAYS", "30"))
|
||||||
|
ART_ERROR_RETRY_SECONDS = int(os.environ.get("ART_ERROR_RETRY_SECONDS", "3600"))
|
||||||
|
# Downloaded art is kept here, named by the album_art row's id. Needs write access
|
||||||
|
# from the worker (which downloads it) and read access from the api (which serves it).
|
||||||
|
ART_STORAGE_DIR = os.environ.get("ART_STORAGE_DIR", "var/album-art")
|
||||||
|
# Largest image a user may upload as their own album art.
|
||||||
|
ART_UPLOAD_MAX_BYTES = int(os.environ.get("ART_UPLOAD_MAX_BYTES", str(5 * 1024 * 1024)))
|
||||||
|
# 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)))
|
IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 1024 * 1024)))
|
||||||
MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests
|
MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests
|
||||||
IMPORT_WORKER_METRICS_PORT = int(os.environ.get("IMPORT_WORKER_METRICS_PORT", "9101"))
|
# IMPORT_WORKER_METRICS_PORT is the pre-0.3 name, still honoured.
|
||||||
|
WORKER_METRICS_PORT = int(
|
||||||
|
os.environ.get("WORKER_METRICS_PORT", os.environ.get("IMPORT_WORKER_METRICS_PORT", "9101"))
|
||||||
|
)
|
||||||
|
|
||||||
# Last.fm behaviour
|
# Last.fm behaviour
|
||||||
AUTH_TOKEN_TTL_SECONDS = 60 * 60
|
AUTH_TOKEN_TTL_SECONDS = 60 * 60
|
||||||
@@ -73,3 +106,11 @@ class TestConfig(Config):
|
|||||||
"postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test",
|
"postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test",
|
||||||
)
|
)
|
||||||
START_METRICS_SERVER = False
|
START_METRICS_SERVER = False
|
||||||
|
LOG_LEVEL = "INFO"
|
||||||
|
LOG_FORMAT = "text"
|
||||||
|
# Tests never inherit optional features or URLs from a developer's .env or
|
||||||
|
# environment; tests that need them turn them on, or override them, explicitly.
|
||||||
|
LASTFM_API_KEY = ""
|
||||||
|
FEDERATION_ENABLED = "0"
|
||||||
|
UI_BASE_URL = "http://localhost:8080"
|
||||||
|
CORS_ORIGINS = ["http://localhost:8080"]
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""Domain events: how the core tells optional modules (such as federation) what happened.
|
||||||
|
|
||||||
|
The core sends these after committing, so receivers only ever see stored data. Modules
|
||||||
|
subscribe with `signal.connect(receiver)`; the core never imports them.
|
||||||
|
|
||||||
|
scrobbles_stored sender=User, scrobbles=[TrackInput, ...], source="scrobble" | "import"
|
||||||
|
Newly stored plays only: duplicates and ignored ones are left out.
|
||||||
|
now_playing_changed sender=User, track=TrackInput | None (None: stopped or cleared)
|
||||||
|
import_finished sender=User, job=ImportJob (completed, failed or cancelled)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from blinker import Namespace, Signal
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_signals = Namespace()
|
||||||
|
|
||||||
|
scrobbles_stored = _signals.signal("scrobbles-stored")
|
||||||
|
now_playing_changed = _signals.signal("now-playing-changed")
|
||||||
|
import_finished = _signals.signal("import-finished")
|
||||||
|
|
||||||
|
|
||||||
|
def send(signal: Signal, sender, **kwargs) -> None:
|
||||||
|
"""Deliver to every receiver. A receiver that raises is logged and skipped: an
|
||||||
|
optional module's bug must never fail a scrobble or an import."""
|
||||||
|
for receiver in signal.receivers_for(sender):
|
||||||
|
try:
|
||||||
|
receiver(sender, **kwargs)
|
||||||
|
except Exception:
|
||||||
|
log.exception("receiver %r of %s failed", receiver, signal.name)
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
# `scrobbler.federation`
|
||||||
|
|
||||||
|
ActivityPub support, kept apart from the rest of the app so it can be changed, replaced
|
||||||
|
or switched off without touching anything else. Design: `docs/design/activitypub.md`.
|
||||||
|
|
||||||
|
## Boundary rules (enforced by `tests/test_federation_boundary.py`)
|
||||||
|
|
||||||
|
1. **Nothing outside this package imports it**, except `create_app()` calling
|
||||||
|
`federation.init_app(app)`. The core reports what happened through the domain events
|
||||||
|
in `scrobbler.events`; this package subscribes to them.
|
||||||
|
2. **`protocol/` is pure**: no Flask, SQLAlchemy, Werkzeug or `scrobbler` imports.
|
||||||
|
Signature schemes, vocabulary and document formats live there.
|
||||||
|
3. **The rest of this package uses only the core's public surface**:
|
||||||
|
- `scrobbler.__version__`
|
||||||
|
- `scrobbler.api.get_api` (to register federation's API blueprint and document its paths)
|
||||||
|
- `scrobbler.events`
|
||||||
|
- `scrobbler.extensions` (`db`)
|
||||||
|
- `scrobbler.worker`
|
||||||
|
- `scrobbler.services.*`
|
||||||
|
- `scrobbler.api.decorators`
|
||||||
|
- `scrobbler.schemas`
|
||||||
|
|
||||||
|
So no core models and no core metrics; federation defines its own.
|
||||||
|
4. **Off means off.** With `FEDERATION_ENABLED` unset, `init_app` registers no routes,
|
||||||
|
no event receivers and no worker tasks.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
| Variable | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `FEDERATION_ENABLED` | `1` to turn federation on (default off) |
|
||||||
|
| `FEDERATION_DOMAIN` | Handle domain, normally the web UI's host: users are `@name@<domain>`. **Permanent once anyone follows.** |
|
||||||
|
| `FEDERATION_BASE_URL` | Public `https://` URL actors live under (`<base>/users/<name>`). Normally the web UI's origin, with the UI's nginx forwarding the ActivityPub paths to the API. |
|
||||||
|
| `FEDERATION_KEY_SECRET` | 32+ characters; encrypts actors' private keys at rest (HKDF → Fernet). **Back it up; never change it.** |
|
||||||
|
| `FEDERATION_SIGNATURE_SCHEMES` | Outgoing signing order; the next scheme is tried only on a 401. Default `draft-cavage,rfc9421` |
|
||||||
|
| `FEDERATION_BLOCKED_DOMAINS` | Comma-separated domains (subdomains included) refused at the inbox |
|
||||||
|
| `FEDERATION_DELIVERY_CONCURRENCY` | Parallel deliveries per worker (1-32, default 4) |
|
||||||
|
| `FEDERATION_INSECURE_TESTING` | **Tests only.** Allows `http://` and private addresses; refused unless the domain is under `.test` |
|
||||||
|
|
||||||
|
The UI container forwards these paths to the API when `API_INTERNAL_URL` is set (see `docker/ui-config.sh`):
|
||||||
|
|
||||||
|
- `/.well-known/webfinger`, `/.well-known/nodeinfo`, `/.well-known/host-meta`
|
||||||
|
- `/nodeinfo/`, `/users/`, `/inbox`, `/actor`
|
||||||
|
|
||||||
|
Every ActivityPub ID is built from `FEDERATION_BASE_URL`, never from the incoming request.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
| Module | Holds |
|
||||||
|
|---|---|
|
||||||
|
| `protocol/` | Pure protocol code: media types, vocabulary, WebFinger, NodeInfo, host-meta, and `signatures/` (draft-cavage and RFC 9421, one module each) |
|
||||||
|
| `net.py` | The SSRF-safe HTTP client, the only way out |
|
||||||
|
| `outbound.py` | Signed GETs (as the instance actor) and POSTs (as a user), with scheme fallback on 401 |
|
||||||
|
| `remote.py` | Remote actors: fetched, validated, cached; key id to actor |
|
||||||
|
| `inbox.py` | Intake (no network) and worker processing: signature check, identity checks, handlers by activity type |
|
||||||
|
| `followers.py` | Follower state: follows, undo, approve, remove, block, sharing off |
|
||||||
|
| `activities.py` | Activities we send (Accept, Reject, Block, Undo), stored and queued per inbox |
|
||||||
|
| `delivery.py` | The delivery worker task: leases, retries with backoff, gone inboxes, gauges |
|
||||||
|
| `models.py` | `federation_*` tables |
|
||||||
|
| `keys.py` | Key pairs, created once and encrypted at rest |
|
||||||
|
| `sharing.py` | Per-user settings, and who is sharing |
|
||||||
|
| `ids.py` | Our ActivityPub ids, all from `FEDERATION_BASE_URL` |
|
||||||
|
| `web.py` | The endpoints other servers call, including a paged outbox and individual posts |
|
||||||
|
| `api.py` and `schemas.py` | `/api/v1/federation/*` for the web UI |
|
||||||
|
| `openapi.py` | OpenAPI descriptions of `web.py`'s endpoints |
|
||||||
|
| `metrics.py` | Federation's own Prometheus metrics |
|
||||||
|
| `cli.py` | `flask federation ...` admin commands |
|
||||||
|
| `actors.py` | Builds a user's actor document body; shared by the live `GET /users/<u>` route and the now-playing `Update(Person)` push, so both render the same shape |
|
||||||
|
| `publishing/` | Posts: shared publish/delete machinery, and one module per kind (see below) |
|
||||||
|
|
||||||
|
## Publishing
|
||||||
|
|
||||||
|
`publishing/base.py` is the only place that knows how to actually post: build the
|
||||||
|
`Note`/`Create`, store it, address it from the user's current visibility, and fan it out
|
||||||
|
to accepted followers' inboxes. It's idempotent (one row per `(user, kind:key)`, via
|
||||||
|
`federation_posts`' unique constraint) and used for both publishing and deleting.
|
||||||
|
|
||||||
|
Each *kind* of post is its own small module that only decides **when** to post and what
|
||||||
|
the text says, then calls into `base.py`:
|
||||||
|
|
||||||
|
- `publishing/weekly.py`: once a week (`check_and_post`/`check_all`, the
|
||||||
|
`federation.weekly` worker task), for the Monday–Sunday week whose posting gate has
|
||||||
|
passed. `post_now()` instead posts the week still in progress immediately, ignoring the
|
||||||
|
gate — used by `flask federation post-weekly --user <name> --now` and `preview()` (a
|
||||||
|
read-only variant for the Sharing page's live preview, never stored).
|
||||||
|
- `publishing/milestones.py`: scrobble-count, artist-plays and top-10-entry thresholds,
|
||||||
|
each posted once. A live scrobble queues a `FederationPendingCheck` row (collapsing
|
||||||
|
repeats), drained by the `federation.milestones` worker task. `set_baseline()` marks
|
||||||
|
every threshold already passed without posting, called when a user turns sharing on
|
||||||
|
and after an import finishes, so old history never produces a burst of "milestone"
|
||||||
|
posts.
|
||||||
|
- `publishing/now_playing.py`: not quite the same shape as the other two, since it
|
||||||
|
covers two things at once - a throttled `Update(Person)` push for the profile field
|
||||||
|
(`actors.py` owns the live version shown on a plain `GET`) and, opt-in, a post per
|
||||||
|
track played 30+ seconds. Both are driven by one periodic scan
|
||||||
|
(`federation.now_playing`, every 30 seconds) rather than an event receiver: the
|
||||||
|
throttle windows (5 and 30 minutes) are far longer than the poll interval, and there's
|
||||||
|
no history to react to retroactively the way milestones does.
|
||||||
|
|
||||||
|
Adding a fourth kind means adding another module here with the same shape as
|
||||||
|
`weekly.py`/`milestones.py` - decide when, build the text, call `publishing.publish()`
|
||||||
|
- not touching `base.py`.
|
||||||
|
|
||||||
|
## Worker tasks
|
||||||
|
|
||||||
|
`federation.inbox` (process received activities), `federation.deliver` (send queued
|
||||||
|
ones), `federation.inbox.maintenance` (re-queue stalled, prune after 30 days),
|
||||||
|
`federation.gauges` (queue and follower gauges), `federation.milestones` (drain pending
|
||||||
|
milestone checks), `federation.weekly` (check every sharing user for a due weekly
|
||||||
|
summary, every 15 minutes) and `federation.now_playing` (push profile updates and posts
|
||||||
|
for users with it on, every 30 seconds). All are registered only when federation is on.
|
||||||
|
|
||||||
|
## Interop
|
||||||
|
|
||||||
|
`scripts/interop/run.sh` runs Scrobbled against a real GoToSocial server on a private
|
||||||
|
`.test` network. `scripts/interop/gotosocial_interop.py` checks the whole follow life
|
||||||
|
cycle, then `run.sh` seeds a scrobble and a now-playing track, runs
|
||||||
|
`flask federation post-weekly --now` directly in the `api` container, and runs the
|
||||||
|
driver a second time (`--check-posts`) to confirm: the post reaches GoToSocial's home
|
||||||
|
timeline with the right content and `private` (followers-only) visibility and
|
||||||
|
disappears from it once deleted; and, with now playing turned on, GoToSocial's own
|
||||||
|
stored copy of the account (not a fresh `resolve()` fetch) picks up a "Now playing"
|
||||||
|
field from the periodic `Update(Person)` push. CI runs the whole thing on every push.
|
||||||
|
GoToSocial 0.22.1 ignores a Reject of an already-accepted follow (a TODO in its code,
|
||||||
|
fixed on its main branch), so that one check on its side is skipped until a release
|
||||||
|
includes the fix.
|
||||||
|
|
||||||
|
## Migrations
|
||||||
|
|
||||||
|
Federation's tables (all prefixed `federation_`) live in their own Alembic branch,
|
||||||
|
labelled `federation`, so they can be changed or dropped without touching core
|
||||||
|
migrations:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
uv run flask --app scrobbler db migrate --head federation@head -m "…" # federation tables
|
||||||
|
uv run flask --app scrobbler db migrate --head core@head -m "…" # everything else
|
||||||
|
uv run flask --app scrobbler db upgrade heads # apply both branches
|
||||||
|
```
|
||||||
|
|
||||||
|
When generating a federation migration, check it only touches `federation_*` tables.
|
||||||
|
Autogenerate compares all models, so core changes would otherwise leak into it.
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""ActivityPub federation: optional, self-contained, replaceable.
|
||||||
|
|
||||||
|
The rest of Scrobbled only calls `init_app(app)` (from `create_app`) and sends domain
|
||||||
|
events (`scrobbler.events`). Everything else about federation lives in this package;
|
||||||
|
see README.md here and docs/design/activitypub.md.
|
||||||
|
|
||||||
|
With FEDERATION_ENABLED off (the default) `init_app` registers nothing: no routes, no
|
||||||
|
event receivers, no worker tasks.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from scrobbler.federation.config import FederationConfig
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def init_app(app: Flask) -> None:
|
||||||
|
# Tables are always part of the schema (migrations run regardless), so the models
|
||||||
|
# are always registered; "off" means no routes, receivers or tasks.
|
||||||
|
from scrobbler.federation import models # noqa: F401
|
||||||
|
|
||||||
|
config = FederationConfig.from_mapping(app.config)
|
||||||
|
app.extensions["federation"] = config
|
||||||
|
if not config.enabled:
|
||||||
|
return
|
||||||
|
log.info("federation enabled: handles @user@%s, actors at %s", config.domain, config.base_url)
|
||||||
|
|
||||||
|
from scrobbler.api import get_api
|
||||||
|
from scrobbler.federation import api, openapi, web
|
||||||
|
from scrobbler.federation.cli import federation_cli
|
||||||
|
|
||||||
|
app.register_blueprint(web.bp)
|
||||||
|
core_api = get_api(app)
|
||||||
|
core_api.register_blueprint(api.blp, url_prefix="/api/v1/federation")
|
||||||
|
openapi.register(app, core_api)
|
||||||
|
app.cli.add_command(federation_cli)
|
||||||
|
|
||||||
|
from scrobbler import events, worker
|
||||||
|
from scrobbler.federation import delivery, inbox
|
||||||
|
from scrobbler.federation.publishing import milestones, now_playing, weekly
|
||||||
|
|
||||||
|
worker.register_task(app, "federation.inbox", inbox.work_once)
|
||||||
|
worker.register_task(app, "federation.deliver", delivery.work_once)
|
||||||
|
worker.register_task(app, "federation.milestones", milestones.work_once)
|
||||||
|
worker.register_periodic(app, "federation.inbox.maintenance", 300, inbox.maintenance)
|
||||||
|
worker.register_periodic(app, "federation.gauges", 30, delivery.maintenance)
|
||||||
|
worker.register_periodic(app, "federation.weekly", 900, weekly.check_all)
|
||||||
|
worker.register_periodic(app, "federation.now_playing", 30, now_playing.check_all)
|
||||||
|
|
||||||
|
# blinker signals are process-wide, not per-app: once any app in a process enables
|
||||||
|
# federation these stay connected for every app in it, including one built with
|
||||||
|
# federation off (see test_federation_boundary.py for why "off" is instead enforced
|
||||||
|
# by each receiver checking its own app's config). weak=False because the receivers
|
||||||
|
# are plain module functions meant to live as long as the process does.
|
||||||
|
events.scrobbles_stored.connect(milestones.on_scrobbles_stored, weak=False)
|
||||||
|
events.import_finished.connect(milestones.on_import_finished, weak=False)
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"""Activities we send: stored (so they have a stable id) and queued for delivery."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from scrobbler.extensions import db
|
||||||
|
from scrobbler.federation import ids
|
||||||
|
from scrobbler.federation.models import (
|
||||||
|
FederationActivity,
|
||||||
|
FederationDelivery,
|
||||||
|
FederationFollower,
|
||||||
|
FederationRemoteActor,
|
||||||
|
)
|
||||||
|
from scrobbler.federation.protocol import vocab
|
||||||
|
|
||||||
|
|
||||||
|
def store(user_id: int, document_for, public: bool = False) -> FederationActivity:
|
||||||
|
"""Create an activity. `document_for(activity_url)` builds its JSON.
|
||||||
|
|
||||||
|
Public: used both for our own narrow activity types below (Accept, Reject, Block,
|
||||||
|
Undo) and, from publishing/base.py, for Create/Delete of posts."""
|
||||||
|
activity_uuid = str(uuid.uuid4())
|
||||||
|
document = document_for(ids.activity_url(activity_uuid))
|
||||||
|
activity = FederationActivity(
|
||||||
|
id=activity_uuid,
|
||||||
|
user_id=user_id,
|
||||||
|
activity_type=document["type"],
|
||||||
|
document=document,
|
||||||
|
public=public,
|
||||||
|
)
|
||||||
|
db.session.add(activity)
|
||||||
|
return activity
|
||||||
|
|
||||||
|
|
||||||
|
def queue(activity: FederationActivity, inboxes: list[str]) -> list[FederationDelivery]:
|
||||||
|
deliveries = [
|
||||||
|
FederationDelivery(activity_id=activity.id, inbox=inbox)
|
||||||
|
for inbox in dict.fromkeys(inboxes) # one per distinct inbox
|
||||||
|
]
|
||||||
|
db.session.add_all(deliveries)
|
||||||
|
return deliveries
|
||||||
|
|
||||||
|
|
||||||
|
def accept_follow(username: str, follower: FederationFollower) -> FederationActivity:
|
||||||
|
activity = store(
|
||||||
|
follower.user_id,
|
||||||
|
lambda url: vocab.accept(url, ids.actor_id(username), follower.follow_activity),
|
||||||
|
)
|
||||||
|
queue(activity, [follower.actor.inbox]) # replies go to their own inbox
|
||||||
|
return activity
|
||||||
|
|
||||||
|
|
||||||
|
def reject_follow(username: str, follower: FederationFollower) -> FederationActivity:
|
||||||
|
activity = store(
|
||||||
|
follower.user_id,
|
||||||
|
lambda url: vocab.reject(url, ids.actor_id(username), follower.follow_activity),
|
||||||
|
)
|
||||||
|
queue(activity, [follower.actor.inbox])
|
||||||
|
return activity
|
||||||
|
|
||||||
|
|
||||||
|
def reject_follow_activity(
|
||||||
|
user_id: int, username: str, follow: dict, actor: FederationRemoteActor
|
||||||
|
) -> FederationActivity:
|
||||||
|
"""Reject a Follow that never became a follower (e.g. from a blocked account)."""
|
||||||
|
activity = store(user_id, lambda url: vocab.reject(url, ids.actor_id(username), follow))
|
||||||
|
queue(activity, [actor.inbox])
|
||||||
|
return activity
|
||||||
|
|
||||||
|
|
||||||
|
def block(user_id: int, username: str, actor: FederationRemoteActor) -> FederationActivity:
|
||||||
|
activity = store(user_id, lambda url: vocab.block(url, ids.actor_id(username), actor.uri))
|
||||||
|
queue(activity, [actor.inbox])
|
||||||
|
return activity
|
||||||
|
|
||||||
|
|
||||||
|
def undo_block(
|
||||||
|
user_id: int, username: str, actor: FederationRemoteActor
|
||||||
|
) -> FederationActivity | None:
|
||||||
|
"""Tell them they're unblocked: Undo our most recent Block of them (if we sent one)."""
|
||||||
|
block_activity = db.session.scalars(
|
||||||
|
db.select(FederationActivity)
|
||||||
|
.filter_by(user_id=user_id, activity_type="Block")
|
||||||
|
.filter(FederationActivity.document["object"].as_string() == actor.uri)
|
||||||
|
.order_by(FederationActivity.created_at.desc())
|
||||||
|
).first()
|
||||||
|
if block_activity is None:
|
||||||
|
return None
|
||||||
|
activity = store(
|
||||||
|
user_id, lambda url: vocab.undo(url, ids.actor_id(username), block_activity.document)
|
||||||
|
)
|
||||||
|
queue(activity, [actor.inbox])
|
||||||
|
return activity
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""Building a user's actor document: shared by the live `GET /users/<u>` route and the
|
||||||
|
now-playing `Update(Person)` push, so both render the same shape.
|
||||||
|
|
||||||
|
The now-playing field is always computed live from the core `now_playing` table, never
|
||||||
|
from federation's own throttled push state (`federation_now_playing`) - a fetch should
|
||||||
|
never lie, even if the last proactive Update was a few minutes ago.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from scrobbler.federation import keys
|
||||||
|
from scrobbler.federation.protocol import vocab
|
||||||
|
from scrobbler.services.scrobbles import get_now_playing
|
||||||
|
|
||||||
|
NOW_PLAYING_FIELD = "Now playing"
|
||||||
|
|
||||||
|
|
||||||
|
def now_playing_text(user) -> str | None:
|
||||||
|
""" "Track by Artist", or None if nothing unexpired is playing (`get_now_playing`
|
||||||
|
already excludes expired tracks). Doesn't look at now_playing_mode: core's
|
||||||
|
now_playing table is populated for every user regardless of federation settings, so
|
||||||
|
a caller must gate this itself (now_playing_field does) rather than leak listening
|
||||||
|
activity for users who never turned now playing on at all."""
|
||||||
|
playing = get_now_playing(user)
|
||||||
|
if playing is None:
|
||||||
|
return None
|
||||||
|
return f"{playing.track} by {playing.artist}"
|
||||||
|
|
||||||
|
|
||||||
|
def now_playing_field(user, settings) -> list[tuple[str, str]]:
|
||||||
|
"""The actor's now-playing `PropertyValue` field: empty unless now_playing_mode is
|
||||||
|
on and something's actually playing."""
|
||||||
|
if settings.now_playing_mode == "off":
|
||||||
|
return []
|
||||||
|
text = now_playing_text(user)
|
||||||
|
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,
|
||||||
|
username=user.username,
|
||||||
|
name=settings.display_name or user.username,
|
||||||
|
summary=settings.bio,
|
||||||
|
public_key_pem=keys.key_for(user.id).public_key_pem,
|
||||||
|
manually_approves_followers=settings.manually_approves_followers,
|
||||||
|
discoverable=settings.discoverable,
|
||||||
|
indexable=settings.indexable,
|
||||||
|
published=settings.created_at.isoformat().replace("+00:00", "Z"),
|
||||||
|
fields=now_playing_field(user, settings),
|
||||||
|
icon=avatar_icon(urls, user, settings),
|
||||||
|
)
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
"""/api/v1/federation: sharing settings for the web UI, and public profiles."""
|
||||||
|
|
||||||
|
from flask import current_app, g
|
||||||
|
from flask_smorest import Blueprint, abort
|
||||||
|
|
||||||
|
from scrobbler.api.decorators import authenticated
|
||||||
|
from scrobbler.extensions import db
|
||||||
|
from scrobbler.federation import activities, actors, ids, publishing, sharing
|
||||||
|
from scrobbler.federation import followers as follower_state
|
||||||
|
from scrobbler.federation import metrics as fed_metrics
|
||||||
|
from scrobbler.federation.models import FederationBlock, FederationFollower, FederationPost
|
||||||
|
from scrobbler.federation.publishing import weekly
|
||||||
|
from scrobbler.federation.schemas import (
|
||||||
|
BlockSchema,
|
||||||
|
FollowerListArgsSchema,
|
||||||
|
FollowerSchema,
|
||||||
|
PostSchema,
|
||||||
|
PublicPostSchema,
|
||||||
|
PublicProfileSchema,
|
||||||
|
SharingSettingsSchema,
|
||||||
|
SharingSettingsUpdateSchema,
|
||||||
|
WeeklyPreviewSchema,
|
||||||
|
)
|
||||||
|
from scrobbler.schemas import ErrorSchema
|
||||||
|
|
||||||
|
blp = Blueprint(
|
||||||
|
"Federation",
|
||||||
|
__name__,
|
||||||
|
description=(
|
||||||
|
"Sharing listening on the fediverse (ActivityPub). These endpoints only exist when "
|
||||||
|
"the server has federation enabled; a 404 means it doesn't."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _identity(username: str) -> dict:
|
||||||
|
config = current_app.extensions["federation"]
|
||||||
|
return {
|
||||||
|
"handle": f"@{username}@{config.domain}",
|
||||||
|
"actor_url": f"{config.base_url}/users/{username}",
|
||||||
|
"profile_url": f"{current_app.config['UI_BASE_URL']}/profile.html?u={username}",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _settings_body(user, settings) -> dict:
|
||||||
|
counts = follower_state.counts(user.id)
|
||||||
|
return {
|
||||||
|
**{field: getattr(settings, field) for field in sharing.EDITABLE},
|
||||||
|
**_identity(user.username),
|
||||||
|
"followers": counts["accepted"],
|
||||||
|
"pending_followers": counts["pending"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/settings", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.response(200, SharingSettingsSchema)
|
||||||
|
def get_settings():
|
||||||
|
"""Your sharing settings
|
||||||
|
|
||||||
|
Sharing is off and posts are followers-only until you change them.
|
||||||
|
"""
|
||||||
|
return _settings_body(g.user, sharing.settings_for(g.user.id))
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/settings", methods=["PATCH"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(SharingSettingsUpdateSchema)
|
||||||
|
@blp.response(200, SharingSettingsSchema)
|
||||||
|
@blp.alt_response(422, schema=ErrorSchema, description="Invalid settings")
|
||||||
|
def update_settings(changes):
|
||||||
|
"""Change your sharing settings
|
||||||
|
|
||||||
|
Turning sharing on makes you findable as your handle. Your handle can't change once
|
||||||
|
people follow you. Visibility changes apply to new posts only. Turning sharing off
|
||||||
|
deletes your posts and removes all your followers (each is told).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
settings, toggled = sharing.update(g.user.id, changes)
|
||||||
|
except ValueError as err:
|
||||||
|
abort(422, code="invalid_settings", message=str(err))
|
||||||
|
if toggled is not None:
|
||||||
|
fed_metrics.sharing_changes_total.labels(change="enabled" if toggled else "disabled").inc()
|
||||||
|
if toggled is False:
|
||||||
|
# Delete every live post first: reject_all removes the followers that
|
||||||
|
# accepted_inboxes() needs to know where to send the Deletes.
|
||||||
|
publishing.delete_all_for(g.user.id, g.user.username)
|
||||||
|
follower_state.reject_all(g.user.id, g.user.username)
|
||||||
|
db.session.commit()
|
||||||
|
return _settings_body(g.user, settings)
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/preview/weekly", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.response(200, WeeklyPreviewSchema)
|
||||||
|
def preview_weekly():
|
||||||
|
"""Preview this week's summary
|
||||||
|
|
||||||
|
What it would say right now, for the week still in progress. Never posted or stored.
|
||||||
|
"""
|
||||||
|
result = weekly.preview(g.user.id)
|
||||||
|
if result is None: # pragma: no cover - g.user is always a real, current account
|
||||||
|
abort(404, code="not_found", message="No such user")
|
||||||
|
text, html = result
|
||||||
|
return {"text": text, "html": html}
|
||||||
|
|
||||||
|
|
||||||
|
def _post_body(post: FederationPost) -> dict:
|
||||||
|
return {
|
||||||
|
"id": post.id,
|
||||||
|
"kind": post.kind,
|
||||||
|
"text": post.content_text,
|
||||||
|
"visibility": post.visibility,
|
||||||
|
"created_at": post.created_at,
|
||||||
|
"deleted_at": post.deleted_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/posts", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.response(200, PostSchema(many=True))
|
||||||
|
def list_posts():
|
||||||
|
"""Your posts
|
||||||
|
|
||||||
|
Newest first, including deleted ones (their text stays visible to you; deleted_at
|
||||||
|
shows when).
|
||||||
|
"""
|
||||||
|
posts = db.session.scalars(
|
||||||
|
db.select(FederationPost)
|
||||||
|
.filter_by(user_id=g.user.id)
|
||||||
|
.order_by(FederationPost.created_at.desc())
|
||||||
|
).all()
|
||||||
|
return [_post_body(p) for p in posts]
|
||||||
|
|
||||||
|
|
||||||
|
def _own_post(post_id: int) -> FederationPost:
|
||||||
|
post = db.session.get(FederationPost, post_id)
|
||||||
|
if post is None or post.user_id != g.user.id:
|
||||||
|
abort(404, code="not_found", message="No such post")
|
||||||
|
return post
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/posts/<int:post_id>", methods=["DELETE"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.response(204)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="No such post")
|
||||||
|
@blp.alt_response(409, schema=ErrorSchema, description="Already deleted")
|
||||||
|
def delete_post(post_id):
|
||||||
|
"""Delete a post
|
||||||
|
|
||||||
|
Sends a Delete to whoever received it.
|
||||||
|
"""
|
||||||
|
post = _own_post(post_id)
|
||||||
|
activity = publishing.delete_post(g.user.id, g.user.username, post)
|
||||||
|
if activity is None:
|
||||||
|
abort(409, code="already_deleted", message="That post is already deleted.")
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/profiles/<string:username>", methods=["GET"])
|
||||||
|
@blp.response(200, PublicProfileSchema)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="No one sharing with that name")
|
||||||
|
def public_profile(username):
|
||||||
|
"""A public fediverse profile
|
||||||
|
|
||||||
|
For the web UI's profile page. Only users who share are visible.
|
||||||
|
"""
|
||||||
|
found = sharing.shared_user(username)
|
||||||
|
if found is None:
|
||||||
|
fed_metrics.lookups_total.labels(kind="profile", result="not_found").inc()
|
||||||
|
abort(404, code="not_found", message="No one here shares their listening under that name.")
|
||||||
|
fed_metrics.lookups_total.labels(kind="profile", result="found").inc()
|
||||||
|
user, settings = found
|
||||||
|
return {
|
||||||
|
"username": user.username,
|
||||||
|
"display_name": settings.display_name or user.username,
|
||||||
|
"bio": settings.bio,
|
||||||
|
"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")
|
||||||
|
def public_post(username, post_uuid):
|
||||||
|
"""A public or unlisted post
|
||||||
|
|
||||||
|
For the web UI's post page (the browser landing spot for a Note's `url`, since it
|
||||||
|
can't itself speak ActivityPub).
|
||||||
|
"""
|
||||||
|
found = sharing.shared_user(username)
|
||||||
|
if found is not None:
|
||||||
|
user, settings = found
|
||||||
|
post = publishing.find_by_note_id(user.id, ids.note_url(username, post_uuid))
|
||||||
|
else:
|
||||||
|
post = None
|
||||||
|
if (
|
||||||
|
post is None
|
||||||
|
or post.deleted_at is not None
|
||||||
|
or post.visibility not in publishing.LISTED_VISIBILITIES
|
||||||
|
):
|
||||||
|
fed_metrics.lookups_total.labels(kind="post", result="not_found").inc()
|
||||||
|
abort(404, code="not_found", message="No such post.")
|
||||||
|
fed_metrics.lookups_total.labels(kind="post", result="found").inc()
|
||||||
|
return {
|
||||||
|
"text": post.content_text,
|
||||||
|
"html": post.content_html,
|
||||||
|
"created_at": post.created_at,
|
||||||
|
"display_name": settings.display_name or user.username,
|
||||||
|
**{k: v for k, v in _identity(user.username).items() if k != "actor_url"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --- Followers ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _follower_body(follower: FederationFollower) -> dict:
|
||||||
|
actor = follower.actor
|
||||||
|
return {
|
||||||
|
"id": follower.id,
|
||||||
|
"state": follower.state,
|
||||||
|
"handle": actor.handle,
|
||||||
|
"display_name": actor.display_name,
|
||||||
|
"actor_url": actor.uri,
|
||||||
|
"server": actor.host,
|
||||||
|
"since": follower.created_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _own_follower(follower_id: int) -> FederationFollower:
|
||||||
|
follower = db.session.get(FederationFollower, follower_id)
|
||||||
|
if follower is None or follower.user_id != g.user.id:
|
||||||
|
abort(404, code="not_found", message="No such follower")
|
||||||
|
return follower
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/followers", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.arguments(FollowerListArgsSchema, location="query")
|
||||||
|
@blp.response(200, FollowerSchema(many=True))
|
||||||
|
def list_followers(args):
|
||||||
|
"""Your followers and follow requests
|
||||||
|
|
||||||
|
Newest first. Filter with `state=pending` (requests) or `state=accepted`.
|
||||||
|
"""
|
||||||
|
query = db.select(FederationFollower).filter_by(user_id=g.user.id)
|
||||||
|
if args["state"]:
|
||||||
|
query = query.filter_by(state=args["state"])
|
||||||
|
followers = db.session.scalars(query.order_by(FederationFollower.created_at.desc())).all()
|
||||||
|
return [_follower_body(f) for f in followers]
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/followers/<int:follower_id>/approve", methods=["POST"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.response(200, FollowerSchema)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="No such follower")
|
||||||
|
@blp.alt_response(409, schema=ErrorSchema, description="Not a pending request")
|
||||||
|
def approve_follower(follower_id):
|
||||||
|
"""Approve a follow request"""
|
||||||
|
follower = _own_follower(follower_id)
|
||||||
|
if follower.state != "pending":
|
||||||
|
abort(409, code="not_pending", message="That follower isn't waiting for approval.")
|
||||||
|
follower_state.approve(g.user.username, follower)
|
||||||
|
db.session.commit()
|
||||||
|
return _follower_body(follower)
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/followers/<int:follower_id>/decline", methods=["POST"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.response(204)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="No such follower")
|
||||||
|
def decline_follower(follower_id):
|
||||||
|
"""Decline a follow request"""
|
||||||
|
follower_state.remove(g.user.username, _own_follower(follower_id))
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/followers/<int:follower_id>/remove", methods=["POST"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.response(204)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="No such follower")
|
||||||
|
def remove_follower(follower_id):
|
||||||
|
"""Remove a follower
|
||||||
|
|
||||||
|
They stop receiving your posts. They can follow you again; block them to prevent it.
|
||||||
|
"""
|
||||||
|
follower_state.remove(g.user.username, _own_follower(follower_id))
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/followers/<int:follower_id>/block", methods=["POST"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.response(204)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="No such follower")
|
||||||
|
def block_follower(follower_id):
|
||||||
|
"""Block a follower
|
||||||
|
|
||||||
|
Removes them and refuses their future follows.
|
||||||
|
"""
|
||||||
|
follower_state.block(g.user.username, _own_follower(follower_id))
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/blocks", methods=["GET"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.response(200, BlockSchema(many=True))
|
||||||
|
def list_blocks():
|
||||||
|
"""Accounts you've blocked"""
|
||||||
|
blocks = db.session.scalars(
|
||||||
|
db.select(FederationBlock)
|
||||||
|
.filter_by(user_id=g.user.id)
|
||||||
|
.order_by(FederationBlock.created_at.desc())
|
||||||
|
).all()
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"id": b.id,
|
||||||
|
"handle": b.actor.handle,
|
||||||
|
"display_name": b.actor.display_name,
|
||||||
|
"actor_url": b.actor.uri,
|
||||||
|
"since": b.created_at,
|
||||||
|
}
|
||||||
|
for b in blocks
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@blp.route("/blocks/<int:block_id>", methods=["DELETE"])
|
||||||
|
@authenticated(blp)
|
||||||
|
@blp.response(204)
|
||||||
|
@blp.alt_response(404, schema=ErrorSchema, description="No such block")
|
||||||
|
def unblock(block_id):
|
||||||
|
"""Unblock an account
|
||||||
|
|
||||||
|
Their server is told (an Undo of the Block). They can follow you again; they aren't
|
||||||
|
re-added.
|
||||||
|
"""
|
||||||
|
block = db.session.get(FederationBlock, block_id)
|
||||||
|
if block is None or block.user_id != g.user.id:
|
||||||
|
abort(404, code="not_found", message="No such block")
|
||||||
|
activities.undo_block(g.user.id, g.user.username, block.actor) # tell their server
|
||||||
|
db.session.delete(block)
|
||||||
|
db.session.commit()
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Fediverse admin commands (`flask federation ...`)."""
|
||||||
|
|
||||||
|
import click
|
||||||
|
from flask.cli import AppGroup, with_appcontext
|
||||||
|
|
||||||
|
federation_cli = AppGroup("federation", help="Fediverse admin commands.")
|
||||||
|
|
||||||
|
|
||||||
|
@federation_cli.command("post-weekly")
|
||||||
|
@click.option("--user", "username", required=True, help="Username to post for.")
|
||||||
|
@click.option(
|
||||||
|
"--now",
|
||||||
|
"immediately",
|
||||||
|
is_flag=True,
|
||||||
|
required=True,
|
||||||
|
help="Post about the week still in progress right now, ignoring the Monday-09:00 "
|
||||||
|
"gate (the only mode this command supports, for operators and testing).",
|
||||||
|
)
|
||||||
|
@with_appcontext
|
||||||
|
def post_weekly(username: str, immediately: bool) -> None:
|
||||||
|
"""Post one user's weekly summary immediately."""
|
||||||
|
from scrobbler.extensions import db
|
||||||
|
from scrobbler.federation.publishing import weekly
|
||||||
|
from scrobbler.services import accounts
|
||||||
|
|
||||||
|
user = accounts.find_user(username)
|
||||||
|
if user is None:
|
||||||
|
raise click.ClickException(f"No such user: {username}")
|
||||||
|
result = weekly.post_now(user.id)
|
||||||
|
db.session.commit()
|
||||||
|
if result == "posted":
|
||||||
|
click.echo(f"Posted a weekly summary for {username}.")
|
||||||
|
elif result == "already_posted":
|
||||||
|
click.echo(f"{username} already has a post for this week.")
|
||||||
|
elif result == "skipped_empty":
|
||||||
|
click.echo(f"{username} hasn't scrobbled anything this week.")
|
||||||
|
else:
|
||||||
|
raise click.ClickException(f"{username} isn't sharing weekly summaries.")
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import os
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
|
||||||
|
class FederationConfigError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _flag(value) -> bool:
|
||||||
|
return str(value).strip().lower() in {"1", "true", "yes", "on"}
|
||||||
|
|
||||||
|
|
||||||
|
def _csv(value: str) -> tuple[str, ...]:
|
||||||
|
return tuple(part.strip().lower() for part in value.split(",") if part.strip())
|
||||||
|
|
||||||
|
|
||||||
|
KNOWN_SCHEMES = ("draft-cavage", "rfc9421")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class FederationConfig:
|
||||||
|
enabled: bool = False
|
||||||
|
domain: str = "" # the handle's domain: @user@<domain>
|
||||||
|
base_url: str = "" # where actors live: <base_url>/users/<username>
|
||||||
|
key_secret: str = "" # encrypts actors' private keys at rest
|
||||||
|
signature_schemes: tuple[str, ...] = KNOWN_SCHEMES # outgoing order; next on a 401
|
||||||
|
blocked_domains: tuple[str, ...] = field(default=())
|
||||||
|
delivery_concurrency: int = 4
|
||||||
|
# TESTS ONLY: allow http:// and private addresses so CI can federate on a private
|
||||||
|
# network. Refused unless the domain is under the reserved .test TLD.
|
||||||
|
insecure_testing: bool = False
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_mapping(cls, config: Mapping) -> "FederationConfig":
|
||||||
|
"""Read FEDERATION_* from the Flask config, falling back to the environment."""
|
||||||
|
|
||||||
|
def get(key: str, default: str = "") -> str:
|
||||||
|
value = config.get(key)
|
||||||
|
return str(value if value is not None else os.environ.get(key, default))
|
||||||
|
|
||||||
|
try:
|
||||||
|
concurrency = int(get("FEDERATION_DELIVERY_CONCURRENCY", "4"))
|
||||||
|
except ValueError:
|
||||||
|
raise FederationConfigError(
|
||||||
|
"FEDERATION_DELIVERY_CONCURRENCY must be a number"
|
||||||
|
) from None
|
||||||
|
result = cls(
|
||||||
|
enabled=_flag(get("FEDERATION_ENABLED", "0")),
|
||||||
|
domain=get("FEDERATION_DOMAIN").strip().lower(),
|
||||||
|
base_url=get("FEDERATION_BASE_URL").strip().rstrip("/"),
|
||||||
|
key_secret=get("FEDERATION_KEY_SECRET"),
|
||||||
|
signature_schemes=_csv(get("FEDERATION_SIGNATURE_SCHEMES", ",".join(KNOWN_SCHEMES))),
|
||||||
|
blocked_domains=_csv(get("FEDERATION_BLOCKED_DOMAINS")),
|
||||||
|
delivery_concurrency=concurrency,
|
||||||
|
insecure_testing=_flag(get("FEDERATION_INSECURE_TESTING", "0")),
|
||||||
|
)
|
||||||
|
result.validate()
|
||||||
|
return result
|
||||||
|
|
||||||
|
def validate(self) -> None:
|
||||||
|
if not self.enabled:
|
||||||
|
return
|
||||||
|
if not self.domain or "/" in self.domain or ":" in self.domain:
|
||||||
|
raise FederationConfigError(
|
||||||
|
"FEDERATION_DOMAIN must be a bare host name (e.g. scrobble.example) when "
|
||||||
|
"FEDERATION_ENABLED is on. It becomes part of every handle and can't change "
|
||||||
|
"once people follow."
|
||||||
|
)
|
||||||
|
if self.insecure_testing and not self.domain.endswith(".test"):
|
||||||
|
raise FederationConfigError(
|
||||||
|
"FEDERATION_INSECURE_TESTING is for automated tests only, and only allowed "
|
||||||
|
"with a FEDERATION_DOMAIN under .test."
|
||||||
|
)
|
||||||
|
url = urlsplit(self.base_url)
|
||||||
|
schemes = ("https", "http") if self.insecure_testing else ("https",)
|
||||||
|
if url.scheme not in schemes or not url.netloc or url.query or url.fragment:
|
||||||
|
raise FederationConfigError(
|
||||||
|
"FEDERATION_BASE_URL must be the public https:// URL the API is served at "
|
||||||
|
"(e.g. https://scrobble.example) when FEDERATION_ENABLED is on."
|
||||||
|
)
|
||||||
|
if len(self.key_secret) < 32:
|
||||||
|
raise FederationConfigError(
|
||||||
|
"FEDERATION_KEY_SECRET must be at least 32 characters when FEDERATION_ENABLED "
|
||||||
|
"is on. It encrypts actors' private keys; keep it safe and never change it "
|
||||||
|
"(e.g. python -c 'import secrets; print(secrets.token_urlsafe(48))')."
|
||||||
|
)
|
||||||
|
unknown = set(self.signature_schemes) - set(KNOWN_SCHEMES)
|
||||||
|
if not self.signature_schemes or unknown:
|
||||||
|
raise FederationConfigError(
|
||||||
|
f"FEDERATION_SIGNATURE_SCHEMES must list some of {', '.join(KNOWN_SCHEMES)}"
|
||||||
|
)
|
||||||
|
if not 1 <= self.delivery_concurrency <= 32:
|
||||||
|
raise FederationConfigError("FEDERATION_DELIVERY_CONCURRENCY must be 1-32")
|
||||||
|
|
||||||
|
def is_blocked(self, host: str) -> bool:
|
||||||
|
host = host.lower().rstrip(".")
|
||||||
|
return any(host == d or host.endswith("." + d) for d in self.blocked_domains)
|
||||||
|
|
||||||
|
def __repr__(self) -> str: # never print the secret
|
||||||
|
return (
|
||||||
|
f"FederationConfig(enabled={self.enabled}, domain={self.domain!r}, "
|
||||||
|
f"base_url={self.base_url!r}, key_secret=***, "
|
||||||
|
f"insecure_testing={self.insecure_testing})"
|
||||||
|
)
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
"""Sending queued activities (the `federation.deliver` worker task).
|
||||||
|
|
||||||
|
Each delivery is one activity to one inbox, signed as the user. Failures are retried
|
||||||
|
with backoff (1m, 5m, 30m, 2h, 6h, then every 12h) and abandoned after 2 days. A claimed
|
||||||
|
delivery is leased (its next attempt pushed forward), so one a crashed worker was
|
||||||
|
sending simply becomes due again.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from flask import current_app
|
||||||
|
from sqlalchemy import func
|
||||||
|
from sqlalchemy.orm import lazyload
|
||||||
|
|
||||||
|
from scrobbler.extensions import db
|
||||||
|
from scrobbler.federation import ids, outbound
|
||||||
|
from scrobbler.federation import metrics as fed_metrics
|
||||||
|
from scrobbler.federation.models import (
|
||||||
|
FederationDelivery,
|
||||||
|
FederationFollower,
|
||||||
|
FederationInboxItem,
|
||||||
|
FederationRemoteActor,
|
||||||
|
)
|
||||||
|
from scrobbler.federation.net import FetchError
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
RETRY_DELAYS = [
|
||||||
|
timedelta(minutes=1),
|
||||||
|
timedelta(minutes=5),
|
||||||
|
timedelta(minutes=30),
|
||||||
|
timedelta(hours=2),
|
||||||
|
timedelta(hours=6),
|
||||||
|
]
|
||||||
|
LATER_DELAY = timedelta(hours=12)
|
||||||
|
GIVE_UP_AFTER = timedelta(days=2)
|
||||||
|
LEASE = timedelta(minutes=10)
|
||||||
|
BATCH = 50
|
||||||
|
RETRYABLE_4XX = {401, 408, 429}
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> datetime:
|
||||||
|
return datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def claim(limit: int = BATCH) -> list[int]:
|
||||||
|
now = _now()
|
||||||
|
due = db.session.scalars(
|
||||||
|
db.select(FederationDelivery)
|
||||||
|
# No eager join here: Postgres can't lock rows on the nullable side of an outer join
|
||||||
|
.options(lazyload(FederationDelivery.activity))
|
||||||
|
.filter(FederationDelivery.status == "pending", FederationDelivery.next_attempt_at <= now)
|
||||||
|
.order_by(FederationDelivery.next_attempt_at)
|
||||||
|
.limit(limit)
|
||||||
|
.with_for_update(skip_locked=True)
|
||||||
|
).all()
|
||||||
|
for delivery in due:
|
||||||
|
delivery.next_attempt_at = now + LEASE # our lease while we send
|
||||||
|
delivery.attempts += 1
|
||||||
|
db.session.commit()
|
||||||
|
return [d.id for d in due]
|
||||||
|
|
||||||
|
|
||||||
|
def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | None) -> str:
|
||||||
|
delivery.last_status, delivery.last_error = status, error[:1000]
|
||||||
|
if _now() - delivery.created_at >= GIVE_UP_AFTER:
|
||||||
|
delivery.status = "abandoned"
|
||||||
|
log.warning(
|
||||||
|
"delivery %s to %s abandoned after %s attempts: %s",
|
||||||
|
delivery.id,
|
||||||
|
delivery.inbox,
|
||||||
|
delivery.attempts,
|
||||||
|
error[:200],
|
||||||
|
)
|
||||||
|
return "abandoned"
|
||||||
|
delay = (
|
||||||
|
RETRY_DELAYS[delivery.attempts - 1]
|
||||||
|
if delivery.attempts <= len(RETRY_DELAYS)
|
||||||
|
else LATER_DELAY
|
||||||
|
)
|
||||||
|
delivery.next_attempt_at = _now() + delay
|
||||||
|
log.warning(
|
||||||
|
"delivery %s to %s failed (attempt %s), retrying in %s: %s",
|
||||||
|
delivery.id,
|
||||||
|
delivery.inbox,
|
||||||
|
delivery.attempts,
|
||||||
|
delay,
|
||||||
|
error[:200],
|
||||||
|
)
|
||||||
|
return "retry"
|
||||||
|
|
||||||
|
|
||||||
|
def _gone(inbox: str) -> None:
|
||||||
|
"""410 from an inbox: whoever it belongs to is gone and follows no one here."""
|
||||||
|
actors = db.session.scalars(
|
||||||
|
db.select(FederationRemoteActor).filter(
|
||||||
|
(FederationRemoteActor.inbox == inbox) | (FederationRemoteActor.shared_inbox == inbox)
|
||||||
|
)
|
||||||
|
).all()
|
||||||
|
for actor in actors:
|
||||||
|
actor.gone = True
|
||||||
|
db.session.execute(db.delete(FederationFollower).filter_by(remote_actor_id=actor.id))
|
||||||
|
|
||||||
|
|
||||||
|
def deliver(delivery_id: int) -> str:
|
||||||
|
"""Send one delivery. Returns the outcome (also its metric label)."""
|
||||||
|
delivery = db.session.get(FederationDelivery, delivery_id)
|
||||||
|
document = delivery.activity.document
|
||||||
|
username = ids.username_from_actor_id(document.get("actor"))
|
||||||
|
started = time.perf_counter()
|
||||||
|
try:
|
||||||
|
response, scheme = outbound.signed_post(
|
||||||
|
delivery.inbox, document, user_id=delivery.activity.user_id, username=username
|
||||||
|
)
|
||||||
|
except FetchError as err:
|
||||||
|
if err.reason == "blocked": # would never be allowed: don't retry
|
||||||
|
delivery.status, delivery.last_error = "abandoned", str(err)[:1000]
|
||||||
|
outcome = "abandoned"
|
||||||
|
else:
|
||||||
|
outcome = _retry_or_abandon(delivery, str(err), err.status)
|
||||||
|
db.session.commit()
|
||||||
|
return outcome
|
||||||
|
fed_metrics.delivery_seconds.observe(time.perf_counter() - started)
|
||||||
|
fed_metrics.signatures_total.labels(direction="out", scheme=scheme, result="sent").inc()
|
||||||
|
|
||||||
|
status = response.status
|
||||||
|
delivery.last_status = status
|
||||||
|
if 200 <= status < 300:
|
||||||
|
delivery.status, delivery.delivered_at, delivery.last_error = "delivered", _now(), None
|
||||||
|
outcome = "delivered"
|
||||||
|
elif status == 410:
|
||||||
|
delivery.status, delivery.last_error = "abandoned", "410 Gone"
|
||||||
|
_gone(delivery.inbox)
|
||||||
|
outcome = "gone"
|
||||||
|
elif 400 <= status < 500 and status not in RETRYABLE_4XX:
|
||||||
|
delivery.status = "abandoned"
|
||||||
|
delivery.last_error = f"{status}: {response.body[:500].decode('utf-8', 'replace')}"
|
||||||
|
outcome = "abandoned"
|
||||||
|
else:
|
||||||
|
outcome = _retry_or_abandon(delivery, f"HTTP {status}", status)
|
||||||
|
db.session.commit()
|
||||||
|
return outcome
|
||||||
|
|
||||||
|
|
||||||
|
def _deliver_in_context(app, delivery_id: int) -> str:
|
||||||
|
with app.app_context():
|
||||||
|
try:
|
||||||
|
return deliver(delivery_id)
|
||||||
|
except Exception:
|
||||||
|
log.exception("delivery %s failed unexpectedly (will be retried)", delivery_id)
|
||||||
|
db.session.rollback()
|
||||||
|
return "retry" # the lease expires and it becomes due again
|
||||||
|
finally:
|
||||||
|
db.session.remove()
|
||||||
|
|
||||||
|
|
||||||
|
def work_once() -> bool:
|
||||||
|
"""Worker task: send a batch of due deliveries, several at a time."""
|
||||||
|
claimed = claim()
|
||||||
|
if not claimed:
|
||||||
|
return False
|
||||||
|
app = current_app._get_current_object()
|
||||||
|
workers = min(current_app.extensions["federation"].delivery_concurrency, len(claimed))
|
||||||
|
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||||
|
for outcome in pool.map(lambda d: _deliver_in_context(app, d), claimed):
|
||||||
|
fed_metrics.deliveries_total.labels(result=outcome).inc()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
QUEUE_STATUSES = {
|
||||||
|
"inbox": (FederationInboxItem, ("queued", "processing", "processed", "rejected", "failed")),
|
||||||
|
"deliveries": (FederationDelivery, ("pending", "delivered", "abandoned")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def maintenance() -> None:
|
||||||
|
"""Worker task (periodic): publish queue and follower gauges."""
|
||||||
|
for queue, (model, statuses) in QUEUE_STATUSES.items():
|
||||||
|
counts = dict(
|
||||||
|
db.session.execute(db.select(model.status, func.count()).group_by(model.status)).all()
|
||||||
|
)
|
||||||
|
for status in statuses:
|
||||||
|
fed_metrics.queue.labels(queue=queue, status=status).set(counts.get(status, 0))
|
||||||
|
states = dict(
|
||||||
|
db.session.execute(
|
||||||
|
db.select(FederationFollower.state, func.count()).group_by(FederationFollower.state)
|
||||||
|
).all()
|
||||||
|
)
|
||||||
|
for state in ("accepted", "pending"):
|
||||||
|
fed_metrics.followers.labels(state=state).set(states.get(state, 0))
|
||||||
|
db.session.rollback()
|
||||||