feat(mastodon): say in Settings when the instance no longer accepts the token

When the instance refuses the token on a post (it was revoked or expired), the account now remembers it: GET /me/mastodon says problem: token_refused and nothing is posted until I connect again with a new token.

- migration 0027 adds mastodon_accounts.problem (SQLite and PostgreSQL).
- Only a refused token marks the account; an instance that is down does not.
- Saving the account again clears the problem.
- Settings shows the warning and the form with the instance already filled in, next to Disconnect.
- English and Italian.
This commit is contained in:
tgiachi 2026-11-14 10:04:07 +01:00
commit a7a258464b
8 changed files with 229 additions and 21 deletions

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)
}
})
}