78 Commits
Author SHA1 Message Date
mattandClaude Sonnet 5 79193fbc8e Merge feature/activitypub-album-art into main
CI / test (push) Successful in 3m41s
CI / federation-interop (push) Successful in 1m39s
CI / notify (push) Successful in 6s
CI / assets (push) Successful in 8s
CI / python-package (push) Successful in 17s
CI / images (push) Successful in 34s
CI / trigger-deploy (push) Successful in 2s
CI / lint (push) Successful in 13s
CI / validate-monitoring (push) Successful in 8s
Attaches cover art to ActivityPub "now playing" posts as a standard
AS2 Image attachment, using the Cover Art Archive URL cached by the
album art feature.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Hn2QwS1HRT8tFAzo8ew63
2026-10-06 19:19:50 +01:00
mattandClaude Sonnet 5 2b984cca6e Merge feature/album-art into main
CI / lint (push) Successful in 14s
CI / federation-interop (push) Successful in 1m8s
CI / test (push) Successful in 3m54s
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 9s
CI / assets (push) Successful in 8s
CI / images (push) Successful in 26s
Adds album art: MusicBrainz + Cover Art Archive lookup, cached and
proxied through a new /api/v1/art/album endpoint, shown on the song
page, dashboard and history.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Hn2QwS1HRT8tFAzo8ew63
2026-10-06 19:17:43 +01:00
mattandClaude Sonnet 5 44abd70caa Attach cover art to ActivityPub "now playing" posts
CI / test (push) Successful in 3m31s
CI / assets (push) Skipped
CI / lint (push) Successful in 11s
CI / trigger-deploy (push) Skipped
CI / federation-interop (push) Successful in 1m38s
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 9s
Note objects can now carry an optional attachment (an AS2 Image),
which Mastodon and other AP servers render as the post's media. Only
"now playing" posts use it for now - it's the only post type tied to
a single track, and therefore the only one with one unambiguous
album; weekly summaries and milestones aggregate many tracks.

The attachment points straight at the Cover Art Archive URL cached
in AlbumArt, not our own authenticated /api/v1/art/album proxy - a
remote server fetches attachments unauthenticated, and Cover Art
Archive is already public. The lookup happens in the periodic
now-playing worker task, not a request, so a cache-miss MusicBrainz/
Cover Art Archive call adds no request latency.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Hn2QwS1HRT8tFAzo8ew63
2026-10-06 19:16:29 +01:00
mattandClaude Sonnet 5 f106d68921 Fix two album art bugs found in manual browser testing
CI / validate-monitoring (push) Successful in 9s
CI / federation-interop (push) Successful in 1m37s
CI / assets (push) Skipped
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 6s
CI / lint (push) Successful in 11s
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / test (push) Successful in 3m24s
- art.js revoked each thumbnail's blob: URL on its own "load" event,
  but the same URL is shared (via the lookup cache) by every
  thumbnail for that album on the page - revoking after the first
  one loaded broke every other <img> still using it. Stop revoking;
  this is a full-page-reload site, so the browser releases the
  memory on navigation anyway.
- .ranking-art/.log-art thumbnails inherited their row's default
  cross-axis alignment (baseline for .ranking, stretch for .log),
  which suits text but left the art sitting high against two-line
  name+artist text. Center them explicitly instead.

Verified in-browser across all four surfaces (song page hero,
dashboard Albums ranking, Recently played, History) with real
MusicBrainz/Cover Art Archive artwork.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Hn2QwS1HRT8tFAzo8ew63
2026-10-06 19:02:53 +01:00
mattandClaude Sonnet 5 dfd2ef868b Show album art on the song page, dashboard and history
CI / validate-monitoring (push) Successful in 9s
CI / lint (push) Successful in 14s
CI / images (push) Skipped
CI / notify (push) Successful in 6s
CI / federation-interop (push) Successful in 1m7s
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / test (push) Successful in 3m24s
CI / trigger-deploy (push) Skipped
New frontend/js/art.js builds a thumbnail that starts as a placeholder
and swaps itself for the real cover once (if) it resolves, fetched
via the new /api/v1/art/album endpoint with the existing bearer-auth
transport and handed to the browser as a blob: object URL (no
query-string tokens, no hotlinking).

Wired into all four places a track/album appears: the song page's
glowing display, the dashboard's "Most played > Albums" list, the
dashboard's "Recently played" list, and the full History page -
Artists/Tracks rankings are left alone.

Also fixes a real reliability gap found during manual testing:
Cover Art Archive's existence check (a HEAD request, redirected
through archive.org) had no retry at all, unlike the MusicBrainz
search next to it, and an occasional slow/flaky response there was
enough to fail a lookup outright. It now retries the same way.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 17:14:44 +01:00
mattandClaude Sonnet 5 5bdeeddb0b Add album art backend: MusicBrainz + Cover Art Archive, proxied and cached
New GET /api/v1/art/album?artist=&album= resolves and streams an
album's cover art. Lookups go through MusicBrainz release-group
search then Cover Art Archive's release-group front-image endpoint,
both free and keyless - no setup required by self-hosters. Results
(hits, misses and errors) are cached in a new album_art table keyed
case-insensitively on (artist, album), since Scrobble.mbid can't be
trusted as a release identifier.

The service layer separates resolving where the art is (lookup())
from fetching the bytes (fetch_image()) so a future move to storing
the bytes ourselves only touches the latter.

Also widens the UI's CSP (img-src) to allow blob: URLs, since the
frontend will fetch art with the existing bearer-auth header and
hand the browser a blob: object URL rather than hotlinking.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 17:05:57 +01:00
matt 7b169ea807 Merge pull request 'Make "Recently played" rows match the Tracks list style' (#3) from fix/recent-list-style into main
CI / federation-interop (push) Successful in 1m13s
CI / assets (push) Successful in 9s
CI / test (push) Successful in 4m26s
CI / lint (push) Successful in 14s
CI / validate-monitoring (push) Successful in 10s
CI / images (push) Successful in 37s
CI / trigger-deploy (push) Successful in 2s
CI / python-package (push) Successful in 18s
CI / notify (push) Successful in 6s
Reviewed-on: #3
2026-10-06 13:45:57 +01:00
mattandClaude Sonnet 5 457e051828 Make "Recently played" rows match the Tracks list style
CI / validate-monitoring (push) Successful in 8s
CI / federation-interop (push) Successful in 1m15s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / notify (push) Successful in 6s
CI / validate-monitoring (pull_request) Successful in 9s
CI / lint (pull_request) Successful in 14s
CI / images (pull_request) Skipped
CI / lint (push) Successful in 12s
CI / test (push) Successful in 3m18s
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
CI / federation-interop (pull_request) Successful in 1m14s
CI / test (pull_request) Successful in 4m38s
CI / assets (pull_request) Skipped
CI / python-package (pull_request) Skipped
CI / trigger-deploy (pull_request) Skipped
CI / notify (pull_request) Successful in 7s
Stack the track above a muted artist line and link each row to its
song page, consistent with how the "Most played > Tracks" list
already looks and behaves. Scoped with a new .log-stacked modifier
so history.html and the song page's own history list (which share
the base .log classes) are unaffected.

Verified manually in-browser: rows render stacked and link to the
right song page, and history.html's layout is unchanged.

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-27 14:17:58 +01:00
mattandClaude Sonnet 5 d90a42046e Merge feature/activitypub: ActivityPub federation (phases 0-4)
CI / test (push) Successful in 3m38s
CI / python-package (push) Successful in 17s
CI / images (push) Successful in 34s
CI / federation-interop (push) Successful in 1m25s
CI / validate-monitoring (push) Successful in 17s
CI / lint (push) Successful in 20s
CI / assets (push) Successful in 7s
CI / notify (push) Successful in 5s
Followable from Mastodon and other fediverse apps: discoverable
profiles, followers, weekly summaries, milestones, now playing (a
live profile field plus opt-in posts), and the web UI and settings
for all of it. Off by default at the server level, and off per user
until they turn sharing on.

Verified with a GoToSocial container in CI on every push throughout,
and with a manual pass against a real Mastodon account and
activitypub.academy over a public HTTPS tunnel before this merge.

See docs/design/activitypub.md and the phase-by-phase design docs
alongside it for the full design and build history.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 23:51:28 +01:00
mattandClaude Sonnet 5 b941a17e07 Split docs into deploy, setup and usage guides
CI / validate-monitoring (push) Successful in 8s
CI / test (push) Successful in 3m13s
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 1m10s
CI / images (push) Skipped
CI / notify (push) Successful in 5s
README had grown into one long file covering deployment, local
development and end-user features together. Split into:

- docs/deploy.md: running a real instance - images, configuration,
  putting it behind TLS (with a minimal Caddy example and the
  CORS_ORIGINS/UI_BASE_URL distinction the last session's manual test
  found the hard way), monitoring, backups, releases.
- docs/setup.md: working on the code - local dev environment,
  migrations, tests, the manual fediverse test, CI/CD.
- docs/usage.md: accounts and apps, connecting a player, importing
  history, sharing on the fediverse.

README is now a short overview and quick start that links to the
three, plus the existing API reference and federation/design docs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 23:46:48 +01:00
mattandClaude Sonnet 5 9ca2ace854 Manual tunnel test: two real bugs found and fixed, docs marked done
CI / test (push) Successful in 4m10s
CI / assets (push) Skipped
CI / notify (push) Successful in 5s
CI / images (push) Skipped
CI / lint (push) Successful in 11s
CI / federation-interop (push) Successful in 1m38s
CI / validate-monitoring (push) Successful in 8s
CI / python-package (push) Skipped
Ran the manual pass with a real Mastodon account through a cloudflared
tunnel - the one gap every phase doc had flagged as outstanding before
merging. WebFinger, actor resolution, follow/unfollow/approve/block,
a forced weekly summary posting and deleting, and the now-playing
profile field appearing/clearing all worked correctly against
mastodon.social and activitypub.academy.

Two real bugs found along the way, both fixed here:

- docker-compose.yml hardcoded the api/worker services' CORS_ORIGINS
  to UI_BASE_URL. 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 -
  .env's own CORS_ORIGINS setting had no effect, since the compose
  file never referenced it. Now its own variable, same default.
- TestConfig wasn't isolating UI_BASE_URL/CORS_ORIGINS from a
  developer's .env, so the same local change broke six tests that
  assert on http://localhost:8080 URLs - the same class of gap an
  earlier session found and fixed for FEDERATION_ENABLED/
  LASTFM_API_KEY. Pinned alongside them.

Marked the manual pass done in each phase doc (1-4) and the overview.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 23:42:58 +01:00
mattandClaude Sonnet 5 9f7ada682c Docs for phase 4: now playing (step 8)
CI / images (push) Skipped
CI / assets (push) Skipped
CI / lint (push) Successful in 12s
CI / test (push) Successful in 3m23s
CI / python-package (push) Skipped
CI / validate-monitoring (push) Successful in 9s
CI / federation-interop (push) Successful in 1m41s
CI / notify (push) Successful in 6s
README: the Sharing page's Now playing section, its three modes and
their throttles.

federation/README.md: now_playing.py added to the publishing
plug-ins list (with a note on why it's not quite the same shape as
weekly.py/milestones.py - a periodic scan covering both the profile
push and the opt-in post, rather than an event receiver), actors.py
added to the layout table, and the worker tasks / interop sections
updated for federation.now_playing and the new profile-field check.

docs/design/activitypub-phase4.md marked done, with the two points
where implementation diverged from the written plan (the key-hashing
fix and the now_playing_mode privacy gate).

docs/openapi.json unchanged - still current from step 4.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 17:32:20 +01:00
mattandClaude Sonnet 5 9883111fa1 Now-playing interop check (phase 4, step 7)
CI / test (push) Successful in 3m33s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / validate-monitoring (push) Successful in 9s
CI / lint (push) Successful in 13s
CI / python-package (push) Skipped
CI / federation-interop (push) Successful in 1m37s
CI / notify (push) Successful in 5s
Extends the GoToSocial driver's second phase: run.sh seeds a
now-playing track alongside the scrobble it already seeds for the
weekly summary; the driver turns now_playing_mode on via the settings
API, then polls GoToSocial's own stored copy of the account (not a
fresh resolve() fetch) for a "Now playing" field, confirming the
periodic Update(Person) push actually reached and updated their cache
- not just that we sent something.

Verified against a real GoToSocial 0.22.1 container locally before
pushing:
    Now playing: 'Interop Now Playing by Interop Artist'
    All post interop checks passed

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 17:29:31 +01:00
mattandClaude Sonnet 5 f3d2b5d578 Dashboard panel for profile updates (phase 4, step 6)
CI / validate-monitoring (push) Successful in 8s
CI / test (push) Successful in 3m33s
CI / federation-interop (push) Successful in 1m8s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 1m20s
CI / lint (push) Failing after 2m10s
One new panel on the Federation dashboard's existing Posts row:
profile updates/min by result (sent/throttled). now_playing posts
already show up in the Posts / min by kind panel from phase 3, under
kind="now_playing" - no changes needed there.

No new alert: unlike weekly summaries, now playing is opt-in and most
instances will have nobody using it, so there's no "should always be
producing something" baseline to alert on the way
FederationWeeklySummariesMissing does.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 17:24:17 +01:00
mattandClaude Sonnet 5 f04e53a972 Web UI for now playing (phase 4, step 5)
CI / lint (push) Successful in 21s
CI / federation-interop (push) Successful in 1m21s
CI / python-package (push) Skipped
CI / test (push) Successful in 4m2s
CI / images (push) Skipped
CI / validate-monitoring (push) Successful in 14s
CI / assets (push) Skipped
CI / notify (push) Successful in 6s
Sharing page gets a "Now playing" section: off / show on profile /
show on profile and post, as a single choice matching the settings
column - generalised sharing.js's visibility-only radio-group handling
to a small RADIO_GROUPS list so now_playing_mode reuses the same fill/
save logic rather than adding a second special case.

