Merge pull request 'Say in Settings when Mastodon no longer accepts my token' (#168) from feat/mastodon-revoked-token into main

This commit is contained in:
squidd 2026-11-14 10:04:56 +01:00
commit 6028d8e686
16 changed files with 229 additions and 21 deletions

View file

@ -26,7 +26,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
- **Playlists.** `POST /playlists` makes a playlist (a name and an optional description) and `GET /playlists` lists yours, the one changed last first. `POST /playlists/{id}/tracks` adds 1 to 500 tracks at the end or at a `position`, `GET /playlists/{id}/tracks` lists them in order, `PATCH /playlists/{id}/tracks/{item}` moves one and `DELETE` takes one out; `PATCH /playlists/{id}` renames and `DELETE /playlists/{id}` deletes (the tracks stay in the library). A track can be in a playlist more than once, which is why each place has its own item id. A playlist is yours alone: someone else's answers `playlist_not_found`, as one that does not exist. A track whose files were deleted or moved away stays in the playlist and shows `available: false`; it plays again when the files come back and a scan finds them. Each playlist says which albums stand for it (`album_ids`: up to 4 albums that have a cover, in the order they first appear in it, each once), for a picture made of their covers; nothing is fetched for it. A user can have 1000 playlists of up to 10000 tracks. Nothing is shared and nothing leaves your server.
- **Wishlist and "not interested".** `PUT /wishlist/{artist}` puts an artist on your wishlist (`GET /wishlist` lists it, `DELETE` takes it off), and `POST /discover/{artist}/dismiss` hides an artist from your Discover for good (`DELETE` brings it back, `GET /discover/dismissed` lists them). An artist is wished or dismissed, never both, and both lists are yours alone. Discover marks the wished artists it shows (`wishlisted`) and never suggests a dismissed one. The wishlist is a list for you and sends nothing anywhere; Sonda downloads nothing, but an admin can send an artist that Discover showed to their own Lidarr (see [External providers](#external-providers)), which works for an artist that has a MusicBrainz id and that Sonda knows of from a list or from your files. An artist that only Last.fm named is kept while you have it marked (your lists still show it, but other users cannot see that it exists), and goes with the rest of Last.fm's data if an admin removes Last.fm's data. Removing MusicBrainz's data does not touch it.
- **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so this setting never sends your listening to a provider. When you turn it on, Discover may start from the artists you listen to most, and their names are sent to Last.fm (only if an admin switched it on). What Last.fm answers is kept in the shared database like any other lookup, so another local user can see, from `retrieved_at` of `GET /artists/{id}/similar`, that someone looked up an artist, but not who.
- **Sharing on Mastodon.** `PUT /me/mastodon` connects your own Mastodon account (the address of your instance and an access token that can only write posts); `GET` shows which account is connected and `DELETE` forgets it and the token. Nothing is connected by default. Once it is, each track of this server that counts as a listen is posted to your account as an unlisted status with the title, artists, album and `#NowPlaying`, and no link: at most one post a minute, never music of a friend. The token stays on the server and is never sent back. The address of the instance must be a domain name on https, and the server never connects to a private, loopback or link-local address for it, never follows a redirect and ignores proxy settings.
- **Sharing on Mastodon.** `PUT /me/mastodon` connects your own Mastodon account (the address of your instance and an access token that can only write posts); `GET` shows which account is connected and `DELETE` forgets it and the token. Nothing is connected by default. Once it is, each track of this server that counts as a listen is posted to your account as an unlisted status with the title, artists, album and `#NowPlaying`, and no link: at most one post a minute, never music of a friend. The token stays on the server and is never sent back. If the instance refuses the token on a post (it was revoked or expired), `GET /me/mastodon` says `problem: token_refused`, Settings shows it, and nothing is posted until you connect again with a new token. The address of the instance must be a domain name on https, and the server never connects to a private, loopback or link-local address for it, never follows a redirect and ignores proxy settings.
- **Tags.** `GET /artists/{id}/tags` shows what Last.fm and MusicBrainz say kind of music an artist plays, each with its own weights, and the genres of the artist's own files, read offline. See [External providers](#external-providers).
- **Similar artists.** With Last.fm switched on, `GET /artists/{id}/similar` lists artists similar to an artist, and says which of them you already have. See [External providers](#external-providers). Without it, Sonda makes no outbound network requests at all.
- **Friends (federation).** Two Sonda servers can become friends, and the listeners of one can read what the other chose to share. `PUT /federation` (admin) turns federation on, which is off by default, and gives this server a name and a public address (`https`; plain `http` only on a network of your own); the server then makes its own Ed25519 key, kept in the database and never returned. `POST /federation/invites` makes an invite that works once and expires in 24 hours (only a hash of its code is kept). The other admin uses it with `POST /federation/friends`: that server is asked to accept this one, the key it answers with must be the one named in the invite, and the friend waits as `outgoing` until the first admin approves it with `POST /federation/friends/{id}/approve` (`POST /federation/friends/{id}/check` lets the waiting side find out). Either side can remove a friend with `DELETE /federation/friends/{id}`. Nothing is shared until an admin turns on `shared` for a library (`PATCH /libraries/{id}`). A friend's server then reads, with requests signed by its key (the method, the path and query, a date, a nonce and the hash of the body), the routes under `/peer`: the artists, albums and tracks that have a file in a shared library, their covers once they are built, and the audio itself with `Range`. A friend never sees a path, a library id, a listen, a taste or a user, never makes this server build a cover or ask a provider, and has a few streams at a time and a number of KiB a second to share (`max_streams`, `max_kib_per_sec`); the admin sees the last requests it made (`GET /federation/requests`, the route and the size, never what was searched for). Sharing a library lets friends play it and, in practice, copy its files. A listener browses the music of a friend with `GET /friends` (the names of the friends whose friendship both admins agreed to, never an address or a key) and `GET /friends/{friend}/artists`, `albums` and `tracks` with `q`, `limit` and `offset`, and one item at a time: this server asks the friend with a signed request, checks the shape of the answer and passes it on, and nothing is kept; the ids are the friend's own. A friend that cannot be reached or no longer takes this server for a friend is told in words. The web app has a Friends section for it, shown only when there is a friend to browse. A listener plays it with `GET /friends/{friend}/tracks/{id}/stream` and sees its covers with `GET /friends/{friend}/albums/{id}/cover`, which accept the access token in the query like the local ones: this server asks the friend with a signed request, forwards `Range` and the conditional headers, and passes on only audio (or a JPEG for a cover) with `Content-Type`, `Content-Length`, `Content-Range`, `Accept-Ranges`, `Last-Modified` and `ETag`, so the friend sees this server and never the listener, and a friend cannot make this server serve anything else. A friend's track plays in the same player as the others but is never reported as a listen and does not feed taste. The admin area has a Federation section for all of it.

View file

@ -20,6 +20,8 @@ type mastodonJSON struct {
Connected bool `json:"connected"`
Instance string `json:"instance,omitempty"`
Handle string `json:"handle,omitempty"`
// Problem is set when posts are paused, for example `token_refused` after the instance refused the token.
Problem string `json:"problem,omitempty"`
}
func (h *mastodonHandlers) get(c *gin.Context) {
@ -33,7 +35,7 @@ func (h *mastodonHandlers) get(c *gin.Context) {
c.JSON(http.StatusOK, mastodonJSON{})
return
}
c.JSON(http.StatusOK, mastodonJSON{Connected: true, Instance: acc.Instance, Handle: acc.Handle})
c.JSON(http.StatusOK, mastodonJSON{Connected: true, Instance: acc.Instance, Handle: acc.Handle, Problem: acc.Problem})
}
type mastodonConnectRequest struct {

View file

@ -17,10 +17,11 @@ import (
// fakeMastodon stands in for the instance: it answers like the one a test sets up and tells what was posted.
type fakeMastodon struct {
mu sync.Mutex
handle string
verify error
posted chan [2]string // token, status
mu sync.Mutex
handle string
verify error
postErr error
posted chan [2]string // token, status
}
func (f *fakeMastodon) Verify(_ context.Context, _, _ string) (string, error) {
@ -33,7 +34,7 @@ func (f *fakeMastodon) Post(_ context.Context, _, token, status, _ string) error
if f.posted != nil {
f.posted <- [2]string{token, status}
}
return nil
return f.postErr
}
// mastodonEnv is the API with the Mastodon service on the given instance. The worker that posts runs for the length of the test.
@ -198,3 +199,36 @@ func TestOnlyAListenThatCountsIsPostedAndOnlyForWhoConnected(t *testing.T) {
case <-time.After(200 * time.Millisecond):
}
}
func TestARefusedTokenShowsAsAProblemUntilTheAccountIsConnectedAgain(t *testing.T) {
remote := &fakeMastodon{handle: "@squid@mastodon.social", postErr: mastodon.ErrRefused, posted: make(chan [2]string, 4)}
h := mastodonEnv(t, remote)
alice := registerAndLogin(t, h)
do(t, h, "PUT", "/api/v1/me/mastodon", alice, map[string]any{"instance": "mastodon.social", "token": "tok"})
if g := do(t, h, "GET", "/api/v1/me/mastodon", alice, nil); g.Body["problem"] != nil {
t.Fatalf("a fresh account has no problem: %v", g.Body)
}
r := do(t, h, "POST", "/api/v1/listens", alice, map[string]any{"track_id": 1, "event_type": "complete", "duration_played_ms": 30000, "idempotency_key": "a1"})
if r.Code != http.StatusCreated {
t.Fatalf("listen: %d %v", r.Code, r.Body)
}
<-remote.posted
deadline := time.Now().Add(3 * time.Second)
for {
g := do(t, h, "GET", "/api/v1/me/mastodon", alice, nil)
if g.Body["problem"] == "token_refused" {
sameKeys(t, "with a problem", g.Body, "connected", "instance", "handle", "problem")
break
}
if time.Now().After(deadline) {
t.Fatalf("the problem never showed: %v", g.Body)
}
time.Sleep(20 * time.Millisecond)
}
// A new token clears it.
remote.postErr = nil
do(t, h, "PUT", "/api/v1/me/mastodon", alice, map[string]any{"instance": "mastodon.social", "token": "new"})
if g := do(t, h, "GET", "/api/v1/me/mastodon", alice, nil); g.Body["problem"] != nil {
t.Errorf("connecting again left the problem: %v", g.Body)
}
}

View file

@ -5388,6 +5388,12 @@ components:
connected: {type: boolean}
instance: {type: string, description: "The instance, like `https://mastodon.social`. Only when connected."}
handle: {type: string, description: "Your handle, like `@name@mastodon.social`. Only when connected."}
problem:
type: string
enum: [token_refused]
description: |
Only when posts are paused. `token_refused`: the instance refused the token on a post (it was revoked or
expired), so nothing is posted until you connect again with a new token (`PUT /me/mastodon`).
ConnectMastodon:
type: object

View file

@ -32,6 +32,9 @@ var (
ErrUnreachable = errors.New("the instance could not be reached")
)
// ProblemTokenRefused is what an account shows after the instance refused its token on a post.
const ProblemTokenRefused = "token_refused"
const (
// maxPost is the length of a post on a stock Mastodon instance.
maxPost = 500
@ -51,6 +54,7 @@ const (
type Account struct {
Instance string // https://mastodon.social
Handle string // @squid@mastodon.social
Problem string // empty while all is well; ProblemTokenRefused when posts are paused
}
// Credentials are what is kept for a person.
@ -58,6 +62,7 @@ type Credentials struct {
Instance string
Token string
Handle string
Problem string // see Account
}
// Track is what a post says about a track.
@ -71,8 +76,10 @@ type Track struct {
type Store interface {
// Get returns what is kept for a person, with found=false when nothing is.
Get(ctx context.Context, userID int64) (Credentials, bool, error)
// Save keeps the credentials of a person, replacing older ones.
// Save keeps the credentials of a person, replacing older ones and clearing any problem.
Save(ctx context.Context, userID int64, c Credentials) error
// SetProblem notes what went wrong with the account of a person. A person with nothing kept is not an error.
SetProblem(ctx context.Context, userID int64, problem string) error
// Delete forgets them. A person with nothing kept is not an error.
Delete(ctx context.Context, userID int64) error
// Track returns what a post needs to say, with found=false for a track that is gone.
@ -166,7 +173,7 @@ func (s *Service) Status(ctx context.Context, userID int64) (Account, bool, erro
if err != nil || !found {
return Account{}, false, err
}
return Account{Instance: c.Instance, Handle: c.Handle}, true, nil
return Account{Instance: c.Instance, Handle: c.Handle, Problem: c.Problem}, true, nil
}
// Connect checks the token with the instance and keeps the account. Nothing is kept when the check fails.
@ -229,6 +236,10 @@ func (s *Service) announce(ctx context.Context, userID, trackID int64) error {
if err != nil || !found {
return err
}
// The instance refused the token: another try would be refused too. Connecting again clears this.
if c.Problem != "" {
return nil
}
track, found, err := s.store.Track(ctx, trackID)
if err != nil || !found {
return err
@ -256,6 +267,11 @@ func (s *Service) announce(ctx context.Context, userID, trackID int64) error {
delete(s.last, userID)
}
s.mu.Unlock()
if errors.Is(err, ErrRefused) {
if perr := s.store.SetProblem(ctx, userID, ProblemTokenRefused); perr != nil {
s.log.Warn("mastodon: could not note the refused token", zap.Error(perr))
}
}
return err
}
return nil

View file

@ -89,6 +89,18 @@ func (f *fakeStore) Save(_ context.Context, id int64, c Credentials) error {
return nil
}
func (f *fakeStore) SetProblem(_ context.Context, id int64, problem string) error {
f.mu.Lock()
defer f.mu.Unlock()
c, ok := f.creds[id]
if !ok {
return nil
}
c.Problem = problem
f.creds[id] = c
return nil
}
func (f *fakeStore) Delete(_ context.Context, id int64) error {
f.mu.Lock()
defer f.mu.Unlock()
@ -266,6 +278,51 @@ func TestAFailedPostIsNotRetriedAndDoesNotCountAgainstTheMinute(t *testing.T) {
}
}
func TestARefusedTokenIsRememberedAndNothingIsPostedUntilTheAccountIsConnectedAgain(t *testing.T) {
s, st, rm := newService(t)
ctx := context.Background()
_ = st.Save(ctx, 1, Credentials{Instance: "https://mastodon.social", Token: "tok", Handle: "@a@x"})
rm.postErr = ErrRefused
if err := s.announce(ctx, 1, 7); !errors.Is(err, ErrRefused) {
t.Fatalf("err = %v", err)
}
acc, _, _ := s.Status(ctx, 1)
if acc.Problem != ProblemTokenRefused {
t.Errorf("problem = %q, want %q", acc.Problem, ProblemTokenRefused)
}
// While the token is refused no post is tried: the instance would say no again.
rm.postErr = nil
before := rm.count()
if err := s.announce(ctx, 1, 7); err != nil {
t.Errorf("a paused account is not an error: %v", err)
}
if rm.count() != before {
t.Errorf("a post was tried with a refused token")
}
// Connecting again with a new token clears it and posts go out again.
if _, err := s.Connect(ctx, 1, "mastodon.social", "new-token"); err != nil {
t.Fatal(err)
}
if acc, _, _ := s.Status(ctx, 1); acc.Problem != "" {
t.Errorf("problem after connecting again = %q", acc.Problem)
}
_ = s.announce(ctx, 1, 7)
if rm.count() != before+1 {
t.Errorf("%d posts: connecting again must let posts go out", rm.count())
}
}
func TestAPostThatFailsForAnyOtherReasonIsNotAProblemOfTheAccount(t *testing.T) {
s, st, rm := newService(t)
ctx := context.Background()
_ = st.Save(ctx, 1, Credentials{Instance: "https://mastodon.social", Token: "tok", Handle: "@a@x"})
rm.postErr = ErrUnreachable
_ = s.announce(ctx, 1, 7)
if acc, _, _ := s.Status(ctx, 1); acc.Problem != "" {
t.Errorf("an instance that is down marked the account: %q", acc.Problem)
}
}
func TestAnnounceReturnsAtOnceAndTheWorkerPostsInTheBackground(t *testing.T) {
s, st, rm := newService(t)
rm.posted = make(chan post, 1)

View file

@ -19,6 +19,7 @@ type mastodonRow struct {
Instance string `bun:"instance,notnull"`
Token string `bun:"token,notnull"`
Handle string `bun:"handle,notnull"`
Problem string `bun:"problem,notnull"`
CreatedAt int64 `bun:"created_at,notnull"`
}
@ -39,17 +40,18 @@ func (r *MastodonRepo) Get(ctx context.Context, userID int64) (mastodon.Credenti
if err != nil {
return mastodon.Credentials{}, false, fmt.Errorf("select mastodon account: %w", err)
}
return mastodon.Credentials{Instance: row.Instance, Token: row.Token, Handle: row.Handle}, true, nil
return mastodon.Credentials{Instance: row.Instance, Token: row.Token, Handle: row.Handle, Problem: row.Problem}, true, nil
}
// Save keeps the account of a person, replacing an older one.
func (r *MastodonRepo) Save(ctx context.Context, userID int64, c mastodon.Credentials) error {
row := &mastodonRow{UserID: userID, Instance: c.Instance, Token: c.Token, Handle: c.Handle, CreatedAt: time.Now().Unix()}
row := &mastodonRow{UserID: userID, Instance: c.Instance, Token: c.Token, Handle: c.Handle, Problem: c.Problem, CreatedAt: time.Now().Unix()}
_, err := r.db.NewInsert().Model(row).
On("CONFLICT (user_id) DO UPDATE").
Set("instance = EXCLUDED.instance").
Set("token = EXCLUDED.token").
Set("handle = EXCLUDED.handle").
Set("problem = EXCLUDED.problem").
Set("created_at = EXCLUDED.created_at").
Exec(ctx)
if err != nil {
@ -58,6 +60,14 @@ func (r *MastodonRepo) Save(ctx context.Context, userID int64, c mastodon.Creden
return nil
}
// SetProblem notes what went wrong with the account of a person; a person with none is not an error.
func (r *MastodonRepo) SetProblem(ctx context.Context, userID int64, problem string) error {
if _, err := r.db.NewUpdate().Model((*mastodonRow)(nil)).Set("problem = ?", problem).Where("user_id = ?", userID).Exec(ctx); err != nil {
return fmt.Errorf("set mastodon problem: %w", err)
}
return nil
}
// Delete forgets the account of a person. A person with none is not an error.
func (r *MastodonRepo) Delete(ctx context.Context, userID int64) error {
if _, err := r.db.NewDelete().Model((*mastodonRow)(nil)).Where("user_id = ?", userID).Exec(ctx); err != nil {

View file

@ -117,3 +117,29 @@ func TestTheTrackOfAPostHasItsTitleItsMainArtistsAndItsAlbum(t *testing.T) {
}
})
}
func TestAProblemWithTheTokenIsKeptUntilTheAccountIsSavedAgain(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewMastodonRepo(db)
uid := seedUser(t, db, "a@example.org")
if err := repo.SetProblem(ctx, uid, mastodon.ProblemTokenRefused); err != nil {
t.Fatalf("a person with no account is not an error: %v", err)
}
_ = repo.Save(ctx, uid, mastodon.Credentials{Instance: "https://mastodon.social", Token: "one", Handle: "@a@x"})
if got, _, _ := repo.Get(ctx, uid); got.Problem != "" {
t.Fatalf("a new account starts with no problem: %q", got.Problem)
}
if err := repo.SetProblem(ctx, uid, mastodon.ProblemTokenRefused); err != nil {
t.Fatal(err)
}
got, _, _ := repo.Get(ctx, uid)
if got.Problem != mastodon.ProblemTokenRefused || got.Token != "one" {
t.Fatalf("after SetProblem: %+v", got)
}
_ = repo.Save(ctx, uid, mastodon.Credentials{Instance: "https://mastodon.social", Token: "two", Handle: "@a@x"})
if got, _, _ := repo.Get(ctx, uid); got.Problem != "" || got.Token != "two" {
t.Errorf("saving again clears the problem: %+v", got)
}
})
}

View file

@ -156,8 +156,8 @@ func TestMigrateCreatesSchemaAndIsIdempotent(t *testing.T) {
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&applied); err != nil {
t.Fatal(err)
}
if applied != 26 {
t.Errorf("applied migrations = %d, want 26", applied)
if applied != 27 {
t.Errorf("applied migrations = %d, want 27", applied)
}
})
}

View file

@ -0,0 +1,3 @@
-- PostgreSQL flavour of sqlite/0027_mastodon_problem.sql.
ALTER TABLE mastodon_accounts ADD COLUMN problem TEXT NOT NULL DEFAULT '';

View file

@ -0,0 +1,4 @@
-- What went wrong with the account of a person, when something did: empty while all is well, `token_refused` after the
-- instance refused the token on a post. While it is set nothing is posted; connecting the account again clears it.
ALTER TABLE mastodon_accounts ADD COLUMN problem TEXT NOT NULL DEFAULT '';

View file

@ -3749,6 +3749,12 @@ export interface components {
instance?: string;
/** @description Your handle, like `@name@mastodon.social`. Only when connected. */
handle?: string;
/**
* @description Only when posts are paused. `token_refused`: the instance refused the token on a post (it was revoked or
* expired), so nothing is posted until you connect again with a new token (`PUT /me/mastodon`).
* @enum {string}
*/
problem?: "token_refused";
};
ConnectMastodon: {
/** @description The address of your instance: `mastodon.social` or `https://mastodon.social`. */

View file

@ -15,6 +15,7 @@ interface Account {
connected: boolean
instance?: string
handle?: string
problem?: 'token_refused'
}
function setup(initial: Account, over: MockRoutes = {}) {
@ -94,3 +95,26 @@ test('a connected account says where the listens go, and can be disconnected', a
expect(await screen.findByLabelText('Instance')).toBeInTheDocument()
expect(calls.filter((c) => c.key === 'DELETE /api/v1/me/mastodon')).toHaveLength(1)
})
test('a token the instance no longer accepts is said at once, and a new one can be pasted', async () => {
const { calls } = setup({ connected: true, instance: 'https://mastodon.social', handle: '@squid@mastodon.social', problem: 'token_refused' })
expect(await screen.findByRole('alert')).toHaveTextContent('Mastodon no longer accepts the token for @squid@mastodon.social, so nothing is posted.')
expect(screen.queryByText(/Your listens are posted to/)).not.toBeInTheDocument()
// The instance is already there; only the new token is missing.
expect(screen.getByLabelText('Instance')).toHaveValue('mastodon.social')
expect(screen.getByLabelText('Access token')).toHaveValue('')
expect(screen.getByRole('button', { name: 'Disconnect' })).toBeInTheDocument()
await userEvent.type(screen.getByLabelText('Access token'), 'new-token')
await userEvent.click(screen.getByRole('button', { name: 'Connect again' }))
expect(JSON.parse(String(puts(calls)[0].init.body))).toEqual({ instance: 'mastodon.social', token: 'new-token' })
// Connected again: the warning is gone and the account is shown as before.
expect(await screen.findByText(/Your listens are posted to/)).toBeInTheDocument()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
})
test('with a refused token the account can still be disconnected', async () => {
const { calls } = setup({ connected: true, instance: 'https://mastodon.social', handle: '@squid@mastodon.social', problem: 'token_refused' })
await userEvent.click(await screen.findByRole('button', { name: 'Disconnect' }))
expect(await screen.findByRole('button', { name: 'Connect' })).toBeInTheDocument()
expect(calls.filter((c) => c.key === 'DELETE /api/v1/me/mastodon')).toHaveLength(1)
})

View file

@ -16,18 +16,21 @@ export default function MastodonBlock() {
const account = useMastodon()
const connect = useConnectMastodon()
const disconnect = useDisconnectMastodon()
const [instance, setInstance] = useState('')
// What was typed; until then, the instance of an account whose token needs replacing.
const [typed, setTyped] = useState<string | null>(null)
const [token, setToken] = useState('')
function submit(event: FormEvent) {
event.preventDefault()
connect.mutate({ instance: instance.trim(), token: token.trim() }, { onSuccess: () => setToken('') })
connect.mutate({ instance: instance.trim(), token: token.trim() }, { onSuccess: () => { setToken(''); setTyped(null) } })
}
if (account.data === undefined) return null
const error = connect.error ?? disconnect.error
const refused = account.data.connected && account.data.problem === 'token_refused'
const instance = typed ?? (refused ? (account.data.instance ?? '').replace(/^https:\/\//, '') : '')
if (account.data.connected) {
if (account.data.connected && !refused) {
return (
<div className="flex max-w-xl flex-col gap-3">
<p className="font-semibold">{t('mastodon.connected', { handle: account.data.handle })}</p>
@ -46,7 +49,13 @@ export default function MastodonBlock() {
return (
<form onSubmit={submit} className="flex max-w-xl flex-col gap-4">
<p className="text-sm text-muted-foreground">{t('mastodon.intro')}</p>
{refused ? (
<p role="alert" className="text-sm font-semibold text-destructive">
{t('mastodon.refused', { handle: account.data.handle })}
</p>
) : (
<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
@ -57,7 +66,7 @@ export default function MastodonBlock() {
spellCheck={false}
placeholder={t('mastodon.instancePlaceholder')}
value={instance}
onChange={(e) => setInstance(e.target.value)}
onChange={(e) => setTyped(e.target.value)}
required
/>
</div>
@ -71,9 +80,16 @@ export default function MastodonBlock() {
{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>
<div className="flex flex-wrap gap-3">
<Button type="submit" disabled={connect.isPending}>
{connect.isPending ? t('mastodon.connecting') : t(refused ? 'mastodon.connectAgain' : 'mastodon.connect')}
</Button>
{refused && (
<Button type="button" variant="outline" disabled={disconnect.isPending} onClick={() => disconnect.mutate()}>
{t('mastodon.disconnect')}
</Button>
)}
</div>
</form>
)
}

View file

@ -71,6 +71,8 @@
"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…",
"refused": "Mastodon no longer accepts the token for {{handle}}, so nothing is posted. Make a new token as described below and paste it here.",
"connectAgain": "Connect again",
"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"

View file

@ -71,6 +71,8 @@
"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…",
"refused": "Mastodon non accetta più il token di {{handle}}, quindi non si pubblica niente. Crea un nuovo token come descritto sotto e incollalo qui.",
"connectAgain": "Collega di nuovo",
"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"