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.
286 lines
9.4 KiB
Go
286 lines
9.4 KiB
Go
// Package mastodon lets a person share what they listen to on their own Mastodon account.
|
||
//
|
||
// Nothing is posted until a person connects an account (the address of their instance and an access token that can
|
||
// write posts), 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 a tag, with no link, because the server is private. A friend's music
|
||
// never reaches this package: it has no track of this server.
|
||
//
|
||
// The token stays on the server. The address of the instance is whatever the person typed, so it is checked hard (https,
|
||
// a name and not a number) and the client refuses to reach a private network (see Remote).
|
||
package mastodon
|
||
|
||
import (
|
||
"context"
|
||
"crypto/rand"
|
||
"encoding/hex"
|
||
"errors"
|
||
"fmt"
|
||
"net/url"
|
||
"strings"
|
||
"sync"
|
||
"time"
|
||
"unicode/utf8"
|
||
|
||
"go.uber.org/zap"
|
||
)
|
||
|
||
// Errors returned by the service.
|
||
var (
|
||
ErrBadInstance = errors.New("the address of the instance must be a domain name, like mastodon.social")
|
||
ErrBadToken = errors.New("the access token is empty or too long")
|
||
ErrRefused = errors.New("the instance refused the access token")
|
||
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
|
||
// postTag closes every post.
|
||
postTag = " #NowPlaying"
|
||
// minGap is the shortest time between two posts of one person.
|
||
minGap = time.Minute
|
||
// maxToken is far more than any token is long.
|
||
maxToken = 512
|
||
// queueSize is how many listens wait for the worker. When it is full, the newest are dropped: a post is never worth
|
||
// holding the server back.
|
||
queueSize = 64
|
||
postTimeout = 20 * time.Second
|
||
)
|
||
|
||
// Account is what a person may see of their connection: never the token.
|
||
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.
|
||
type Credentials struct {
|
||
Instance string
|
||
Token string
|
||
Handle string
|
||
Problem string // see Account
|
||
}
|
||
|
||
// Track is what a post says about a track.
|
||
type Track struct {
|
||
Title string
|
||
Artists []string
|
||
Album string
|
||
}
|
||
|
||
// Store keeps the accounts and knows the tracks.
|
||
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 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.
|
||
Track(ctx context.Context, trackID int64) (Track, bool, error)
|
||
}
|
||
|
||
// Remote talks to a Mastodon instance. The address is always one Normalize accepted.
|
||
type Remote interface {
|
||
// Verify asks the instance who the token belongs to and returns the handle (@name@instance).
|
||
// ErrRefused means the token is not valid; ErrUnreachable that the instance could not be asked.
|
||
Verify(ctx context.Context, instance, token string) (string, error)
|
||
// Post publishes an unlisted status. `key` makes a retry of the same post harmless.
|
||
Post(ctx context.Context, instance, token, status, key string) error
|
||
}
|
||
|
||
// Normalize turns what a person typed (mastodon.social, https://mastodon.social/) into https://mastodon.social. It
|
||
// refuses what is not a domain name on https: a number, a name with no dot, a path, a password.
|
||
func Normalize(in string) (string, error) {
|
||
in = strings.TrimSpace(in)
|
||
if in == "" || strings.ContainsAny(in, " \t\r\n@") {
|
||
return "", ErrBadInstance
|
||
}
|
||
if !strings.Contains(in, "://") {
|
||
in = "https://" + in
|
||
}
|
||
u, err := url.Parse(in)
|
||
if err != nil || u.Scheme != "https" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Opaque != "" {
|
||
return "", ErrBadInstance
|
||
}
|
||
if strings.Trim(u.Path, "/") != "" {
|
||
return "", ErrBadInstance
|
||
}
|
||
host := strings.ToLower(u.Hostname())
|
||
if host == "" || len(host) > 253 || !strings.Contains(host, ".") || strings.HasSuffix(host, ".") {
|
||
return "", ErrBadInstance
|
||
}
|
||
for _, r := range host {
|
||
ok := r == '-' || r == '.' || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r > 127
|
||
if !ok {
|
||
return "", ErrBadInstance
|
||
}
|
||
}
|
||
// A number is not the name of an instance (and an address like 10.0.0.5 would be a way into a private network).
|
||
if last := host[strings.LastIndex(host, ".")+1:]; last == "" || strings.Trim(last, "0123456789") == "" {
|
||
return "", ErrBadInstance
|
||
}
|
||
if port := u.Port(); port != "" {
|
||
return "https://" + host + ":" + port, nil
|
||
}
|
||
return "https://" + host, nil
|
||
}
|
||
|
||
// Compose is the text of a post: "🎵 Title – Artists (Album) #NowPlaying", cut with a mark where it would be too long.
|
||
func Compose(t Track) string {
|
||
text := "🎵 " + t.Title
|
||
if len(t.Artists) > 0 {
|
||
text += " – " + strings.Join(t.Artists, ", ")
|
||
}
|
||
if t.Album != "" {
|
||
text += " (" + t.Album + ")"
|
||
}
|
||
room := maxPost - utf8.RuneCountInString(postTag)
|
||
if utf8.RuneCountInString(text) > room {
|
||
text = string([]rune(text)[:room-1]) + "…"
|
||
}
|
||
return text + postTag
|
||
}
|
||
|
||
type listen struct{ userID, trackID int64 }
|
||
|
||
// Service connects accounts and posts listens.
|
||
type Service struct {
|
||
store Store
|
||
remote Remote
|
||
log *zap.Logger
|
||
now func() time.Time
|
||
queue chan listen
|
||
|
||
mu sync.Mutex
|
||
last map[int64]time.Time
|
||
}
|
||
|
||
// NewService builds a Service. Call Run to have it post.
|
||
func NewService(store Store, remote Remote, log *zap.Logger) *Service {
|
||
return &Service{store: store, remote: remote, log: log, now: time.Now, queue: make(chan listen, queueSize), last: map[int64]time.Time{}}
|
||
}
|
||
|
||
// Status says which account a person connected.
|
||
func (s *Service) Status(ctx context.Context, userID int64) (Account, bool, error) {
|
||
c, found, err := s.store.Get(ctx, userID)
|
||
if err != nil || !found {
|
||
return Account{}, false, err
|
||
}
|
||
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.
|
||
func (s *Service) Connect(ctx context.Context, userID int64, instance, token string) (Account, error) {
|
||
base, err := Normalize(instance)
|
||
if err != nil {
|
||
return Account{}, err
|
||
}
|
||
token = strings.TrimSpace(token)
|
||
if token == "" || len(token) > maxToken {
|
||
return Account{}, ErrBadToken
|
||
}
|
||
handle, err := s.remote.Verify(ctx, base, token)
|
||
if err != nil {
|
||
return Account{}, err
|
||
}
|
||
if err := s.store.Save(ctx, userID, Credentials{Instance: base, Token: token, Handle: handle}); err != nil {
|
||
return Account{}, fmt.Errorf("keep the account: %w", err)
|
||
}
|
||
return Account{Instance: base, Handle: handle}, nil
|
||
}
|
||
|
||
// Disconnect forgets the account and its token.
|
||
func (s *Service) Disconnect(ctx context.Context, userID int64) error {
|
||
s.mu.Lock()
|
||
delete(s.last, userID)
|
||
s.mu.Unlock()
|
||
return s.store.Delete(ctx, userID)
|
||
}
|
||
|
||
// Announce asks for a track to be posted for a person, if they connected an account. It never waits and never fails:
|
||
// when too many are waiting the listen is simply not posted.
|
||
func (s *Service) Announce(userID, trackID int64) {
|
||
select {
|
||
case s.queue <- listen{userID, trackID}:
|
||
default:
|
||
}
|
||
}
|
||
|
||
// Run posts what Announce was asked until the context ends.
|
||
func (s *Service) Run(ctx context.Context) {
|
||
for {
|
||
select {
|
||
case <-ctx.Done():
|
||
return
|
||
case l := <-s.queue:
|
||
pctx, cancel := context.WithTimeout(ctx, postTimeout)
|
||
if err := s.announce(pctx, l.userID, l.trackID); err != nil {
|
||
// No name, no track: only what went wrong.
|
||
s.log.Warn("mastodon post failed", zap.Error(err))
|
||
}
|
||
cancel()
|
||
}
|
||
}
|
||
}
|
||
|
||
// announce posts one listen, unless nothing is connected, the track is gone or a post went out less than a minute ago.
|
||
func (s *Service) announce(ctx context.Context, userID, trackID int64) error {
|
||
c, found, err := s.store.Get(ctx, userID)
|
||
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
|
||
}
|
||
now := s.now()
|
||
s.mu.Lock()
|
||
if at, ok := s.last[userID]; ok && now.Sub(at) < minGap {
|
||
s.mu.Unlock()
|
||
return nil
|
||
}
|
||
// The minute starts now, so that a burst does not post twice while the first is still on its way; a failure gives it back.
|
||
prev, had := s.last[userID]
|
||
s.last[userID] = now
|
||
s.mu.Unlock()
|
||
|
||
key, err := newKey()
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if err := s.remote.Post(ctx, c.Instance, c.Token, Compose(track), key); err != nil {
|
||
s.mu.Lock()
|
||
if had {
|
||
s.last[userID] = prev
|
||
} else {
|
||
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
|
||
}
|
||
|
||
func newKey() (string, error) {
|
||
b := make([]byte, 16)
|
||
if _, err := rand.Read(b); err != nil {
|
||
return "", err
|
||
}
|
||
return hex.EncodeToString(b), nil
|
||
}
|