forked from andersfylling/disgord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest.go
757 lines (652 loc) · 18.1 KB
/
rest.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
package disgord
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"strconv"
"github.com/andersfylling/disgord/internal/constant"
"github.com/andersfylling/disgord/json"
"github.com/andersfylling/disgord/internal/httd"
)
type ErrRest = httd.ErrREST
// URLQueryStringer converts a struct of values to a valid URL query string
type URLQueryStringer interface {
URLQueryString() string
}
// AvatarParamHolder is used when handling avatar related REST structs.
// since a Avatar can be reset by using nil, it causes some extra issues as omit empty cannot be used
// to get around this, the struct requires an internal state and must also handle custom marshalling
type AvatarParamHolder interface {
json.Marshaler
Empty() bool
SetAvatar(avatar string)
UseDefaultAvatar()
}
type urlQuery map[string]interface{}
var _ URLQueryStringer = (*urlQuery)(nil)
var _ fmt.Stringer = (*urlQuery)(nil)
func (p urlQuery) String() string {
return p.URLQueryString()
}
func (p urlQuery) URLQueryString() string {
if len(p) == 0 {
return ""
}
query := url.Values{}
for k, v := range p {
query.Add(k, fmt.Sprint(v))
}
if len(query) > 0 {
return "?" + query.Encode()
}
return ""
}
type restStepDoRequest func() (resp *http.Response, body []byte, err error)
type rest struct {
c *Client
flags Flag // merge flags
httpMethod string
// item creation
// pool is prioritized over factory
pool Pool
factory func() interface{}
conf *httd.Request
// steps
doRequest restStepDoRequest
}
func (r *rest) Put(x interface{}) {
if r.pool != nil {
r.pool.Put(x.(Reseter))
} else {
x = nil // GC
}
}
func (r *rest) Get() (x interface{}) {
if r.pool != nil {
return r.pool.Get()
}
return r.factory()
}
func (r *rest) init() {
if r.conf != nil {
r.conf.PopulateMissing()
}
r.httpMethod = r.conf.Method.String()
r.doRequest = r.stepDoRequest
}
func (r *rest) bindParams(params interface{}) {
if params == nil {
return
}
}
func (r *rest) stepDoRequest() (resp *http.Response, body []byte, err error) {
if r.conf == nil {
err = errors.New("missing httd.Request configuration")
return
}
resp, body, err = r.c.req.Do(r.conf.Ctx, r.conf)
return
}
func (r *rest) processContent(body []byte) (v interface{}, err error) {
if len(body) == 0 {
return nil, nil // nothing more to do
}
// next we create the object and save it to cache
if r.pool == nil && r.factory == nil {
return nil, errors.New("missing factory method for either pool or factory")
}
obj := r.Get()
if err = json.Unmarshal(body, obj); err != nil {
r.Put(obj)
return nil, err
}
executeInternalUpdater(obj)
return obj, nil
}
func (r *rest) Execute() (v interface{}, err error) {
var resp *http.Response
var body []byte
if resp, body, err = r.doRequest(); err != nil {
return nil, err
}
successful := func(code int) bool {
return code >= http.StatusOK && code < 300
}
if !successful(resp.StatusCode) {
err = &httd.ErrREST{
HTTPCode: resp.StatusCode,
Msg: "unexpected http response code. Got " + resp.Status,
}
return nil, err
}
var obj interface{}
if obj, err = r.processContent(body); err != nil {
return nil, err
}
if r.flags.Sort() {
Sort(obj, r.flags)
}
return obj, nil
}
type fRESTRequestMiddleware func(resp *http.Response, body []byte, err error) error
type fRESTCacheMiddleware func(resp *http.Response, v interface{}, err error) error
type fRESTItemFactory func() interface{}
//go:generate go run internal/generate/restbuilders/main.go
type RESTBuilder struct {
middleware fRESTRequestMiddleware
config *httd.Request
client httd.Requester
flags []Flag // TODO: checking
prerequisites []string // error msg
itemFactory fRESTItemFactory
body map[string]interface{}
urlParams urlQuery
ignoreCache bool
cancelOnRatelimit bool
headerReason string
}
// addPrereq the naming here is kinda reversed..
// just think that each resembles a normal; if true => error
func (b *RESTBuilder) addPrereq(condition bool, errorMsg string) {
if condition == false {
return
}
b.prerequisites = append(b.prerequisites, errorMsg)
}
func (b *RESTBuilder) setup(client httd.Requester, config *httd.Request, middleware fRESTRequestMiddleware) {
b.body = make(map[string]interface{})
b.urlParams = make(map[string]interface{})
b.client = client
b.config = config
b.middleware = middleware
if b.config == nil {
b.config = &httd.Request{
Ctx: context.Background(),
Method: http.MethodGet,
}
}
}
func (b *RESTBuilder) prepare() {
// update the config
if b.config.ContentType != "" {
b.config.Body = b.body
}
b.config.Endpoint += b.urlParams.URLQueryString()
flags := mergeFlags(b.flags)
if flags.Ignorecache() {
b.IgnoreCache()
}
if b.config.Ctx == nil {
b.config.Ctx = context.Background()
}
}
// execute ... v must be a nil pointer.
func (b *RESTBuilder) execute() (v interface{}, err error) {
for i := range b.prerequisites {
return nil, errors.New(b.prerequisites[i])
}
b.prepare()
if b.headerReason != "" {
b.config.Reason = b.headerReason
}
var resp *http.Response
var body []byte
resp, body, err = b.client.Do(b.config.Ctx, b.config)
if err != nil {
return nil, err
}
if b.middleware != nil {
if err = b.middleware(resp, body, err); err != nil {
return nil, err
}
}
if len(body) > 1 && b.itemFactory != nil {
v = b.itemFactory()
if err = json.Unmarshal(body, v); err != nil {
return nil, err
}
executeInternalUpdater(v)
}
if mergeFlags(b.flags).Sort() {
Sort(v, b.flags...)
}
return v, nil
}
type restReqBuilderAsync struct {
Data interface{}
Err error
// FromCache bool // TODO
}
func (b *RESTBuilder) async() <-chan *restReqBuilderAsync {
A := make(chan *restReqBuilderAsync)
go func() {
resp := &restReqBuilderAsync{}
resp.Data, resp.Err = b.execute()
A <- resp
close(A)
}()
return A
}
func (b *RESTBuilder) param(name string, v interface{}) *RESTBuilder {
if b.config.Method == http.MethodGet {
// RFC says you can not send a body in a GET request
b.queryParam(name, v)
} else {
b.body[name] = v
}
return b
}
func (b *RESTBuilder) queryParam(name string, v interface{}) *RESTBuilder {
b.urlParams[name] = v
return b
}
func (b *RESTBuilder) IgnoreCache() *RESTBuilder {
b.ignoreCache = true
return b
}
func (b *RESTBuilder) CancelOnRatelimit() *RESTBuilder {
b.cancelOnRatelimit = true
return b
}
//generate-rest-basic-execute: err:error,
type basicBuilder struct {
r RESTBuilder
}
type ClientQueryBuilderExecutables interface {
// CreateGuild Create a new guild. Returns a guild object on success. Fires a Guild Create Gateway event.
CreateGuild(guildName string, params *CreateGuildParams, flags ...Flag) (*Guild, error)
// GetVoiceRegionsBuilder Returns an array of voice region objects that can be used when creating servers.
GetVoiceRegions(flags ...Flag) ([]*VoiceRegion, error)
BotAuthorizeURL() (*url.URL, error)
SendMsg(channelID Snowflake, data ...interface{}) (*Message, error)
}
type ClientQueryBuilder interface {
WithContext(ctx context.Context) ClientQueryBuilderExecutables
ClientQueryBuilderExecutables
Invite(code string) InviteQueryBuilder
Channel(cid Snowflake) ChannelQueryBuilder
User(uid Snowflake) UserQueryBuilder
CurrentUser() CurrentUserQueryBuilder
Guild(id Snowflake) GuildQueryBuilder
Gateway() GatewayQueryBuilder
}
type clientQueryBuilder struct {
ctx context.Context
client *Client
}
func (c clientQueryBuilder) WithContext(ctx context.Context) ClientQueryBuilderExecutables {
c.ctx = ctx
return &c
}
// SendMsg should convert all inputs into a single message. If you supply a object with an ID
// such as a channel, message, role, etc. It will become a reference. If say the Message provided
// does not have an ID, the Message will populate a CreateMessage with it's fields.
//
// If you want to affect the actual message data besides .Content; provide a
// MessageCreateParams. The reply message will be updated by the last one provided.
func (c clientQueryBuilder) SendMsg(channelID Snowflake, data ...interface{}) (msg *Message, err error) {
var flags []Flag
params := &CreateMessageParams{}
addEmbed := func(e *Embed) error {
if params.Embed != nil {
return errors.New("can only send one embed")
}
params.Embed = e
return nil
}
msgToParams := func(m *Message) (s string, err error) {
if s, err = m.DiscordURL(); err != nil {
// try to reference the message, otherwise use it to
// populate the params
if len(m.Embeds) > 1 {
return "", errors.New("can only create a message with a single embed")
} else if len(m.Embeds) > 0 {
params.Embed = m.Embeds[0]
}
params.Content = m.Content
params.Components = m.Components
params.SpoilerTagAllAttachments = m.SpoilerTagAllAttachments
params.SpoilerTagContent = m.SpoilerTagContent
params.Tts = m.Tts
return "", nil
}
return s, nil
}
for i := range data {
if data[i] == nil {
continue
}
var s string
switch t := data[i].(type) {
case *CreateMessageParams:
*params = *t
case CreateMessageParams:
*params = t
case CreateMessageFileParams:
params.Files = append(params.Files, t)
case *CreateMessageFileParams:
params.Files = append(params.Files, *t)
case Embed:
if err = addEmbed(&t); err != nil {
return nil, err
}
case *Embed:
if err = addEmbed(t); err != nil {
return nil, err
}
case *os.File:
return nil, errors.New("can not handle *os.File, use a CreateMessageFileParams instead")
case string:
s = t
case *Flag:
flags = append(flags, *t)
case Flag:
flags = append(flags, t)
case Message:
if s, err = msgToParams(&t); err != nil {
return nil, err
}
case *Message:
if s, err = msgToParams(t); err != nil {
return nil, err
}
case AllowedMentions:
params.AllowedMentions = &t
case *AllowedMentions:
params.AllowedMentions = t
default:
var mentioned bool
if mentionable, ok := t.(Mentioner); ok {
if s = mentionable.Mention(); len(s) > 5 {
mentioned = true
}
}
if !mentioned {
if str, ok := t.(fmt.Stringer); ok {
s = str.String()
} else {
s = fmt.Sprint(t)
}
}
}
if s != "" {
params.Content += " " + s
}
}
// wtf?
if data == nil {
if mergeFlags(flags).IgnoreEmptyParams() {
params.Content = ""
} else {
return nil, errors.New("params were nil")
}
}
return c.Channel(channelID).WithContext(c.ctx).CreateMessage(params, flags...)
}
// BotAuthorizeURL creates a URL that can be used to invite this bot to a guild/server.
// Note that it depends on the bot ID to be after the Discord update where the Client ID
// is the same as the Bot ID.
//
// By default the permissions will be 0, as in none. If you want to add/set the minimum required permissions
// for your bot to run successfully, you should utilise
// Client.
func (c clientQueryBuilder) BotAuthorizeURL() (*url.URL, error) {
format := "https://discord.com/oauth2/authorize?scope=bot&client_id=%s&permissions=%d"
u := fmt.Sprintf(format, c.client.botID.String(), c.client.permissions)
return url.Parse(u)
}
func ensureDiscordGatewayURLHasQueryParams(urlString string) (string, error) {
u, err := url.Parse(urlString)
if err != nil {
return urlString, err
}
q, err := url.ParseQuery(u.RawQuery)
if err != nil {
return urlString, err
}
q.Add("encoding", constant.Encoding)
q.Add("v", strconv.FormatUint(uint64(constant.DiscordVersion), 10))
u.RawQuery = q.Encode()
return u.String(), nil
}
func exec(f func() (interface{}, error), flags ...Flag) (v interface{}, err error) {
if v, err = f(); err != nil {
return nil, err
}
if v == nil {
return nil, errors.New("object was nil")
}
return v, nil
}
// TODO: auto generate
func getChannel(f func() (interface{}, error), flags ...Flag) (channel *Channel, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*Channel), nil
}
// TODO: auto generate
func getChannels(f func() (interface{}, error), flags ...Flag) (channels []*Channel, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
if list, ok := v.(*[]*Channel); ok {
return *list, nil
} else if list, ok := v.([]*Channel); ok {
return list, nil
}
panic("v was not assumed type. Got " + fmt.Sprint(v))
}
// TODO: auto generate
func getRole(f func() (interface{}, error), flags ...Flag) (role *Role, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*Role), nil
}
// TODO: auto generate
func getRoles(f func() (interface{}, error), flags ...Flag) (roles []*Role, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
if list, ok := v.(*[]*Role); ok {
return *list, nil
} else if list, ok := v.([]*Role); ok {
return list, nil
}
panic("v was not assumed type. Got " + fmt.Sprint(v))
}
// TODO: auto generate
func getMember(f func() (interface{}, error), flags ...Flag) (member *Member, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*Member), nil
}
// TODO: auto generate
func getMembers(f func() (interface{}, error), flags ...Flag) (members []*Member, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
if list, ok := v.(*[]*Member); ok {
return *list, nil
} else if list, ok := v.([]*Member); ok {
return list, nil
}
panic("v was not assumed type. Got " + fmt.Sprint(v))
}
// TODO: auto generate
func getWebhook(f func() (interface{}, error), flags ...Flag) (wh *Webhook, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*Webhook), nil
}
// TODO: auto generate
func getWebhooks(f func() (interface{}, error), flags ...Flag) (whs []*Webhook, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
if list, ok := v.(*[]*Webhook); ok {
return *list, nil
} else if list, ok := v.([]*Webhook); ok {
return list, nil
}
panic("v was not assumed type. Got " + fmt.Sprint(v))
}
// TODO: auto generate
func getMessage(f func() (interface{}, error), flags ...Flag) (msg *Message, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*Message), nil
}
// TODO: auto generate
func getMessages(f func() (interface{}, error), flags ...Flag) (msgs []*Message, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
if list, ok := v.(*[]*Message); ok {
return *list, nil
} else if list, ok := v.([]*Message); ok {
return list, nil
}
panic("v was not assumed type. Got " + fmt.Sprint(v))
}
// TODO: auto generate
func getUser(f func() (interface{}, error), flags ...Flag) (user *User, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*User), nil
}
// TODO: auto generate
func getUsers(f func() (interface{}, error), flags ...Flag) (users []*User, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
if list, ok := v.(*[]*User); ok {
return *list, nil
} else if list, ok := v.([]*User); ok {
return list, nil
}
panic("v was not assumed type. Got " + fmt.Sprint(v))
}
// TODO: auto generate
func getNickName(f func() (interface{}, error), flags ...Flag) (nick string, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return "", err
}
return v.(*nickNameResponse).Nickname, nil
}
// TODO: auto generate
func getBan(f func() (interface{}, error), flags ...Flag) (ban *Ban, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*Ban), nil
}
// TODO: auto generate
func getEmoji(f func() (interface{}, error), flags ...Flag) (emoji *Emoji, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*Emoji), nil
}
// TODO: auto generate
func getInvite(f func() (interface{}, error), flags ...Flag) (invite *Invite, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*Invite), nil
}
// TODO: auto generate
func getInvites(f func() (interface{}, error), flags ...Flag) (invite []*Invite, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
if list, ok := v.(*[]*Invite); ok {
return *list, nil
} else if list, ok := v.([]*Invite); ok {
return list, nil
}
panic("v was not assumed type. Got " + fmt.Sprint(v))
}
// TODO: auto generate
func getGuild(f func() (interface{}, error), flags ...Flag) (guild *Guild, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*Guild), nil
}
// TODO: auto generate
func getIntegrations(f func() (interface{}, error), flags ...Flag) (integrations []*Integration, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
if list, ok := v.(*[]*Integration); ok {
return *list, nil
} else if list, ok := v.([]*Integration); ok {
return list, nil
}
panic("v was not assumed type. Got " + fmt.Sprint(v))
}
// TODO: auto generate
func getVoiceRegions(f func() (interface{}, error), flags ...Flag) (regions []*VoiceRegion, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
if list, ok := v.(*[]*VoiceRegion); ok {
return *list, nil
} else if list, ok := v.([]*VoiceRegion); ok {
return list, nil
}
panic("v was not assumed type. Got " + fmt.Sprint(v))
}
// TODO: auto generate
func getVoiceRegion(f func() (interface{}, error), flags ...Flag) (region *VoiceRegion, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*VoiceRegion), nil
}
// TODO: auto generate
func getPartialInvite(f func() (interface{}, error), flags ...Flag) (invite *PartialInvite, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*PartialInvite), nil
}
// TODO: auto generate
func getGuildEmbed(f func() (interface{}, error), flags ...Flag) (embed *GuildEmbed, err error) {
var v interface{}
if v, err = exec(f, flags...); err != nil {
return nil, err
}
return v.(*GuildEmbed), nil
}