-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
mastodon.go
462 lines (405 loc) · 11.3 KB
/
mastodon.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// Package mastodon provides functions and structs for accessing the mastodon API.
package mastodon
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"time"
"github.com/tomnomnom/linkheader"
)
// Config is a setting for access mastodon APIs.
type Config struct {
Server string
ClientID string
ClientSecret string
AccessToken string
}
type WriterResetter interface {
io.Writer
Reset()
}
// Client is a API client for mastodon.
type Client struct {
http.Client
Config *Config
UserAgent string
JSONWriter io.Writer
}
func (c *Client) doAPI(ctx context.Context, method string, uri string, params interface{}, res interface{}, pg *Pagination) error {
u, err := url.Parse(c.Config.Server)
if err != nil {
return err
}
u.Path = path.Join(u.Path, uri)
var req *http.Request
ct := "application/x-www-form-urlencoded"
if values, ok := params.(url.Values); ok {
var body io.Reader
if method == http.MethodGet {
if pg != nil {
values = pg.setValues(values)
}
u.RawQuery = values.Encode()
} else {
body = strings.NewReader(values.Encode())
}
req, err = http.NewRequest(method, u.String(), body)
if err != nil {
return err
}
} else if media, ok := params.(*Media); ok {
r, contentType, err := media.bodyAndContentType()
if err != nil {
return err
}
req, err = http.NewRequest(method, u.String(), r)
if err != nil {
return err
}
ct = contentType
} else {
if method == http.MethodGet && pg != nil {
u.RawQuery = pg.toValues().Encode()
}
req, err = http.NewRequest(method, u.String(), nil)
if err != nil {
return err
}
}
req = req.WithContext(ctx)
req.Header.Set("Authorization", "Bearer "+c.Config.AccessToken)
if params != nil {
req.Header.Set("Content-Type", ct)
}
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
var resp *http.Response
backoff := time.Second
for {
resp, err = c.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// handle status code 429, which indicates the server is throttling
// our requests. Do an exponential backoff and retry the request.
if resp.StatusCode == 429 {
if backoff > time.Hour {
break
}
select {
case <-time.After(backoff):
case <-ctx.Done():
return ctx.Err()
}
backoff = time.Duration(1.5 * float64(backoff))
continue
}
break
}
if resp.StatusCode != http.StatusOK {
return parseAPIError("bad request", resp)
} else if res == nil {
return nil
} else if pg != nil {
if lh := resp.Header.Get("Link"); lh != "" {
pg2, err := newPagination(lh)
if err != nil {
return err
}
*pg = *pg2
}
}
if c.JSONWriter != nil {
if resetter, ok := c.JSONWriter.(WriterResetter); ok {
resetter.Reset()
}
return json.NewDecoder(io.TeeReader(resp.Body, c.JSONWriter)).Decode(&res)
} else {
return json.NewDecoder(resp.Body).Decode(&res)
}
}
// NewClient returns a new mastodon API client.
func NewClient(config *Config) *Client {
return &Client{
Client: *http.DefaultClient,
Config: config,
}
}
// Authenticate gets access-token to the API.
// DEPRECATED: Authenticating with username and password is no longer supported, please use
// GetAppAccessToken() or GetUserAccessToken() instead
func (c *Client) Authenticate(ctx context.Context, username, password string) error {
params := url.Values{
"client_id": {c.Config.ClientID},
"client_secret": {c.Config.ClientSecret},
"grant_type": {"password"},
"username": {username},
"password": {password},
"scope": {"read write follow"},
}
return c.authenticate(ctx, params)
}
// AuthenticateApp logs in using client credentials.
// DEPRECATED: use GetAppAccessToken() instead
func (c *Client) AuthenticateApp(ctx context.Context) error {
params := url.Values{
"client_id": {c.Config.ClientID},
"client_secret": {c.Config.ClientSecret},
"grant_type": {"client_credentials"},
"redirect_uri": {"urn:ietf:wg:oauth:2.0:oob"},
}
return c.authenticate(ctx, params)
}
// GetAppAccessToken exchanges API Credentials for an application Access Token
// https://docs.joinmastodon.org/api/oauth-tokens/#app-tokens
func (c *Client) GetAppAccessToken(ctx context.Context, redirectURI string) error {
params := url.Values{
"client_id": {c.Config.ClientID},
"client_secret": {c.Config.ClientSecret},
"grant_type": {"client_credentials"},
"redirect_uri": {redirectURI},
}
return c.getAccessToken(ctx, params)
}
// AuthenticateToken logs in using a grant token returned by Application.AuthURI.
// redirectURI should be the same as Application.RedirectURI.
// DEPRECATED: Use GetUserAccessToken() instead
func (c *Client) AuthenticateToken(ctx context.Context, authCode, redirectURI string) error {
params := url.Values{
"client_id": {c.Config.ClientID},
"client_secret": {c.Config.ClientSecret},
"grant_type": {"authorization_code"},
"code": {authCode},
"redirect_uri": {redirectURI},
}
return c.authenticate(ctx, params)
}
// GetUserAccessToken exhanges a user provided authorization code for an User Access Token
// https://docs.joinmastodon.org/api/oauth-tokens/#user-tokens
func (c *Client) GetUserAccessToken(ctx context.Context, authCode, redirectURI string) error {
params := url.Values{
"client_id": {c.Config.ClientID},
"client_secret": {c.Config.ClientSecret},
"grant_type": {"authorization_code"},
"code": {authCode},
"redirect_uri": {redirectURI},
}
return c.getAccessToken(ctx, params)
}
// DEPRECATED: Use getAccessToken() instead
func (c *Client) authenticate(ctx context.Context, params url.Values) error {
u, err := url.Parse(c.Config.Server)
if err != nil {
return err
}
u.Path = path.Join(u.Path, "/oauth/token")
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(params.Encode()))
if err != nil {
return err
}
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
resp, err := c.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return parseAPIError("bad authorization", resp)
}
var res struct {
AccessToken string `json:"access_token"`
}
err = json.NewDecoder(resp.Body).Decode(&res)
if err != nil {
return err
}
c.Config.AccessToken = res.AccessToken
return nil
}
// Exchanges credentials for an access token to be used by applications and sets the access token in the client config
func (c *Client) getAccessToken(ctx context.Context, params url.Values) error {
u, err := url.Parse(c.Config.Server)
if err != nil {
return err
}
u.Path = path.Join(u.Path, "/oauth/token")
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(params.Encode()))
if err != nil {
return err
}
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
resp, err := c.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return parseAPIError("bad authorization", resp)
}
var res struct {
AccessToken string `json:"access_token"`
}
err = json.NewDecoder(resp.Body).Decode(&res)
if err != nil {
return err
}
c.Config.AccessToken = res.AccessToken
return nil
}
// Convenience constants for Toot.Visibility
const (
VisibilityPublic = "public"
VisibilityUnlisted = "unlisted"
VisibilityFollowersOnly = "private"
VisibilityDirectMessage = "direct"
)
// Toot is a struct to post status.
type Toot struct {
Status string `json:"status"`
InReplyToID ID `json:"in_reply_to_id"`
MediaIDs []ID `json:"media_ids"`
Sensitive bool `json:"sensitive"`
SpoilerText string `json:"spoiler_text"`
Visibility string `json:"visibility"`
Language string `json:"language"`
ScheduledAt *time.Time `json:"scheduled_at,omitempty"`
Poll *TootPoll `json:"poll"`
}
// TootPoll holds information for creating a poll in Toot.
type TootPoll struct {
Options []string `json:"options"`
ExpiresInSeconds int64 `json:"expires_in"`
Multiple bool `json:"multiple"`
HideTotals bool `json:"hide_totals"`
}
// Mention hold information for mention.
type Mention struct {
URL string `json:"url"`
Username string `json:"username"`
Acct string `json:"acct"`
ID ID `json:"id"`
}
// Tag hold information for tag.
type Tag struct {
Name string `json:"name"`
URL string `json:"url"`
History []History `json:"history"`
}
// History hold information for history.
type History struct {
Day string `json:"day"`
Uses string `json:"uses"`
Accounts string `json:"accounts"`
}
// Attachment hold information for attachment.
type Attachment struct {
ID ID `json:"id"`
Type string `json:"type"`
URL string `json:"url"`
RemoteURL string `json:"remote_url"`
PreviewURL string `json:"preview_url"`
TextURL string `json:"text_url"`
Description string `json:"description"`
Meta AttachmentMeta `json:"meta"`
}
// AttachmentMeta holds information for attachment metadata.
type AttachmentMeta struct {
Original AttachmentSize `json:"original"`
Small AttachmentSize `json:"small"`
}
// AttachmentSize holds information for attatchment size.
type AttachmentSize struct {
Width int64 `json:"width"`
Height int64 `json:"height"`
Size string `json:"size"`
Aspect float64 `json:"aspect"`
}
// Emoji hold information for CustomEmoji.
type Emoji struct {
ShortCode string `json:"shortcode"`
StaticURL string `json:"static_url"`
URL string `json:"url"`
VisibleInPicker bool `json:"visible_in_picker"`
}
// Results hold information for search result.
type Results struct {
Accounts []*Account `json:"accounts"`
Statuses []*Status `json:"statuses"`
Hashtags []*Tag `json:"hashtags"`
}
// Pagination is a struct for specifying the get range.
type Pagination struct {
MaxID ID
SinceID ID
MinID ID
Limit int64
}
func newPagination(rawlink string) (*Pagination, error) {
if rawlink == "" {
return nil, errors.New("empty link header")
}
p := &Pagination{}
for _, link := range linkheader.Parse(rawlink) {
switch link.Rel {
case "next":
maxID, err := getPaginationID(link.URL, "max_id")
if err != nil {
return nil, err
}
p.MaxID = maxID
case "prev":
sinceID, err := getPaginationID(link.URL, "since_id")
if err != nil {
return nil, err
}
p.SinceID = sinceID
minID, err := getPaginationID(link.URL, "min_id")
if err != nil {
return nil, err
}
p.MinID = minID
}
}
return p, nil
}
func getPaginationID(rawurl, key string) (ID, error) {
u, err := url.Parse(rawurl)
if err != nil {
return "", err
}
return ID(u.Query().Get(key)), nil
}
func (p *Pagination) toValues() url.Values {
return p.setValues(url.Values{})
}
func (p *Pagination) setValues(params url.Values) url.Values {
if p.MaxID != "" {
params.Set("max_id", string(p.MaxID))
}
if p.SinceID != "" {
params.Set("since_id", string(p.SinceID))
}
if p.MinID != "" {
params.Set("min_id", string(p.MinID))
}
if p.Limit > 0 {
params.Set("limit", fmt.Sprint(p.Limit))
}
return params
}