feat: post what I listen to on Mastodon, if I connect an account

In Settings a person connects their Mastodon account: the address of their instance and an access token that can only write posts. Nothing is connected by default, and disconnecting forgets the token.

- When a track of this server counts as a listen, it is posted as an unlisted status: title, artists, album and #NowPlaying, with no link. Music of a friend is never reported as a listen, so it is never posted. At most one post a minute for each person, in the background, with a bounded queue.
- PUT, GET and DELETE /me/mastodon. The token is never sent back.
- The address of the instance is typed by a person, so it must be a domain name on https, and the client never connects to a private, loopback or link-local address (checked on the address it really dials, so a name that points inside is no way in), never follows a redirect, ignores proxy settings and reads at most a megabyte.
- New table mastodon_accounts (SQLite and PostgreSQL) that goes with the account.
- README: the feature, and the credit for butterchurn and its presets.
This commit is contained in:
tgiachi 2026-11-13 21:59:03 +01:00
commit 0dc7782028
8 changed files with 1953 additions and 7 deletions

29
web/src/api/mastodon.ts Normal file
View file

@ -0,0 +1,29 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '@/api/client'
import type { components } from '@/api/schema'
export type MastodonAccount = components['schemas']['MastodonAccount']
export type ConnectMastodon = components['schemas']['ConnectMastodon']
const KEY = ['me', 'mastodon']
/** Which Mastodon account this person connected to share what they listen to, if any. The token is never sent back. */
export function useMastodon() {
return useQuery({ queryKey: KEY, queryFn: () => api.get<MastodonAccount>('/me/mastodon') })
}
export function useConnectMastodon() {
const client = useQueryClient()
return useMutation({
mutationFn: (body: ConnectMastodon) => api.put<MastodonAccount>('/me/mastodon', body),
onSuccess: (account) => client.setQueryData(KEY, account),
})
}
export function useDisconnectMastodon() {
const client = useQueryClient()
return useMutation({
mutationFn: () => api.del<void>('/me/mastodon'),
onSuccess: () => client.setQueryData(KEY, { connected: false } satisfies MastodonAccount),
})
}

View file