Public profile API and profile.html gain a live "now playing" field,
sourced from the same actors.now_playing_text() the actor document
uses and gated the same way (now_playing_mode off means never showing
it, whatever's actually playing).

Refactored actors.py along the way: now_playing_field() takes settings
directly and does its own off-mode gating, rather than build_document()
doing it externally - one place decides whether the field is shown,
reused by the actor document, the push Update, and now the public
profile API.

Verified by hand in a real browser: settings round-trip through the
Sharing page's new radio group, the public profile page shows "Now
playing: Reckoner by Radiohead" once now_playing_mode is on, and the
raw actor document (curl, Accept: application/activity+json) carries
the same PropertyValue attachment.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 17:22:02 +01:00
mattandClaude Sonnet 5 515acae233 Settings API and schema for now_playing_mode (phase 4, step 4)
CI / test (push) Successful in 3m39s
CI / images (push) Skipped
CI / federation-interop (push) Successful in 1m8s
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s
CI / lint (push) Successful in 13s
CI / validate-monitoring (push) Successful in 40s
CI / assets (push) Skipped
now_playing_mode was already in sharing.EDITABLE (step 1), so
_settings_body() was already returning it - but SharingSettingsSchema
never declared the field, so marshmallow was silently dropping it from
every response. Same class of gap phase 3 hit with timezone/
post_weekly_summary/post_milestones.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 17:15:51 +01:00
mattandClaude Sonnet 5 ba30d5cb15 Now-playing publisher and worker task (phase 4, step 3)
CI / validate-monitoring (push) Successful in 8s
CI / federation-interop (push) Successful in 1m7s
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s
CI / lint (push) Successful in 11s
CI / test (push) Successful in 3m15s
CI / assets (push) Skipped
publishing/now_playing.py: a periodic scan (federation.now_playing,
every 30s) that pushes a throttled Update(Person) for the profile
field (5 minutes) and, for users opted into posts, publishes a Note
after a track's been playing 30+ seconds (throttled to 30 minutes),
deleting the previous now-playing post once the new one is confirmed
published - not before, so a failed publish never leaves a user with
none showing. Reuses publishing.publish()/delete_post() unchanged;
now_playing is just another post kind.

Fixed a real bug before it ever ran against Postgres: the key
(artist/track/started_at) was going straight into federation_posts.key
(VARCHAR(64)), which routinely overflows for real track and artist
names. Hashed instead - it's an idempotency token, not something
anyone needs to read.

New metric scrobbler_federation_profile_updates_total{result}; posts
already get scrobbler_federation_posts_total{kind="now_playing",...}
for free from the existing publish() instrumentation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 17:13:10 +01:00
mattandClaude Sonnet 5 9ab8bd8e03 Fix: never show now-playing when now_playing_mode is off
CI / lint (push) Successful in 13s
CI / images (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 9s
CI / federation-interop (push) Successful in 1m7s
CI / test (push) Successful in 3m3s
CI / assets (push) Skipped
CI / python-package (push) Skipped
now_playing_field() read core's now_playing table unconditionally, so
a user who never turned federation's now-playing feature on at all
would still leak what they're currently listening to on their public
actor document, since core's now_playing table is populated for every
user regardless of federation settings.

Found while designing step 3 (the periodic push task): querying only
sharing users with now_playing_mode != "off" made me notice
build_document() itself had no equivalent guard, and the existing
tests happened not to catch it (they only combined "nothing playing"
with "mode off", and "something playing" with "mode on"). Added the
missing combination - something playing, mode off - to both the
actors.py unit tests and the web-level actor route test.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 17:06:55 +01:00
mattandClaude Sonnet 5 c38e2e392a Update(Person) vocabulary and the live now-playing actor field (phase 4, step 2)
CI / federation-interop (push) Successful in 1m47s
CI / notify (push) Successful in 6s
CI / test (push) Successful in 3m51s
CI / validate-monitoring (push) Successful in 15s
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / lint (push) Successful in 16s
CI / assets (push) Skipped
vocab.update() wraps a document as an Update, addressed explicitly
(unlike undo(), which derives `to` from the undone activity - an actor
document has no `to` of its own).

New actors.py builds the actor document body, shared by GET /users/<u>
(live) and the coming Update(Person) push (throttled) so both render
the same shape without web.py depending on the worker-side module or
vice versa. now_playing_field() reads core's get_now_playing()
directly - never federation's own throttled push state - so a fetch
always shows the truth, whatever the last proactive push said.

GET /users/<u> now includes a "Now playing" PropertyValue attachment
whenever something unexpired is playing, and omits it otherwise.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 17:03:04 +01:00
mattandClaude Sonnet 5 cb8f9c997e Settings column and now-playing state table (phase 4, step 1)
CI / validate-monitoring (push) Successful in 7s
CI / test (push) Successful in 3m5s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / notify (push) Successful in 6s
CI / federation-interop (push) Successful in 1m9s
CI / lint (push) Successful in 13s
CI / python-package (push) Skipped
federation_settings gains now_playing_mode (off/profile/posts,
default off), validated in sharing.update() the same way visibility
is. New federation_now_playing table: one row per user, tracking what
we've last told the fediverse (profile_key/profile_updated_at,
post_key/post_posted_at) - separate from core's now_playing table,
which is what's actually playing right now.

Verified the migration both ways against the local dev database: full
downgrade to base and back up to heads on both branches, not just a
single-step round trip.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 16:57:34 +01:00
mattandClaude Sonnet 5 7d86bad929 Plan for ActivityPub phase 4 (now playing)
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
CI / images (push) Skipped
CI / validate-monitoring (push) Successful in 9s
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 1m6s
CI / test (push) Successful in 2m57s
Resolves the overview doc's last open decision: now playing builds
both options it described, not one or the other - the profile field
(recommended default, live on every GET, throttled Update(Person) push
every 5 minutes) plus a separate opt-in for actual posts (min 30s
played, throttled to one every 30 minutes, previous post deleted when
the next goes out).

No event receiver or pending-checks queue like milestones needed: a
plain periodic scan (federation.now_playing, every 30s) is simplest
here, since the throttle windows are minutes-long and there's no
history to react to retroactively - unlike milestones, now playing
only ever reflects what's playing right now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 16:54:00 +01:00
mattandClaude Sonnet 5 e0423d04bc Docs for phase 3: what gets posted, the publishing plug-ins (step 11)
CI / lint (push) Successful in 16s
CI / federation-interop (push) Successful in 1m8s
CI / validate-monitoring (push) Successful in 8s
CI / test (push) Successful in 2m55s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / notify (push) Successful in 6s
CI / python-package (push) Skipped
README: the fediverse section now describes what's actually posted
(weekly summaries, milestones) and their settings, instead of pointing
at "still being built"; notes now playing is the one piece left.

federation/README.md: a new Publishing section explains the plug-in
shape (base.py owns idempotent publish/delete/fan-out; each kind -
weekly.py, milestones.py - only decides when to post and what to say),
so adding a third kind later means adding a module, not touching
base.py. Worker tasks and layout tables updated for federation.weekly,
federation.milestones and cli.py. Interop section covers the new post
check.

docs/design/activitypub-phase3.md marked done, following the precedent
from phases 1-2's own docs, with the three points where implementation
diverged from the written plan (the top-10-needs-a-real-top-10 fix,
post_now() as a separate window computation, and post_page_url()
needing the username).

docs/openapi.json unchanged - still current from step 8.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 16:44:32 +01:00
mattandClaude Sonnet 5 860d4d0f93 Admin post-weekly command and GoToSocial post interop checks (phase 3, step 10)
CI / lint (push) Successful in 13s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / notify (push) Successful in 6s
CI / validate-monitoring (push) Successful in 8s
CI / federation-interop (push) Successful in 1m8s
CI / test (push) Successful in 2m56s
CI / python-package (push) Skipped
`flask federation post-weekly --user <name> --now` posts a user's
summary for the week still in progress immediately, ignoring the
Monday-09:00 gate - for operators, and so the interop test can produce
a real post without waiting on calendar time. Backed by a new
weekly.post_now(), sharing _post_for_window() with the normal
check_and_post() path so both go through the same has_post/empty-week/
publish logic; only the window (this week so far, vs. the last gated
one) differs.

Extends the GoToSocial interop driver to a second phase: run.sh seeds
one scrobble directly (the driver container has no way to sign a
Last.fm-API request, and doesn't need one just to seed data), triggers
the CLI command via `docker compose exec api`, then re-runs the driver
with --check-posts to confirm the post reaches the already-following
GoToSocial account's home timeline as `private` (followers-only, our
default) with the expected content, deletes it via the existing
DELETE /posts/{id} API, and confirms it disappears from GoToSocial's
timeline too. The main flow now ends by re-following instead of the
previous test's decline, so the post-check phase has a follower to
check against.

Verified end to end against a real GoToSocial 0.22.1 container locally
before pushing (scripts/interop/run.sh), not just left to CI:
    private post: '<p><strong>My week in music: 1 play</strong></p>...'
    All post interop checks passed

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 16:40:34 +01:00
mattandClaude Sonnet 5 de1519a066 Metrics, dashboard and alert for posts (phase 3, step 9)
CI / images (push) Skipped
CI / assets (push) Skipped
CI / federation-interop (push) Successful in 59s
CI / notify (push) Successful in 6s
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 13s
CI / test (push) Successful in 2m53s
CI / python-package (push) Skipped
New counters: scrobbler_federation_posts_total{kind,visibility},
post_deletions_total{reason} (manual vs sharing_off), and
milestone_checks_total / weekly_total{result}, each incremented at a
single point (publish()/_delete(), and a thin public wrapper around
each module's check_and_post()) rather than at every call site.

Federation dashboard gains a "Posts" row: posts/min by kind and
visibility, deletions/min by reason, and weekly/milestone checks by
result - the same shape as the existing rows, so a stalled worker (all
zero) looks the same as one with nothing to do (all "disabled"/"none").

New alert FederationWeeklySummariesMissing, on scrobbler_worker_tasks_total
rather than the new weekly_total metric: weekly_total only increments
once check_all() reaches a real sharing user, so on a quiet instance
with nobody sharing yet it would sit at zero forever and false-alarm
immediately. worker_tasks_total counts every periodic run regardless of
whether there was anyone to check, matching the same pattern already
used by ImportWorkerDown and FederationInboxBacklog.

Verified deploy/prometheus/alerts.yml and prometheus.yml with promtool
(via the prom/prometheus image, matching CI's validate-monitoring job).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 16:31:16 +01:00
mattandClaude Sonnet 5 0acce9b948 API and web UI for posts, previews and post settings (phase 3, step 8)
CI / federation-interop (push) Successful in 1m0s
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / lint (push) Successful in 13s
CI / test (push) Successful in 2m53s
CI / assets (push) Skipped
CI / validate-monitoring (push) Successful in 8s
CI / notify (push) Successful in 5s
/api/v1/federation gains:
  - GET /posts, DELETE /posts/{id}: manage your own posts from the UI.
  - GET /preview/weekly: what the weekly summary would say right now, for
    the week still in progress - never posted or stored. Backed by a new
    weekly.preview() and schedule.current_week_start().
  - GET /profiles/{username}/posts/{post_uuid} (public, unauthenticated):
    backs the UI's post page, which can't itself speak ActivityPub.

Settings gain timezone/post_weekly_summary/post_milestones, already
present in sharing.EDITABLE since phase 3 step 2 but never added to
SharingSettingsSchema, so the API was silently dropping them from
responses. timezone validates against the same is_valid_timezone() the
service layer uses, with a dedicated marshmallow validator.

Fixed a real gap found while wiring the post page: ids.post_page_url()
took a username but never put it in the URL, so post.html would have
had no way to know whose post to look up. It's now ?u=<username>&id=<uuid>.

Sharing page gets a "What to post" section (weekly summary and
milestones toggles, a timezone field with a browser-supplied IANA
datalist where Intl.supportedValuesOf exists, and a live preview).
New posts.html lists a user's posts with delete (mirroring followers.js's
confirm-before-destructive-action pattern); new post.html is the public
landing page for a post's `url`, reached by browsers redirected from the
raw ActivityPub endpoint.

Verified by hand against a local dev server and a real browser: sign in,
enable sharing, preview and publish, list and delete a post, and follow
the ActivityPub redirect through to the public post page and its 404
after deletion - fixed one bug found this way (the preview box was
collapsing the summary's line breaks).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 16:24:35 +01:00
mattandClaude Sonnet 5 d4f3607eef Page the outbox and serve individual posts (phase 3, step 7)
CI / validate-monitoring (push) Successful in 8s
CI / test (push) Successful in 2m47s
CI / assets (push) Skipped
CI / lint (push) Successful in 1m10s
CI / python-package (push) Skipped
CI / federation-interop (push) Successful in 1m1s
CI / images (push) Skipped
CI / notify (push) Successful in 5s
GET /users/<u>/outbox is now a real OrderedCollection pointing at
paged OrderedCollectionPages of 20 Creates, newest first - public and
unlisted posts only, since it's unauthenticated. Adds
publishing.outbox_page() for the query and publishing.find_by_note_id()
to look a post up by its Note's id (the two ActivityPub ids a post has
- the wrapping Create's and the embedded Note's - were already
generated independently in publish(); finding by the Note's id reuses
the existing JSONB-path query pattern already established by
activities.undo_block(), rather than adding a new column just for this
lookup).

GET /users/<u>/posts/<uuid> serves that Note for public and unlisted
posts; followers-only and deleted posts 404 (they reach followers by
delivery instead); a browser without an ActivityPub Accept is
redirected to the UI post page unconditionally, before any lookup,
matching actor()'s existing reasoning that a 404-vs-302 difference
must never be usable to probe which posts exist.

Documents both endpoints in federation/openapi.py and regenerates
docs/openapi.json (test_every_api_route_is_documented already enforces
this on every new federation route, so it can't wait for the docs
step at the end of the phase).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 13:37:38 +01:00
mattandClaude Sonnet 5 6fd028d108 Trim artist-plays milestone thresholds to match the phase 3 plan
CI / test (push) Successful in 3m6s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / lint (push) Successful in 14s
CI / python-package (push) Skipped
CI / notify (push) Successful in 1m3s
CI / validate-monitoring (push) Successful in 8s
CI / federation-interop (push) Successful in 1m2s
The plan specifies 100/500/1k for an artist's plays; 2500 and 5000 had
crept in beyond that.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 12:25:26 +01:00
mattandClaude Sonnet 5 c3a8233e73 Add federation milestones: scrobble-count, artist-plays, top-10 entries
CI / validate-monitoring (push) Successful in 9s
CI / lint (push) Successful in 15s
CI / python-package (push) Skipped
CI / federation-interop (push) Successful in 1m1s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / test (push) Successful in 3m7s
CI / notify (push) Failing after 2m31s
Adds publishing/milestones.py: one post per check, in priority order
(scrobble count > top-10 entry > artist plays), each threshold marked
done the first time it's reached so it's never posted twice. A live
scrobble queues a per-user FederationPendingCheck row (collapsing
repeats so the event receiver stays fast); the new federation.milestones
worker task drains it, requeuing to the back of the queue on failure
rather than retrying immediately, since a milestone check is a pure DB
read with no external server to fail against.

Enabling sharing, and finishing an import, call set_baseline() instead
of a live check: every threshold already passed is marked done without
posting, so history already on file never produces a burst of
retroactive "milestone" posts. Wired into sharing.update()'s
enable-toggle branch with a local import, mirroring farewell_user()'s
existing precedent for the same sharing<->federation-internals
circularity.

A top-10 entry now requires the user to actually have TOP_N distinct
artists first - caught by a test with unpatched thresholds, where every
first play of a new artist was trivially "entering an empty top 10".

Fixes test_federation_boundary.py's off-means-off check: blinker
signals are process-wide, so once any app in the test process enables
federation the milestone receivers stay connected for the rest of the
run regardless of which app is "current" - there's no per-app scoping
to introspect. Replaced the receiver-absence assertion with a
behavioural one (firing an event through the off app's own context is
a no-op), and kept the existing per-app-scoped view/worker checks as
they were.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 12:24:04 +01:00
mattandClaude Sonnet 5 0766c09fb3 Weekly summary task (phase 3, step 5)
CI / validate-monitoring (push) Successful in 10s
CI / lint (push) Successful in 16s
CI / federation-interop (push) Successful in 1m2s
CI / python-package (push) Skipped
CI / test (push) Successful in 2m40s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / notify (push) Successful in 6s
protocol/schedule.py (pure): target_week(now_utc, tz) resolves to
exactly one Monday-Sunday week — the most recent one whose Monday
09:00-local posting gate has passed — computed via wall-clock
arithmetic in the user's own zone so it's correct across a DST change
(a week can be 6h23/7h01 of real time, never silently 7 flat days).
Because it's a pure function of "now", a worker that was down for
weeks naturally catches up with one post, not a backlog. Also
resolve_timezone()/is_valid_timezone() for a settings field that can
otherwise crash a task or silently do nothing forever.

protocol/content.py (pure): the small HTML subset shared by every post
kind (p, strong, em, ol, li), with escaping split from formatting so a
hostile artist/track name can't inject markup.

publishing/weekly.py: build_content() (the template) and
check_and_post()/check_all() (the federation.weekly periodic task,
every 15 minutes). An empty week is simply never posted, and — since
the target week only ever advances — never reconsidered either, with
no separate marker needed. has_post() lets the common "already posted
this week" pass skip the stats queries entirely.

Core: accounts.get_user(id) (federation needs it and can't import the
User model directly); sharing.EDITABLE and update() gain
timezone/post_weekly_summary/post_milestones, with the same
now-not-later validation visibility already had.

Tested: the DST week and gate boundaries against real computed
reference dates (not guessed ones — one guess was wrong and the test
caught it before it shipped), hostile/emoji/RTL names in the template,
and the full task against a real database (empty vs non-empty weeks,
posting twice, disabled settings, a worker down for weeks, a bad
stored timezone not stopping other users).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 12:02:02 +01:00
mattandClaude Sonnet 5 b16ba116c4 Publishing core: post, fan out, delete (phase 3, step 4)
CI / assets (push) Skipped
CI / notify (push) Successful in 6s
CI / lint (push) Successful in 13s
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / validate-monitoring (push) Successful in 8s
CI / federation-interop (push) Successful in 1m1s
CI / test (push) Successful in 2m26s
federation/publishing/base.py:
- publish(user_id, username, kind, key, text=, html=): idempotent —
  refuses (returns None, doesn't post) if the user has stopped sharing
  or a post with that key already exists, including when two worker
  passes race (caught as a duplicate-key error at commit, not raised).
  Builds Note + Create addressed from the user's current visibility,
  stores both, and fans out one delivery per distinct accepted
  follower's inbox (shared inbox preferred).
- delete_post(user_id, username, post): sends Delete(Tombstone) to the
  same followers and tombstones the row; a no-op if already deleted.
  Addressed by the post's own visibility at the time it was posted,
  not the user's current setting.
- delete_all_for(user_id, username): deletes every live post, for
  turning sharing off.

Wired into PATCH /settings: turning sharing off now deletes every live
post *before* rejecting followers (reject_all removes the followers
that accepted_inboxes() needs). The phase 2 farewell-actor mechanism
already covers these deliveries with no changes, since it just checks
for any pending delivery on the user's activities.

Small supporting changes: activities.store() made public (used from
publishing now, not just activities.py's own narrow helpers);
followers.accepted_inboxes() for fan-out; ids.py gains
followers_url/note_url/post_page_url; sharing.settings_for()'s unsaved
default object now sets every field a caller might read, not just the
ones the old callers happened to need.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 11:51:06 +01:00
mattandClaude Sonnet 5 dce90400e6 Post vocabulary and visibility addressing (phase 3, step 3)
CI / images (push) Skipped
CI / assets (push) Skipped
CI / notify (push) Successful in 6s
CI / federation-interop (push) Successful in 1m1s
CI / test (push) Successful in 2m19s
CI / lint (push) Successful in 12s
CI / python-package (push) Skipped
CI / validate-monitoring (push) Successful in 8s
Pure additions to federation/protocol:
- vocab: note() (a Note, no @context of its own — always embedded in
  a Create), create() (wraps an object with the post's addressing),
  delete() (a Tombstone, the shape Mastodon sends), hashtag() (name
  only; we don't serve tag pages), ordered_collection_page() for
  outbox paging, and ordered_collection() gains an optional `first`
  link
- addressing.py: one function turning a visibility (followers/
  unlisted/public) into (to, cc), unit-tested for each value

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 11:39:59 +01:00
mattandClaude Sonnet 5 ed74a78625 Settings, posts, milestone marks and pending-checks tables (phase 3, step 2)
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 58s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / notify (push) Successful in 5s
CI / test (push) Successful in 2m19s
CI / python-package (push) Skipped
federation_settings gains timezone (IANA name, default UTC),
post_weekly_summary and post_milestones (both on by default), with a
server_default backfilling any existing rows.

New tables on the federation branch:
- federation_posts: one row per (user, key) — e.g. weekly:2026-W39 or
  milestone:scrobbles:10000 — which is what makes posting idempotent;
  wraps the Create activity, keeps its own content and visibility, and
  a deleted_at tombstone
- federation_milestone_marks: thresholds a user has passed, with
  posted=false for ones passed silently (enabling sharing, or an
  import finishing) so they're never reconsidered
- federation_pending_checks: a one-row-per-user queue filled by the
  scrobbles_stored receiver and drained by the worker, so a scrobble
  request never does milestone-checking work itself

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 11:36:34 +01:00
mattandClaude Sonnet 5 ea6b10637e Core: listening stats over an explicit date window (phase 3, step 1)
CI / federation-interop (push) Successful in 1m1s
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 9s
CI / lint (push) Successful in 13s
CI / test (push) Successful in 2m5s
CI / assets (push) Skipped
CI / images (push) Skipped
scrobbler.services.stats gains scrobble_count_between, top_artists_between
and top_tracks_between, over [start, end) (start inclusive, end
exclusive) rather than a rolling period. The existing period-based
functions are re-expressed on the same _between() primitive instead of
duplicating the windowing logic.

These are for federation's weekly summaries (phase 3), which need a
fixed Monday-to-Sunday window rather than "N days back". No public API
changes; the Last.fm and /api/v1/me endpoints are unaffected (pinned by
a regression test).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 11:34:08 +01:00
mattandClaude Opus 5.5 bc717c2a06 Plan for ActivityPub phase 3 (posts)
CI / federation-interop (push) Successful in 1m0s
CI / test (push) Successful in 2m1s
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 13s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 7s
Weekly summaries (Monday 09:00 in each user's time zone) and
milestones, followers-only by default: a core stats-window addition,
idempotent posts keyed per week/threshold, Note/Create/Delete with
visibility addressing, fan-out to followers' shared inboxes, no
retroactive posts (baselines on enabling sharing and after imports),
deletable posts and deletion when sharing is switched off, a paged
outbox, API/UI, metrics and an alert, and interop checks with
GoToSocial.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 10:58:48 +01:00
mattandClaude Opus 5.5 fefdeb90ec Document following on the fediverse; mark phase 2 done (phase 2, step 9)
CI / lint (push) Successful in 11s
CI / federation-interop (push) Successful in 1m3s
CI / python-package (push) Skipped
CI / assets (push) Skipped
CI / validate-monitoring (push) Successful in 9s
CI / notify (push) Successful in 1m20s
CI / test (push) Successful in 2m4s
CI / images (push) Skipped
README: following works, the Followers page, optional federation
settings and the worker requirement. Federation README: settings,
module layout, worker tasks and the interop test. Design doc: what
interop testing changed. Phase 2 plan marked done with its deviations
(httpcore, no in-process two-instance test, Undo of Block), leaving
only the manual Mastodon check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 22:17:02 +01:00
mattandClaude Opus 5.5 fe95f59fc8 CI: run the GoToSocial interop test
CI / images (push) Skipped
CI / notify (push) Successful in 6s
CI / validate-monitoring (push) Successful in 8s
CI / federation-interop (push) Successful in 1m9s
CI / assets (push) Skipped
CI / lint (push) Successful in 13s
CI / test (push) Successful in 2m11s
CI / python-package (push) Skipped
A federation-interop job runs scripts/interop/run.sh on every push
(not for pull requests from forks), with a per-run compose project and
subnet so concurrent runs can't collide. Publishing waits for it too.

The driver is now an image with the script baked in, and the interop
overlay avoids bind mounts, since CI jobs drive the host's Docker from
inside a container.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 22:13:12 +01:00
mattandClaude Opus 5.5 b93cfea5b3 Interop with a real GoToSocial server, and the fixes it found (phase 2, step 8)
CI / test (push) Successful in 2m16s
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 10s
CI / images (push) Skipped
scripts/interop/run.sh brings up Scrobbler (API, worker, UI behind a
throwaway-TLS Caddy) and GoToSocial 0.22.1 on a private .test network,
creates a GoToSocial user, drives its sign-in/OAuth screens for a token,
and checks: lookup by handle, follow accepted, unfollow, manual approval
and approve, remove, block and unblock, and decline.

Found and fixed along the way:
- Keys whose id is a path serving the actor (GoToSocial's
  <actor>/main-key) weren't resolved; now all three publishing styles
  are handled
- An Undo of an older Follow arriving after a newer Follow removed the
  new follower; an Undo now only removes the Follow it names (and Undo
  referencing a Follow by id is understood)
- Rejects embedded the Follow, which some servers (GoToSocial) match by
  account pair, so a late Reject could cancel a newer request; Rejects
  now reference the Follow by id
- Unblocking didn't tell the other server; it now sends Undo(Block)
- Actors publish an (empty) featured collection, which Mastodon and
  GoToSocial fetch

GoToSocial 0.22.1 ignores Reject for already-accepted follows (a TODO
in its code, fixed on its main branch); the removal check on its side
is skipped until a release has it (GTS_REJECT_ENDS_FOLLOWS=1 enables).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 22:11:39 +01:00
mattandClaude Opus 5.5 ec658a7751 Federation monitoring: followers, inbox and delivery panels, alerts (phase 2, step 7)
CI / test (push) Successful in 2m2s
CI / images (push) Skipped
CI / notify (push) Successful in 5s
CI / python-package (push) Skipped
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 12s
CI / assets (push) Skipped
Federation dashboard gains follower and request counts, inbox and
delivery queue depths, activities received by type and result,
incoming signature results by scheme and reason, deliveries by result,
delivery latency and outgoing signature schemes. Every query was run
against a live Prometheus.

Alerts: FederationDeliveryBacklog (>100 waiting for 30m),
FederationInboxBacklog (unprocessed for 15m) and
FederationSignatureFailures (>20% failing for 15m).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 21:44:34 +01:00
mattandClaude Opus 5.5 a90cd14f59 Manage followers from the API and web UI (phase 2, step 6)
CI / images (push) Skipped
CI / assets (push) Skipped
CI / validate-monitoring (push) Successful in 7s
CI / test (push) Successful in 2m4s
CI / python-package (push) Skipped
CI / lint (push) Successful in 11s
CI / notify (push) Successful in 6s
- /api/v1/federation: list followers and requests, approve (Accept),
  decline or remove (Reject), block (Block, and future follows are
  refused), list and remove blocks; settings report follower counts
- The actor now reflects the user's real follow-approval setting and
  the followers collection its accepted count
- Turning sharing off sends every follower a Reject and forgets them;
  while those are being delivered the actor stays fetchable with just
  its key (no name or bio) so other servers can verify them, and
  WebFinger already says not found
- Web UI: a Followers page (requests with Approve/Decline, followers
  with Remove/Block behind a confirm step, blocked accounts with
  Unblock; remote names shown as plain text only), follower counts on
  the Sharing page, and a confirmation before turning sharing off
  when that would remove followers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 21:42:29 +01:00
mattandClaude Opus 5.5 142dc13fea Deliver outgoing activities with retries (phase 2, step 5)
CI / lint (push) Successful in 9s
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 8s
CI / test (push) Successful in 1m57s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
The federation.deliver worker task sends queued activities:
- signed POSTs as the user, draft-cavage first and RFC 9421 after a
  401 (double-knocking), several at once (FEDERATION_DELIVERY_
  CONCURRENCY), up to 50 per pass
- 2xx delivered; 410 removes whoever that inbox belongs to as a
  follower and marks them gone; other 4xx (except 401/408/429) are
  abandoned; everything else retries at 1m, 5m, 30m, 2h, 6h, then
  every 12h, abandoned after 2 days
- claiming leases a delivery (pushes its next attempt forward), so a
  crashed worker's sends become due again on their own; claiming
  skips the eager join Postgres can't lock through
- metrics: deliveries by result, delivery time, outgoing signatures,
  queue depths and follower totals (gauges set every 30s)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 21:36:05 +01:00
mattandClaude Opus 5.5 5897e8217f Tests: reuse a pool of RSA keys
CI / lint (push) Successful in 14s
CI / notify (push) Successful in 5s
CI / test (push) Successful in 1m51s
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / validate-monitoring (push) Successful in 8s
CI / assets (push) Skipped
Generating 2048-bit keys for every sharing user and scripted remote
account dominated federation test time. Tests only need distinct valid
keys, so an autouse fixture hands out a pool of 16 generated once per
run (50s -> 40s for the suite).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 21:31:52 +01:00
mattandClaude Opus 5.5 f312c4b577 Inbox: intake and verified processing of follows (phase 2, step 4)
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 14s
CI / test (push) Successful in 1m57s
CI / assets (push) Skipped
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s
Intake (in the request, no network): size, content type and shape
checks, blocked domains refused (403), duplicates acknowledged once,
then stored and answered 202.

Processing (federation.inbox worker task):
- verify the HTTP signature with either scheme, as of when it arrived,
  using the cached key and refreshing the sender once on failure (key
  rotation); a deleted account's Delete still verifies from cache
- the signer must be the activity's actor and the activity id must be
  on the actor's host
- handlers: Follow (accept, or pending with manual approval; repeat
  follows re-accepted; blocked accounts rejected), Undo of a Follow
  (only by the same actor), Delete of an actor, Update of an actor;
  anything else recorded
- items being processed are marked, retried on transient failures,
  re-queued if a worker dies, and pruned after 30 days

Outgoing Accept/Reject/Block activities are stored with stable ids and
queued per inbox for the delivery task (next step). Public activities
are fetchable at /activities/<uuid>. Metrics for inbox activities and
signature checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 21:29:55 +01:00
mattandClaude Opus 5.5 c1a7dd0877 Worker tasks are registered per app
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 10s
CI / python-package (push) Skipped
CI / images (push) Skipped
CI / assets (push) Skipped
CI / notify (push) Successful in 5s
CI / test (push) Successful in 1m46s
The task registry was module-global, so tasks registered by an app with
federation enabled would also run under an app without it (and break
the "federation off registers nothing" guarantee depending on order).
Tasks now live on each app (app.extensions["worker_tasks"]);
register_task/register_periodic take the app, and the worker runs the
current app's tasks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 21:24:41 +01:00
mattandClaude Opus 5.5 d49aa72be1 Federation tables for followers, inbox and deliveries (phase 2, step 3)
CI / lint (push) Successful in 11s
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / test (push) Successful in 1m42s
CI / images (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 7s
New tables on the federation migration branch: followers (pending or
accepted, with the Follow activity), per-user blocks, the inbox queue
(raw deliveries awaiting verification, deduplicated by activity id),
our outgoing activities, and deliveries (per inbox, with retry state).

Inbox URLs are capped at 1024 characters (remote actors are validated
against it) so the delivery unique index stays within Postgres's btree
limit; the remote actor inbox columns shrink to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 21:23:15 +01:00
mattandClaude Opus 5.5 52b9f0b27b Safe outbound HTTP and remote actors (phase 2, step 2)
CI / images (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 10s
CI / test (push) Successful in 1m22s
CI / assets (push) Skipped
CI / python-package (push) Skipped
- net.py: the only client federation uses, on httpcore (BSD-3-Clause)
  with a guarded network backend: https only, every resolved address
  must be public (private, loopback, link-local, CGNAT, multicast and
  IPv4-mapped forms refused), and the connection goes to the checked
  address; 3 redirects max (GET only), 1 MB cap, 10s/20s timeouts
- outbound.py: signed GETs (instance actor, so authorized-fetch servers
  answer) and signed POSTs (as the user), trying the configured
  signature schemes in order and the next only on a 401
- remote.py + federation_remote_actors: fetch, validate (id matches
  URL and host, actor type, inbox on its host, key owned by the actor),
  cache for 24h, refresh on demand, 410 marks an actor gone; resolve a
  key id to its actor, including standalone key documents
- Config: FEDERATION_SIGNATURE_SCHEMES, FEDERATION_BLOCKED_DOMAINS,
  FEDERATION_DELIVERY_CONCURRENCY, and FEDERATION_INSECURE_TESTING
  (http and private addresses; only allowed for .test domains)
- Tests against a real local HTTP server, including verifying that our
  fetches carry a valid signature

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 21:21:00 +01:00
mattandClaude Opus 5.5 a6d3fb6c93 HTTP signatures: draft-cavage and RFC 9421 (phase 2, step 1)
CI / validate-monitoring (push) Successful in 7s
CI / notify (push) Successful in 6s
CI / lint (push) Successful in 12s
CI / test (push) Successful in 1m6s
CI / python-package (push) Skipped
CI / images (push) Skipped
CI / assets (push) Skipped
Pure code in federation/protocol/signatures, one module per scheme and
a registry to pick them by name:
- draft-cavage: sign (request-target) host date digest with rsa-sha256;
  verify rsa-sha256/hs2019, require the ActivityPub minimum, check
  Digest and a ±12h Date window
- RFC 9421: sign @method @target-uri content-digest with
  rsa-v1_5-sha256 and created/keyid/alg; verify with a generic
  signature-base builder, created/expires checks and Content-Digest
  (sha-256/sha-512); includes the RFC 8941 subset these headers use
- Failures carry a reason (missing, malformed, expired,
  digest_mismatch, bad_signature, unsupported, unknown_key,
  insufficient) for metrics

Tested against the published vectors (draft-cavage-12 C.1 and C.2,
RFC 9421's rsa-v1_5-sha256 example; test keys extracted from the
specs into tests/data), round trips, and tampering with body, URL,
method, date, key, coverage and clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 21:15:36 +01:00
mattandClaude Opus 5.5 044f25e2fd Plan for ActivityPub phase 2 (followers)
CI / validate-monitoring (push) Successful in 8s
CI / python-package (push) Skipped
CI / test (push) Successful in 1m3s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / lint (push) Successful in 12s
CI / notify (push) Successful in 5s
Step-by-step plan: both HTTP signature schemes with test vectors, an
SSRF-safe outbound client and remote-actor cache, follower/inbox/
delivery tables, network-free inbox intake with worker processing,
signed Accept/Reject/Block delivery with retries, follower management
API and UI, metrics/alerts, in-process two-instance tests and a
GoToSocial interop job in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:56:59 +01:00
mattandClaude Opus 5.5 6b09e041b8 Document fediverse sharing; mark phase 1 done (phase 1, step 9)
CI / test (push) Successful in 1m7s
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 12s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
README: what sharing does today, how an operator enables it (settings,
UI forwarding, HTTPS), and the permanence of handles and the key
secret. Federation README: key secret, forwarded paths and module
layout. The phase 1 plan is marked done, with the real-Mastodon check
still outstanding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:37:30 +01:00
mattandClaude Opus 5.5 913ef67aca Federation dashboard (phase 1, step 7)
CI / test (push) Successful in 1m5s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 10s
A fifth provisioned Grafana dashboard: fediverse lookups by kind and
result, sharing switched on/off, federation endpoint rates and p95
latency, and inbox deliveries. Dashboard tests now know federation's
own metrics, and a new test rejects PromQL string escapes Prometheus
can't parse (the endpoint filter first used \. and failed live).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:36:42 +01:00
mattandClaude Opus 5.5 f21ce173b8 Tests don't inherit optional features from the local environment
CI / validate-monitoring (push) Successful in 7s
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / test (push) Successful in 1m2s
CI / lint (push) Successful in 13s
CI / assets (push) Skipped
CI / notify (push) Successful in 5s
TestConfig pins FEDERATION_ENABLED off and LASTFM_API_KEY empty, so a
developer's .env (e.g. federation switched on to try it locally) can't
change what the "feature off" tests see. Tests that need a feature turn
it on explicitly (FederatedTestConfig, lastfm_config).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:34:23 +01:00
mattandClaude Opus 5.5 8d12922f6a Serve fediverse paths on the UI's domain (phase 1, step 6)
CI / images (push) Skipped
CI / lint (push) Successful in 12s
CI / test (push) Successful in 1m6s
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / validate-monitoring (push) Successful in 8s
CI / notify (push) Successful in 5s
- The UI container forwards /.well-known/{webfinger,nodeinfo,host-meta},
  /nodeinfo/, /users/, /inbox and /actor to API_INTERNAL_URL (compose:
  http://api:8000), passing Host and X-Forwarded-*; unset means no
  forwarding
- The API's name is resolved per request via the container's resolver,
  so the UI starts before the API and survives API restarts
- Compose passes the FEDERATION_* settings to api and worker;
  .env.example documents them, including FEDERATION_KEY_SECRET
- gunicorn: disable the 26.x control socket (the container user has no
  home directory)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:32:40 +01:00
mattandClaude Opus 5.5 c0b9e85519 Sharing settings and public profile pages (phase 1, step 5)
- sharing.html: switch sharing on/off, see the handle (with the
  "permanent once followed" warning and a note that following comes
  later), choose who sees posts (followers only by default; help text
  on why approval matters), follower approval, directory and search
  opt-ins, display name and bio; save status shown by the button
- profile.html?u=<name>: the public page browsers land on from an actor
  URL: name, handle (with copy), bio and how to follow; never asks the
  visitor to sign in
- "Sharing" appears in the nav only when the server federates
  (remembered per tab)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:32:40 +01:00
mattandClaude Opus 5.5 0b10469514 Sharing settings API, public profiles and ActivityPub docs (phase 1, step 4)
CI / test (push) Successful in 1m5s
CI / images (push) Skipped
CI / lint (push) Successful in 12s
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 7s
- /api/v1/federation/settings (GET, PATCH): sharing on/off, visibility
  (followers-only default), follow approval, discoverable/indexable,
  display name and bio, plus the read-only handle and URLs
- /api/v1/federation/profiles/<name>: public profile for the UI page,
  only for users sharing
- ActivityPub endpoints documented under an ActivityPub tag
- docs/openapi.json is now exported with every optional module on
  (python -m scrobbler.openapi.export); the drift test and route checks
  cover both a federation-off and a federation-on app
- Boundary: federation may use scrobbler.api.get_api to register its
  blueprint; the checker proves other scrobbler.api modules stay off
  limits

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:26:33 +01:00
mattandClaude Opus 5.5 ce39e8f865 ActivityPub discovery endpoints (phase 1, step 3)
CI / images (push) Skipped
CI / notify (push) Successful in 5s
CI / lint (push) Successful in 11s
CI / test (push) Successful in 59s
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / validate-monitoring (push) Successful in 7s
Registered only when federation is enabled:
- WebFinger (acct: and actor-URL resources, the instance actor, CORS *)
- host-meta, NodeInfo discovery and 2.1 (counts users sharing)
- /users/<name>: the Person actor for ActivityPub clients, a redirect to
  the UI profile page for browsers (for any name, so redirects don't
  reveal accounts); outbox/followers/following collections
- /actor: the instance Application actor
- Inboxes accept (202) and count deliveries; size-limited; processing
  arrives in phase 2. Actors advertise manual approval until then.
- Unknown and non-sharing users get byte-identical 404s; all IDs come
  from FEDERATION_BASE_URL, never the request
- Federation metrics: lookups, sharing changes, inbox deliveries
- scrobbler.__version__ joins the core's public surface for NodeInfo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:23:02 +01:00
mattandClaude Opus 5.5 e890568c54 Federation protocol building blocks (phase 1, step 2)
CI / validate-monitoring (push) Successful in 7s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / lint (push) Successful in 12s
CI / test (push) Successful in 57s
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s
Pure, framework-free code in federation/protocol:
- media: ActivityPub content types and Accept negotiation
- vocab: actor URLs, Person and Application actors (Mastodon's extension
  terms), public keys, collections, plain text to safe HTML
- webfinger: acct:/actor-URL resource parsing (other domains and bad
  usernames rejected) and JRD documents
- nodeinfo: discovery and NodeInfo 2.1; hostmeta: XRD pointing at
  WebFinger

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:20:24 +01:00
mattandClaude Opus 5.5 98c65547f3 Federation data and actor keys (phase 1, step 1)
CI / images (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 11s
CI / test (push) Successful in 57s
CI / assets (push) Skipped
CI / python-package (push) Skipped
- federation_settings (per user; off, followers-only, not discoverable
  by default) and federation_keys (RSA-2048; NULL user = instance
  actor), on the federation migration branch
- Private keys encrypted at rest with Fernet, keyed by HKDF-SHA256 from
  FEDERATION_KEY_SECRET (now required, 32+ chars, never printed)
- Keys are created when a user first enables sharing and never
  regenerated; sharing.shared_user() treats unknown and non-sharing
  users identically
- One flask-smorest Api per app (get_api(app)), so apps with and
  without federation never share an OpenAPI spec
- Test fixtures for a second, federation-enabled app on the same DB

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:19:14 +01:00
mattandClaude Opus 5.5 00ad8e9e6d ActivityPub decisions: UI domain, followers-only posts; phase 1 plan
CI / validate-monitoring (push) Successful in 8s
CI / assets (push) Skipped
CI / lint (push) Successful in 13s
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
CI / test (push) Successful in 48s
- Handles and actor URLs live on the web UI's domain; the UI's nginx
  forwards the ActivityPub paths to the API
- Posts default to followers only, settable per user, with the privacy
  caveat about automatic follow approval spelled out
- docs/design/activitypub-phase1.md: the discoverable-profile phase,
  step by step

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:10:08 +01:00
mattandClaude Opus 5.5 cae97380fc Mark ActivityPub phase 0 as done
CI / notify (push) Successful in 5s
CI / lint (push) Successful in 11s
CI / test (push) Successful in 47s
CI / validate-monitoring (push) Successful in 7s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:02:09 +01:00
mattandClaude Opus 5.5 eb5802f420 Federation boundary tests (phase 0, step 5)
CI / lint (push) Successful in 12s
CI / test (push) Successful in 48s
CI / images (push) Skipped
CI / notify (push) Successful in 6s
CI / validate-monitoring (push) Successful in 7s
CI / assets (push) Skipped
CI / python-package (push) Skipped
Static checks (ast, so imports inside functions and relative imports
count): nothing outside scrobbler.federation imports it except
create_app; federation.protocol imports no framework or scrobbler code;
the rest of federation uses only the core's public surface (events,
extensions, worker, services, api.decorators, schemas). The checker is
itself tested against deliberate violations and permitted imports.

Runtime checks: with federation off no federation views, event
receivers or worker tasks exist; enabling it needs a bare domain and
an https base URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 20:00:56 +01:00
mattandClaude Opus 5.5 c79c42ee00 Federation module skeleton and its own migration branch (phase 0, steps 3-4)
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 12s
CI / notify (push) Successful in 5s
CI / test (push) Successful in 50s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
- scrobbler.federation with init_app() as its only entry point, called
  from create_app(); does nothing unless FEDERATION_ENABLED
- FederationConfig validates FEDERATION_DOMAIN (bare host) and
  FEDERATION_BASE_URL (https) when enabled, with clear errors
- federation/protocol/ package for pure, framework-free protocol code
- Package README with the boundary rules, configuration and migration
  workflow; .env.example lists the settings (off)
- Alembic: existing history labelled `core`; new empty `federation`
  branch root (depends on the core users table). Everything upgrades
  `heads` (entrypoint, CI, tests); tests check both branches apply and
  that federation can be removed without touching core

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 19:59:47 +01:00
mattandClaude Opus 5.5 098eab025f Generic background worker (phase 0, step 2)
CI / lint (push) Failing after 38s
CI / images (push) Skipped
CI / validate-monitoring (push) Successful in 8s
CI / notify (push) Successful in 5s
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / test (push) Successful in 46s
scrobbler/worker.py runs tasks that modules register: queue tasks
(called while they report work) and periodic tasks. A failing task is
logged, counted, rolled back and doesn't stop the others. Imports are
now just a registered task plus a periodic stall check.

- `flask worker` replaces `flask imports worker` (kept as an alias);
  compose uses the new command
- scrobbler_worker_tasks_total{task,outcome} and a Worker tasks panel
  on the Usage dashboard
- WORKER_METRICS_PORT (IMPORT_WORKER_METRICS_PORT still honoured)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 19:57:25 +01:00
mattandClaude Opus 5.5 59ff1bdfa0 Domain events for optional modules (phase 0, step 1)
CI / test (push) Successful in 48s
CI / assets (push) Skipped
CI / lint (push) Successful in 9s
CI / validate-monitoring (push) Successful in 7s
CI / images (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
scrobbler/events.py defines blinker signals sent after commit:
scrobbles_stored (newly stored plays only, source scrobble/import),
now_playing_changed (track or None) and import_finished. A receiver
that raises is logged and skipped, so optional modules can't break
scrobbling or imports. store_chunk now reports which plays it stored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 19:54:27 +01:00
mattandClaude Opus 5.5 247c94a79c Plan for ActivityPub phase 0 (groundwork)
CI / test (push) Successful in 44s
CI / assets (push) Skipped
CI / images (push) Skipped
CI / validate-monitoring (push) Successful in 7s
CI / python-package (push) Skipped
CI / lint (push) Successful in 10s
CI / notify (push) Successful in 5s
Step-by-step plan: domain events, a generic worker with imports moved
onto it, the empty federation module and config, separate Alembic
branches, and boundary tests enforcing the module rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 19:52:39 +01:00
mattandClaude Opus 5.5 5d71116613 ActivityPub design: build in-house as one replaceable module
CI / notify (push) Successful in 5s
CI / assets (push) Skipped
CI / lint (push) Successful in 14s
CI / images (push) Skipped
CI / validate-monitoring (push) Successful in 9s
CI / test (push) Successful in 49s
CI / python-package (push) Skipped
- Settles build vs buy: write it ourselves (Scrobbler is BSD-3-Clause;
  the Python library option is AGPL)
- New "Module structure" section: everything in scrobbler.federation,
  a pure protocol/ subpackage for spec-dependent code, pluggable
  signature schemes/inbox handlers/post kinds, core → federation only
  via blinker domain events, own federation_* tables in a separate
  Alembic branch, generic task worker, and boundary tests enforcing it
- Adds a groundwork phase 0 and updates the open decisions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 19:48:04 +01:00
matt caf1d3c2f8 Merge branch 'main' into feature/activitypub 2026-09-25 19:47:16 +01:00
mattandClaude Opus 5.5 373efbcb2d License under BSD 3-Clause
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 11s
CI / test (push) Successful in 44s
CI / python-package (push) Skipped
CI / images (push) Successful in 1m31s
CI / assets (push) Successful in 10s
Adds LICENSE, the licence expression and file in the package metadata,
an OCI licence label on both images, and a Licence section in the README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 19:47:06 +01:00
mattandClaude Opus 5.5 d2c71d50f1 Design proposal: ActivityPub federation
CI / test (push) Successful in 44s
CI / python-package (push) Skipped
CI / notify (push) Successful in 7s
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 11s
CI / images (push) Skipped
CI / assets (push) Skipped
Research write-up for making Scrobbler users followable from the
fediverse: protocol pieces (WebFinger, actor, inbox, signatures in both
draft-cavage and RFC 9421, delivery), what gets posted (weekly summary,
milestones, now playing), build-vs-library, data model, security,
testing against GoToSocial, phased plan and open decisions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-25 19:36:45 +01:00
148 changed files with 18303 additions and 299 deletions

No files matched your search

+1
View File
@@ -11,3 +11,4 @@ tests
docs
deploy/grafana
deploy/prometheus
# (scripts/interop is used by the interop driver image)
+12
View File
@@ -16,9 +16,21 @@ METRICS_PORT=9100
# Set to allow importing history straight from Last.fm (https://www.last.fm/api/account/create).
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=
# docker compose host ports (defaults shown)
API_PORT=5050
UI_PORT=8080
PROMETHEUS_PORT=9090
GRAFANA_PORT=3000
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=
+38 -5
View File
@@ -52,7 +52,7 @@ jobs:
- run: uv sync --locked
- name: Migrations are in sync with the models
run: |
uv run flask --app scrobbler db upgrade
uv run flask --app scrobbler db upgrade heads
uv run flask --app scrobbler db check
- run: uv run pytest
@@ -77,14 +77,31 @@ jobs:
- name: Dashboards are valid JSON
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 Scrobbler 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: Scrobbler <-> GoToSocial
env:
INTEROP_PROJECT: interop-${{ github.run_id }}
run: |
# A subnet of its own, so concurrent runs can't collide
export INTEROP_SUBNET="172.30.$(( ${{ github.run_number }} % 200 + 20 )).0/24"
scripts/interop/run.sh
# ---- Publishing (main and v* tags only) -------------------------------------
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'))
runs-on: ubuntu-latest
outputs:
tags: ${{ steps.version.outputs.image_tags }}
version: ${{ steps.version.outputs.version }}
steps:
- uses: actions/checkout@v4
- uses: https://github.com/astral-sh/setup-uv@v6
@@ -123,7 +140,7 @@ jobs:
run: docker logout "${{ vars.PKGS_HOST }}" || true
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'))
runs-on: ubuntu-latest
steps:
@@ -147,7 +164,7 @@ jobs:
done
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')
runs-on: ubuntu-latest
steps:
@@ -163,8 +180,24 @@ jobs:
--publish-url "https://${{ vars.PKGS_HOST }}/pypi/${{ vars.PKGS_PYPI_FEED }}/legacy"
--username api --password "${{ secrets.PKGS_API_KEY }}"
trigger-deploy:
needs: [images]
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
- name: Trigger ScrobbledDeploy
env:
VERSION: ${{ needs.images.outputs.version }}
TOKEN: ${{ secrets.SCROBBLEDDEPLOY_DISPATCH_TOKEN }}
run: |
curl -fsS -X POST \
-H "Authorization: token ${TOKEN}" \
-H "Content-Type: application/json" \
-d "{\"ref\":\"main\",\"inputs\":{\"image_tag\":\"${VERSION}\"}}" \
"https://git.daubney.dev/api/v1/repos/matt/ScrobbledDeploy/actions/workflows/deploy.yml/dispatches"
notify:
needs: [lint, test, validate-monitoring, images, assets, python-package]
needs: [lint, test, validate-monitoring, federation-interop, images, assets, python-package, trigger-deploy]
if: always()
runs-on: ubuntu-latest
steps:
+28
View File
@@ -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.
+24 -149
View File
@@ -1,6 +1,10 @@
# Scrobbler
A self-hosted music scrobbling service. It speaks the **Last.fm (Audioscrobbler 2.0) API**, so players and scrobblers that let you set a custom Last.fm server can use it unchanged. It also has a web UI for your listening history.
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
@@ -9,160 +13,31 @@ web UI (static files) ──► API /api/v1/ JSON API for the UI
Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
```
- **API** (`src/scrobbler/`): Flask under gunicorn. It is API-only and serves no pages.
- **Web UI** (`frontend/`): plain HTML, CSS and JavaScript with no build step. Host it anywhere static files can be served.
- **Docs**: OpenAPI at `/api/openapi.json`, Swagger UI at `/api/docs` and ReDoc at `/api/redoc`. A copy of the spec is committed at `docs/openapi.json`.
- **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.
## Docs
## 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
cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD
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
SCROBBLER_IMAGE_TAG=main docker compose up -d --no-build
```
The images are `pkgs.daubney.dev/scrobbler/scrobbler-api` and `pkgs.daubney.dev/scrobbler/scrobbler-ui`.
### Configuration
| Variable | Used by | Default | Purpose |
|---|---|---|---|
| `DATABASE_URL` | api | local Postgres | SQLAlchemy URL (`postgresql+psycopg://…`) |
| `SECRET_KEY` | api | `dev-insecure-secret` | Flask secret |
| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated UI origins allowed to call `/api/v1` |
| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins |
| `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` |
| `METRICS_PORT` | api | `9100` | Prometheus metrics port (keep it off the public network) |
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
| `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.
BSD 3-Clause; see [LICENSE](LICENSE). The fonts vendored in `frontend/fonts/` are under
the SIL Open Font License 1.1.
File diff suppressed because it is too large. Load diff
+65 -4
View File
@@ -572,7 +572,7 @@
},
{
"type": "row",
"title": "Imports",
"title": "Background work",
"id": 13,
"collapsed": false,
"gridPos": {
@@ -878,6 +878,67 @@
"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",
"title": "Import duration (p95)",
@@ -921,10 +982,10 @@
"sort": "desc"
}
},
"id": 19,
"id": 20,
"gridPos": {
"x": 12,
"y": 38,
"x": 0,
"y": 46,
"w": 12,
"h": 8
}
+84
View File
@@ -0,0 +1,84 @@
# Federation interop test: Scrobbler 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; Scrobbler 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
networks:
fedi:
ipam:
config:
- subnet: ${INTEROP_SUBNET:-172.30.0.0/24}
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_SUBNET:-172.30.0.0/24} # let it reach Scrobbler on this network
GTS_HTTP_CLIENT_TLS_INSECURE_SKIP_VERIFY: "true" # Caddy's throwaway certificate
GTS_TRUSTED_PROXIES: ${INTEROP_SUBNET:-172.30.0.0/24}
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]
+5
View File
@@ -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"]
+10 -1
View File
@@ -1,4 +1,10 @@
# 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 {
listen 80;
server_name _;
@@ -12,11 +18,14 @@ server {
try_files $uri $uri/ =404;
# Files aren't fingerprinted, so always revalidate.
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 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/ {
add_header Cache-Control "public, max-age=2592000, immutable";
}
+34
View File
@@ -73,6 +73,40 @@ groups:
summary: Imports have been waiting for 15 minutes with nothing running
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: PostgresDown
expr: pg_up == 0
for: 2m
+14 -3
View File
@@ -29,11 +29,16 @@ services:
environment:
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
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}
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
FORWARDED_ALLOW_IPS: "*"
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-}
ports:
- "${API_PORT:-5050}:8000"
expose:
@@ -42,17 +47,21 @@ services:
db:
condition: service_healthy
# Processes history imports (uploaded exports and pulls from Last.fm).
# Background work: history imports, and tasks registered by optional modules.
worker:
image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-api:${SCROBBLER_IMAGE_TAG:-local}
build:
context: .
dockerfile: docker/api.Dockerfile
command: ["flask", "--app", "scrobbler", "imports", "worker"]
command: ["flask", "--app", "scrobbler", "worker"]
environment:
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
SECRET_KEY: ${SECRET_KEY:-change-me}
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
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
expose:
- "9101" # metrics: internal network only
@@ -69,6 +78,8 @@ services:
dockerfile: docker/ui.Dockerfile
environment:
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:
- "${UI_PORT:-8080}:80"
+1 -1
View File
@@ -3,6 +3,6 @@
set -e
if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then
# 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
exec "$@"
+1
View File
@@ -11,6 +11,7 @@ COPY src ./src
RUN uv sync --locked --no-dev --no-editable
FROM python:3.13-slim
LABEL org.opencontainers.image.licenses="BSD-3-Clause"
RUN useradd --system --uid 10001 --no-create-home scrobbler
WORKDIR /app
COPY --from=build /app/.venv /app/.venv
+34 -1
View File
@@ -1,5 +1,6 @@
#!/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
case "$API_BASE_URL" in
http://*|https://*) ;;
@@ -11,3 +12,35 @@ window.SCROBBLER_CONFIG = {
apiBaseUrl: "$url",
};
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
View File
@@ -1,5 +1,6 @@
# Scrobbler web UI: static files served by nginx.
FROM nginx:1.29-alpine
LABEL org.opencontainers.image.licenses="BSD-3-Clause"
ENV API_BASE_URL=http://localhost:5050
COPY deploy/nginx/default.conf.template /etc/nginx/templates/default.conf.template
COPY docker/ui-config.sh /docker-entrypoint.d/40-scrobbler-config.sh
+264
View File
@@ -0,0 +1,264 @@
# Admin guide
Running a real Scrobbler instance: architecture, installation, configuration, TLS,
fediverse sharing, monitoring, backups, upgrades and troubleshooting. If you're using an
instance someone else runs, see the [user guide](user-guide.md) instead. If you're
working on Scrobbler's own code, see [setup.md](setup.md).
## 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 and background tasks for optional
modules (federation's deliveries, scheduled posts, and so on).
- **`db`**: PostgreSQL.
- With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`.
Everything Scrobbler needs to run is in these five services plus optional monitoring —
there's no separate cache, queue or search service to operate.
## Installing
```sh
cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD
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 Scrobbler. Before putting it in front of real users, also
read **Putting it behind TLS** below — the quick start above serves plain HTTP only.
## Configuration
| Variable | Used by | Default | Purpose |
|---|---|---|---|
| `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` |
| `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 | `UI_BASE_URL` | Contact URL/email sent to MusicBrainz for album art lookups (no key needed, but they ask for one) |
| `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
Scrobbler itself only speaks plain HTTP; something in front of it needs to terminate
TLS. Any reverse proxy works — nginx, Caddy, or a tunnel like Cloudflare Tunnel for
testing without a public IP (see `docs/design/activitypub-phase4.md` for how the
project's own manual federation test used one).
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
**Scrobbler** 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.
## 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 Scrobbler API at …" or
requests failing silently).** Almost always `CORS_ORIGINS` on the `api` service not
listing the exact origin the browser loads the UI from (scheme and host both have to
match — `https://scrobble.example` is not the same origin as `http://scrobble.example`
or `www.scrobble.example`). Check with:
```sh
curl -i -X OPTIONS https://scrobble.example/api/v1/auth/me \
-H "Origin: https://scrobble.example" -H "Access-Control-Request-Method: GET"
```
A missing `access-control-allow-origin` header in the response confirms it. This is
separate from `UI_BASE_URL` — setting one does not set the other.
**Federation looks enabled but the "Sharing" page/nav link doesn't appear for a user.**
First confirm federation is actually on server-side, independent of what any log line
says (gunicorn drops `log.info` by default unless something configures logging):
```sh
curl -o /dev/null -w '%{http_code}\n' https://scrobble.example/actor # 200 = federation is on
```
If that's `200`, the server is fine and the problem is client-side: the web UI caches
whether federation is available in the browser's `sessionStorage` for the tab, and
caches static JS in the ordinary browser cache. Ask the user to hard-refresh
(Ctrl/Cmd+Shift+R) or try a private window — if it works there, it's a stale cache, not
a server problem.
**A fediverse profile 404s from a specific remote server (e.g. mastodon.social) right
after you enable sharing, even though WebFinger looks correct from curl.** Large
instances cache a *negative* WebFinger lookup for a while. Confirm the server's own
response is correct first:
```sh
curl -H 'Accept: application/jrd+json' \
'https://scrobble.example/.well-known/webfinger?resource=acct:name@scrobble.example'
```
If that's correct, the fix is time (or trying a smaller/different instance to confirm
it's not a Scrobbler-side problem) — there's nothing to change on the server.
**A legacy scrobbler client (e.g. VLC's built-in scrobbler) fails to connect at all.**
Scrobbler implements the Last.fm 2.0 API only, not the legacy 1.2 Audioscrobbler
handshake (`hs=true&p=1.2&...`). Clients that only speak 1.2 can't be pointed at
Scrobbler regardless of configuration — point users at a client with 2.0 support
instead.
+90
View File
@@ -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.
+118
View File
@@ -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.
+214
View File
@@ -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 Scrobbler instances.** Scrobbler 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. Scrobbler 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 `Scrobbler/<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 Scrobbler (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 Scrobbler'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, Scrobbler, so it has no effect on Scrobbler'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.
+192
View File
@@ -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: `#Scrobbler`, 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)
> #Scrobbler
**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 Scrobbler 🎉"* 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 | `#Scrobbler` on every post |
| Deleting individual posts | Allowed, from the web UI |
+117
View File
@@ -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 Scrobbler 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 `#Scrobbler` (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 | `#Scrobbler` and `#NowPlaying` |
+403
View File
@@ -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 Scrobbler 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**: Scrobbler 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). Scrobbler 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, … Scrobbler
────────────────────────────────────────────────────────────────────────────
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 Scrobbler 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`, `#Scrobbler`) 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)
> #Scrobbler
### 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.** Scrobbler 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 Scrobbler 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 Scrobbler 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 Scrobbler 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 Scrobbler 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.
+2024 -1
View File
File diff suppressed because it is too large. Load diff
+106
View File
@@ -0,0 +1,106 @@
# Working on Scrobbler
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 Scrobbler 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.
+119
View File
@@ -0,0 +1,119 @@
# User guide
What Scrobbler does once you're signed in: connecting a player, importing your old
history, and sharing your listening on the fediverse. If you're setting up or running an
instance rather than using one, see the [admin guide](admin-guide.md) instead.
## Getting started
Register in the web UI, then go to **Apps** and create one app per player or scrobbler
client you use — each gets its own API key and shared secret, and can be revoked on its
own from the **Sessions** page without affecting the others. If a friend runs your
instance, ask them for its address; that's the only thing you need from them to get
going.
## Connecting a player
In the player's scrobbling settings, choose a custom or self-hosted Last.fm server:
- **API URL**: `https://your-host/2.0/`
- **API key and shared secret**: from an app on the **Apps** page
- **Username and password**: your Scrobbler account
Two sign-in flows are supported, and most players use one or the other automatically:
- **Mobile**: you enter your username and password directly in the player.
- **Desktop**: the player opens a browser page for you to approve, then signs itself in
— no password ever passed to the player.
A sign-in method that hashes your password before sending it (sometimes offered as a
"stored password" or "password hash" option, e.g. pylast's `password_hash`) isn't
supported — use the plain username/password or desktop-approval flow instead.
Supported methods, if your player lets you check: `auth.getMobileSession`,
`auth.getToken`, `auth.getSession`, `track.scrobble` (up to 50 per request),
`track.updateNowPlaying`, `user.getInfo`, `user.getRecentTracks`, `user.getTopArtists`,
`user.getTopAlbums`, `user.getTopTracks`. `/api/docs` on your instance has the full
parameters and example responses for each, if you're curious or debugging a client.
A play is silently skipped (not rejected as an error) if the artist or track name is
empty, or its timestamp is more than 14 days old or more than 5 minutes in the future.
Sending the same play twice — a common side effect of a player retrying after a network
blip — is accepted both times but only stored once, so retries are always safe.
**A legacy scrobbler that speaks the old 1.2 "handshake" protocol (rather than 2.0) won't
work here** — this is a client limitation, not a setting to fix. VLC's built-in
scrobbler is one example; look for a plugin or a different player with 2.0 support.
## Importing history
Open **Import** in the web UI:
- **An export file**:
- CSV from [lastfm-to-csv](https://benjaminbenben.com/lastfm-to-csv/), no header row,
artist/album/track/date columns.
- Any CSV or TSV with a header row naming artist, track and a date or Unix-time
column. Comma, semicolon and tab delimiters all work.
- A JSON export of `user.getRecentTracks` pages (such as lastfm.ghan.nl's), a single
`recenttracks` response, or a flat list of tracks.
- Files can be gzipped.
- **Last.fm directly**: enter a Last.fm username and the import runs against that
account's public history. Only appears if your instance's admin has set this up.
Imports run in the background — the page shows progress and you can cancel one in
flight. Unlike live scrobbles, imports keep plays of any age (still skipping rows with no
artist or track, or plays dated in the future). Plays already in your history are
skipped, so importing the same export again, or importing overlapping exports, is safe.
## Sharing on the fediverse
Only available if your instance's admin has turned this on — ask them, or check whether
**Sharing** appears in the navigation. Turn it on there, and you're findable as
`@name@<your instance's host>` from Mastodon and other fediverse apps.
- Follows are accepted automatically, or wait for your approval if you turn that on
under **Followers and discovery**.
- **Followers** lists requests, followers and blocked accounts, with approve, decline,
remove, block and unblock.
Once someone follows you, **Sharing**'s **What to post** section controls what they see:
- **Weekly summary**: your play count and top artist(s), posted once a week (Monday
09:00 in your own time zone, for the week that just ended). A live preview shows what
it would say so far.
- **Milestones**: total scrobbles, an artist's plays, and a new entry into your all-time
top 10 — each posted once, the first time you reach it. History already on file when
you turn sharing on, or added by an import, is never posted about retroactively.
Both are on by default and can be switched off independently. Posts use the same
visibility as your profile (followers only by default, or unlisted/public); **Posts**
lists your own posts, each with a delete button.
**Now playing** is a separate, three-way choice:
- **Off** (default): nothing shown or posted.
- **Show on my profile**: a "Now playing: *Track* by Artist" field on your profile,
refreshed at most every 5 minutes while something's playing and cleared a few minutes
after it stops.
- **Show on my profile and post**: the profile field, plus a post for each track played
30 seconds or more, at most one every 30 minutes, with the previous now-playing post
deleted once the new one is confirmed published.
**Your handle can't change once anyone follows you** — if you get to choose the
instance's domain yourself, or you're choosing which instance to join, bear that in mind
before you start sharing.
## Troubleshooting
**I turned Sharing on but can't see it in the menu.** Try a hard refresh
(Ctrl/Cmd+Shift+R) or a private/incognito window. The menu remembers whether sharing is
available for the length of a browser tab, so it can lag behind a setting your admin just
changed.
**My profile 404s on a big instance like mastodon.social right after I start sharing.**
Some servers cache a "not found" for a little while after they first look you up. Give it
an hour, or try searching from a smaller instance to confirm your handle really works.
**A change I made under Sharing doesn't seem to have taken effect.** Make sure you
clicked **Save sharing settings** at the bottom of the page — ticking a box alone doesn't
save it.
+305
View File
@@ -582,6 +582,16 @@ input {
background: var(--slate);
}
.ranking a.name {
color: inherit;
text-decoration: none;
}
.ranking a.name:hover,
.ranking a.name:focus-visible {
text-decoration: underline;
}
/* ---- Listening log -------------------------------------------------------- */
.log {
list-style: none;
@@ -615,6 +625,22 @@ input {
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 {
margin: 2rem 0 0.25rem;
font-size: var(--step-0);
@@ -844,3 +870,282 @@ input {
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 .brand-mark's small round "lamp" motif */
.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 */
}
+32
View File
@@ -0,0 +1,32 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Followers · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/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>
+10 -1
View File
@@ -14,6 +14,14 @@
<main id="main">
<h1 class="visually-hidden">Overview</h1>
<div id="panel" class="panel" aria-live="polite"></div>
<section aria-labelledby="song-search-title" class="song-search">
<h2 id="song-search-title" class="visually-hidden">Find a song</h2>
<div class="field">
<label for="song-search">Find a song</label>
<input id="song-search" type="search" autocomplete="off" placeholder="Search your scrobbles…">
</div>
<ul class="search-results" id="song-search-results" hidden></ul>
</section>
<section aria-labelledby="charts-title">
<div class="section-head">
<h2 id="charts-title">Most played</h2>
@@ -23,6 +31,7 @@
</div>
<div class="charts">
<div><h3 class="muted">Artists</h3><ol class="ranking" id="top-artists"></ol></div>
<div><h3 class="muted">Albums</h3><ol class="ranking ranking-art" id="top-albums"></ol></div>
<div><h3 class="muted">Tracks</h3><ol class="ranking" id="top-tracks"></ol></div>
</div>
</section>
@@ -31,7 +40,7 @@
<h2 id="recent-title">Recently played</h2>
<a href="history.html">Full history</a>
</div>
<ol class="log" id="recent"></ol>
<ol class="log log-stacked log-art" id="recent"></ol>
</section>
</main>
</body>
+23
View File
@@ -40,6 +40,29 @@ export function redirectToLogin() {
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 } = {}) {
const headers = {};
if (body !== undefined) headers["Content-Type"] = "application/json";
+31
View File
@@ -0,0 +1,31 @@
// 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
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 = `${artist.toLowerCase()}␟${album.toLowerCase()}`;
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;
}
+84 -61
View File
@@ -1,6 +1,8 @@
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 { spectrum } from "./spectrum.js";
const PERIODS = [
["7day", "7 days"],
@@ -9,7 +11,6 @@ const PERIODS = [
["overall", "All time"],
];
const PERIOD_KEY = "scrobbler.period";
const SEGMENTS = 10; // lit segments per spectrum column at the busiest day
const NOW_PLAYING_POLL_MS = 30_000;
const panel = document.getElementById("panel");
@@ -19,6 +20,7 @@ let progressTimer;
await signedInPage("index.html");
renderPeriodSelector();
initSongSearch();
await Promise.all([loadPanel(), loadTop(currentPeriod()), loadRecent()]).catch(showError);
setInterval(() => refreshDisplay().catch(() => {}), NOW_PLAYING_POLL_MS);
@@ -117,55 +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 ------------------------------------------------------------
function currentPeriod() {
@@ -199,39 +152,103 @@ function renderPeriodSelector() {
}
async function loadTop(period) {
const [artists, tracks] = await Promise.all([
const [artists, albums, tracks] = await Promise.all([
api(`/me/top/artists?period=${period}&limit=10`),
api(`/me/top/albums?period=${period}&limit=10`),
api(`/me/top/tracks?period=${period}&limit=10`),
]);
renderRanking(document.getElementById("top-artists"), artists.items, false);
renderRanking(document.getElementById("top-tracks"), tracks.items, true);
renderRanking(document.getElementById("top-albums"), albums.items, true, 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) {
replace(list, h("li", { class: "empty" }, "No plays in this period."));
return;
}
const max = items[0].playcount;
const meterOffset = withArt ? "5.75rem" : "2.75rem";
replace(
list,
items.map((item) =>
h(
items.map((item) => {
const by = withArtist ? h("span", { class: "by" }, item.artist) : null;
const name = linkToSong
? h("a", { class: "name", href: songHref(item.artist, item.name) }, item.name, by)
: h("span", { class: "name" }, item.name, by);
return h(
"li",
{},
withArt ? artThumb(item.artist, item.name) : null,
h("span", { class: "rank" }, item.rank),
h("span", { class: "name" }, item.name, withArtist ? h("span", { class: "by" }, item.artist) : null),
name,
h("span", { class: "plays" }, num(item.playcount)),
h("span", {
class: "meter",
"aria-hidden": "true",
style: `width: calc((100% - 2.75rem) * ${item.playcount / max})`,
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 ----------------------------------------------------------
async function loadRecent() {
@@ -247,8 +264,14 @@ async function loadRecent() {
h(
"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("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),
),
),
),
);
+143
View File
@@ -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"),
),
);
}
+3 -1
View File
@@ -1,4 +1,5 @@
import { api } from "./api.js";
import { artThumb } from "./art.js";
import { errorBox, formatDay, formatTime, h, num, replace } from "./dom.js";
import { signedInPage } from "./layout.js";
@@ -38,11 +39,12 @@ function render(result) {
h("h2", { class: "log-day" }, formatDay(scrobbles[0].played_at)),
h(
"ol",
{ class: "log log-clock" },
{ class: "log log-clock log-art" },
scrobbles.map((s) =>
h(
"li",
{},
artThumb(s.album_artist || s.artist, s.album),
h("time", { datetime: s.played_at }, formatTime(s.played_at)),
h(
"span",
+33
View File
@@ -20,6 +20,7 @@ export async function signedInPage(active) {
const header = document.getElementById("site-header");
replace(header, brand(), nav(active));
const user = await api("/auth/me");
addSharingLink(header.querySelector("nav ul"), active);
header.append(
h(
"div",
@@ -61,3 +62,35 @@ async function signOut() {
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")));
}
+40
View File
@@ -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} · Scrobbler`;
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),
);
}
+80
View File
@@ -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,
),
);
}
+46
View File
@@ -0,0 +1,46 @@
import { api } from "./api.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} · Scrobbler`;
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,
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),
);
}
+179
View File
@@ -0,0 +1,179 @@
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",
"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,
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;
}
}
+118
View File
@@ -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} · Scrobbler`;
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"),
);
}
+55
View File
@@ -0,0 +1,55 @@
// A segmented level meter: daily play counts drawn as columns of lit/unlit segments,
// like a hi-fi spectrum analyser. Shared by the dashboard (30 days, all plays) and the
// song page (90 days, one track).
import { formatDate, h, num } from "./dom.js";
const SEGMENTS = 10; // lit segments per column at the busiest day
export function spectrum(counts, subject = "Plays", windowLabel = "30 days") {
const NS = "http://www.w3.org/2000/svg";
const width = 1000;
const height = 96;
const gap = 4;
const max = Math.max(1, ...counts.map((c) => c.count));
const columnWidth = width / counts.length;
const segmentHeight = height / SEGMENTS;
const total = counts.reduce((sum, c) => sum + c.count, 0);
const svg = document.createElementNS(NS, "svg");
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
svg.setAttribute("preserveAspectRatio", "none");
svg.setAttribute("role", "img");
svg.setAttribute("aria-label", `${subject} per day over the last ${counts.length} days: ${num(total)} in total`);
counts.forEach((day, i) => {
const lit = day.count ? Math.max(1, Math.round((day.count / max) * SEGMENTS)) : 0;
const group = document.createElementNS(NS, "g");
const title = document.createElementNS(NS, "title");
title.textContent = `${formatDate(day.start)}: ${num(day.count)} ${day.count === 1 ? "play" : "plays"}`;
group.append(title);
for (let s = 0; s < SEGMENTS; s++) {
const rect = document.createElementNS(NS, "rect");
rect.setAttribute("x", i * columnWidth + gap / 2);
rect.setAttribute("y", height - (s + 1) * segmentHeight + 1.5);
rect.setAttribute("width", columnWidth - gap);
rect.setAttribute("height", segmentHeight - 3);
rect.setAttribute("class", s < lit ? "seg-on" : "seg-off");
group.append(rect);
}
svg.append(group);
});
return h(
"div",
{ class: "spectrum" },
svg,
h(
"div",
{ class: "spectrum-axis" },
h("span", {}, formatDate(counts[0].start)),
h("span", {}, `${num(total)} ${subject.toLowerCase()} in ${windowLabel}`),
h("span", {}, "Today"),
),
);
}
+18
View File
@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Post · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/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>
+21
View File
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Posts · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/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>
+18
View File
@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Profile · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/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>
+124
View File
@@ -0,0 +1,124 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sharing · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/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>
<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>
+25
View File
@@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Song · Scrobbler</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='7' fill='%231c2330'/%3E%3Ccircle cx='8' cy='8' r='3.5' fill='%23f2a541'/%3E%3C/svg%3E">
<link rel="stylesheet" href="css/style.css">
<script src="config.js"></script>
<script type="module" src="js/song.js"></script>
</head>
<body>
<header class="site-header" id="site-header"></header>
<main id="main">
<h1 class="visually-hidden">Song</h1>
<div id="panel" class="panel" aria-live="polite"></div>
<dl class="song-meta" id="song-meta"></dl>
<section aria-labelledby="song-history-title">
<h2 id="song-history-title">History</h2>
<div id="song-history"></div>
<nav class="pager" aria-label="Pages" id="pager"></nav>
</section>
</main>
</body>
</html>
+2
View File
@@ -12,6 +12,8 @@ bind = os.environ.get("BIND", "0.0.0.0:8000")
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
accesslog = "-"
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 on_starting(server):
+4
View File
@@ -3,14 +3,18 @@ name = "scrobby"
version = "0.1.0"
description = "Self-hosted, Last.fm-compatible music scrobbling service"
readme = "README.md"
license = "BSD-3-Clause"
license-files = ["LICENSE"]
requires-python = ">=3.13"
dependencies = [
"cryptography>=50.0.1",
"flask>=3.1.3",
"flask-cors>=6.0.5",
"flask-migrate>=4.1.0",
"flask-smorest>=0.47.0",
"flask-sqlalchemy>=3.1.1",
"gunicorn>=26.2.0",
"httpcore>=1.0.9",
"prometheus-client>=0.26.0",
"psycopg[binary]>=3.3.6",
"python-dotenv>=1.2.3",
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
# docker compose for the federation interop stack (Scrobbler + GoToSocial).
set -euo pipefail
root="$(cd "$(dirname "$0")/../.." && pwd)"
# INTEROP_PROJECT and INTEROP_SUBNET let 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" "$@"
+437
View File
@@ -0,0 +1,437 @@
"""Federation interop test: a real GoToSocial account follows a Scrobbler 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 Scrobbler:
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 Scrobbler: {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 Scrobbler 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 Scrobbler")
alice = Scrobbler()
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("Scrobbler to list the follower", lambda: alice.followers("accepted"))
print(f" Scrobbler follower: {followers[0]['handle']}")
if followers[0]["handle"] != "@gtsuser@gts.test":
fail(f"unexpected follower {followers[0]['handle']}")
step("Unfollow: Scrobbler drops the follower (their signed Undo verified)")
gts.unfollow(account_id)
wait_for("Scrobbler 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("Scrobbler 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: Scrobbler 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("Scrobbler 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("Scrobbler 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 = Scrobbler() # 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()
+71
View File
@@ -0,0 +1,71 @@
#!/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 ] || "$compose" down -v --remove-orphans >/dev/null 2>&1; }
trap cleanup EXIT
"$compose" down -v --remove-orphans >/dev/null 2>&1
echo "==> Building and starting Scrobbler + 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 "==> Scrobbler 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
+8 -1
View File
@@ -30,6 +30,10 @@ def create_app(config_object=None):
app.register_blueprint(lastfm_bp)
api.init_app(app)
from scrobbler import federation # the only place the core touches federation
federation.init_app(app)
CORS(
app,
resources={r"/api/v1/*": {"origins": app.config["CORS_ORIGINS"]}},
@@ -37,9 +41,12 @@ def create_app(config_object=None):
max_age=600,
)
from scrobbler.cli import imports_cli
from scrobbler.cli import imports_cli, worker_command
from scrobbler.services import imports as import_service
app.cli.add_command(worker_command)
app.cli.add_command(imports_cli)
import_service.register_worker_tasks(app)
from scrobbler.metrics import db as db_metrics
+10 -3
View File
@@ -29,11 +29,16 @@ class ScrobblerApi(Api):
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:
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(
"bearerAuth",
{
@@ -43,14 +48,16 @@ def init_app(app: Flask) -> None:
},
)
from scrobbler.api import apps, auth, health, imports, sessions, stats, tokens
from scrobbler.api import apps, art, auth, health, imports, sessions, stats, tokens, tracks
api.register_blueprint(auth.blp, url_prefix="/api/v1/auth")
api.register_blueprint(apps.blp, url_prefix="/api/v1/apps")
api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions")
api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens")
api.register_blueprint(stats.blp, url_prefix="/api/v1/me")
api.register_blueprint(tracks.blp, url_prefix="/api/v1/me/tracks")
api.register_blueprint(imports.blp, url_prefix="/api/v1/imports")
api.register_blueprint(art.blp, url_prefix="/api/v1/art")
api.register_blueprint(health.blp)
from scrobbler.openapi import lastfm
+42
View File
@@ -0,0 +1,42 @@
from flask import Response
from flask_smorest import Blueprint, abort
from scrobbler.api.decorators import authenticated
from scrobbler.schemas import AlbumArtArgsSchema, ErrorSchema
from scrobbler.services import art
blp = Blueprint(
"Art", __name__, description="Album art, proxied from MusicBrainz / Cover Art Archive"
)
@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")
@blp.alt_response(404, schema=ErrorSchema, description="No cover art found for this album")
@blp.alt_response(
502, schema=ErrorSchema, description="MusicBrainz or Cover Art Archive is unreachable"
)
def album_art(args):
"""An album's cover art
Resolved via MusicBrainz + Cover Art Archive and cached; bytes are proxied on every
call, so cache this response client-side.
"""
result = art.lookup(args["artist"], args["album"])
if result.status == "not_found":
abort(404, code="no_album_art", message="No cover art found for this album")
if result.status == "error":
abort(
502,
code="art_upstream_unavailable",
message="Couldn't reach MusicBrainz or Cover Art Archive",
)
try:
image = art.fetch_image(result.image_url)
except art.ArtFetchFailed:
abort(502, code="art_upstream_unavailable", message="Couldn't reach Cover Art Archive")
response = Response(image.body, mimetype=image.content_type)
response.headers["Cache-Control"] = "private, max-age=604800" # 7 days; art rarely changes
return response
+56
View File
@@ -0,0 +1,56 @@
from flask import g
from flask_smorest import Blueprint, abort
from scrobbler.api.decorators import authenticated
from scrobbler.schemas import (
ErrorSchema,
TrackDetailArgsSchema,
TrackDetailSchema,
TrackSearchArgsSchema,
TrackSearchResultSchema,
)
from scrobbler.services import stats
blp = Blueprint("Tracks", __name__, description="Look up a specific song's history and metadata")
@blp.route("/search", methods=["GET"])
@authenticated(blp)
@blp.arguments(TrackSearchArgsSchema, location="query")
@blp.response(200, TrackSearchResultSchema(many=True))
def search(args):
"""Find a song by track or artist name"""
return stats.track_search(g.user, args["q"], args["limit"])
@blp.route("", methods=["GET"])
@authenticated(blp)
@blp.arguments(TrackDetailArgsSchema, location="query")
@blp.response(200, TrackDetailSchema)
@blp.alt_response(404, schema=ErrorSchema, description="You've never scrobbled this song")
def detail(args):
"""A song's play history and recorded metadata"""
metadata = stats.track_metadata(g.user, args["artist"], args["track"])
if metadata is None:
abort(404, code="not_found", message="You've never scrobbled this song")
history = stats.recent(
g.user,
page=args["page"],
per_page=args["limit"],
artist=args["artist"],
track=args["track"],
)
counts = stats.listen_counts(
g.user, period="3month", bucket="day", artist=args["artist"], track=args["track"]
)
return {
"artist": metadata.artist,
"track": metadata.track,
"metadata": metadata,
"items": history.items,
"counts": counts,
"page": history.page,
"per_page": history.per_page,
"total": history.total,
"total_pages": history.total_pages,
}
+36 -14
View File
@@ -2,22 +2,44 @@ import logging
import click
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
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
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.command("worker")
@click.option("--once", is_flag=True, help="Process waiting jobs, then exit.")
@click.option("--poll", default=2.0, show_default=True, help="Seconds between checks when idle.")
@click.option("--metrics/--no-metrics", default=True, help="Serve Prometheus metrics.")
def worker(once: bool, poll: float, metrics: bool) -> None:
"""Process import jobs: uploaded Last.fm exports and pulls from Last.fm."""
from scrobbler.services.imports import run_worker
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
if metrics:
from scrobbler.metrics.server import start_metrics_server
start_metrics_server(current_app.config["IMPORT_WORKER_METRICS_PORT"])
run_worker(poll_seconds=poll, once=once)
@_worker_options
def imports_worker(once: bool, poll: float, serve_metrics: bool) -> None:
"""Alias for `flask worker` (kept for existing deployments)."""
_run_worker(once, poll, serve_metrics)
+21 -1
View File
@@ -54,9 +54,23 @@ class Config:
LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY", "")
LASTFM_API_URL = os.environ.get("LASTFM_API_URL", "https://ws.audioscrobbler.com/2.0/")
LASTFM_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25"))
# 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"))
IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 1024 * 1024)))
MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests
IMPORT_WORKER_METRICS_PORT = int(os.environ.get("IMPORT_WORKER_METRICS_PORT", "9101"))
# 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
AUTH_TOKEN_TTL_SECONDS = 60 * 60
@@ -73,3 +87,9 @@ class TestConfig(Config):
"postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test",
)
START_METRICS_SERVER = False
# 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"]
+32
View File
@@ -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)
+141
View File
@@ -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 Scrobbler 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.
+59
View File
@@ -0,0 +1,59 @@
"""ActivityPub federation: optional, self-contained, replaceable.
The rest of Scrobbler 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)
+92
View File
@@ -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
+49
View File
@@ -0,0 +1,49 @@
"""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 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),
)
+344
View File
@@ -0,0 +1,344 @@
"""/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,
**{k: v for k, v in _identity(user.username).items() if k != "profile_url"},
}
@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()
+38
View File
@@ -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.")
+106
View File
@@ -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})"
)
+179
View File
@@ -0,0 +1,179 @@
"""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"
return "abandoned"
delay = (
RETRY_DELAYS[delivery.attempts - 1]
if delivery.attempts <= len(RETRY_DELAYS)
else LATER_DELAY
)
delivery.next_attempt_at = _now() + delay
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", 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()
+150
View File
@@ -0,0 +1,150 @@
"""Follower state changes, from incoming activities and from the user's own actions.
Every change that the other server needs to know about queues an activity (Accept,
Reject or Block); the delivery task sends it. Callers commit.
"""
from datetime import UTC, datetime
from scrobbler.extensions import db
from scrobbler.federation import activities
from scrobbler.federation.models import FederationBlock, FederationFollower, FederationRemoteActor
def _now() -> datetime:
return datetime.now(UTC)
def get(user_id: int, actor: FederationRemoteActor) -> FederationFollower | None:
return db.session.scalar(
db.select(FederationFollower).filter_by(user_id=user_id, remote_actor_id=actor.id)
)
def is_blocked(user_id: int, actor: FederationRemoteActor) -> bool:
return (
db.session.scalar(
db.select(FederationBlock).filter_by(user_id=user_id, remote_actor_id=actor.id)
)
is not None
)
def follow_received(
user_id: int, username: str, manual_approval: bool, actor: FederationRemoteActor, follow: dict
) -> str:
"""Handle a Follow. Returns what happened: accepted, pending, refollowed or blocked."""
if is_blocked(user_id, actor):
activities.reject_follow_activity(user_id, username, follow, actor)
return "blocked"
follower = get(user_id, actor)
if follower is not None:
# A repeat Follow (e.g. they lost our Accept): keep the newest activity and
# answer again if we'd already accepted.
follower.follow_activity_id, follower.follow_activity = follow["id"], follow
if follower.state == "accepted":
activities.accept_follow(username, follower)
return "refollowed"
return "pending"
follower = FederationFollower(
user_id=user_id,
remote_actor_id=actor.id,
actor=actor,
state="pending" if manual_approval else "accepted",
follow_activity_id=follow["id"],
follow_activity=follow,
accepted_at=None if manual_approval else _now(),
)
db.session.add(follower)
db.session.flush()
if not manual_approval:
activities.accept_follow(username, follower)
return "accepted"
return "pending"
def undo_follow(user_id: int, actor: FederationRemoteActor, follow_id: str | None) -> str:
"""Handle an Undo of a Follow. It only removes the follower if it undoes their current
Follow: an Undo of an older one can arrive after a newer Follow (deliveries race)."""
follower = get(user_id, actor)
if follower is None:
return "undo_not_following"
if follow_id is not None and follow_id != follower.follow_activity_id:
return "undo_stale"
db.session.delete(follower)
return "unfollowed"
def undo_follow_by_id(actor: FederationRemoteActor, follow_id: str) -> str:
"""An Undo naming the Follow only by id: remove whoever follows with that Follow."""
follower = db.session.scalar(
db.select(FederationFollower).filter_by(
remote_actor_id=actor.id, follow_activity_id=follow_id
)
)
if follower is None:
return "undo_not_following"
db.session.delete(follower)
return "unfollowed"
def actor_deleted(actor: FederationRemoteActor) -> int:
"""The remote account was deleted: it follows no one here any more."""
followers = db.session.scalars(
db.select(FederationFollower).filter_by(remote_actor_id=actor.id)
).all()
for follower in followers:
db.session.delete(follower)
actor.gone = True
return len(followers)
# --- The user's own actions --------------------------------------------------------------
def approve(username: str, follower: FederationFollower) -> None:
if follower.state != "pending":
return
follower.state, follower.accepted_at = "accepted", _now()
activities.accept_follow(username, follower)
def remove(username: str, follower: FederationFollower) -> None:
"""Decline a request or remove a follower: both are a Reject for the other server."""
activities.reject_follow(username, follower)
db.session.delete(follower)
def block(username: str, follower: FederationFollower) -> FederationBlock:
blocked = FederationBlock(user_id=follower.user_id, remote_actor_id=follower.remote_actor_id)
db.session.add(blocked)
activities.block(follower.user_id, username, follower.actor)
db.session.delete(follower)
return blocked
def reject_all(user_id: int, username: str) -> int:
"""Sharing switched off: tell every follower, then forget them."""
followers = db.session.scalars(db.select(FederationFollower).filter_by(user_id=user_id)).all()
for follower in followers:
remove(username, follower)
return len(followers)
def counts(user_id: int) -> dict[str, int]:
rows = db.session.execute(
db.select(FederationFollower.state, db.func.count())
.filter_by(user_id=user_id)
.group_by(FederationFollower.state)
).all()
found = dict(rows)
return {"accepted": found.get("accepted", 0), "pending": found.get("pending", 0)}
def accepted_inboxes(user_id: int) -> list[str]:
"""Delivery inbox (their shared one, or their own) of every accepted follower, for
fanning out a post. Pending followers are excluded: they haven't been let in yet."""
accepted = db.session.scalars(
db.select(FederationFollower).filter_by(user_id=user_id, state="accepted")
).all()
return [follower.actor.delivery_inbox for follower in accepted]
+51
View File
@@ -0,0 +1,51 @@
"""Our ActivityPub IDs, all built from FEDERATION_BASE_URL (never the request)."""
from flask import current_app
def base_url() -> str:
return current_app.extensions["federation"].base_url
def actor_id(username: str) -> str:
return f"{base_url()}/users/{username}"
def followers_url(username: str) -> str:
return f"{actor_id(username)}/followers"
def key_id(username: str) -> str:
return f"{actor_id(username)}#main-key"
def instance_actor_id() -> str:
return f"{base_url()}/actor"
def instance_key_id() -> str:
return f"{instance_actor_id()}#main-key"
def activity_url(activity_uuid: str) -> str:
return f"{base_url()}/activities/{activity_uuid}"
def note_url(username: str, post_uuid: str) -> str:
"""The Note's ActivityPub id (served at /users/<u>/posts/<uuid>)."""
return f"{actor_id(username)}/posts/{post_uuid}"
def post_page_url(username: str, post_uuid: str) -> str:
"""Where a browser following the Note's `url` lands, in the web UI. Carries the
username too: the UI page has no other way to know whose post to look up."""
return f"{current_app.config['UI_BASE_URL']}/post.html?u={username}&id={post_uuid}"
def username_from_actor_id(uri: str | None) -> str | None:
"""`<base>/users/<name>` -> name; None for anything else."""
prefix = f"{base_url()}/users/"
if not uri or not uri.startswith(prefix):
return None
name = uri[len(prefix) :]
return name if name and "/" not in name and "#" not in name and "?" not in name else None
+323
View File
@@ -0,0 +1,323 @@
"""Receiving activities.
Intake (in the request): cheap checks only, then store and answer 202. No network calls,
so a flood of deliveries can't make us fetch things.
Processing (the `federation.inbox` worker task): verify the HTTP signature (fetching the
sender's key), check the sender is who the activity says, then dispatch by type.
"""
import json
import logging
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from urllib.parse import urlsplit
from flask import current_app
from sqlalchemy import delete, update
from sqlalchemy.exc import IntegrityError
from scrobbler.extensions import db
from scrobbler.federation import followers, ids, remote, sharing
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation.models import FederationInboxItem, FederationRemoteActor
from scrobbler.federation.net import FetchError
from scrobbler.federation.protocol import signatures
from scrobbler.federation.protocol.signatures import SignatureError, SignedRequest
from scrobbler.federation.protocol.vocab import object_id
log = logging.getLogger(__name__)
MAX_BYTES = 256 * 1024
MAX_ATTEMPTS = 3
KEPT_FOR = timedelta(days=30)
STALE_AFTER = timedelta(minutes=10)
# Only what signature checks need is kept from the request.
KEPT_HEADERS = (
"host",
"date",
"digest",
"content-digest",
"signature",
"signature-input",
"authorization",
"content-type",
"content-length",
)
# Metric labels are limited to these; anything else is "other".
KNOWN_TYPES = {
"Follow",
"Undo",
"Delete",
"Update",
"Accept",
"Reject",
"Like",
"Announce",
"Create",
"Add",
"Remove",
"Move",
"Block",
"Flag",
"EmojiReact",
}
def type_label(activity_type) -> str:
return activity_type if activity_type in KNOWN_TYPES else "other"
def _host(url: str) -> str:
return (urlsplit(url).hostname or "").lower()
def _config():
return current_app.extensions["federation"]
# --- Intake -------------------------------------------------------------------------------
def receive(inbox_path: str, headers: dict[str, str], body: bytes) -> tuple[int, str]:
"""Store a delivery for processing. Returns (HTTP status, outcome)."""
if len(body) > MAX_BYTES:
return 413, "too_large"
try:
doc = json.loads(body)
except (json.JSONDecodeError, UnicodeDecodeError):
doc = None
activity_id = doc.get("id") if isinstance(doc, dict) else None
activity_type = doc.get("type") if isinstance(doc, dict) else None
actor = object_id(doc.get("actor")) if isinstance(doc, dict) else None
if not all(isinstance(v, str) and v for v in (activity_id, activity_type, actor)):
fed_metrics.inbox_activities_total.labels(type="other", result="invalid").inc()
return 400, "invalid"
label = type_label(activity_type)
if len(activity_id) > 2048 or len(actor) > 2048:
fed_metrics.inbox_activities_total.labels(type=label, result="invalid").inc()
return 400, "invalid"
if _config().is_blocked(_host(actor)):
fed_metrics.inbox_activities_total.labels(type=label, result="blocked").inc()
return 403, "blocked"
kept = {k.lower(): v for k, v in headers.items() if k.lower() in KEPT_HEADERS}
db.session.add(
FederationInboxItem(
activity_id=activity_id,
activity_type=activity_type[:64],
actor_uri=actor,
inbox_path=inbox_path[:512],
headers=kept,
body=body,
)
)
try:
db.session.commit()
except IntegrityError: # seen this activity before
db.session.rollback()
fed_metrics.inbox_activities_total.labels(type=label, result="duplicate").inc()
return 202, "duplicate"
fed_metrics.inbox_activities_total.labels(type=label, result="queued").inc()
return 202, "queued"
# --- Processing -------------------------------------------------------------------------------
class Rejected(Exception):
"""The activity won't be acted on; `reason` says why."""
def __init__(self, reason: str):
self.reason = reason
super().__init__(reason)
Handler = Callable[[dict, FederationRemoteActor], str]
HANDLERS: dict[str, Handler] = {}
def handles(activity_type: str):
def register(fn: Handler) -> Handler:
HANDLERS[activity_type] = fn
return fn
return register
def _verify(item: FederationInboxItem) -> FederationRemoteActor:
"""Check the signature (as of when it arrived); return the signing actor."""
request = SignedRequest("POST", ids.base_url() + item.inbox_path, item.headers, item.body)
try:
scheme = signatures.detect(request).name
except SignatureError:
fed_metrics.signatures_total.labels(direction="in", scheme="none", result="missing").inc()
raise Rejected("signature_missing") from None
signer: dict[str, FederationRemoteActor] = {}
def public_key_for(refresh: bool):
def lookup(key_id: str):
actor = remote.actor_for_key(key_id, refresh=refresh)
signer["actor"] = actor
return remote.load_public_key(actor.public_key_pem)
return lookup
try:
try:
signatures.verify(request, public_key_for(False), now=item.received_at)
except SignatureError as err:
if err.reason not in ("bad_signature", "unknown_key"):
raise
# Maybe they rotated their key: fetch the actor again, once
signatures.verify(request, public_key_for(True), now=item.received_at)
except SignatureError as err:
fed_metrics.signatures_total.labels(direction="in", scheme=scheme, result=err.reason).inc()
raise Rejected(f"signature_{err.reason}") from err
except remote.ActorError as err:
fed_metrics.signatures_total.labels(direction="in", scheme=scheme, result="bad_actor").inc()
raise Rejected("bad_actor") from err
fed_metrics.signatures_total.labels(direction="in", scheme=scheme, result="ok").inc()
return signer["actor"]
def _handle(item: FederationInboxItem) -> str:
actor = _verify(item)
doc = json.loads(item.body)
if object_id(doc.get("actor")) != actor.uri:
raise Rejected("actor_mismatch") # signed by someone other than the actor
if _host(doc["id"]) != actor.host:
raise Rejected("id_host_mismatch")
if _config().is_blocked(actor.host):
raise Rejected("blocked_domain")
handler = HANDLERS.get(doc.get("type"))
return handler(doc, actor) if handler else "recorded"
def claim_next() -> FederationInboxItem | None:
item = db.session.scalar(
db.select(FederationInboxItem)
.filter_by(status="queued")
.order_by(FederationInboxItem.received_at)
.limit(1)
.with_for_update(skip_locked=True)
)
if item is None:
db.session.rollback()
return None
item.status = "processing" # processing commits (e.g. caching actors), so mark it
item.attempts += 1
db.session.commit()
return item
def process(item: FederationInboxItem) -> None:
label = type_label(item.activity_type)
try:
outcome = _handle(item)
except Rejected as rejected:
db.session.rollback()
_finish(item, "rejected", rejected.reason)
fed_metrics.inbox_activities_total.labels(type=label, result="rejected").inc()
return
except Exception as err:
db.session.rollback()
transient = isinstance(err, FetchError) and err.reason == "network"
if not transient:
log.exception("inbox item %s failed", item.id)
if item.attempts < MAX_ATTEMPTS:
_finish(item, "queued", f"retrying: {err}"[:255], done=False)
return
_finish(item, "failed", str(err)[:255])
fed_metrics.inbox_activities_total.labels(type=label, result="failed").inc()
return
db.session.commit()
_finish(item, "processed", outcome)
fed_metrics.inbox_activities_total.labels(type=label, result="processed").inc()
def _finish(item: FederationInboxItem, status: str, reason: str, done: bool = True) -> None:
item = db.session.get(FederationInboxItem, item.id)
item.status, item.reason = status, reason
if done:
item.processed_at = datetime.now(UTC)
db.session.commit()
def work_once() -> bool:
"""Worker task: process the oldest queued delivery."""
item = claim_next()
if item is None:
return False
process(item)
return True
def maintenance() -> None:
"""Worker task (periodic): re-queue items a dead worker left behind; drop old ones."""
now = datetime.now(UTC)
db.session.execute(
update(FederationInboxItem)
.where(FederationInboxItem.status == "processing")
.where(FederationInboxItem.received_at < now - STALE_AFTER)
.values(status="queued")
)
db.session.execute(
delete(FederationInboxItem)
.where(FederationInboxItem.status != "queued")
.where(FederationInboxItem.received_at < now - KEPT_FOR)
)
db.session.commit()
# --- Handlers ----------------------------------------------------------------------------------
def _local_user(target):
"""The sharing user an activity is addressed to, or Rejected."""
username = ids.username_from_actor_id(object_id(target))
found = sharing.shared_user(username) if username else None
if found is None:
raise Rejected("not_our_user")
return found
@handles("Follow")
def on_follow(doc: dict, actor: FederationRemoteActor) -> str:
user, settings = _local_user(doc.get("object"))
outcome = followers.follow_received(
user.id, user.username, settings.manually_approves_followers, actor, doc
)
return f"follow_{outcome}"
@handles("Undo")
def on_undo(doc: dict, actor: FederationRemoteActor) -> str:
inner = doc.get("object")
if isinstance(inner, str): # the Follow referenced by id rather than embedded
return followers.undo_follow_by_id(actor, inner)
if not isinstance(inner, dict) or inner.get("type") != "Follow":
return "undo_ignored"
if object_id(inner.get("actor")) not in (None, actor.uri):
raise Rejected("undo_other_actors_follow")
user, _ = _local_user(inner.get("object"))
return followers.undo_follow(user.id, actor, object_id(inner))
@handles("Delete")
def on_delete(doc: dict, actor: FederationRemoteActor) -> str:
if object_id(doc.get("object")) != actor.uri:
return "delete_ignored" # a post or similar: we don't store remote content
followers.actor_deleted(actor)
return "actor_deleted"
@handles("Update")
def on_update(doc: dict, actor: FederationRemoteActor) -> str:
obj = doc.get("object")
if not isinstance(obj, dict) or obj.get("type") not in remote.ACTOR_TYPES:
return "update_ignored"
if object_id(obj) != actor.uri:
raise Rejected("update_other_actor")
remote.get_actor(actor.uri, refresh=True)
return "actor_updated"
+66
View File
@@ -0,0 +1,66 @@
"""Actor key pairs: RSA-2048 (what Mastodon's draft signatures need), private keys
encrypted at rest with a key derived from FEDERATION_KEY_SECRET.
Keys are created once and never regenerated: remote servers pin them.
"""
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from flask import current_app
from scrobbler.extensions import db
from scrobbler.federation.models import FederationKey
_HKDF_INFO = b"scrobbler federation actor keys v1"
def _fernet(secret: str) -> Fernet:
key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=_HKDF_INFO).derive(
secret.encode()
)
return Fernet(base64.urlsafe_b64encode(key))
def _secret() -> str:
return current_app.extensions["federation"].key_secret
def _new_key(user_id: int | None) -> FederationKey:
private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
private_pem = private.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
)
public_pem = private.public_key().public_bytes(
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
)
return FederationKey(
user_id=user_id,
public_key_pem=public_pem.decode(),
private_key_encrypted=_fernet(_secret()).encrypt(private_pem),
)
def key_for(user_id: int | None) -> FederationKey:
"""The actor's key pair, created on first use. user_id=None is the instance actor."""
query = db.select(FederationKey)
query = query.filter(
FederationKey.user_id.is_(None) if user_id is None else FederationKey.user_id == user_id
)
key = db.session.scalar(query)
if key is None:
key = _new_key(user_id)
db.session.add(key)
db.session.commit()
return key
def private_key(key: FederationKey) -> RSAPrivateKey:
pem = _fernet(_secret()).decrypt(key.private_key_encrypted)
return serialization.load_pem_private_key(pem, password=None)
+79
View File
@@ -0,0 +1,79 @@
"""Federation's own metrics (the core's HTTP metrics already cover rate/latency)."""
from prometheus_client import Counter, Gauge, Histogram
lookups_total = Counter(
"scrobbler_federation_lookups_total",
"Fediverse lookups answered: WebFinger, actor, NodeInfo, profile",
["kind", "result"],
)
sharing_changes_total = Counter(
"scrobbler_federation_sharing_changes_total",
"Users switching fediverse sharing on or off",
["change"],
)
inbox_requests_total = Counter(
"scrobbler_federation_inbox_requests_total",
"Deliveries received at an inbox (not yet processed: phase 2)",
["inbox"],
)
inbox_activities_total = Counter(
"scrobbler_federation_inbox_activities_total",
"Activities received: queued, duplicate, blocked or invalid at intake; then processed, "
"rejected or failed",
["type", "result"],
)
signatures_total = Counter(
"scrobbler_federation_signatures_total",
"HTTP signature checks (in) and signing (out), by scheme and result",
["direction", "scheme", "result"],
)
deliveries_total = Counter(
"scrobbler_federation_deliveries_total",
"Outgoing deliveries: delivered, retry, abandoned (gave up or refused) or gone (410)",
["result"],
)
delivery_seconds = Histogram(
"scrobbler_federation_delivery_seconds",
"Time to deliver one activity to one inbox",
buckets=(0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20),
)
queue = Gauge(
"scrobbler_federation_queue",
"Inbox items and deliveries by status (set by the worker)",
["queue", "status"],
multiprocess_mode="max",
)
followers = Gauge(
"scrobbler_federation_followers",
"Followers across all users, by state (set by the worker)",
["state"],
multiprocess_mode="max",
)
posts_total = Counter(
"scrobbler_federation_posts_total",
"Posts published: weekly summaries, milestones and now-playing",
["kind", "visibility"],
)
post_deletions_total = Counter(
"scrobbler_federation_post_deletions_total",
"Posts deleted, by reason",
["reason"],
)
milestone_checks_total = Counter(
"scrobbler_federation_milestone_checks_total",
"Milestone checks, by result: disabled, none or posted",
["result"],
)
weekly_total = Counter(
"scrobbler_federation_weekly_total",
"Weekly summary checks, by result: disabled, skipped_empty, already_posted or posted",
["result"],
)
profile_updates_total = Counter(
"scrobbler_federation_profile_updates_total",
"Now-playing Update(Person) pushes: sent, or throttled (still within the 5-minute "
"window since the last one)",
["result"],
)
+270
View File
@@ -0,0 +1,270 @@
"""Federation's own tables. All prefixed federation_; the only link to the core schema
is a foreign key to users. Migrations live on the `federation` Alembic branch."""
from datetime import UTC, datetime
from sqlalchemy import (
JSON,
Boolean,
DateTime,
ForeignKey,
Index,
Integer,
LargeBinary,
String,
Text,
UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from scrobbler.extensions import db
VISIBILITIES = ("followers", "unlisted", "public")
NOW_PLAYING_MODES = ("off", "profile", "posts")
def utcnow() -> datetime:
return datetime.now(UTC)
class FederationSettings(db.Model):
__tablename__ = "federation_settings"
user_id: Mapped[int] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
)
enabled: Mapped[bool] = mapped_column(Boolean, default=False)
visibility: Mapped[str] = mapped_column(String(16), default="followers")
manually_approves_followers: Mapped[bool] = mapped_column(Boolean, default=False)
discoverable: Mapped[bool] = mapped_column(Boolean, default=False)
indexable: Mapped[bool] = mapped_column(Boolean, default=False)
display_name: Mapped[str | None] = mapped_column(String(100))
bio: Mapped[str | None] = mapped_column(Text)
# An IANA zone name (validated with zoneinfo), used to decide when a Monday starts.
timezone: Mapped[str] = mapped_column(String(64), default="UTC")
post_weekly_summary: Mapped[bool] = mapped_column(Boolean, default=True)
post_milestones: Mapped[bool] = mapped_column(Boolean, default=True)
# off, profile or posts (posts implies profile too)
now_playing_mode: Mapped[str] = mapped_column(String(16), default="off")
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=utcnow, onupdate=utcnow
)
class FederationKey(db.Model):
"""An actor's RSA key pair. user_id is NULL for the instance actor."""
__tablename__ = "federation_keys"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int | None] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"), unique=True
)
public_key_pem: Mapped[str] = mapped_column(Text)
private_key_encrypted: Mapped[bytes] = mapped_column(LargeBinary)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class FederationRemoteActor(db.Model):
"""A cached copy of another server's actor (who follows us, and their key)."""
__tablename__ = "federation_remote_actors"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
uri: Mapped[str] = mapped_column(String(2048), unique=True)
host: Mapped[str] = mapped_column(String(255), index=True)
inbox: Mapped[str] = mapped_column(String(1024))
shared_inbox: Mapped[str | None] = mapped_column(String(1024))
username: Mapped[str | None] = mapped_column(String(255)) # preferredUsername
display_name: Mapped[str | None] = mapped_column(String(255))
public_key_id: Mapped[str] = mapped_column(String(2048), index=True)
public_key_pem: Mapped[str] = mapped_column(Text)
fetched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
gone: Mapped[bool] = mapped_column(Boolean, default=False)
@property
def handle(self) -> str:
return f"@{self.username or '?'}@{self.host}"
@property
def delivery_inbox(self) -> str:
return self.shared_inbox or self.inbox
class FederationFollower(db.Model):
"""A remote actor following one of our users."""
__tablename__ = "federation_followers"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
remote_actor_id: Mapped[int] = mapped_column(
ForeignKey("federation_remote_actors.id", ondelete="CASCADE")
)
state: Mapped[str] = mapped_column(String(16)) # pending or accepted
follow_activity_id: Mapped[str] = mapped_column(String(2048))
follow_activity: Mapped[dict] = mapped_column(JSON().with_variant(JSONB, "postgresql"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
accepted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
actor: Mapped[FederationRemoteActor] = relationship(lazy="joined")
__table_args__ = (
UniqueConstraint("user_id", "remote_actor_id", name="uq_federation_follower"),
)
class FederationBlock(db.Model):
"""A user blocking a remote actor (their follows are refused)."""
__tablename__ = "federation_blocks"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
remote_actor_id: Mapped[int] = mapped_column(
ForeignKey("federation_remote_actors.id", ondelete="CASCADE")
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
actor: Mapped[FederationRemoteActor] = relationship(lazy="joined")
__table_args__ = (UniqueConstraint("user_id", "remote_actor_id", name="uq_federation_block"),)
class FederationInboxItem(db.Model):
"""A delivery received at an inbox, queued for the worker to verify and process."""
__tablename__ = "federation_inbox"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
activity_id: Mapped[str] = mapped_column(String(2048), unique=True)
activity_type: Mapped[str] = mapped_column(String(64))
actor_uri: Mapped[str] = mapped_column(String(2048))
inbox_path: Mapped[str] = mapped_column(String(512)) # as received, for the signature
headers: Mapped[dict] = mapped_column(JSON().with_variant(JSONB, "postgresql"))
body: Mapped[bytes] = mapped_column(LargeBinary)
status: Mapped[str] = mapped_column(
String(16), default="queued"
) # queued, processed, rejected, failed
reason: Mapped[str | None] = mapped_column(String(255))
attempts: Mapped[int] = mapped_column(Integer, default=0)
received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
processed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
__table_args__ = (Index("ix_federation_inbox_status_received", "status", "received_at"),)
class FederationActivity(db.Model):
"""An activity we sent (Accept, Reject, Block; posts in phase 3)."""
__tablename__ = "federation_activities"
id: Mapped[str] = mapped_column(String(36), primary_key=True) # UUID, part of its URL
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
activity_type: Mapped[str] = mapped_column(String(64))
document: Mapped[dict] = mapped_column(JSON().with_variant(JSONB, "postgresql"))
public: Mapped[bool] = mapped_column(Boolean, default=False) # may be fetched by anyone
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class FederationDelivery(db.Model):
"""One activity to one inbox, with retries."""
__tablename__ = "federation_deliveries"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
activity_id: Mapped[str] = mapped_column(
ForeignKey("federation_activities.id", ondelete="CASCADE"), index=True
)
inbox: Mapped[str] = mapped_column(String(1024)) # keeps the unique index small
# pending, delivered, failed or abandoned
status: Mapped[str] = mapped_column(String(16), default="pending")
attempts: Mapped[int] = mapped_column(Integer, default=0)
next_attempt_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
last_status: Mapped[int | None] = mapped_column(Integer)
last_error: Mapped[str | None] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
activity: Mapped[FederationActivity] = relationship(lazy="joined")
__table_args__ = (
UniqueConstraint("activity_id", "inbox", name="uq_federation_delivery"),
Index("ix_federation_deliveries_due", "status", "next_attempt_at"),
)
class FederationPost(db.Model):
"""A published Note (weekly summary or milestone), wrapped in the Create activity it
was sent with. One row per (user, key): the unique constraint is what makes posting
idempotent, since a key like `weekly:2026-W39` can only be inserted once."""
__tablename__ = "federation_posts"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
kind: Mapped[str] = mapped_column(String(16)) # weekly or milestone
key: Mapped[str] = mapped_column(String(64)) # e.g. weekly:2026-W39, milestone:scrobbles:10000
activity_id: Mapped[str] = mapped_column(
ForeignKey("federation_activities.id", ondelete="CASCADE"), unique=True
)
visibility: Mapped[str] = mapped_column(String(16)) # as posted; unaffected by later changes
content_text: Mapped[str] = mapped_column(Text)
content_html: Mapped[str] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
activity: Mapped[FederationActivity] = relationship(lazy="joined")
__table_args__ = (UniqueConstraint("user_id", "key", name="uq_federation_post_key"),)
class FederationMilestoneMark(db.Model):
"""A milestone threshold a user has reached. `posted=False` for thresholds passed
silently (the baseline set when a user enables sharing, or after an import finishes)
so they're marked done without ever producing a post."""
__tablename__ = "federation_milestone_marks"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
key: Mapped[str] = mapped_column(String(64)) # e.g. scrobbles:10000, artist:radiohead:500
posted: Mapped[bool] = mapped_column(Boolean, default=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
__table_args__ = (UniqueConstraint("user_id", "key", name="uq_federation_milestone_mark"),)
class FederationPendingCheck(db.Model):
"""A user whose milestones need checking, queued by the scrobbles_stored event
receiver and drained by the worker. One row per user: further scrobbles before the
worker gets to it just update `since`, so scrobbling stays fast and the receiver never
does real work inside a scrobble request."""
__tablename__ = "federation_pending_checks"
user_id: Mapped[int] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
)
since: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
reason: Mapped[str] = mapped_column(String(32), default="scrobble")
class FederationNowPlaying(db.Model):
"""What we've last told the fediverse is playing, as opposed to `now_playing` in the
core schema, which is what's actually playing. A "key" is a short hash of `artist,
track, started_at` (see publishing/now_playing.py): playing the same track again
later is a new now-playing moment, not a stale repeat, and it doubles as
federation_posts.key for the posts side."""
__tablename__ = "federation_now_playing"
user_id: Mapped[int] = mapped_column(
ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
)
profile_key: Mapped[str | None] = mapped_column(String(512))
profile_updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
post_key: Mapped[str | None] = mapped_column(String(512))
post_posted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+165
View File
@@ -0,0 +1,165 @@
"""The only way federation code talks to other servers.
Guards against server-side request forgery (a remote document or redirect pointing us
at internal services):
* https only (http only with FEDERATION_INSECURE_TESTING, for CI on private networks);
* a host's addresses are resolved once and the request is refused if any is loopback,
private, link-local, multicast or otherwise not globally routable; the connection
then goes to the address that was checked (SNI and Host keep the name), so the name
can't be re-resolved somewhere else mid-request;
* at most 3 redirects, each checked the same way; responses capped at 1 MB;
10s to connect, 20s to read.
"""
import ipaddress
import json
import socket
from collections.abc import Callable
from dataclasses import dataclass
from urllib.parse import urljoin, urlsplit
import httpcore
from scrobbler.federation.protocol.media import ACTIVITY_JSON, LD_JSON
MAX_BYTES = 1024 * 1024
MAX_REDIRECTS = 3
TIMEOUTS = {"connect": 10.0, "read": 20.0, "write": 20.0, "pool": 10.0}
_REDIRECTS = {301, 302, 303, 307, 308}
Resolver = Callable[[str, int], list[str]]
class FetchError(Exception):
"""A request we refused to make or that didn't succeed."""
def __init__(self, reason: str, message: str, status: int | None = None):
self.reason, self.status = (
reason,
status,
) # reason: blocked, http, too_large, network, invalid
super().__init__(message)
@dataclass(frozen=True)
class Response:
status: int
headers: dict[str, str] # lower-cased names
body: bytes
url: str # after redirects
def json(self) -> dict:
try:
doc = json.loads(self.body)
except (json.JSONDecodeError, UnicodeDecodeError) as err:
raise FetchError("invalid", f"{self.url} didn't return JSON") from err
if not isinstance(doc, dict):
raise FetchError("invalid", f"{self.url} didn't return a JSON object")
return doc
def system_resolver(host: str, port: int) -> list[str]:
try:
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
except socket.gaierror as err:
raise FetchError("network", f"can't resolve {host}") from err
return list(dict.fromkeys(info[4][0] for info in infos))
def is_public(address: str) -> bool:
ip = ipaddress.ip_address(address.split("%", 1)[0])
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped:
ip = ip.ipv4_mapped
return ip.is_global and not ip.is_multicast and not ip.is_reserved
class _GuardedBackend(httpcore.SyncBackend):
def __init__(self, resolver: Resolver, allow_private: bool):
super().__init__()
self.resolver, self.allow_private = resolver, allow_private
def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None):
addresses = self.resolver(host, port)
if not addresses:
raise FetchError("network", f"{host} has no addresses")
if not self.allow_private:
refused = [a for a in addresses if not is_public(a)]
if refused:
raise FetchError("blocked", f"{host} resolves to a non-public address")
return super().connect_tcp(addresses[0], port, timeout, local_address, socket_options)
class Client:
def __init__(
self,
user_agent: str,
insecure_testing: bool = False,
resolver: Resolver = system_resolver,
):
self.user_agent = user_agent
self.insecure_testing = insecure_testing
self._pool = httpcore.ConnectionPool(
network_backend=_GuardedBackend(resolver, allow_private=insecure_testing),
max_connections=32,
keepalive_expiry=30,
)
def _check_url(self, url: str) -> None:
parts = urlsplit(url)
schemes = ("https", "http") if self.insecure_testing else ("https",)
if parts.scheme not in schemes or not parts.hostname:
raise FetchError("blocked", f"refusing to fetch {url}")
if parts.username or parts.password:
raise FetchError("blocked", "credentials in URL")
def request(
self, method: str, url: str, headers: dict[str, str] | None = None, body: bytes = b""
) -> Response:
"""One request, following redirects for GET only. Doesn't raise for HTTP errors."""
for _ in range(MAX_REDIRECTS + 1):
self._check_url(url)
response = self._send(method, url, headers or {}, body)
location = response.headers.get("location")
if method == "GET" and response.status in _REDIRECTS and location:
url = urljoin(url, location)
continue
return response
raise FetchError("blocked", "too many redirects")
def _send(self, method: str, url: str, headers: dict[str, str], body: bytes) -> Response:
sent = {"User-Agent": self.user_agent, **headers}
try:
with self._pool.stream(
method,
url,
headers=list(sent.items()),
content=body or None,
extensions={"timeout": TIMEOUTS},
) as response:
chunks, size = [], 0
for chunk in response.iter_stream():
size += len(chunk)
if size > MAX_BYTES:
raise FetchError("too_large", f"{url} sent more than {MAX_BYTES} bytes")
chunks.append(chunk)
return Response(
status=response.status,
headers={k.decode().lower(): v.decode("latin-1") for k, v in response.headers},
body=b"".join(chunks),
url=url,
)
except httpcore.TimeoutException as err:
raise FetchError("network", f"{url} timed out") from err
except (httpcore.NetworkError, httpcore.ProtocolError, httpcore.UnsupportedProtocol) as err:
raise FetchError("network", f"{url}: {err}") from err
def get_json(self, url: str, headers: dict[str, str] | None = None) -> dict:
response = self.request(
"GET", url, {"Accept": f"{ACTIVITY_JSON}, {LD_JSON}", **(headers or {})}
)
if response.status != 200:
raise FetchError("http", f"{url} answered {response.status}", response.status)
return response.json()
def close(self) -> None:
self._pool.close()
+211
View File
@@ -0,0 +1,211 @@
"""OpenAPI descriptions of the ActivityPub endpoints (served on the UI's domain)."""
from flask import Flask
from flask_smorest import Api
TAG = "ActivityPub"
_AP = {"application/activity+json": {"schema": {"type": "object"}}}
_NOT_FOUND = {"description": "Unknown, or not sharing (the two are indistinguishable)"}
_INBOX_RESPONSES = {
"202": {"description": "Accepted for processing (also for a repeated activity)"},
"400": {"description": "Not an activity with an id, type and actor"},
"403": {"description": "The sender's domain is blocked"},
"404": {"description": "No such user sharing (user inbox)"},
"413": {"description": "Larger than 256 KB"},
"415": {"description": "Not ActivityPub JSON"},
}
_USERNAME = {"name": "username", "in": "path", "required": True, "schema": {"type": "string"}}
# endpoint -> (method, summary, description, extra parameters, responses)
_OPERATIONS = {
"federation.webfinger_lookup": (
"get",
"WebFinger",
"Resolves `acct:user@domain` (or an actor URL) to the user's actor. Only users "
"sharing their listening can be found.",
[
{
"name": "resource",
"in": "query",
"required": True,
"schema": {"type": "string"},
"example": "acct:alice@scrobble.example",
}
],
{
"200": {
"description": "JRD",
"content": {"application/jrd+json": {"schema": {"type": "object"}}},
},
"400": {"description": "Not a resource on this server"},
"404": _NOT_FOUND,
},
),
"federation.host_meta": (
"get",
"host-meta",
"XRD pointing at WebFinger (RFC 6415).",
[],
{
"200": {
"description": "XRD",
"content": {"application/xrd+xml": {"schema": {"type": "string"}}},
}
},
),
"federation.nodeinfo_discovery": (
"get",
"NodeInfo discovery",
"Links to the NodeInfo 2.1 document.",
[],
{
"200": {
"description": "Links",
"content": {"application/json": {"schema": {"type": "object"}}},
}
},
),
"federation.nodeinfo_document": (
"get",
"NodeInfo 2.1",
"Software name and version, protocols, and users sharing.",
[],
{
"200": {
"description": "NodeInfo",
"content": {"application/json": {"schema": {"type": "object"}}},
}
},
),
"federation.actor": (
"get",
"Actor",
"A user's `Person` actor when asked for ActivityPub JSON; browsers are redirected to "
"the web UI's profile page.",
[_USERNAME],
{
"200": {"description": "Person", "content": _AP},
"302": {"description": "Redirect to the profile page (non-ActivityPub Accept)"},
"404": _NOT_FOUND,
},
),
"federation.outbox": (
"get",
"Outbox",
"The user's public and unlisted posts (followers-only posts are never listed "
"here, since this endpoint isn't authenticated). Without `page`, an "
"OrderedCollection pointing at the first page; with it, an OrderedCollectionPage "
"of up to 20 `Create`s, newest first.",
[
_USERNAME,
{
"name": "page",
"in": "query",
"required": False,
"schema": {"type": "integer", "minimum": 1},
},
],
{
"200": {
"description": "OrderedCollection or OrderedCollectionPage",
"content": _AP,
},
"404": _NOT_FOUND,
},
),
"federation.post_note": (
"get",
"Post",
"One public or unlisted post's `Note`, when asked for ActivityPub JSON; browsers "
"are redirected to the web UI's post page. Followers-only and deleted posts "
"answer 404 here (they're delivered directly to followers instead).",
[
_USERNAME,
{"name": "post_uuid", "in": "path", "required": True, "schema": {"type": "string"}},
],
{
"200": {"description": "Note", "content": _AP},
"302": {"description": "Redirect to the post page (non-ActivityPub Accept)"},
"404": {"description": "Not found, not listed, or deleted"},
},
),
"federation.followers": (
"get",
"Followers",
"Follower count (members aren't listed).",
[_USERNAME],
{"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND},
),
"federation.following": (
"get",
"Following",
"Accounts the user follows.",
[_USERNAME],
{"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND},
),
"federation.featured": (
"get",
"Featured",
"Pinned posts (always empty for now).",
[_USERNAME],
{"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND},
),
"federation.instance_actor": (
"get",
"Instance actor",
"The server's `Application` actor.",
[],
{"200": {"description": "Application", "content": _AP}},
),
"federation.instance_outbox": (
"get",
"Instance outbox",
"Always empty.",
[],
{"200": {"description": "OrderedCollection", "content": _AP}},
),
"federation.user_inbox": (
"post",
"User inbox",
"Receives signed activities for one user. They're stored and answered with 202, then "
"verified and processed in the background.",
[_USERNAME],
_INBOX_RESPONSES,
),
"federation.shared_inbox": (
"post",
"Shared inbox",
"Receives signed activities for any user on this server (as for the user inbox).",
[],
_INBOX_RESPONSES,
),
"federation.activity": (
"get",
"Activity",
"One of our activities, when public. Replies to follows aren't public.",
[{"name": "activity_uuid", "in": "path", "required": True, "schema": {"type": "string"}}],
{
"200": {"description": "Activity", "content": _AP},
"404": {"description": "Not found or not public"},
},
),
}
def register(app: Flask, api: Api) -> None:
api.spec.tag({"name": TAG, "description": "Fediverse endpoints, served on the web UI's domain"})
rules = {rule.endpoint: rule for rule in app.url_map.iter_rules()}
for endpoint, (method, summary, description, parameters, responses) in _OPERATIONS.items():
operation = {
"tags": [TAG],
"summary": summary,
"description": description,
"operationId": endpoint.replace(".", "_"),
"responses": responses,
}
if parameters:
operation["parameters"] = parameters
if method == "post":
operation["requestBody"] = {"content": _AP}
api.spec.path(rule=rules[endpoint], operations={method: operation})
+64
View File
@@ -0,0 +1,64 @@
"""Signed requests to other servers, through the SSRF-safe client in net.py."""
import json
from flask import current_app
from scrobbler.federation import ids, keys
from scrobbler.federation.net import Client, FetchError, Response
from scrobbler.federation.protocol import signatures
from scrobbler.federation.protocol.media import ACTIVITY_JSON, LD_JSON
from scrobbler.federation.protocol.signatures import SignedRequest
def client() -> Client:
"""One pooled client per app (created on first use)."""
existing = current_app.extensions.get("federation_client")
if existing is None:
from scrobbler import __version__
config = current_app.extensions["federation"]
existing = Client(
user_agent=f"Scrobbler/{__version__} (+{config.base_url})",
insecure_testing=config.insecure_testing,
)
current_app.extensions["federation_client"] = existing
return existing
def _signed_headers(method, url, headers, body, key_id, private_key, scheme) -> dict[str, str]:
request = SignedRequest(method, url, headers, body)
return {**headers, **signatures.sign(request, scheme, key_id, private_key)}
def signed_get_json(url: str) -> dict:
"""GET an ActivityPub document, signed as the instance actor, so servers using
'authorized fetch' answer too."""
private = keys.private_key(keys.key_for(None))
headers = {"Accept": f"{ACTIVITY_JSON}, {LD_JSON}"}
schemes = current_app.extensions["federation"].signature_schemes
response = None
for scheme in schemes:
signed = _signed_headers("GET", url, headers, b"", ids.instance_key_id(), private, scheme)
response = client().request("GET", url, signed)
if response.status != 401:
break
if response.status != 200:
raise FetchError("http", f"{url} answered {response.status}", response.status)
return response.json()
def signed_post(url: str, activity: dict, *, user_id: int, username: str) -> tuple[Response, str]:
"""POST an activity to an inbox, signed as the user. Tries the configured signature
schemes in order, moving to the next only when the server answers 401. Returns the
response and the scheme used."""
body = json.dumps(activity).encode()
private = keys.private_key(keys.key_for(user_id))
headers = {"Content-Type": LD_JSON, "Accept": ACTIVITY_JSON}
response, used = None, ""
for used in current_app.extensions["federation"].signature_schemes:
signed = _signed_headers("POST", url, headers, body, ids.key_id(username), private, used)
response = client().request("POST", url, signed, body)
if response.status != 401:
break
return response, used
@@ -0,0 +1,7 @@
"""Pure ActivityPub protocol code: vocabulary builders, addressing, WebFinger and
NodeInfo documents, HTTP signature schemes.
Rule: nothing in this package imports Flask, SQLAlchemy, Werkzeug or any other part of
Scrobbler; only the standard library and `cryptography`. Spec changes land here and are
tested with spec test vectors alone. (Enforced by tests/test_federation_boundary.py.)
"""
@@ -0,0 +1,26 @@
"""to/cc addressing for our posts, by visibility."""
from scrobbler.federation.protocol.vocab import PUBLIC
VISIBILITIES = ("followers", "unlisted", "public")
def address(visibility: str, followers_url: str) -> tuple[list[str], list[str]]:
"""(to, cc) for a Note/Create/Delete with this visibility.
followers: to followers, no cc (never reaches a public timeline or search).
unlisted: to followers, cc Public (visible to anyone who looks, not pushed to feeds).
public: to Public, cc followers (the normal public-post shape).
"""
if visibility not in VISIBILITIES:
raise ValueError(f"unknown visibility: {visibility!r}")
if visibility == "public":
return [PUBLIC], [followers_url]
if visibility == "unlisted":
return [followers_url], [PUBLIC]
return [followers_url], []
def is_public_or_unlisted(visibility: str) -> bool:
"""Whether a post at this visibility may be listed in the public outbox."""
return visibility in ("public", "unlisted")
@@ -0,0 +1,31 @@
"""Safe post content: plain text and matching HTML, shared by every post kind so
they're formatted consistently and every track/artist name is escaped the same way.
Only the tags Mastodon keeps: p, strong, em, ol, li. No br is needed here since each
line of a post is its own paragraph.
"""
import html
HASHTAG = "Scrobbler"
def escape(text: str) -> str:
"""HTML-escape a name (artist, track, ...) for embedding in generated markup."""
return html.escape(text, quote=False)
def paragraph(inner_html: str) -> str:
return f"<p>{inner_html}</p>"
def numbered_list(items_html: list[str]) -> str:
return "<ol>" + "".join(f"<li>{item}</li>" for item in items_html) + "</ol>"
def hashtag_line() -> str:
return f"#{HASHTAG}"
def plural(count: int, word: str) -> str:
return word if count == 1 else f"{word}s"
@@ -0,0 +1,15 @@
"""/.well-known/host-meta (RFC 6415): points older clients at WebFinger."""
from xml.sax.saxutils import quoteattr
CONTENT_TYPE = "application/xrd+xml"
def xrd(base_url: str) -> str:
template = quoteattr(f"{base_url}/.well-known/webfinger?resource={{uri}}")
return (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">\n'
f' <Link rel="lrdd" type="application/jrd+json" template={template}/>\n'
"</XRD>\n"
)
@@ -0,0 +1,37 @@
"""ActivityPub media types and content negotiation."""
ACTIVITY_JSON = "application/activity+json"
AS_PROFILE = "https://www.w3.org/ns/activitystreams"
LD_JSON = f'application/ld+json; profile="{AS_PROFILE}"'
JRD_JSON = "application/jrd+json"
def _media_ranges(header: str):
for part in (header or "").split(","):
pieces = [p.strip() for p in part.split(";")]
media = pieces[0].lower()
params = {}
for piece in pieces[1:]:
name, _, value = piece.partition("=")
params[name.strip().lower()] = value.strip().strip('"')
try:
quality = float(params.get("q", "1"))
except ValueError:
quality = 0.0
yield media, params, quality
def is_activitypub(media: str, params: dict) -> bool:
if media == ACTIVITY_JSON:
return True
# ld+json counts when it names the ActivityStreams profile (or no profile at all)
return media == "application/ld+json" and params.get("profile", AS_PROFILE) == AS_PROFILE
def wants_activitypub(accept: str | None) -> bool:
"""True if an Accept header asks for ActivityPub JSON (rather than HTML)."""
return any(q > 0 and is_activitypub(m, p) for m, p, q in _media_ranges(accept or ""))
def is_activitypub_content_type(content_type: str | None) -> bool:
return any(is_activitypub(m, p) for m, p, _ in _media_ranges(content_type or ""))
@@ -0,0 +1,19 @@
"""NodeInfo 2.1 (https://nodeinfo.diaspora.software/): what software a server runs."""
SCHEMA_21 = "http://nodeinfo.diaspora.software/ns/schema/2.1"
def discovery(base_url: str) -> dict:
return {"links": [{"rel": SCHEMA_21, "href": f"{base_url}/nodeinfo/2.1"}]}
def document(*, version: str, users_total: int, open_registrations: bool) -> dict:
return {
"version": "2.1",
"software": {"name": "scrobbler", "version": version},
"protocols": ["activitypub"],
"services": {"inbound": [], "outbound": []},
"openRegistrations": open_registrations,
"usage": {"users": {"total": users_total}, "localPosts": 0},
"metadata": {},
}
@@ -0,0 +1,64 @@
"""Pure date/time math for scheduled posts: which week is due, in a user's own zone.
Weeks run Monday 00:00 to Sunday 24:00 *local time*, computed in the zone itself (not as
a fixed UTC offset), so the window is correct across a daylight-saving change.
"""
from datetime import UTC, date, datetime, timedelta
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
POST_HOUR = 9 # local time a week's summary becomes postable, on the following Monday
def week_key(day: date) -> str:
"""The ISO year-week key (e.g. "2026-W02") for the week a date falls in."""
year, week, _ = day.isocalendar()
return f"{year}-W{week:02d}"
def target_week(now_utc: datetime, tz: ZoneInfo) -> tuple[datetime, datetime, str]:
"""The [start, end) UTC window, and ISO year-week key (e.g. "2026-W02"), of the most
recent Monday-Sunday week whose Monday-POST_HOUR-local posting gate has passed.
Always resolves to exactly one week, so a worker that was down for a while catches up
with a single post (the latest eligible week), not one per week it missed.
"""
local_now = now_utc.astimezone(tz)
gate_monday = local_now.date() - timedelta(days=local_now.weekday())
gate = datetime(gate_monday.year, gate_monday.month, gate_monday.day, POST_HOUR, tzinfo=tz)
if local_now < gate:
gate_monday -= timedelta(days=7)
week_start = gate_monday - timedelta(days=7)
start_local = datetime(week_start.year, week_start.month, week_start.day, tzinfo=tz)
end_local = start_local + timedelta(days=7) # wall-clock +7 days: DST-correct on conversion
return start_local.astimezone(UTC), end_local.astimezone(UTC), week_key(week_start)
def current_week_start(now_utc: datetime, tz: ZoneInfo) -> datetime:
"""The UTC instant of this week's Monday 00:00 local time - the week still in
progress, not yet postable. For previewing what a summary would say so far."""
local_now = now_utc.astimezone(tz)
monday = local_now.date() - timedelta(days=local_now.weekday())
return datetime(monday.year, monday.month, monday.day, tzinfo=tz).astimezone(UTC)
def resolve_timezone(name: str) -> ZoneInfo:
"""A user's timezone setting, or UTC for anything that isn't a valid IANA name (a
bad or since-removed name in one user's settings must never crash the task for
everyone else)."""
try:
return ZoneInfo(name)
except (ZoneInfoNotFoundError, ValueError):
return ZoneInfo("UTC")
def is_valid_timezone(name: str) -> bool:
"""For validating user input (reject a bad name with an error), as opposed to
resolve_timezone's silent fallback (never crash the periodic task over one user's
stale setting)."""
try:
ZoneInfo(name)
except (ZoneInfoNotFoundError, ValueError):
return False
return True
@@ -0,0 +1,61 @@
"""HTTP signatures for ActivityPub: one module per scheme, chosen by name.
verify(request, public_key_for) whichever scheme the request carries
sign(request, scheme, key_id, key) headers to add, using the named scheme
Adding or dropping a scheme is a module here plus an entry in SCHEMES.
"""
from datetime import UTC, datetime
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from scrobbler.federation.protocol.signatures.base import (
PublicKeyFor,
SignatureError,
SignatureScheme,
SignedRequest,
VerifiedSignature,
)
from scrobbler.federation.protocol.signatures.draft_cavage import DraftCavage
from scrobbler.federation.protocol.signatures.rfc9421 import Rfc9421
SCHEMES: dict[str, SignatureScheme] = {s.name: s for s in (Rfc9421(), DraftCavage())}
__all__ = [
"SCHEMES",
"PublicKeyFor",
"SignatureError",
"SignedRequest",
"VerifiedSignature",
"detect",
"sign",
"verify",
]
def detect(request: SignedRequest) -> SignatureScheme:
for scheme in SCHEMES.values(): # RFC 9421 first: its Signature header differs
if scheme.present(request):
return scheme
raise SignatureError("missing")
def verify(
request: SignedRequest, public_key_for: PublicKeyFor, now: datetime | None = None
) -> VerifiedSignature:
return detect(request).verify(request, public_key_for, now or datetime.now(UTC))
def sign(
request: SignedRequest,
scheme: str,
key_id: str,
private_key: RSAPrivateKey,
now: datetime | None = None,
) -> dict[str, str]:
try:
chosen = SCHEMES[scheme]
except KeyError:
raise SignatureError("unsupported", f"scheme {scheme}") from None
return chosen.sign(request, key_id, private_key, now or datetime.now(UTC))
@@ -0,0 +1,108 @@
"""Shared pieces of the HTTP signature schemes."""
import base64
import hashlib
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from urllib.parse import urlsplit
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
MAX_SKEW = timedelta(hours=12) # Mastodon's window
class SignatureError(Exception):
"""Why a signature couldn't be verified: a short, metric-friendly reason."""
REASONS = (
"missing",
"malformed",
"expired",
"digest_mismatch",
"bad_signature",
"unsupported",
"unknown_key",
"insufficient", # doesn't cover what we require
)
def __init__(self, reason: str, detail: str = ""):
assert reason in self.REASONS, reason
self.reason = reason
super().__init__(f"{reason}: {detail}" if detail else reason)
@dataclass(frozen=True)
class SignedRequest:
"""An HTTP request, as signed or as received."""
method: str
url: str # absolute, as the signer addressed it
headers: Mapping[str, str] = field(default_factory=dict)
body: bytes = b""
def header(self, name: str) -> str | None:
name = name.lower()
for key, value in self.headers.items():
if key.lower() == name:
return value
return None
@property
def path_and_query(self) -> str:
parts = urlsplit(self.url)
return (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
@property
def host(self) -> str:
return urlsplit(self.url).netloc.lower()
@dataclass(frozen=True)
class VerifiedSignature:
scheme: str
key_id: str
# key id -> the public key it names (None if it can't be found)
PublicKeyFor = Callable[[str], RSAPublicKey | None]
def b64(data: bytes) -> str:
return base64.b64encode(data).decode()
def unb64(text: str) -> bytes:
try:
return base64.b64decode(text, validate=True)
except (ValueError, TypeError) as err:
raise SignatureError("malformed", "bad base64") from err
def sha256(body: bytes) -> bytes:
return hashlib.sha256(body).digest()
def check_time(when: datetime, now: datetime, max_skew: timedelta = MAX_SKEW) -> None:
if abs(now - when) > max_skew:
raise SignatureError("expired", f"signed at {when.isoformat()}")
class SignatureScheme:
"""Interface each scheme implements."""
name: str
def present(self, request: SignedRequest) -> bool: # pragma: no cover - interface
raise NotImplementedError
def sign(
self, request: SignedRequest, key_id: str, private_key: RSAPrivateKey, now: datetime
) -> dict[str, str]: # pragma: no cover - interface
"""Headers to add to the request."""
raise NotImplementedError
def verify(
self, request: SignedRequest, public_key_for: PublicKeyFor, now: datetime
) -> VerifiedSignature: # pragma: no cover - interface
raise NotImplementedError
@@ -0,0 +1,158 @@
"""draft-cavage-http-signatures (version 12): what most of the fediverse still uses.
Signature: keyId="…",algorithm="rsa-sha256",headers="(request-target) host date digest",
signature="<base64>"
"""
import re
from datetime import UTC, datetime
from email.utils import format_datetime, parsedate_to_datetime
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from scrobbler.federation.protocol.signatures.base import (
PublicKeyFor,
SignatureError,
SignatureScheme,
SignedRequest,
VerifiedSignature,
b64,
check_time,
sha256,
unb64,
)
NAME = "draft-cavage"
_PARAM = re.compile(r'\s*([a-zA-Z]+)\s*=\s*"([^"]*)"\s*(?:,|$)')
_ALGORITHMS = {"rsa-sha256", "hs2019"} # hs2019: "derive from the key"; ours are RSA
SIGN_GET = ("(request-target)", "host", "date")
SIGN_POST = ("(request-target)", "host", "date", "digest")
def _signature_header(request: SignedRequest) -> str | None:
value = request.header("signature")
if value:
return value
authorization = request.header("authorization") or ""
if authorization[:10].lower() == "signature ":
return authorization[10:]
return None
def parse(value: str) -> dict[str, str]:
params, position = {}, 0
while position < len(value):
match = _PARAM.match(value, position)
if not match or match.end() == position:
raise SignatureError("malformed", "unparseable Signature header")
params[match.group(1)] = match.group(2)
position = match.end()
if "keyId" not in params or "signature" not in params:
raise SignatureError("malformed", "keyId and signature are required")
return params
def signing_string(request: SignedRequest, headers: list[str], params: dict[str, str]) -> str:
lines = []
for name in headers:
if name == "(request-target)":
value = f"{request.method.lower()} {request.path_and_query}"
elif name in ("(created)", "(expires)"):
value = params.get(name[1:-1])
if value is None:
raise SignatureError("malformed", f"{name} signed but not given")
else:
value = request.header(name)
if value is None:
raise SignatureError("malformed", f"signed header {name} is missing")
lines.append(f"{name}: {value.strip()}")
return "\n".join(lines)
def digest_header(body: bytes) -> str:
return f"SHA-256={b64(sha256(body))}"
def check_digest(request: SignedRequest) -> None:
header = request.header("digest")
if not header:
raise SignatureError("insufficient", "no Digest header")
for part in header.split(","):
algorithm, _, value = part.strip().partition("=")
if algorithm.lower() == "sha-256":
if unb64(value) != sha256(request.body):
raise SignatureError("digest_mismatch")
return
raise SignatureError("unsupported", "no SHA-256 digest")
class DraftCavage(SignatureScheme):
name = NAME
def present(self, request: SignedRequest) -> bool:
return _signature_header(request) is not None and request.header("signature-input") is None
def sign(
self, request: SignedRequest, key_id: str, private_key: RSAPrivateKey, now: datetime
) -> dict[str, str]:
added = {"Host": request.host, "Date": format_datetime(now.astimezone(UTC), usegmt=True)}
headers = SIGN_GET
if request.body or request.method.upper() == "POST":
added["Digest"] = digest_header(request.body)
headers = SIGN_POST
signing = SignedRequest(
request.method, request.url, {**request.headers, **added}, request.body
)
base = signing_string(signing, list(headers), {})
signature = private_key.sign(base.encode(), padding.PKCS1v15(), hashes.SHA256())
added["Signature"] = (
f'keyId="{key_id}",algorithm="rsa-sha256",headers="{" ".join(headers)}",'
f'signature="{b64(signature)}"'
)
return added
def verify(
self,
request: SignedRequest,
public_key_for: PublicKeyFor,
now: datetime,
require: tuple[str, ...] | None = None,
) -> VerifiedSignature:
"""Verify the signature. `require` lists the headers that must be covered;
by default the ActivityPub minimum for the request's method."""
header = _signature_header(request)
if header is None:
raise SignatureError("missing")
params = parse(header)
algorithm = params.get("algorithm", "hs2019").lower()
if algorithm not in _ALGORITHMS:
raise SignatureError("unsupported", f"algorithm {algorithm}")
headers = params.get("headers", "date").lower().split()
if require is None:
require = SIGN_POST if request.method.upper() == "POST" else SIGN_GET
missing = set(require) - set(headers)
if missing:
raise SignatureError("insufficient", f"not signed: {sorted(missing)}")
if "digest" in headers:
check_digest(request)
if "date" in headers:
try:
check_time(parsedate_to_datetime(request.header("date") or ""), now)
except (TypeError, ValueError) as err:
raise SignatureError("malformed", "bad Date header") from err
key = public_key_for(params["keyId"])
if key is None:
raise SignatureError("unknown_key", params["keyId"])
base = signing_string(request, headers, params)
try:
key.verify(
unb64(params["signature"]), base.encode(), padding.PKCS1v15(), hashes.SHA256()
)
except InvalidSignature as err:
raise SignatureError("bad_signature") from err
return VerifiedSignature(NAME, params["keyId"])
@@ -0,0 +1,328 @@
"""RFC 9421 HTTP Message Signatures, as Mastodon 4.5+ accepts and 4.7+ sends them.
Signature-Input: sig1=("@method" "@target-uri" "content-digest");created=…;keyid="…"
Signature: sig1=:<base64>:
Content-Digest: sha-256=:<base64>:
Includes the small part of RFC 8941 (structured fields) these headers use.
"""
import hashlib
from dataclasses import dataclass
from datetime import UTC, datetime
from urllib.parse import urlsplit
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from scrobbler.federation.protocol.signatures.base import (
PublicKeyFor,
SignatureError,
SignatureScheme,
SignedRequest,
VerifiedSignature,
b64,
check_time,
unb64,
)
NAME = "rfc9421"
ALGORITHM = "rsa-v1_5-sha256"
LABEL = "sig1"
# --- RFC 8941 structured fields (the subset used here) --------------------------------
@dataclass(frozen=True)
class Item:
value: object # str (string or token), int, bool or bytes
params: tuple[tuple[str, object], ...] = ()
@dataclass(frozen=True)
class InnerList:
items: tuple[Item, ...]
params: tuple[tuple[str, object], ...] = ()
class _Parser:
def __init__(self, text: str):
self.text, self.pos = text, 0
def error(self, message: str):
return SignatureError("malformed", f"{message} at {self.pos}")
def peek(self) -> str:
return self.text[self.pos] if self.pos < len(self.text) else ""
def skip(self, chars: str = " \t") -> None:
while self.peek() and self.peek() in chars:
self.pos += 1
def key(self) -> str:
start = self.pos
if not (self.peek().islower() or self.peek() == "*"):
raise self.error("expected a key")
while self.peek() and (
self.peek().islower() or self.peek().isdigit() or self.peek() in "_-.*"
):
self.pos += 1
return self.text[start : self.pos]
def bare_item(self) -> object:
char = self.peek()
if char == '"':
self.pos += 1
out = []
while True:
char = self.peek()
if not char:
raise self.error("unterminated string")
self.pos += 1
if char == "\\":
out.append(self.peek())
self.pos += 1
elif char == '"':
return "".join(out)
else:
out.append(char)
if char == ":":
end = self.text.find(":", self.pos + 1)
if end < 0:
raise self.error("unterminated byte sequence")
value = unb64(self.text[self.pos + 1 : end])
self.pos = end + 1
return value
if char == "?":
self.pos += 2
return self.text[self.pos - 1] == "1"
if char == "-" or char.isdigit():
start = self.pos
self.pos += 1
while self.peek().isdigit():
self.pos += 1
return int(self.text[start : self.pos])
if char.isalpha() or char == "*": # token
start = self.pos
while self.peek() and self.peek() not in ' \t,;()"=':
self.pos += 1
return self.text[start : self.pos]
raise self.error("unexpected character")
def params(self) -> tuple[tuple[str, object], ...]:
out = []
while self.peek() == ";":
self.pos += 1
self.skip(" ")
name = self.key()
value: object = True
if self.peek() == "=":
self.pos += 1
value = self.bare_item()
out.append((name, value))
return tuple(out)
def item_or_inner_list(self) -> Item | InnerList:
if self.peek() == "(":
self.pos += 1
items = []
while True:
self.skip(" ")
if self.peek() == ")":
self.pos += 1
return InnerList(tuple(items), self.params())
items.append(Item(self.bare_item(), self.params()))
if self.peek() not in " )":
raise self.error("bad inner list")
return Item(self.bare_item(), self.params())
def dictionary(self) -> dict[str, Item | InnerList]:
out: dict[str, Item | InnerList] = {}
self.skip()
while self.peek():
name = self.key()
if self.peek() == "=":
self.pos += 1
out[name] = self.item_or_inner_list()
else:
out[name] = Item(True, self.params())
self.skip()
if not self.peek():
break
if self.peek() != ",":
raise self.error("expected ','")
self.pos += 1
self.skip()
return out
def parse_dictionary(text: str) -> dict[str, Item | InnerList]:
return _Parser(text).dictionary()
def _serialize_bare(value: object) -> str:
if isinstance(value, bool):
return "?1" if value else "?0"
if isinstance(value, int):
return str(value)
if isinstance(value, bytes):
return f":{b64(value)}:"
text = str(value)
return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'
def _serialize_params(params) -> str:
return "".join(
f";{name}" if value is True else f";{name}={_serialize_bare(value)}"
for name, value in params
)
def serialize_inner_list(inner: InnerList) -> str:
items = " ".join(_serialize_bare(i.value) + _serialize_params(i.params) for i in inner.items)
return f"({items}){_serialize_params(inner.params)}"
# --- Signature base (RFC 9421 §2.5) ------------------------------------------------------
def _component_value(request: SignedRequest, item: Item) -> str:
name = str(item.value)
if item.params:
raise SignatureError("unsupported", f"component parameters on {name}")
parts = urlsplit(request.url)
if name == "@method":
return request.method.upper()
if name == "@target-uri":
return request.url
if name == "@authority":
return parts.netloc.lower()
if name == "@scheme":
return parts.scheme.lower()
if name == "@request-target":
return request.path_and_query
if name == "@path":
return parts.path or "/"
if name == "@query":
return f"?{parts.query}"
if name.startswith("@"):
raise SignatureError("unsupported", f"component {name}")
value = request.header(name)
if value is None:
raise SignatureError("malformed", f"covered header {name} is missing")
return value.strip()
def signature_base(request: SignedRequest, inner: InnerList) -> str:
lines = [f'"{item.value}": {_component_value(request, item)}' for item in inner.items]
lines.append(f'"@signature-params": {serialize_inner_list(inner)}')
return "\n".join(lines)
# --- Content-Digest (RFC 9530) -------------------------------------------------------------
_DIGESTS = {"sha-256": hashlib.sha256, "sha-512": hashlib.sha512}
def content_digest(body: bytes) -> str:
return f"sha-256=:{b64(hashlib.sha256(body).digest())}:"
def check_content_digest(request: SignedRequest) -> None:
header = request.header("content-digest")
if not header:
raise SignatureError("insufficient", "no Content-Digest header")
for name, member in parse_dictionary(header).items():
if name in _DIGESTS and isinstance(member, Item) and isinstance(member.value, bytes):
if member.value != _DIGESTS[name](request.body).digest():
raise SignatureError("digest_mismatch")
return
raise SignatureError("unsupported", "no sha-256 or sha-512 Content-Digest")
# --- The scheme ------------------------------------------------------------------------------
class Rfc9421(SignatureScheme):
name = NAME
def present(self, request: SignedRequest) -> bool:
return request.header("signature-input") is not None
def sign(
self, request: SignedRequest, key_id: str, private_key: RSAPrivateKey, now: datetime
) -> dict[str, str]:
added: dict[str, str] = {}
components = ["@method", "@target-uri"]
if request.body or request.method.upper() == "POST":
added["Content-Digest"] = content_digest(request.body)
components.append("content-digest")
inner = InnerList(
tuple(Item(c) for c in components),
(("created", int(now.timestamp())), ("keyid", key_id), ("alg", ALGORITHM)),
)
signing = SignedRequest(
request.method, request.url, {**request.headers, **added}, request.body
)
base = signature_base(signing, inner)
signature = private_key.sign(base.encode(), padding.PKCS1v15(), hashes.SHA256())
added["Signature-Input"] = f"{LABEL}={serialize_inner_list(inner)}"
added["Signature"] = f"{LABEL}=:{b64(signature)}:"
return added
def verify(
self,
request: SignedRequest,
public_key_for: PublicKeyFor,
now: datetime,
require: tuple[str, ...] | None = None,
) -> VerifiedSignature:
"""Verify the (first) signature. `require` lists components that must be covered;
by default the ActivityPub minimum: method, target and, with a body, the digest."""
raw_input, raw_signature = request.header("signature-input"), request.header("signature")
if not raw_input or not raw_signature:
raise SignatureError("missing")
inputs, signatures = parse_dictionary(raw_input), parse_dictionary(raw_signature)
label = next((name for name in inputs if name in signatures), None)
if label is None:
raise SignatureError("malformed", "no Signature for any Signature-Input label")
inner, value = inputs[label], signatures[label]
if (
not isinstance(inner, InnerList)
or not isinstance(value, Item)
or not isinstance(value.value, bytes)
):
raise SignatureError("malformed")
params = dict(inner.params)
covered = {str(item.value) for item in inner.items}
if "keyid" not in params:
raise SignatureError("malformed", "no keyid")
if params.get("alg", ALGORITHM) != ALGORITHM:
raise SignatureError("unsupported", f"alg {params['alg']}")
if require is None:
require = ("@method", "@target-uri") + (("content-digest",) if request.body else ())
if "created" not in params:
raise SignatureError("insufficient", "no created time")
missing = set(require) - covered
if missing:
raise SignatureError("insufficient", f"not covered: {sorted(missing)}")
if "created" in params:
check_time(datetime.fromtimestamp(int(params["created"]), UTC), now)
if "expires" in params and now.timestamp() > int(params["expires"]):
raise SignatureError("expired", "past expires")
if "content-digest" in covered:
check_content_digest(request)
key_id = str(params["keyid"])
key = public_key_for(key_id)
if key is None:
raise SignatureError("unknown_key", key_id)
base = signature_base(request, inner)
try:
key.verify(value.value, base.encode(), padding.PKCS1v15(), hashes.SHA256())
except InvalidSignature as err:
raise SignatureError("bad_signature") from err
return VerifiedSignature(NAME, key_id)
+306
View File
@@ -0,0 +1,306 @@
"""ActivityStreams / ActivityPub document builders (plain dicts, ready for JSON)."""
import html
from dataclasses import dataclass
AS_CONTEXT = "https://www.w3.org/ns/activitystreams"
SECURITY_CONTEXT = "https://w3id.org/security/v1"
PUBLIC = "https://www.w3.org/ns/activitystreams#Public"
# The extension terms Mastodon and friends understand on actors.
ACTOR_CONTEXT = [
AS_CONTEXT,
SECURITY_CONTEXT,
{
"manuallyApprovesFollowers": "as:manuallyApprovesFollowers",
"toot": "http://joinmastodon.org/ns#",
"discoverable": "toot:discoverable",
"indexable": "toot:indexable",
"featured": {"@id": "toot:featured", "@type": "@id"},
"schema": "http://schema.org#",
"PropertyValue": "schema:PropertyValue",
"value": "schema:value",
},
]
@dataclass(frozen=True)
class ActorUrls:
id: str
inbox: str
outbox: str
followers: str
following: str
featured: str
shared_inbox: str
key_id: str
profile_page: str
def actor_urls(base_url: str, username: str, profile_page: str) -> ActorUrls:
actor = f"{base_url}/users/{username}"
return ActorUrls(
id=actor,
inbox=f"{actor}/inbox",
outbox=f"{actor}/outbox",
followers=f"{actor}/followers",
following=f"{actor}/following",
featured=f"{actor}/collections/featured",
shared_inbox=f"{base_url}/inbox",
key_id=f"{actor}#main-key",
profile_page=profile_page,
)
def text_to_html(text: str | None) -> str:
"""Plain text (e.g. a bio) as the small HTML subset Mastodon keeps."""
if not text or not text.strip():
return ""
paragraphs = [p for p in text.strip().replace("\r\n", "\n").split("\n\n") if p.strip()]
return "".join(
"<p>" + "<br>".join(html.escape(line) for line in p.split("\n")) + "</p>"
for p in paragraphs
)
def public_key(urls: ActorUrls, public_key_pem: str) -> dict:
return {"id": urls.key_id, "owner": urls.id, "publicKeyPem": public_key_pem}
def person(
urls: ActorUrls,
*,
username: str,
name: str,
summary: str | None,
public_key_pem: str,
manually_approves_followers: bool,
discoverable: bool,
indexable: bool,
published: str | None = None,
fields: list[tuple[str, str]] = (),
) -> dict:
"""A user's actor document. `fields` are (name, plain-text value) profile fields."""
doc = {
"@context": ACTOR_CONTEXT,
"id": urls.id,
"type": "Person",
"preferredUsername": username,
"name": name,
"summary": text_to_html(summary),
"url": urls.profile_page,
"inbox": urls.inbox,
"outbox": urls.outbox,
"followers": urls.followers,
"following": urls.following,
"featured": urls.featured,
"endpoints": {"sharedInbox": urls.shared_inbox},
"publicKey": public_key(urls, public_key_pem),
"manuallyApprovesFollowers": manually_approves_followers,
"discoverable": discoverable,
"indexable": indexable,
"attachment": [
{"type": "PropertyValue", "name": field, "value": html.escape(value)}
for field, value in fields
],
}
if published:
doc["published"] = published
return doc
def application(
*,
actor_id: str,
username: str,
inbox: str,
outbox: str,
shared_inbox: str,
key_id: str,
public_key_pem: str,
url: str,
) -> dict:
"""The instance actor: signs fetches on the server's behalf."""
return {
"@context": ACTOR_CONTEXT,
"id": actor_id,
"type": "Application",
"preferredUsername": username,
"name": username,
"url": url,
"inbox": inbox,
"outbox": outbox,
"endpoints": {"sharedInbox": shared_inbox},
"publicKey": {"id": key_id, "owner": actor_id, "publicKeyPem": public_key_pem},
"manuallyApprovesFollowers": True,
"discoverable": False,
"indexable": False,
}
def ordered_collection(
collection_id: str, total: int, items: list | None = None, first: str | None = None
) -> dict:
"""A collection. With items=None only the count is published (e.g. followers). With
`first`, the collection just points at its first page rather than listing items
itself (e.g. the outbox, paged by ordered_collection_page)."""
doc = {
"@context": AS_CONTEXT,
"id": collection_id,
"type": "OrderedCollection",
"totalItems": total,
}
if items is not None:
doc["orderedItems"] = items
if first:
doc["first"] = first
return doc
def ordered_collection_page(
page_id: str,
*,
part_of: str,
items: list,
next_page: str | None = None,
prev_page: str | None = None,
) -> dict:
doc = {
"@context": AS_CONTEXT,
"id": page_id,
"type": "OrderedCollectionPage",
"partOf": part_of,
"orderedItems": items,
}
if next_page:
doc["next"] = next_page
if prev_page:
doc["prev"] = prev_page
return doc
def _response(kind: str, activity_id: str, actor_id: str, obj, to: str) -> dict:
return {
"@context": AS_CONTEXT,
"id": activity_id,
"type": kind,
"actor": actor_id,
"object": obj,
"to": [to],
}
def accept(activity_id: str, actor_id: str, follow: dict) -> dict:
"""Accept a Follow (the original Follow is embedded, as Mastodon expects)."""
return _response("Accept", activity_id, actor_id, follow, follow["actor"])
def reject(activity_id: str, actor_id: str, follow: dict) -> dict:
"""Decline a follow request, or end an existing follow.
The Follow is referenced by id rather than embedded: some servers match an embedded
Follow by the pair of accounts, so a late Reject of an old Follow would cancel a
newer request between the same accounts. An id matches exactly that Follow."""
return _response("Reject", activity_id, actor_id, follow["id"], follow["actor"])
def block(activity_id: str, actor_id: str, blocked_actor: str) -> dict:
return _response("Block", activity_id, actor_id, blocked_actor, blocked_actor)
def undo(activity_id: str, actor_id: str, undone: dict) -> dict:
"""Withdraw one of our earlier activities (e.g. a Block when unblocking)."""
to = undone.get("to") or []
return {
"@context": AS_CONTEXT,
"id": activity_id,
"type": "Undo",
"actor": actor_id,
"object": undone,
"to": list(to),
}
def update(activity_id: str, actor_id: str, obj: dict, *, to: list[str]) -> dict:
"""Tells already-following servers something about the actor changed (their now
playing field, here), so they don't have to re-fetch it to notice."""
return {
"@context": AS_CONTEXT,
"id": activity_id,
"type": "Update",
"actor": actor_id,
"object": obj,
"to": list(to),
}
def hashtag(name: str) -> dict:
"""A Hashtag tag, e.g. #Scrobbler. No href: we don't serve tag pages, and Mastodon
still recognises and indexes the tag from `name` alone."""
return {"type": "Hashtag", "name": f"#{name}"}
def note(
note_id: str,
*,
actor_id: str,
content_html: str,
published: str,
url: str,
to: list[str],
cc: list[str],
tags: list[str] = (),
attachment: list[dict] = (),
) -> dict:
"""A post (now playing, weekly summary or milestone). No `@context`: it's always
embedded in the Create that carries the same addressing, as Mastodon does."""
doc = {
"id": note_id,
"type": "Note",
"attributedTo": actor_id,
"content": content_html,
"contentMap": {"en": content_html},
"published": published,
"url": url,
"to": list(to),
"cc": list(cc),
"tag": [hashtag(t) for t in tags],
"sensitive": False,
}
if attachment:
doc["attachment"] = list(attachment)
return doc
def create(activity_id: str, actor_id: str, obj: dict, *, to: list[str], cc: list[str]) -> dict:
"""Wraps a Note (or other object) for publishing, with the same addressing."""
return {
"@context": AS_CONTEXT,
"id": activity_id,
"type": "Create",
"actor": actor_id,
"object": obj,
"published": obj.get("published"),
"to": list(to),
"cc": list(cc),
}
def delete(activity_id: str, actor_id: str, note_id: str, *, to: list[str], cc: list[str]) -> dict:
"""Withdraws one of our Notes, as a Tombstone (the shape Mastodon sends)."""
return {
"@context": AS_CONTEXT,
"id": activity_id,
"type": "Delete",
"actor": actor_id,
"object": {"id": note_id, "type": "Tombstone"},
"to": list(to),
"cc": list(cc),
}
def object_id(value) -> str | None:
"""An object's id, whether it's given inline (a dict) or as a bare URI."""
if isinstance(value, dict):
value = value.get("id")
return value if isinstance(value, str) and value else None
@@ -0,0 +1,44 @@
"""WebFinger (RFC 7033): resolving acct:user@domain to an actor."""
import re
from scrobbler.federation.protocol.media import ACTIVITY_JSON
_USERNAME = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
class ResourceError(ValueError):
"""The resource isn't something this server answers for (400, not 404)."""
def parse_resource(resource: str | None, *, domain: str, base_url: str) -> str:
"""The username in `acct:user@domain` (optionally with a leading @), or in an actor URL
`<base_url>/users/<user>`. Raises ResourceError for anything else."""
value = (resource or "").strip()
if value.lower().startswith(f"{base_url.lower()}/users/"):
username = value[len(base_url) + len("/users/") :]
else:
if value.lower().startswith("acct:"):
value = value[5:]
value = value.lstrip("@")
username, at, host = value.rpartition("@")
if not at or host.lower() != domain.lower():
raise ResourceError("resource must be acct:user@" + domain)
if not _USERNAME.match(username):
raise ResourceError("invalid username")
return username
def jrd(*, username: str, domain: str, actor_id: str, profile_page: str) -> dict:
return {
"subject": f"acct:{username}@{domain}",
"aliases": [actor_id, profile_page],
"links": [
{"rel": "self", "type": ACTIVITY_JSON, "href": actor_id},
{
"rel": "http://webfinger.net/rel/profile-page",
"type": "text/html",
"href": profile_page,
},
],
}
@@ -0,0 +1,26 @@
"""Posts to followers: weekly summaries (weekly.py) and milestones (milestones.py), and
later now-playing. Shared machinery — idempotent publishing, addressing, fan-out and
deletion — lives in base.py.
"""
from scrobbler.federation.publishing.base import (
LISTED_VISIBILITIES,
OUTBOX_PAGE_SIZE,
delete_all_for,
delete_post,
find_by_note_id,
has_post,
outbox_page,
publish,
)
__all__ = [
"LISTED_VISIBILITIES",
"OUTBOX_PAGE_SIZE",
"delete_all_for",
"delete_post",
"find_by_note_id",
"has_post",
"outbox_page",
"publish",
]
+189
View File
@@ -0,0 +1,189 @@
"""Publishing posts: building and storing the Note/Create, fanning out to accepted
followers, and deleting.
Each post kind (weekly.py, milestones.py, and later now-playing) decides *when* to post
and builds the text; this module handles what every post shares: idempotence (one row
per (user, key), enforced by federation_posts' unique constraint), addressing from the
user's current visibility, storage, delivery and deletion.
"""
import uuid
from datetime import UTC, datetime
from sqlalchemy.exc import IntegrityError
from scrobbler.extensions import db
from scrobbler.federation import activities, followers, ids, sharing
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation.models import FederationActivity, FederationPost
from scrobbler.federation.protocol import addressing, vocab
DEFAULT_TAGS = ("Scrobbler",)
OUTBOX_PAGE_SIZE = 20
LISTED_VISIBILITIES = ("public", "unlisted") # followers-only posts aren't listed unauthenticated
def _now() -> datetime:
return datetime.now(UTC)
def _listed(user_id: int):
return (
FederationPost.user_id == user_id,
FederationPost.deleted_at.is_(None),
FederationPost.visibility.in_(LISTED_VISIBILITIES),
)
def outbox_page(
user_id: int, page: int, per_page: int = OUTBOX_PAGE_SIZE
) -> tuple[list[dict], int]:
"""Create documents for a user's outbox: public and unlisted posts only, newest
first, paged. `page` is 1-based."""
conditions = _listed(user_id)
total = db.session.scalar(
db.select(db.func.count()).select_from(FederationPost).filter(*conditions)
)
rows = db.session.scalars(
db.select(FederationActivity)
.join(FederationPost, FederationPost.activity_id == FederationActivity.id)
.filter(*conditions)
.order_by(FederationActivity.created_at.desc())
.limit(per_page)
.offset((page - 1) * per_page)
).all()
return [row.document for row in rows], total
def find_by_note_id(user_id: int, note_id: str) -> FederationPost | None:
"""The post whose Note has this id (the URL served at /users/<u>/posts/<uuid>)."""
return db.session.scalar(
db.select(FederationPost)
.join(FederationActivity, FederationActivity.id == FederationPost.activity_id)
.filter(
FederationPost.user_id == user_id,
FederationActivity.document["object"]["id"].as_string() == note_id,
)
)
def has_post(user_id: int, kind: str, key: str) -> bool:
"""Whether a post with this (user, kind, key) already exists (posted or since
deleted). Lets a caller skip expensive work — computing stats, say — before deciding
whether to call publish() at all."""
full_key = f"{kind}:{key}"
return (
db.session.scalar(db.select(FederationPost.id).filter_by(user_id=user_id, key=full_key))
is not None
)
def publish(
user_id: int,
username: str,
kind: str,
key: str,
*,
text: str,
html: str,
tags: tuple[str, ...] = DEFAULT_TAGS,
attachment: list[dict] = (),
) -> FederationPost | None:
"""Post `text`/`html` for the user, keyed by `kind:key`.
Idempotent: a second call with the same (user, kind, key) is a no-op, including when
two worker passes race each other (caught as a duplicate-key error, not raised).
Returns None, without posting, if the user isn't sharing or the key already exists.
"""
settings = sharing.settings_for(user_id)
if not settings.enabled:
return None
full_key = f"{kind}:{key}"
already = db.session.scalar(
db.select(FederationPost.id).filter_by(user_id=user_id, key=full_key)
)
if already:
return None
published = _now().isoformat().replace("+00:00", "Z")
post_uuid = str(uuid.uuid4())
to, cc = addressing.address(settings.visibility, ids.followers_url(username))
note_doc = vocab.note(
ids.note_url(username, post_uuid),
actor_id=ids.actor_id(username),
content_html=html,
published=published,
url=ids.post_page_url(username, post_uuid),
to=to,
cc=cc,
tags=list(tags),
attachment=list(attachment),
)
# activity.id is a Python-generated UUID (see activities.store), so it's already
# usable below without a flush.
activity = activities.store(
user_id,
lambda url: vocab.create(url, ids.actor_id(username), note_doc, to=to, cc=cc),
public=addressing.is_public_or_unlisted(settings.visibility),
)
post = FederationPost(
user_id=user_id,
kind=kind,
key=full_key,
activity_id=activity.id,
visibility=settings.visibility,
content_text=text,
content_html=html,
)
db.session.add(post)
inboxes = followers.accepted_inboxes(user_id)
if inboxes:
activities.queue(activity, inboxes)
try:
db.session.commit()
except IntegrityError: # posted with this key by a concurrent pass
db.session.rollback()
return None
fed_metrics.posts_total.labels(kind=kind, visibility=settings.visibility).inc()
return post
def delete_post(user_id: int, username: str, post: FederationPost) -> FederationActivity | None:
"""Delete one post: sends Delete to the same inboxes the Create went to, and
tombstones the row (kept, so its key can never be reused). The caller commits.
None if it's already deleted."""
if post.deleted_at is not None:
return None
return _delete(user_id, username, post, reason="manual")
def delete_all_for(user_id: int, username: str) -> int:
"""Sharing switched off: delete every live post before the Rejects go out (call this
before followers.reject_all — it needs accepted_inboxes() to still have somewhere to
send the Deletes). The caller commits. Returns how many were deleted."""
posts = db.session.scalars(
db.select(FederationPost).filter_by(user_id=user_id, deleted_at=None)
).all()
for post in posts:
_delete(user_id, username, post, reason="sharing_off")
return len(posts)
def _delete(
user_id: int, username: str, post: FederationPost, *, reason: str
) -> FederationActivity:
# The post's own visibility at the time it was posted, not the user's current
# setting: a Delete has to reach whoever could have seen the Create.
note_id = post.activity.document["object"]["id"]
to, cc = addressing.address(post.visibility, ids.followers_url(username))
activity = activities.store(
user_id,
lambda url: vocab.delete(url, ids.actor_id(username), note_id, to=to, cc=cc),
public=addressing.is_public_or_unlisted(post.visibility),
)
inboxes = followers.accepted_inboxes(user_id)
if inboxes:
activities.queue(activity, inboxes)
post.deleted_at = _now()
fed_metrics.post_deletions_total.labels(reason=reason).inc()
return activity
@@ -0,0 +1,241 @@
"""Milestones: total scrobbles, plays of one artist, and entries into a user's all-time
top 10 — each posted once, the first time it's reached.
Checked only for a user's own live scrobbles (never for imports, which would otherwise
flood years of history through as if it just happened): the `scrobbles_stored` receiver
below queues a FederationPendingCheck row, drained by the `federation.milestones` worker
task. Enabling sharing, and finishing an import, instead call `set_baseline` — every
threshold already passed is marked done without posting, so a new or returning sharer
never gets a burst of "congratulations" for plays from years ago.
"""
import logging
from scrobbler.extensions import db
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation import publishing, sharing
from scrobbler.federation.models import FederationMilestoneMark, FederationPendingCheck
from scrobbler.federation.protocol import content
from scrobbler.services import accounts, stats
log = logging.getLogger(__name__)
KIND = "milestone"
SCROBBLE_THRESHOLDS = [1000, 5000, 10000, *range(25000, 500_000, 25000)]
ARTIST_THRESHOLDS = [100, 500, 1000]
TOP_N = 10
# A top-10 entry and an artist-plays threshold are only ever checked against a user's
# current top ARTIST_SCAN artists: crossing 100+ plays for one artist keeps it well
# within a generous slice, and scanning a user's entire artist list on every scrobble
# would be unbounded. A crossing that (rarely) falls outside this slice is simply
# missed rather than triggering a full unpaginated scan.
ARTIST_SCAN = 20
def _existing_marks(user_id: int) -> set[str]:
rows = db.session.scalars(db.select(FederationMilestoneMark.key).filter_by(user_id=user_id))
return set(rows)
def _mark(user_id: int, key: str, *, posted: bool) -> None:
db.session.add(FederationMilestoneMark(user_id=user_id, key=key, posted=posted))
def _scrobbles_content(threshold: int) -> tuple[str, str]:
words = content.plural(threshold, "play")
headline = f"{threshold:,} {words} scrobbled"
text = "\n".join([headline, content.hashtag_line()])
html = content.paragraph(f"<strong>{content.escape(headline)}</strong>") + content.paragraph(
content.hashtag_line()
)
return text, html
def _artist_content(artist: str, threshold: int) -> tuple[str, str]:
words = content.plural(threshold, "play")
headline = f"{threshold:,} {words} of {artist}"
text = "\n".join([headline, content.hashtag_line()])
html = content.paragraph(
f"<strong>{threshold:,} {words} of {content.escape(artist)}</strong>"
) + content.paragraph(content.hashtag_line())
return text, html
def _top10_content(artist: str, rank: int) -> tuple[str, str]:
headline = f"{artist} entered my all-time top 10 (#{rank})"
text = "\n".join([headline, content.hashtag_line()])
html = content.paragraph(f"<strong>{content.escape(headline)}</strong>") + content.paragraph(
content.hashtag_line()
)
return text, html
def _scrobble_milestone(user, existing: set[str]) -> tuple[str, str, str] | None:
"""(key, text, html) for the highest not-yet-marked scrobble-count threshold this
user has reached, marking every lower one reached at the same time silently. None if
none has been reached."""
count = stats.summary(user)["scrobbles"]
reached = [t for t in SCROBBLE_THRESHOLDS if t <= count and f"scrobbles:{t}" not in existing]
if not reached:
return None
for threshold in reached[:-1]:
_mark(user.id, f"scrobbles:{threshold}", posted=False)
top = reached[-1]
text, html = _scrobbles_content(top)
return f"scrobbles:{top}", text, html
def _artist_milestone(user, existing: set[str]) -> tuple[str, str, str] | None:
"""(key, text, html) for the highest not-yet-marked plays-of-one-artist threshold
reached by any artist in the user's current top ARTIST_SCAN. Only one post per
check, even if more than one artist or threshold qualifies at once."""
top_artists = stats.top_artists(user, per_page=ARTIST_SCAN).items
best: tuple[str, str, int, int] | None = None # (key, artist, threshold, playcount)
for artist in top_artists:
name = artist.name.lower()
reached = [
t
for t in ARTIST_THRESHOLDS
if t <= artist.playcount and f"artist:{name}:{t}" not in existing
]
for threshold in reached[:-1]:
_mark(user.id, f"artist:{name}:{threshold}", posted=False)
if reached and (best is None or reached[-1] > best[2]):
best = (f"artist:{name}:{reached[-1]}", artist.name, reached[-1], artist.playcount)
if best is None:
return None
key, artist_name, threshold, _ = best
text, html = _artist_content(artist_name, threshold)
return key, text, html
def _top10_milestone(user, existing: set[str]) -> tuple[str, str, str] | None:
"""(key, text, html) for the highest-ranked, not-yet-marked new entry into the
user's current all-time top 10. Only one post per check.
Nothing is posted until the user actually has TOP_N distinct artists: with fewer
than that, every first play of a new artist would trivially "enter the top 10",
which isn't a real milestone.
"""
page = stats.top_artists(user, per_page=TOP_N)
if page.total < TOP_N:
return None
for artist in page.items: # already ranked best first
key = f"top10:{artist.name.lower()}"
if key not in existing:
text, html = _top10_content(artist.name, artist.rank)
return key, text, html
return None
def check_and_post(user_id: int) -> str:
"""For one user, post at most one milestone: the first of scrobble-count, top-10
entry, or artist-plays (in that priority) that has a new, unmarked threshold to
report. Returns a result: disabled, none or posted."""
result = _check_and_post(user_id)
fed_metrics.milestone_checks_total.labels(result=result).inc()
return result
def _check_and_post(user_id: int) -> str:
settings = sharing.settings_for(user_id)
if not (settings.enabled and settings.post_milestones):
return "disabled"
user = accounts.get_user(user_id)
if user is None: # the account was deleted; federation_settings should follow, but be safe
return "disabled"
existing = _existing_marks(user_id)
found = (
_scrobble_milestone(user, existing)
or _top10_milestone(user, existing)
or _artist_milestone(user, existing)
)
if found is None:
return "none"
key, text, html = found
post = publishing.publish(user.id, user.username, KIND, key, text=text, html=html)
if post is not None:
_mark(user.id, key, posted=True)
return "posted" if post is not None else "none" # lost a race with another pass
def set_baseline(user_id: int) -> None:
"""Mark every threshold this user has already passed, without posting: called when
a user enables sharing, and after an import finishes, so history already on file
never produces a flood of retroactive "milestone" posts."""
user = accounts.get_user(user_id)
if user is None:
return
existing = _existing_marks(user_id)
count = stats.summary(user)["scrobbles"]
for threshold in SCROBBLE_THRESHOLDS:
if threshold <= count and f"scrobbles:{threshold}" not in existing:
_mark(user_id, f"scrobbles:{threshold}", posted=False)
top_artists = stats.top_artists(user, per_page=max(TOP_N, ARTIST_SCAN))
has_top10 = top_artists.total >= TOP_N
for artist in top_artists.items:
name = artist.name.lower()
if has_top10 and artist.rank <= TOP_N and f"top10:{name}" not in existing:
_mark(user_id, f"top10:{name}", posted=False)
for threshold in ARTIST_THRESHOLDS:
if threshold <= artist.playcount and f"artist:{name}:{threshold}" not in existing:
_mark(user_id, f"artist:{name}:{threshold}", posted=False)
db.session.commit()
def on_scrobbles_stored(sender, *, scrobbles, source, **kwargs) -> None:
"""Queue a milestone check for the user's own live scrobbles. Imports are never
live listening, so they're excluded here and instead handled by set_baseline via
on_import_finished."""
if source != "scrobble" or not scrobbles:
return
settings = sharing.settings_for(sender.id)
if not (settings.enabled and settings.post_milestones):
return
if db.session.get(FederationPendingCheck, sender.id) is None:
db.session.add(FederationPendingCheck(user_id=sender.id))
db.session.commit()
def on_import_finished(sender, *, job, **kwargs) -> None:
"""An import just finished: mark whatever it added as baseline, silently, rather
than queuing a live check that would post about years-old history."""
settings = sharing.settings_for(sender.id)
if not settings.enabled: # skip the computation for users who've never touched federation
return
set_baseline(sender.id)
def work_once() -> bool:
"""Claim one pending user (oldest first) and check them. On failure, the row is
requeued at the back rather than retried immediately, so one persistently-failing
user's checks (a pure DB read — unlike delivery, there's no external server to fail
against) can't head-of-line-block everyone behind them."""
row = db.session.execute(
db.select(FederationPendingCheck)
.order_by(FederationPendingCheck.since)
.limit(1)
.with_for_update(skip_locked=True)
).scalar_one_or_none()
if row is None:
return False
user_id = row.user_id
try:
check_and_post(user_id)
except Exception:
log.exception("milestone check failed for user %s", user_id)
db.session.rollback()
db.session.execute(
db.update(FederationPendingCheck)
.where(FederationPendingCheck.user_id == user_id)
.values(since=db.func.now())
)
db.session.commit()
return True
db.session.execute(
db.delete(FederationPendingCheck).where(FederationPendingCheck.user_id == user_id)
)
db.session.commit()
return True
@@ -0,0 +1,181 @@
"""Now playing: a live field on the actor profile (actors.py handles that part), and
opt-in posts.
No event receiver or pending-checks queue like milestones has: the throttle windows (5
minutes for the profile push, 30 for posts) are far longer than a 30-second poll, so a
plain periodic scan - the same shape as weekly.check_all - is simplest and cheapest.
There's no baseline/import concern either: this only ever reflects what's playing right
now, never history.
"""
import hashlib
import logging
from datetime import UTC, datetime, timedelta
from flask import current_app
from scrobbler.extensions import db
from scrobbler.federation import activities, actors, followers, publishing, sharing
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation.models import FederationNowPlaying, FederationPost, FederationSettings
from scrobbler.federation.protocol import content, vocab
from scrobbler.services import accounts, art
from scrobbler.services.scrobbles import get_now_playing
KIND = "now_playing"
PROFILE_THROTTLE = timedelta(minutes=5)
POST_THROTTLE = timedelta(minutes=30)
MIN_PLAYED = timedelta(seconds=30)
log = logging.getLogger(__name__)
def _key(playing) -> str:
"""A short, fixed-length identifier for "this track, starting at this instant" -
hashed rather than the raw artist/track/timestamp, since federation_posts.key is only
VARCHAR(64) and real artist and track names routinely blow past that on their own."""
raw = f"{playing.artist}\x1f{playing.track}\x1f{playing.started_at.isoformat()}"
return hashlib.sha256(raw.encode()).hexdigest()[:16]
def _state_for(user_id: int) -> FederationNowPlaying:
state = db.session.get(FederationNowPlaying, user_id)
if state is None:
state = FederationNowPlaying(user_id=user_id)
db.session.add(state)
return state
def _due(last: datetime | None, throttle: timedelta, now: datetime) -> bool:
return last is None or now - last >= throttle
def _urls_for(username: str) -> vocab.ActorUrls:
config = current_app.extensions["federation"]
profile_page = f"{current_app.config['UI_BASE_URL']}/profile.html?u={username}"
return vocab.actor_urls(config.base_url, username, profile_page)
def _push_profile(user, settings) -> None:
urls = _urls_for(user.username)
doc = actors.build_document(urls, user, settings)
activity = activities.store(
user.id, lambda url: vocab.update(url, urls.id, doc, to=[urls.followers])
)
inboxes = followers.accepted_inboxes(user.id)
if inboxes:
activities.queue(activity, inboxes)
def _build_content(playing) -> tuple[str, str]:
text = "\n".join(
[
f"Now playing: {playing.track} by {playing.artist}",
f"{content.hashtag_line()} #NowPlaying",
]
)
html = content.paragraph(
f"Now playing: <em>{content.escape(playing.track)}</em> by {content.escape(playing.artist)}"
) + content.paragraph(f"{content.hashtag_line()} #NowPlaying")
return text, html
def _attachment_for(playing) -> list[dict]:
"""Cover art for the post, if we have an album and can resolve it. Cover Art
Archive's sized convenience endpoints (what art.lookup() resolves to) are always
JPEG, whatever the original upload was."""
if not playing.album:
return []
result = art.lookup(playing.artist, playing.album)
if result.status != "found":
return []
return [
{
"type": "Image",
"mediaType": "image/jpeg",
"url": result.image_url,
"name": f"Cover art for {playing.album}",
}
]
def _post_now_playing(user, playing, key: str, state: FederationNowPlaying, now: datetime) -> str:
text, html = _build_content(playing)
post = publishing.publish(
user.id,
user.username,
KIND,
key,
text=text,
html=html,
tags=("Scrobbler", "NowPlaying"),
attachment=_attachment_for(playing),
)
if post is None:
return "none"
if state.post_key is not None:
previous = db.session.scalar(
db.select(FederationPost).filter_by(user_id=user.id, key=f"{KIND}:{state.post_key}")
)
if previous is not None and previous.deleted_at is None:
publishing.delete_post(user.id, user.username, previous)
state.post_key = key
state.post_posted_at = now
return "posted"
def check_and_post(user_id: int, now_utc: datetime | None = None) -> dict[str, str]:
"""For one user: push a throttled profile update and/or post, whichever their
now_playing_mode calls for. Returns {"profile": ..., "post": ...}; "profile" is
"unchanged", "throttled" or "sent", "post" is "off", "none" or "posted"."""
settings = sharing.settings_for(user_id)
if settings.now_playing_mode == "off":
return {"profile": "off", "post": "off"}
user = accounts.get_user(user_id)
if user is None: # the account was deleted; federation_settings should follow, but be safe
return {"profile": "off", "post": "off"}
now_utc = now_utc or datetime.now(UTC)
playing = get_now_playing(user)
current_key = _key(playing) if playing else None
state = _state_for(user_id)
profile_result = "unchanged"
if current_key != state.profile_key:
if _due(state.profile_updated_at, PROFILE_THROTTLE, now_utc):
_push_profile(user, settings)
state.profile_key = current_key
state.profile_updated_at = now_utc
profile_result = "sent"
else:
profile_result = "throttled"
fed_metrics.profile_updates_total.labels(result=profile_result).inc()
post_result = "off"
if settings.now_playing_mode == "posts":
post_result = "none"
if (
playing is not None
and now_utc - playing.started_at >= MIN_PLAYED
and current_key != state.post_key
and _due(state.post_posted_at, POST_THROTTLE, now_utc)
):
post_result = _post_now_playing(user, playing, current_key, state, now_utc)
db.session.commit()
return {"profile": profile_result, "post": post_result}
def check_all(now_utc: datetime | None = None) -> None:
"""Worker task (periodic, every 30 seconds): check every user with now playing on.
One user's failure is logged and doesn't stop the rest from being checked."""
now_utc = now_utc or datetime.now(UTC)
user_ids = db.session.scalars(
db.select(FederationSettings.user_id).filter(FederationSettings.now_playing_mode != "off")
).all()
for user_id in user_ids:
try:
check_and_post(user_id, now_utc)
except Exception:
log.exception("now playing check failed for user %s", user_id)
db.session.rollback()
@@ -0,0 +1,149 @@
"""Weekly summaries: for each sharing user with them on, once the Monday-09:00-local
posting gate has passed (see protocol/schedule.target_week), post about the Monday-
Sunday week that just ended.
Empty weeks aren't posted. Since the target week only ever moves forward — once its own
gate has passed, it never becomes the target again — an empty week is never reconsidered
either, without needing a separate "skipped" marker.
"""
import logging
from datetime import UTC, datetime
from scrobbler.extensions import db
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation import publishing, sharing
from scrobbler.federation.models import FederationSettings
from scrobbler.federation.protocol import content, schedule
from scrobbler.services import accounts, stats
KIND = "weekly"
TOP_ARTISTS = 3
log = logging.getLogger(__name__)
def build_content(count: int, top_artists: list, top_tracks: list) -> tuple[str, str]:
headline = f"My week in music: {count} {content.plural(count, 'play')}"
text_lines = [headline]
html_parts = [content.paragraph(f"<strong>{content.escape(headline)}</strong>")]
if top_artists:
text_lines.append(
"Top artists: "
+ " ".join(f"{i}. {a.name} ({a.playcount})" for i, a in enumerate(top_artists, 1))
)
html_parts.append(
content.numbered_list(
[
f"{content.escape(a.name)} — {a.playcount} "
f"{content.plural(a.playcount, 'play')}"
for a in top_artists
]
)
)
if top_tracks:
top = top_tracks[0]
words = content.plural(top.playcount, "play")
text_lines.append(f"Most played: {top.name} by {top.artist} ({top.playcount} {words})")
html_parts.append(
content.paragraph(
f"Most played: <em>{content.escape(top.name)}</em> by "
f"{content.escape(top.artist)} ({top.playcount} {words})"
)
)
text_lines.append(content.hashtag_line())
html_parts.append(content.paragraph(content.hashtag_line()))
return "\n".join(text_lines), "".join(html_parts)
def check_and_post(settings: FederationSettings, now_utc: datetime) -> str:
"""For one user's settings, post their most recent eligible week if it's due and not
already posted. Returns a result: disabled, already_posted, skipped_empty or posted."""
result = _check_and_post(settings, now_utc)
fed_metrics.weekly_total.labels(result=result).inc()
return result
def _check_and_post(settings: FederationSettings, now_utc: datetime) -> str:
if not settings.post_weekly_summary:
return "disabled"
user = accounts.get_user(settings.user_id)
if user is None: # the account was deleted; federation_settings should follow, but be safe
return "disabled"
tz = schedule.resolve_timezone(settings.timezone)
start, end, key = schedule.target_week(now_utc, tz)
return _post_for_window(user, key, start, end)
def _post_for_window(user, key: str, start: datetime, end: datetime) -> str:
if publishing.has_post(user.id, KIND, key):
return "already_posted" # the common case: checked before, nothing new to do
count = stats.scrobble_count_between(user, start, end)
if count == 0:
return "skipped_empty"
top_artists = stats.top_artists_between(user, start, end, limit=TOP_ARTISTS)
top_tracks = stats.top_tracks_between(user, start, end, limit=1)
text, html = build_content(count, top_artists, top_tracks)
post = publishing.publish(user.id, user.username, KIND, key, text=text, html=html)
return "posted" if post is not None else "already_posted" # lost a race with another pass
def post_now(user_id: int, now_utc: datetime | None = None) -> str:
"""Post this user's summary immediately, for the week still in progress, ignoring
the Monday-09:00 gate. For operators (`flask federation post-weekly --now`) and the
interop test - not part of the automated pipeline (check_and_post/check_all), so it
isn't itself gated on post_weekly_summary being checked by a worker pass."""
settings = sharing.settings_for(user_id)
if not (settings.enabled and settings.post_weekly_summary):
result = "disabled"
else:
user = accounts.get_user(user_id)
if user is None:
result = "disabled"
else:
now_utc = now_utc or datetime.now(UTC)
tz = schedule.resolve_timezone(settings.timezone)
start = schedule.current_week_start(now_utc, tz)
key = schedule.week_key(start.astimezone(tz).date())
result = _post_for_window(user, key, start, now_utc)
fed_metrics.weekly_total.labels(result=result).inc()
return result
def preview(user_id: int, now_utc: datetime | None = None) -> tuple[str, str] | None:
"""What a weekly summary would say right now, for the week still in progress. Never
stored or posted: for the Sharing page's live preview. None if the account is gone."""
user = accounts.get_user(user_id)
if user is None:
return None
settings = sharing.settings_for(user_id)
tz = schedule.resolve_timezone(settings.timezone)
now_utc = now_utc or datetime.now(UTC)
start = schedule.current_week_start(now_utc, tz)
count = stats.scrobble_count_between(user, start, now_utc)
top_artists = stats.top_artists_between(user, start, now_utc, limit=TOP_ARTISTS)
top_tracks = stats.top_tracks_between(user, start, now_utc, limit=1)
return build_content(count, top_artists, top_tracks)
def check_all(now_utc: datetime | None = None) -> None:
"""Worker task (periodic): check every sharing user with weekly summaries on. One
user's failure is logged and doesn't stop the rest from being checked."""
now_utc = now_utc or datetime.now(UTC)
settings_rows = db.session.scalars(
db.select(FederationSettings).filter_by(enabled=True, post_weekly_summary=True)
).all()
for settings in settings_rows:
try:
check_and_post(settings, now_utc)
except Exception:
log.exception("weekly summary check failed for user %s", settings.user_id)
db.session.rollback()
else:
db.session.commit()
+144
View File
@@ -0,0 +1,144 @@
"""Remote actors: fetched with a signed GET, validated, cached for a day.
Validation (a document must really be the actor it claims to be):
* its `id` equals the URL it was fetched from, and the host matches;
* it's an actor type with an inbox on the same host;
* its `publicKey` is owned by it (`publicKey.owner == id`).
"""
from datetime import UTC, datetime, timedelta
from urllib.parse import urldefrag, urlsplit
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
from scrobbler.extensions import db
from scrobbler.federation import outbound
from scrobbler.federation.models import FederationRemoteActor
from scrobbler.federation.net import FetchError
ACTOR_TYPES = {"Person", "Service", "Application", "Group", "Organization"}
MAX_AGE = timedelta(hours=24)
MAX_URL = 1024
class ActorError(Exception):
"""A remote document that isn't a valid actor (or key)."""
def _host(url: str) -> str:
return (urlsplit(url).hostname or "").lower()
def _text(value, limit: int) -> str | None:
return value[:limit] if isinstance(value, str) and value else None
def _parse_actor(uri: str, doc: dict) -> dict:
if len(uri) > 2048:
raise ActorError("actor URI too long")
if doc.get("id") != uri:
raise ActorError(f"{uri} claims to be {doc.get('id')!r}")
if doc.get("type") not in ACTOR_TYPES:
raise ActorError(f"{uri} isn't an actor ({doc.get('type')!r})")
host = _host(uri)
inbox = doc.get("inbox")
if not isinstance(inbox, str) or _host(inbox) != host or len(inbox) > MAX_URL:
raise ActorError(f"{uri} has no inbox on its own host")
endpoints = doc.get("endpoints") if isinstance(doc.get("endpoints"), dict) else {}
shared = endpoints.get("sharedInbox")
if not isinstance(shared, str) or _host(shared) != host or len(shared) > MAX_URL:
shared = None
key = doc.get("publicKey")
if isinstance(key, list): # some servers list several
key = next((k for k in key if isinstance(k, dict) and k.get("owner") == uri), None)
if not isinstance(key, dict) or key.get("owner") != uri or not key.get("publicKeyPem"):
raise ActorError(f"{uri} has no public key of its own")
key_id = key.get("id")
if not isinstance(key_id, str) or _host(key_id) != host:
raise ActorError(f"{uri}'s key id isn't on its host")
load_public_key(key["publicKeyPem"]) # must parse
return {
"host": host,
"inbox": inbox,
"shared_inbox": shared,
"username": _text(doc.get("preferredUsername"), 255),
"display_name": _text(doc.get("name"), 255),
"public_key_id": key_id,
"public_key_pem": key["publicKeyPem"],
}
def load_public_key(pem: str) -> RSAPublicKey:
try:
key = serialization.load_pem_public_key(pem.encode())
except (ValueError, TypeError) as err:
raise ActorError("unreadable public key") from err
if not isinstance(key, RSAPublicKey):
raise ActorError("only RSA keys are supported")
return key
def get_actor(uri: str, refresh: bool = False) -> FederationRemoteActor:
"""The actor at `uri`, from cache if fresh. Raises ActorError or FetchError."""
actor = db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=uri))
fresh = actor is not None and datetime.now(UTC) - actor.fetched_at < MAX_AGE
if actor is not None and not refresh and (fresh or actor.gone):
return actor
try:
fields = _parse_actor(uri, outbound.signed_get_json(uri))
except FetchError as err:
if err.status == 410 and actor is not None: # deleted account
actor.gone = True
db.session.commit()
raise
if actor is None:
actor = FederationRemoteActor(uri=uri, **fields)
db.session.add(actor)
else:
for name, value in fields.items():
setattr(actor, name, value)
actor.gone = False
actor.fetched_at = datetime.now(UTC)
db.session.commit()
return actor
def actor_for_key(key_id: str, refresh: bool = False) -> FederationRemoteActor:
"""The actor that owns `key_id`. Servers publish keys three ways:
* a fragment of the actor (`<actor>#main-key`, Mastodon);
* a URL that serves the actor document itself (`<actor>/main-key`, GoToSocial);
* a separate key document naming its `owner`."""
cached = db.session.scalar(db.select(FederationRemoteActor).filter_by(public_key_id=key_id))
if cached is not None and not refresh:
# Any age will do for checking a signature (a failure refreshes once). This also
# lets a deleted account's Delete verify although its server now answers 410.
return cached
document_url = urldefrag(key_id).url
try:
return _matching(get_actor(document_url, refresh=True), key_id)
except ActorError:
pass # the key's URL isn't the actor's own URL: find the owner from the document
doc = outbound.signed_get_json(document_url)
if doc.get("id") == key_id and isinstance(doc.get("owner"), str):
owner = doc["owner"] # a standalone key document
elif isinstance(doc.get("id"), str) and _key_id_of(doc) == key_id:
owner = doc["id"] # the actor document, served at the key's URL
else:
raise ActorError(f"can't find who owns key {key_id}")
if _host(owner) != _host(key_id):
raise ActorError(f"key {key_id} claims an owner on another host")
return _matching(get_actor(owner, refresh=True), key_id)
def _key_id_of(doc: dict) -> str | None:
key = doc.get("publicKey")
if isinstance(key, list):
key = next((k for k in key if isinstance(k, dict)), None)
return key.get("id") if isinstance(key, dict) else None
def _matching(actor: FederationRemoteActor, key_id: str) -> FederationRemoteActor:
if actor.public_key_id != key_id:
raise ActorError(f"{actor.uri} doesn't use key {key_id}")
return actor
+126
View File
@@ -0,0 +1,126 @@
from marshmallow import Schema, ValidationError, fields, validate
from scrobbler.federation.models import NOW_PLAYING_MODES, VISIBILITIES
from scrobbler.federation.protocol.schedule import is_valid_timezone
def _valid_timezone(value: str) -> None:
if not is_valid_timezone(value):
raise ValidationError("Not a known time zone.")
class SharingSettingsSchema(Schema):
enabled = fields.Boolean(metadata={"description": "Share listening on the fediverse"})
visibility = fields.String(
validate=validate.OneOf(VISIBILITIES),
metadata={
"description": (
"Who sees posts: `followers` (default), `unlisted` (anyone visiting the "
"profile, not public timelines) or `public`. Followers-only is only as private "
"as who may follow: see `manually_approves_followers`."
)
},
)
manually_approves_followers = fields.Boolean()
discoverable = fields.Boolean(metadata={"description": "May appear in profile directories"})
indexable = fields.Boolean(metadata={"description": "Posts may be indexed for search"})
display_name = fields.String(allow_none=True, validate=validate.Length(max=100))
bio = fields.String(allow_none=True, validate=validate.Length(max=500))
timezone = fields.String(
validate=_valid_timezone,
metadata={
"description": (
"IANA time zone, e.g. `Europe/London`. Decides when a week ends for the "
"weekly summary."
),
"example": "Europe/London",
},
)
post_weekly_summary = fields.Boolean(
metadata={"description": "Post a weekly summary of your listening"}
)
post_milestones = fields.Boolean(
metadata={
"description": "Post scrobble-count, artist-plays and top-10 milestones as you hit them"
}
)
now_playing_mode = fields.String(
validate=validate.OneOf(NOW_PLAYING_MODES),
metadata={
"description": (
'`off` (default): nothing. `profile`: a "Now playing" field on your '
"profile, refreshed at most every 5 minutes and cleared when you stop. "
"`posts`: the profile field, plus a post for each track played 30+ "
"seconds, at most one every 30 minutes, replacing the last one."
)
},
)
handle = fields.String(dump_only=True, metadata={"example": "@alice@scrobble.example"})
actor_url = fields.String(dump_only=True)
profile_url = fields.String(dump_only=True)
followers = fields.Integer(dump_only=True, metadata={"description": "Accepted followers"})
pending_followers = fields.Integer(
dump_only=True, metadata={"description": "Waiting for approval"}
)
class PublicProfileSchema(Schema):
username = fields.String()
display_name = fields.String()
bio = fields.String(allow_none=True)
now_playing = fields.String(
allow_none=True, metadata={"description": '"Track by Artist", or null'}
)
handle = fields.String(metadata={"example": "@alice@scrobble.example"})
actor_url = fields.String()
class SharingSettingsUpdateSchema(SharingSettingsSchema):
"""Any subset of the editable settings (read-only fields are rejected)."""
class FollowerSchema(Schema):
id = fields.Integer()
state = fields.String(validate=validate.OneOf(["pending", "accepted"]))
handle = fields.String(metadata={"example": "@bob@mastodon.example"})
display_name = fields.String(allow_none=True)
actor_url = fields.String()
server = fields.String(metadata={"example": "mastodon.example"})
since = fields.DateTime(metadata={"description": "When they followed (or asked to)"})
class FollowerListArgsSchema(Schema):
state = fields.String(load_default=None, validate=validate.OneOf(["pending", "accepted"]))
class BlockSchema(Schema):
id = fields.Integer()
handle = fields.String()
display_name = fields.String(allow_none=True)
actor_url = fields.String()
since = fields.DateTime()
class PostSchema(Schema):
id = fields.Integer()
kind = fields.String(metadata={"description": "weekly, milestone or now_playing"})
text = fields.String()
visibility = fields.String()
created_at = fields.DateTime()
deleted_at = fields.DateTime(allow_none=True)
class WeeklyPreviewSchema(Schema):
text = fields.String()
html = fields.String()
class PublicPostSchema(Schema):
"""A public or unlisted post, for the web UI's post page (post.html)."""
text = fields.String()
html = fields.String()
created_at = fields.DateTime()
display_name = fields.String()
handle = fields.String(metadata={"example": "@alice@scrobble.example"})
profile_url = fields.String()
+108
View File
@@ -0,0 +1,108 @@
"""Per-user sharing settings: whether a user federates, and how."""
from scrobbler.extensions import db
from scrobbler.federation import keys
from scrobbler.federation.models import NOW_PLAYING_MODES, VISIBILITIES, FederationSettings
from scrobbler.federation.protocol.schedule import is_valid_timezone
from scrobbler.services import accounts
EDITABLE = (
"enabled",
"visibility",
"manually_approves_followers",
"discoverable",
"indexable",
"display_name",
"bio",
"timezone",
"post_weekly_summary",
"post_milestones",
"now_playing_mode",
)
def settings_for(user_id: int) -> FederationSettings:
"""The user's settings; unsaved defaults if they've never changed them."""
settings = db.session.get(FederationSettings, user_id)
if settings is None:
# Not added to the session: the model's column defaults apply on INSERT, not
# here, so every field a caller might read has to be set explicitly.
settings = FederationSettings(
user_id=user_id,
enabled=False,
visibility="followers",
manually_approves_followers=False,
discoverable=False,
indexable=False,
timezone="UTC",
post_weekly_summary=True,
post_milestones=True,
now_playing_mode="off",
)
return settings
def update(user_id: int, changes: dict) -> tuple[FederationSettings, bool | None]:
"""Apply changes. Returns the settings and True/False if sharing was switched
on/off by this update (None if unchanged)."""
unknown = set(changes) - set(EDITABLE)
if unknown:
raise ValueError(f"not editable: {sorted(unknown)}")
if changes.get("visibility", "followers") not in VISIBILITIES:
raise ValueError("visibility must be one of " + ", ".join(VISIBILITIES))
if changes.get("now_playing_mode", "off") not in NOW_PLAYING_MODES:
raise ValueError("now_playing_mode must be one of " + ", ".join(NOW_PLAYING_MODES))
if "timezone" in changes and not is_valid_timezone(changes["timezone"]):
raise ValueError(f"not a known time zone: {changes['timezone']!r}")
settings = settings_for(user_id)
was_enabled = bool(settings.enabled)
for field, value in changes.items():
setattr(settings, field, value)
db.session.add(settings)
db.session.commit()
if settings.enabled and not was_enabled:
keys.key_for(user_id) # create the key pair before anyone can fetch the actor
from scrobbler.federation.publishing import milestones
milestones.set_baseline(user_id) # history already on file isn't a "milestone"
toggled = None if settings.enabled == was_enabled else bool(settings.enabled)
return settings, toggled
def shared_user(username: str):
"""(user, settings) for a user who has switched sharing on, else None. Callers must
treat 'unknown user' and 'not sharing' identically, so accounts can't be probed."""
user = accounts.find_user(username)
if user is None:
return None
settings = db.session.get(FederationSettings, user.id)
if settings is None or not settings.enabled:
return None
return user, settings
def sharing_count() -> int:
return db.session.scalar(
db.select(db.func.count()).select_from(FederationSettings).filter_by(enabled=True)
)
def farewell_user(username: str):
"""A user who has stopped sharing but still has messages on their way out (the
Rejects telling followers). Their actor stays fetchable, minimally, so other servers
can verify those messages. None otherwise."""
from scrobbler.federation.models import FederationActivity, FederationDelivery
user = accounts.find_user(username)
if user is None:
return None
settings = db.session.get(FederationSettings, user.id)
if settings is None or settings.enabled:
return None
pending = db.session.scalar(
db.select(db.func.count())
.select_from(FederationDelivery)
.join(FederationActivity, FederationActivity.id == FederationDelivery.activity_id)
.filter(FederationActivity.user_id == user.id, FederationDelivery.status == "pending")
)
return user if pending else None
+278
View File
@@ -0,0 +1,278 @@
"""The ActivityPub endpoints remote servers call. Served on the UI's domain: its nginx
forwards these paths to the API. Every ID is built from FEDERATION_BASE_URL, never from
the request, so a proxy misconfiguration can't produce wrong IDs."""
import json
from flask import Blueprint, Response, current_app, redirect, request
from scrobbler.extensions import db
from scrobbler.federation import actors, ids, inbox, keys, publishing, sharing
from scrobbler.federation import followers as follower_state
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation.models import FederationActivity
from scrobbler.federation.protocol import hostmeta, media, nodeinfo, vocab, webfinger
bp = Blueprint("federation", __name__)
_NOT_FOUND = {"error": "not found"}
def _config():
return current_app.extensions["federation"]
def _profile_page(username: str) -> str:
return f"{current_app.config['UI_BASE_URL']}/profile.html?u={username}"
def _urls(username: str) -> vocab.ActorUrls:
return vocab.actor_urls(_config().base_url, username, _profile_page(username))
def _json(doc, content_type: str = media.ACTIVITY_JSON, status: int = 200, cache: int = 300):
response = Response(json.dumps(doc), status=status, content_type=content_type)
if status == 200 and cache:
response.headers["Cache-Control"] = f"public, max-age={cache}"
response.headers["Vary"] = "Accept"
return response
def _not_found(kind: str):
fed_metrics.lookups_total.labels(kind=kind, result="not_found").inc()
return _json(_NOT_FOUND, content_type="application/json", status=404)
def _found(kind: str) -> None:
fed_metrics.lookups_total.labels(kind=kind, result="found").inc()
# --- Discovery -----------------------------------------------------------------------
@bp.get("/.well-known/webfinger")
def webfinger_lookup():
config = _config()
try:
username = webfinger.parse_resource(
request.args.get("resource"), domain=config.domain, base_url=config.base_url
)
except webfinger.ResourceError as err:
return _json({"error": str(err)}, content_type="application/json", status=400)
if username.lower() == config.domain: # the instance actor, as Mastodon names it
actor_id, canonical = f"{config.base_url}/actor", config.domain
profile = current_app.config["UI_BASE_URL"]
else:
found = sharing.shared_user(username)
if found is None:
return _not_found("webfinger")
canonical = found[0].username
actor_id, profile = _urls(canonical).id, _profile_page(canonical)
_found("webfinger")
doc = webfinger.jrd(
username=canonical, domain=config.domain, actor_id=actor_id, profile_page=profile
)
response = _json(doc, content_type=media.JRD_JSON)
response.headers["Access-Control-Allow-Origin"] = "*" # RFC 7033 §5
return response
@bp.get("/.well-known/host-meta")
def host_meta():
return Response(hostmeta.xrd(_config().base_url), content_type=hostmeta.CONTENT_TYPE)
@bp.get("/.well-known/nodeinfo")
def nodeinfo_discovery():
return _json(nodeinfo.discovery(_config().base_url), content_type="application/json")
@bp.get("/nodeinfo/2.1")
def nodeinfo_document():
from scrobbler import __version__
_found("nodeinfo")
doc = nodeinfo.document(
version=__version__, users_total=sharing.sharing_count(), open_registrations=True
)
schema = f'application/json; profile="{nodeinfo.SCHEMA_21}#"'
return _json(doc, content_type=schema, cache=1800)
# --- Actors and collections -------------------------------------------------------------
@bp.get("/users/<username>")
def actor(username: str):
if not media.wants_activitypub(request.headers.get("Accept")):
# A person following a link: show them the profile page (for everyone, so
# redirects don't reveal which accounts exist).
return redirect(_profile_page(username), code=302)
found = sharing.shared_user(username)
if found is None:
leaving = sharing.farewell_user(username)
if leaving is None:
return _not_found("actor")
# Stopped sharing, but Rejects are still on their way: just enough for other
# servers to verify them. No name, bio or other profile details.
_found("actor")
doc = vocab.person(
_urls(leaving.username),
username=leaving.username,
name=leaving.username,
summary=None,
public_key_pem=keys.key_for(leaving.id).public_key_pem,
manually_approves_followers=True,
discoverable=False,
indexable=False,
)
return _json(doc, cache=0)
user, settings = found
_found("actor")
doc = actors.build_document(_urls(user.username), user, settings)
return _json(doc)
def _collection(username: str, which: str, items: list | None, total: int = 0):
found = sharing.shared_user(username)
if found is None:
return _not_found("actor")
urls = _urls(found[0].username)
return _json(vocab.ordered_collection(getattr(urls, which), total, items))
@bp.get("/users/<username>/outbox")
def outbox(username: str):
found = sharing.shared_user(username)
if found is None:
return _not_found("actor")
urls = _urls(found[0].username)
page_param = request.args.get("page")
if page_param is None:
total = publishing.outbox_page(found[0].id, page=1)[1]
return _json(vocab.ordered_collection(urls.outbox, total, first=f"{urls.outbox}?page=1"))
try:
page = max(int(page_param), 1)
except ValueError:
page = 1
per_page = publishing.OUTBOX_PAGE_SIZE
items, total = publishing.outbox_page(found[0].id, page, per_page=per_page)
next_page = f"{urls.outbox}?page={page + 1}" if page * per_page < total else None
prev_page = f"{urls.outbox}?page={page - 1}" if page > 1 else None
return _json(
vocab.ordered_collection_page(
f"{urls.outbox}?page={page}",
part_of=urls.outbox,
items=items,
next_page=next_page,
prev_page=prev_page,
)
)
@bp.get("/users/<username>/posts/<post_uuid>")
def post_note(username: str, post_uuid: str):
if not media.wants_activitypub(request.headers.get("Accept")):
# Same reasoning as actor(): redirect everyone, so the response can't be used to
# probe which posts exist.
return redirect(ids.post_page_url(username, post_uuid), code=302)
found = sharing.shared_user(username)
if found is None:
return _not_found("post")
post = publishing.find_by_note_id(found[0].id, ids.note_url(username, post_uuid))
if (
post is None
or post.deleted_at is not None
or post.visibility not in publishing.LISTED_VISIBILITIES
):
return _not_found("post")
return _json(post.activity.document["object"], cache=60)
@bp.get("/users/<username>/followers")
def followers(username: str):
found = sharing.shared_user(username)
total = follower_state.counts(found[0].id)["accepted"] if found else 0
return _collection(username, "followers", None, total) # the count, not who
@bp.get("/users/<username>/collections/featured")
def featured(username: str):
return _collection(username, "featured", []) # pinned posts: none (yet)
@bp.get("/users/<username>/following")
def following(username: str):
return _collection(username, "following", [])
# --- Instance actor -------------------------------------------------------------------
@bp.get("/actor")
def instance_actor():
config = _config()
actor_id = f"{config.base_url}/actor"
doc = vocab.application(
actor_id=actor_id,
username=config.domain,
inbox=f"{config.base_url}/inbox",
outbox=f"{actor_id}/outbox",
shared_inbox=f"{config.base_url}/inbox",
key_id=f"{actor_id}#main-key",
public_key_pem=keys.key_for(None).public_key_pem,
url=current_app.config["UI_BASE_URL"],
)
return _json(doc)
@bp.get("/actor/outbox")
def instance_outbox():
return _json(vocab.ordered_collection(f"{_config().base_url}/actor/outbox", 0, []))
# --- Inboxes ----------------------------------------------------------------------------
def _receive(inbox_path: str, kind: str):
if (request.content_length or 0) > inbox.MAX_BYTES:
return _json({"error": "too large"}, content_type="application/json", status=413)
if not media.is_activitypub_content_type(request.content_type):
return _json(
{"error": "expected ActivityPub JSON"}, content_type="application/json", status=415
)
fed_metrics.inbox_requests_total.labels(inbox=kind).inc()
status, outcome = inbox.receive(inbox_path, dict(request.headers), request.get_data())
if status == 202:
return Response(status=202)
return _json({"error": outcome}, content_type="application/json", status=status)
def _path() -> str:
return request.full_path.rstrip("?")
@bp.post("/users/<username>/inbox")
def user_inbox(username: str):
if sharing.shared_user(username) is None:
return _not_found("actor")
return _receive(_path(), "user")
@bp.post("/inbox")
def shared_inbox():
return _receive(_path(), "shared")
# --- Our activities ------------------------------------------------------------------------
@bp.get("/activities/<activity_uuid>")
def activity(activity_uuid: str):
"""Activities are fetchable when public; follow responses aren't."""
found = db.session.get(FederationActivity, activity_uuid)
if found is None or not found.public:
return _json(_NOT_FOUND, content_type="application/json", status=404)
return _json(found.document)
+7
View File
@@ -115,6 +115,13 @@ import_duration_seconds = Histogram(
buckets=(1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600, 7200),
)
# Background worker
worker_tasks_total = Counter(
"scrobbler_worker_tasks_total",
"Worker task runs that did work (queue tasks) or ran (periodic tasks), and failures",
["task", "outcome"],
)
# Database
db_query_duration_seconds = Histogram(
"scrobbler_db_query_duration_seconds",
@@ -0,0 +1,99 @@
"""federation posts and milestones
Revision ID: 0b81b61c932a
Revises: a481855fcb93
Create Date: 2026-09-26 11:34:52.240684
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "0b81b61c932a"
down_revision = "a481855fcb93"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"federation_milestone_marks",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("key", sa.String(length=64), nullable=False),
sa.Column("posted", sa.Boolean(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("user_id", "key", name="uq_federation_milestone_mark"),
)
with op.batch_alter_table("federation_milestone_marks", schema=None) as batch_op:
batch_op.create_index(
batch_op.f("ix_federation_milestone_marks_user_id"), ["user_id"], unique=False
)
op.create_table(
"federation_pending_checks",
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("since", sa.DateTime(timezone=True), nullable=False),
sa.Column("reason", sa.String(length=32), nullable=False),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("user_id"),
)
op.create_table(
"federation_posts",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("kind", sa.String(length=16), nullable=False),
sa.Column("key", sa.String(length=64), nullable=False),
sa.Column("activity_id", sa.String(length=36), nullable=False),
sa.Column("visibility", sa.String(length=16), nullable=False),
sa.Column("content_text", sa.Text(), nullable=False),
sa.Column("content_html", sa.Text(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
sa.ForeignKeyConstraint(["activity_id"], ["federation_activities.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("activity_id"),
sa.UniqueConstraint("user_id", "key", name="uq_federation_post_key"),
)
with op.batch_alter_table("federation_posts", schema=None) as batch_op:
batch_op.create_index(batch_op.f("ix_federation_posts_user_id"), ["user_id"], unique=False)
# server_default backfills existing rows (any user who's already touched their
# sharing settings); the model's Python-side default covers new ones.
with op.batch_alter_table("federation_settings", schema=None) as batch_op:
batch_op.add_column(
sa.Column("timezone", sa.String(length=64), nullable=False, server_default="UTC")
)
batch_op.add_column(
sa.Column("post_weekly_summary", sa.Boolean(), nullable=False, server_default=sa.true())
)
batch_op.add_column(
sa.Column("post_milestones", sa.Boolean(), nullable=False, server_default=sa.true())
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("federation_settings", schema=None) as batch_op:
batch_op.drop_column("post_milestones")
batch_op.drop_column("post_weekly_summary")
batch_op.drop_column("timezone")
with op.batch_alter_table("federation_posts", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_federation_posts_user_id"))
op.drop_table("federation_posts")
op.drop_table("federation_pending_checks")
with op.batch_alter_table("federation_milestone_marks", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_federation_milestone_marks_user_id"))
op.drop_table("federation_milestone_marks")
# ### end Alembic commands ###
@@ -0,0 +1,50 @@
"""federation remote actors
Revision ID: 211d4743f081
Revises: 34508576a6c7
Create Date: 2026-09-25 21:17:31.469467
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '211d4743f081'
down_revision = '34508576a6c7'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('federation_remote_actors',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('uri', sa.String(length=2048), nullable=False),
sa.Column('host', sa.String(length=255), nullable=False),
sa.Column('inbox', sa.String(length=2048), nullable=False),
sa.Column('shared_inbox', sa.String(length=2048), nullable=True),
sa.Column('username', sa.String(length=255), nullable=True),
sa.Column('display_name', sa.String(length=255), nullable=True),
sa.Column('public_key_id', sa.String(length=2048), nullable=False),
sa.Column('public_key_pem', sa.Text(), nullable=False),
sa.Column('fetched_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('gone', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('uri')
)
with op.batch_alter_table('federation_remote_actors', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_federation_remote_actors_host'), ['host'], unique=False)
batch_op.create_index(batch_op.f('ix_federation_remote_actors_public_key_id'), ['public_key_id'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('federation_remote_actors', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_federation_remote_actors_public_key_id'))
batch_op.drop_index(batch_op.f('ix_federation_remote_actors_host'))
op.drop_table('federation_remote_actors')
# ### end Alembic commands ###
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more