-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestapi.go
449 lines (376 loc) · 12.4 KB
/
restapi.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
package vrmlgo
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// All error constants
var (
ErrJSONUnmarshal = errors.New("json unmarshal")
ErrPruneDaysBounds = errors.New("the number of days should be more than or equal to 1")
ErrUnauthorized = errors.New("HTTP request was unauthorized. This could be because the provided token was not a bot token. Please add \"Bot \" to the start of your token. https://discord.com/developers/docs/reference#authentication-example-bot-token-authorization-header")
)
var (
// Marshal defines function used to encode JSON payloads
Marshal func(v interface{}) ([]byte, error) = json.Marshal
// Unmarshal defines function used to decode JSON payloads
Unmarshal func(src []byte, v interface{}) error = json.Unmarshal
)
// RESTError stores error information about a request with a bad response code.
// Message is not always present, there are cases where api calls can fail
// without returning a json message.
type RESTError struct {
Request *http.Request
Response *http.Response
ResponseBody []byte
Message *APIErrorMessage // Message may be nil.
}
// newRestError returns a new REST API error.
func newRestError(req *http.Request, resp *http.Response, body []byte) *RESTError {
restErr := &RESTError{
Request: req,
Response: resp,
ResponseBody: body,
}
// Attempt to decode the error and assume no message was provided if it fails
var msg *APIErrorMessage
err := Unmarshal(body, &msg)
if err == nil {
restErr.Message = msg
}
return restErr
}
// Error returns a Rest API Error with its status code and body.
func (r RESTError) Error() string {
return "HTTP " + r.Response.Status + ", " + string(r.ResponseBody)
}
// RateLimitError is returned when a request exceeds a rate limit
// and ShouldRetryOnRateLimit is false. The request may be manually
// retried after waiting the duration specified by RetryAfter.
type RateLimitError struct {
*TooManyRequests
URL string
}
// Error returns a rate limit error with rate limited endpoint and retry time.
func (e RateLimitError) Error() string {
return "Rate limit exceeded on " + e.URL + ", retry after " + e.RetryAfter.String()
}
// RequestConfig is an HTTP request configuration.
type RequestConfig struct {
Request *http.Request
ShouldRetryOnRateLimit bool
ShouldIgnoreCacheFail bool
ShouldUseCache bool
MaxRestRetries int
Client *http.Client
}
// newRequestConfig returns a new HTTP request configuration based on parameters in Session.
func newRequestConfig(s *Session, req *http.Request) *RequestConfig {
return &RequestConfig{
ShouldRetryOnRateLimit: s.ShouldRetryOnRateLimit,
ShouldUseCache: s.CacheEnabled,
MaxRestRetries: s.MaxRestRetries,
Client: s.Client,
Request: req,
}
}
// RequestOption is a function which mutates request configuration.
// It can be supplied as an argument to any REST method.
type RequestOption func(cfg *RequestConfig)
// WithClient changes the HTTP client used for the request.
func WithClient(client *http.Client) RequestOption {
return func(cfg *RequestConfig) {
if client != nil {
cfg.Client = client
}
}
}
// WithRetryOnRatelimit controls whether session will retry the request on rate limit.
func WithRetryOnRatelimit(retry bool) RequestOption {
return func(cfg *RequestConfig) {
cfg.ShouldRetryOnRateLimit = retry
}
}
// WithRestRetries changes maximum amount of retries if request fails.
func WithRestRetries(max int) RequestOption {
return func(cfg *RequestConfig) {
cfg.MaxRestRetries = max
}
}
// WithHeader sets a header in the request.
func WithHeader(key, value string) RequestOption {
return func(cfg *RequestConfig) {
cfg.Request.Header.Set(key, value)
}
}
// WithContext changes context of the request.
func WithContext(ctx context.Context) RequestOption {
return func(cfg *RequestConfig) {
cfg.Request = cfg.Request.WithContext(ctx)
}
}
// WithRetryOnRatelimit controls whether session will retry the request on rate limit.
func WithIgnoreCacheFailure(ignore bool) RequestOption {
return func(cfg *RequestConfig) {
cfg.ShouldIgnoreCacheFail = ignore
}
}
func WithUseCache(use bool) RequestOption {
return func(cfg *RequestConfig) {
cfg.ShouldUseCache = use
}
}
// Request is the same as RequestWithBucketID but the bucket id is the same as the urlStr
func (s *Session) Request(method, urlStr string, data interface{}, options ...RequestOption) (response []byte, err error) {
return s.RequestWithBucketID(method, urlStr, data, strings.SplitN(urlStr, "?", 2)[0], options...)
}
// RequestWithBucketID makes a (GET/POST/...) Requests to Discord REST API with JSON data.
func (s *Session) RequestWithBucketID(method, urlStr string, data interface{}, bucketID string, options ...RequestOption) (response []byte, err error) {
var body []byte
if data != nil {
body, err = Marshal(data)
if err != nil {
return
}
}
return s.request(method, urlStr, "application/json", body, bucketID, 0, options...)
}
// request makes a (GET/POST/...) Requests to Discord REST API.
// Sequence is the sequence number, if it fails with a 502 it will
// retry with sequence+1 until it either succeeds or sequence >= session.MaxRestRetries
func (s *Session) request(method, urlStr, contentType string, b []byte, bucketID string, sequence int, options ...RequestOption) (response []byte, err error) {
if bucketID == "" {
bucketID = strings.SplitN(urlStr, "?", 2)[0]
}
return s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucket(bucketID), sequence, options...)
}
// RequestWithLockedBucket makes a request using a bucket that's already been locked
func (s *Session) RequestWithLockedBucket(method, urlStr, contentType string, b []byte, bucket *Bucket, sequence int, options ...RequestOption) (response []byte, err error) {
if s.Debug {
log.Printf("API REQUEST %8s :: %s\n", method, urlStr)
log.Printf("API REQUEST PAYLOAD :: [%s]\n", string(b))
}
req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b))
if err != nil {
bucket.Release(nil)
return
}
// Not used on initial login..
// TODO: Verify if a login, otherwise complain about no-token
if s.Token != "" {
req.Header.Set("authorization", "Bearer "+s.Token)
}
// Discord's API returns a 400 Bad Request is Content-Type is set, but the
// request body is empty.
if b != nil {
req.Header.Set("Content-Type", contentType)
}
// TODO: Make a configurable static variable.
req.Header.Set("User-Agent", s.UserAgent)
cfg := newRequestConfig(s, req)
for _, opt := range options {
opt(cfg)
}
req = cfg.Request
if s.Debug {
for k, v := range req.Header {
log.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v)
}
}
if cfg.ShouldUseCache && method == "GET" {
if data, found, err := s.Cache.Get(urlStr); err != nil {
bucket.Release(nil)
return nil, fmt.Errorf("error getting cached data: %w", err)
} else if found {
bucket.Release(nil)
return []byte(data), nil
}
}
resp, err := cfg.Client.Do(req)
if err != nil {
bucket.Release(nil)
return
}
defer func() {
err2 := resp.Body.Close()
if s.Debug && err2 != nil {
log.Println("error closing resp body")
}
}()
err = bucket.Release(resp.Header)
if err != nil {
return
}
response, err = io.ReadAll(resp.Body)
if err != nil {
return
}
if s.Debug {
log.Printf("API RESPONSE STATUS :: %s\n", resp.Status)
for k, v := range resp.Header {
log.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v)
}
log.Printf("API RESPONSE BODY :: [%s]\n\n\n", response)
}
switch resp.StatusCode {
case http.StatusOK:
case http.StatusCreated:
case http.StatusNoContent:
case http.StatusBadGateway:
// Retry sending request if possible
if sequence < cfg.MaxRestRetries {
s.log(LogInformational, "%s Failed (%s), Retrying...", urlStr, resp.Status)
response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence+1, options...)
} else {
err = fmt.Errorf("exceeded Max retries HTTP %s, %s", resp.Status, response)
}
case 429: // TOO MANY REQUESTS - Rate limiting
rl := TooManyRequests{
Message: resp.Header.Get("X-Ratelimit-Limit"),
}
if resp.Header.Get("X-Ratelimit-Global") == "true" {
rl.Bucket = "global"
}
if resetAfter := resp.Header.Get("X-Ratelimit-Reset-After"); resetAfter != "" {
parsedAfter, err := strconv.ParseFloat(resetAfter, 64)
if err != nil {
return nil, err
}
whole, frac := math.Modf(parsedAfter)
rl.RetryAfter = time.Duration(whole)*time.Second + time.Duration(frac*1000)*time.Millisecond
}
if cfg.ShouldRetryOnRateLimit {
s.log(LogInformational, "Rate Limiting %s, retry in %v", urlStr, rl.RetryAfter)
time.Sleep(rl.RetryAfter)
// we can make the above smarter
// this method can cause longer delays than required
response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence, options...)
} else {
err = &RateLimitError{TooManyRequests: &rl, URL: urlStr}
}
case http.StatusUnauthorized:
fallthrough
default: // Error condition
err = newRestError(req, resp, response)
}
if cfg.ShouldUseCache && s.Cache != nil {
if method == "GET" {
if err := s.Cache.Set(urlStr, string(response)); err != nil && !cfg.ShouldIgnoreCacheFail {
return nil, fmt.Errorf("error setting cached data: %w", err)
}
}
}
return
}
func unmarshal(data []byte, v interface{}) error {
err := Unmarshal(data, v)
if err != nil {
return fmt.Errorf("%w: %s", ErrJSONUnmarshal, err)
}
return nil
}
func (s *Session) Me(options ...RequestOption) (st *User, err error) {
// Do not cache @Me requests
options = append(options, WithUseCache(false))
endpoint := EndpointMe
body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
func (s *Session) Member(userID string, options ...RequestOption) (st *Member, err error) {
endpoint := EndpointMember(userID)
body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
func (s *Session) GameSeasons(gameName string, options ...RequestOption) (st []*Season, err error) {
endpoint := EndpointGameSeasons(gameName)
body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
func (s *Session) TeamMatchesHistory(teamID string, options ...RequestOption) (st []*MatchHistory, err error) {
endpoint := EndpointTeamMatchesHistory(teamID)
body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
func (s *Session) Team(teamID string, options ...RequestOption) (st *TeamDetails, err error) {
endpoint := EndpointTeam(teamID)
body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
func (s *Session) Player(playerID string, options ...RequestOption) (st *Player, err error) {
endpoint := EndpointPlayer(playerID)
body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
func (s *Session) GameSearch(gameName string, options ...RequestOption) (st *GameDetails, err error) {
endpoint := EndpointGame(gameName)
body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
func (s *Session) GameMatch(gName, matchID string, options ...RequestOption) (st *MatchDetails, err error) {
endpoint := EndpointGameMatch(gName, matchID)
body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
func (s *Session) GamePlayersSearch(gameName string, seasonID string, name string, options ...RequestOption) (players []*PlayerSearchResult, err error) {
endpoint := EndpointGamePlayersSearch(gameName)
uri := endpoint
v := url.Values{}
if seasonID != "" {
v.Set("season", seasonID)
}
if name != "" {
v.Set("name", name)
}
if len(v) > 0 {
uri += "?" + v.Encode()
}
body, err := s.RequestWithBucketID("GET", uri, nil, endpoint, options...)
if err != nil {
return
}
players = make([]*PlayerSearchResult, 0)
err = unmarshal(body, &players)
return
}