@ -1508,6 +1508,44 @@ export interface paths {
patch: operations["updateMySettings"];
trace?: never;
};
"/me/mastodon": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The Mastodon account you connected
* @description Whether you connected a Mastodon account to share what you listen to, and which one. Nothing is connected
* until you do it. The access token is never sent back.
*/
get: operations["getMyMastodon"];
/**
* Connect a Mastodon account
* @description Connects your Mastodon account, or replaces the one you had. Send the address of your instance (a domain name
* on https, like `mastodon.social`; an address that points at a private network is never reached) and an access
* token. Make the token in your instance, under Preferences, Development, New application, and give it only
* the `write:statuses` permission. The server asks the instance who the token belongs to; if the instance
* refuses it nothing is kept.
*
* From then on, each time a track of this server counts as a listen, the server posts it to your account as an
* unlisted status: title, artists, album and `#NowPlaying`, with no link. Music of a friend is never posted. At
* most one post a minute. The token stays on the server and is forgotten by `DELETE /me/mastodon`. The body
* must be one JSON object with these two names and nothing else.
*/
put: operations["connectMyMastodon"];
post?: never;
/**
* Disconnect your Mastodon account
* @description Forgets the account and its token. Nothing more is posted. Disconnecting when nothing is connected is not an error.
*/
delete: operations["disconnectMyMastodon"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/artists/{id}/lidarr": {
parameters: {
query?: never;
@ -2037,6 +2075,9 @@ export interface paths {
* **Plausibility.** When the length of the track is known, `duration_played_ms` may not exceed
* twice that length plus 10 seconds (a listener can seek back and loop). Streaming a file never
* records anything on its own.
*
* **Sharing.** A new event that counts is also posted to the Mastodon account of the listener, but only
* when they connected one with `PUT /me/mastodon`. That happens in the background and never changes the answer.
*/
post: operations["recordListen"];
delete?: never;
@ -3702,6 +3743,19 @@ export interface components {
*/
discover_from_listening: boolean;
};
MastodonAccount: {
connected: boolean;
/** @description The instance, like `https://mastodon.social`. Only when connected. */
instance?: string;
/** @description Your handle, like `@name@mastodon.social`. Only when connected. */
handle?: string;
};
ConnectMastodon: {
/** @description The address of your instance: `mastodon.social` or `https://mastodon.social`. */
instance: string;
/** @description An access token with the `write:statuses` permission. Never sent back. */
token: string;
};
UpdateUserSettings: {
discover_from_listening?: boolean | null;
};
@ -6398,6 +6452,98 @@ export interface operations {
401: components["responses"]["Unauthorized"];
};
};
getMyMastodon: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Your account, or `connected` false when there is none. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["MastodonAccount"];
};
};
401: components["responses"]["Unauthorized"];
};
};
connectMyMastodon: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["ConnectMastodon"];
};
};
responses: {
/** @description The account that is now connected. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["MastodonAccount"];
};
};
/** @description The body is malformed (`invalid_input`), the instance is not a domain name on https (`invalid_instance`) or the token is empty or too long (`invalid_token`). */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
401: components["responses"]["Unauthorized"];
/** @description The instance refused the token (`mastodon_refused`). */
422: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description The instance could not be reached, or did not answer like Mastodon (`mastodon_unreachable`). */
502: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
disconnectMyMastodon: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Disconnected. */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
401: components["responses"]["Unauthorized"];
};
};
getArtistInLidarr: {
parameters: {
query?: never;

View file

@ -0,0 +1,96 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, expect, test, vi } from 'vitest'
import { initI18n } from '@/i18n'
import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch'
import MastodonBlock from './MastodonBlock'
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
})
interface Account {
connected: boolean
instance?: string
handle?: string
}
function setup(initial: Account, over: MockRoutes = {}) {
let account = initial
const mocked = mockFetch({
'GET /api/v1/me/mastodon': () => account,
'PUT /api/v1/me/mastodon': ({ init }) => {
const body = JSON.parse(String(init.body))
account = { connected: true, instance: `https://${body.instance}`, handle: `@squid@${body.instance}` }
return account
},
'DELETE /api/v1/me/mastodon': () => {
account = { connected: false }
return new Response(null, { status: 204 })
},
...over,
})
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
render(
<QueryClientProvider client={client}>
<MastodonBlock />
</QueryClientProvider>,
)
return mocked
}
const puts = (calls: RecordedCall[]) => calls.filter((c) => c.key === 'PUT /api/v1/me/mastodon')
test('with nothing connected it says what will be posted, and shows a form', async () => {
setup({ connected: false })
expect(await screen.findByLabelText('Instance')).toBeInTheDocument()
expect(screen.getByLabelText('Access token')).toHaveAttribute('type', 'password')
expect(screen.getByText(/title, artists and album/i)).toBeInTheDocument()
expect(screen.getByText(/write:statuses/)).toBeInTheDocument()
expect(screen.getByText(/never posted/i)).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Disconnect' })).not.toBeInTheDocument()
})
test('connecting sends the instance and the token, and then shows the account and never the token', async () => {
const { calls } = setup({ connected: false })
await userEvent.type(await screen.findByLabelText('Instance'), 'mastodon.social')
await userEvent.type(screen.getByLabelText('Access token'), 'secret-token')
await userEvent.click(screen.getByRole('button', { name: 'Connect' }))
await screen.findByText(/@squid@mastodon\.social/)
expect(puts(calls)).toHaveLength(1)
expect(JSON.parse(String(puts(calls)[0].init.body))).toEqual({ instance: 'mastodon.social', token: 'secret-token' })
expect(document.body.textContent).not.toContain('secret-token')
expect(screen.queryByLabelText('Access token')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Disconnect' })).toBeInTheDocument()
})
test('the form needs both an instance and a token', async () => {
const { calls } = setup({ connected: false })
await userEvent.click(await screen.findByRole('button', { name: 'Connect' }))
expect(puts(calls)).toHaveLength(0)
})
test.each([
['mastodon_refused', 'The instance refused that token. Check that it has the write:statuses permission.', 422],
['mastodon_unreachable', 'That instance could not be reached. Check the address and try again.', 502],
['invalid_instance', 'The instance must be a domain name, like mastodon.social.', 400],
['invalid_token', 'The token is empty or too long.', 400],
])('when the server says %s the person is told what to fix, and the form stays', async (code, text, status) => {
setup({ connected: false }, { 'PUT /api/v1/me/mastodon': () => apiError(status, code, 'x') })
await userEvent.type(await screen.findByLabelText('Instance'), 'mastodon.social')
await userEvent.type(screen.getByLabelText('Access token'), 'tok')
await userEvent.click(screen.getByRole('button', { name: 'Connect' }))
expect(await screen.findByRole('alert')).toHaveTextContent(text)
expect(screen.getByLabelText('Instance')).toBeInTheDocument()
})
test('a connected account says where the listens go, and can be disconnected', async () => {
const { calls } = setup({ connected: true, instance: 'https://mastodon.social', handle: '@squid@mastodon.social' })
expect(await screen.findByText(/@squid@mastodon\.social/)).toBeInTheDocument()
expect(screen.queryByLabelText('Instance')).not.toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Disconnect' }))
expect(await screen.findByLabelText('Instance')).toBeInTheDocument()
expect(calls.filter((c) => c.key === 'DELETE /api/v1/me/mastodon')).toHaveLength(1)
})

View file

@ -0,0 +1,79 @@
import { useState, type FormEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { ApiError } from '@/api/client'
import { useConnectMastodon, useDisconnectMastodon, useMastodon } from '@/api/mastodon'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { errorMessageKey } from '@/i18n'
/**
* Sharing what you listen to on your own Mastodon account. Nothing is posted until an account is connected. The token
* is typed here once and the server never sends it back, so what is shown after connecting is only the handle.
*/
export default function MastodonBlock() {
const { t } = useTranslation()
const account = useMastodon()
const connect = useConnectMastodon()
const disconnect = useDisconnectMastodon()
const [instance, setInstance] = useState('')
const [token, setToken] = useState('')
function submit(event: FormEvent) {
event.preventDefault()
connect.mutate({ instance: instance.trim(), token: token.trim() }, { onSuccess: () => setToken('') })
}
if (account.data === undefined) return null
const error = connect.error ?? disconnect.error
if (account.data.connected) {
return (
<div className="flex max-w-xl flex-col gap-3">
<p className="font-semibold">{t('mastodon.connected', { handle: account.data.handle })}</p>
<p className="text-sm text-muted-foreground">{t('mastodon.connectedHelp')}</p>
{disconnect.isError && (
<p role="alert" className="text-sm text-destructive">
{t(errorMessageKey(error instanceof ApiError ? error.code : 'unknown'))}
</p>
)}
<Button variant="outline" className="self-start" disabled={disconnect.isPending} onClick={() => disconnect.mutate()}>
{t('mastodon.disconnect')}
</Button>
</div>
)
}
return (
<form onSubmit={submit} className="flex max-w-xl flex-col gap-4">
<p className="text-sm text-muted-foreground">{t('mastodon.intro')}</p>
<div className="flex flex-col gap-2">
<Label htmlFor="mastodon-instance">{t('mastodon.instance')}</Label>
<Input
id="mastodon-instance"
inputMode="url"
autoComplete="off"
autoCapitalize="none"
spellCheck={false}
placeholder={t('mastodon.instancePlaceholder')}
value={instance}
onChange={(e) => setInstance(e.target.value)}
required
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="mastodon-token">{t('mastodon.token')}</Label>
<Input id="mastodon-token" type="password" autoComplete="off" value={token} onChange={(e) => setToken(e.target.value)} required />
<p className="text-sm text-muted-foreground">{t('mastodon.tokenHelp')}</p>
</div>
{connect.isError && (
<p role="alert" className="text-sm text-destructive">
{t(errorMessageKey(error instanceof ApiError ? error.code : 'unknown'))}
</p>
)}
<Button type="submit" disabled={connect.isPending} className="self-start">
{connect.isPending ? t('mastodon.connecting') : t('mastodon.connect')}
</Button>
</form>
)
}

View file

@ -63,6 +63,18 @@
"fromFriend": "From {{name}}’s server",
"friendNote": "The audio passes through your server. {{name}} does not see who listens."
},
"mastodon": {
"intro": "Share what you listen to on your own Mastodon account. Each track that counts as a listen is posted as an unlisted status: title, artists and album, with #NowPlaying and no link. Music of a friend is never posted, and at most one post goes out a minute. Nothing is posted until you connect an account.",
"instance": "Instance",
"instancePlaceholder": "mastodon.social",
"token": "Access token",
"tokenHelp": "In your instance open Preferences, Development, New application, and give it only the write:statuses permission. Paste its access token here. The server keeps it and never shows it again.",
"connect": "Connect",
"connecting": "Connecting…",
"connected": "Your listens are posted to {{handle}}.",
"connectedHelp": "Each track that counts as a listen is posted as an unlisted status with #NowPlaying. Music of a friend is never posted.",
"disconnect": "Disconnect"
},
"settings": {
"account": "Account",
"admin": "Admin",
@ -71,6 +83,7 @@
"appearance": "Appearance",
"theme": "Theme",
"language": "Language",
"mastodon": "Mastodon",
"visualizer": "Picture of the sound in the player",
"visualizerHelp": "Milkdrop fills the full-screen player; in the bar of the player the spectrogram stands in for it. Milkdrop flashes, so with reduced motion on you get the spectrogram. Pick None to keep a phone or a laptop cooler. The choice stays on this device.",
"visualizerSpectrogram": "Spectrogram",
@ -682,6 +695,10 @@
"invalid_input": "Check what you typed and try again.",
"unauthorized": "Your session has ended. Sign in again.",
"network": "Cannot reach the server. Check your connection and try again.",
"invalid_instance": "The instance must be a domain name, like mastodon.social.",
"invalid_token": "The token is empty or too long.",
"mastodon_refused": "The instance refused that token. Check that it has the write:statuses permission.",
"mastodon_unreachable": "That instance could not be reached. Check the address and try again.",
"unknown": "Something went wrong. Try again.",
"playlist_not_found": "This playlist does not exist.",
"limit_reached": "Limit reached: a user can have 1000 playlists, and a playlist up to 10000 songs.",

View file

@ -63,6 +63,18 @@
"fromFriend": "Dal server di {{name}}",
"friendNote": "L’audio passa dal tuo server. {{name}} non vede chi ascolta."
},
"mastodon": {
"intro": "Condividi ciò che ascolti sul tuo account Mastodon. Ogni brano che conta come ascolto viene pubblicato come post non in elenco: titolo, artisti e album, con #NowPlaying e senza link. La musica di un amico non viene mai pubblicata, e esce al massimo un post al minuto. Non si pubblica niente finché non colleghi un account.",
"instance": "Istanza",
"instancePlaceholder": "mastodon.social",
"token": "Token di accesso",
"tokenHelp": "Nella tua istanza apri Preferenze, Sviluppo, Nuova applicazione, e dalle solo il permesso write:statuses. Incolla qui il suo token di accesso. Il server lo tiene e non lo mostra più.",
"connect": "Collega",
"connecting": "Collego…",
"connected": "I tuoi ascolti vengono pubblicati su {{handle}}.",
"connectedHelp": "Ogni brano che conta come ascolto viene pubblicato come post non in elenco con #NowPlaying. La musica di un amico non viene mai pubblicata.",
"disconnect": "Scollega"
},
"settings": {
"account": "Account",
"admin": "Admin",
@ -71,6 +83,7 @@
"appearance": "Aspetto",
"theme": "Tema",
"language": "Lingua",
"mastodon": "Mastodon",
"visualizer": "Immagine del suono nel player",
"visualizerHelp": "Milkdrop riempie il player a schermo intero; nella barra del player al suo posto c’è lo spettrogramma. Milkdrop lampeggia, quindi con il movimento ridotto vedi lo spettrogramma. Scegli Nessuna per tenere più fresco un telefono o un portatile. La scelta resta su questo dispositivo.",
"visualizerSpectrogram": "Spettrogramma",
@ -682,6 +695,10 @@
"invalid_input": "Controlla quello che hai scritto e riprova.",
"unauthorized": "La sessione è terminata. Accedi di nuovo.",
"network": "Il server non risponde. Controlla la connessione e riprova.",
"invalid_instance": "L’istanza deve essere un nome di dominio, come mastodon.social.",
"invalid_token": "Il token è vuoto o troppo lungo.",
"mastodon_refused": "L’istanza ha rifiutato il token. Controlla che abbia il permesso write:statuses.",
"mastodon_unreachable": "Non riesco a raggiungere quell’istanza. Controlla l’indirizzo e riprova.",
"unknown": "Qualcosa è andato storto. Riprova.",
"playlist_not_found": "Questa playlist non esiste.",
"limit_reached": "Limite raggiunto: un utente può avere 1000 playlist e una playlist fino a 10000 brani.",

View file

@ -25,7 +25,7 @@ function renderSettings() {
}
beforeEach(async () => {
mockFetch({ 'GET /api/v1/me/settings': () => ({ discover_from_listening: false }) })
mockFetch({ 'GET /api/v1/me/settings': () => ({ discover_from_listening: false }), 'GET /api/v1/me/mastodon': () => ({ connected: false }) })
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
initTheme()
@ -211,3 +211,9 @@ test('the picture of the sound in the player is chosen from five, and the choice
await userEvent.click(within(group).getByRole('radio', { name: 'None' }))
expect(localStorage.getItem('sonda.visualizer')).toBe('off')
})
test('there is a place to connect a Mastodon account, off until it is connected', async () => {
renderSettings()
const section = await screen.findByRole('region', { name: 'Mastodon' })
expect(await within(section).findByRole('button', { name: 'Connect' })).toBeInTheDocument()
})

View file

@ -4,6 +4,7 @@ import { api, ApiError } from '@/api/client'
import { logout, useSession } from '@/auth/session'
import ChoiceGroup from '@/components/ChoiceGroup'
import ListeningSwitch from '@/components/ListeningSwitch'
import MastodonBlock from '@/components/MastodonBlock'
import Section from '@/components/Section'
import { useInstall } from '@/pwa/useInstall'
import { Button } from '@/components/ui/button'
@ -164,6 +165,10 @@ export default function SettingsPage() {
<ListeningSwitch />
</Section>
<Section title={t('settings.mastodon')}>
<MastodonBlock />
</Section>
<Section title={t('settings.password')}>
<ChangePassword />
</Section>