-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
state.go
553 lines (430 loc) · 11 KB
/
state.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
// Package state provides interfaces for a local or remote state, as well as
// abstractions around the REST API and Gateway events.
package state
import (
"context"
"sync"
"github.com/diamondburned/arikawa/discord"
"github.com/diamondburned/arikawa/gateway"
"github.com/diamondburned/arikawa/handler"
"github.com/diamondburned/arikawa/session"
"github.com/pkg/errors"
)
var (
MaxFetchMembers uint = 1000
MaxFetchGuilds uint = 100
)
type State struct {
*session.Session
Store
// *: State doesn't actually keep track of pinned messages.
// Ready is not updated by the state.
Ready gateway.ReadyEvent
// StateLog logs all errors that come from the state cache. This includes
// not found errors. Defaults to a no-op, as state errors aren't that
// important.
StateLog func(error)
// PreHandler is the manual hook that is executed before the State handler
// is. This should only be used for low-level operations.
// It's recommended to set Synchronous to true if you mutate the events.
PreHandler *handler.Handler // default nil
// Command handler with inherited methods. Ran after PreHandler. You should
// most of the time use this instead of Session's, to avoid race conditions
// with the State
*handler.Handler
unhooker func()
// List of channels with few messages, so it doesn't bother hitting the API
// again.
fewMessages map[discord.Snowflake]struct{}
fewMutex *sync.Mutex
}
func New(token string) (*State, error) {
return NewWithStore(token, NewDefaultStore(nil))
}
func NewWithStore(token string, store Store) (*State, error) {
s, err := session.New(token)
if err != nil {
return nil, err
}
return NewFromSession(s, store)
}
func NewFromSession(s *session.Session, store Store) (*State, error) {
state := &State{
Session: s,
Store: store,
Handler: handler.New(),
StateLog: func(err error) {},
fewMessages: map[discord.Snowflake]struct{}{},
fewMutex: new(sync.Mutex),
}
return state, state.hookSession()
}
// WithContext returns a shallow copy of State with the context replaced in the
// API client. All methods called on the State will use this given context. This
// method is thread-safe.
func (s *State) WithContext(ctx context.Context) *State {
copied := *s
copied.Client = copied.Client.WithContext(ctx)
return &copied
}
//// Helper methods
func (s *State) AuthorDisplayName(message *gateway.MessageCreateEvent) string {
if !message.GuildID.Valid() {
return message.Author.Username
}
if message.Member != nil {
if message.Member.Nick != "" {
return message.Member.Nick
}
return message.Author.Username
}
n, err := s.MemberDisplayName(message.GuildID, message.Author.ID)
if err != nil {
return message.Author.Username
}
return n
}
func (s *State) MemberDisplayName(guildID, userID discord.Snowflake) (string, error) {
member, err := s.Member(guildID, userID)
if err != nil {
return "", err
}
if member.Nick == "" {
return member.User.Username, nil
}
return member.Nick, nil
}
func (s *State) AuthorColor(message *gateway.MessageCreateEvent) discord.Color {
if !message.GuildID.Valid() {
return discord.DefaultMemberColor
}
if message.Member != nil {
guild, err := s.Guild(message.GuildID)
if err != nil {
return discord.DefaultMemberColor
}
return discord.MemberColor(*guild, *message.Member)
}
return s.MemberColor(message.GuildID, message.Author.ID)
}
func (s *State) MemberColor(guildID, userID discord.Snowflake) discord.Color {
member, err := s.Member(guildID, userID)
if err != nil {
return discord.DefaultMemberColor
}
guild, err := s.Guild(guildID)
if err != nil {
return discord.DefaultMemberColor
}
return discord.MemberColor(*guild, *member)
}
////
func (s *State) Permissions(channelID, userID discord.Snowflake) (discord.Permissions, error) {
ch, err := s.Channel(channelID)
if err != nil {
return 0, errors.Wrap(err, "Failed to get channel")
}
g, err := s.Guild(ch.GuildID)
if err != nil {
return 0, errors.Wrap(err, "Failed to get guild")
}
m, err := s.Member(ch.GuildID, userID)
if err != nil {
return 0, errors.Wrap(err, "Failed to get member")
}
return discord.CalcOverwrites(*g, *ch, *m), nil
}
////
func (s *State) Me() (*discord.User, error) {
u, err := s.Store.Me()
if err == nil {
return u, nil
}
u, err = s.Session.Me()
if err != nil {
return nil, err
}
return u, s.Store.MyselfSet(u)
}
////
func (s *State) Channel(id discord.Snowflake) (*discord.Channel, error) {
c, err := s.Store.Channel(id)
if err == nil {
return c, nil
}
c, err = s.Session.Channel(id)
if err != nil {
return nil, err
}
return c, s.Store.ChannelSet(c)
}
func (s *State) Channels(guildID discord.Snowflake) ([]discord.Channel, error) {
c, err := s.Store.Channels(guildID)
if err == nil {
return c, nil
}
c, err = s.Session.Channels(guildID)
if err != nil {
return nil, err
}
for _, ch := range c {
ch := ch
if err := s.Store.ChannelSet(&ch); err != nil {
return nil, err
}
}
return c, nil
}
func (s *State) CreatePrivateChannel(recipient discord.Snowflake) (*discord.Channel, error) {
c, err := s.Store.CreatePrivateChannel(recipient)
if err == nil {
return c, nil
}
c, err = s.Session.CreatePrivateChannel(recipient)
if err != nil {
return nil, err
}
return c, s.Store.ChannelSet(c)
}
func (s *State) PrivateChannels() ([]discord.Channel, error) {
c, err := s.Store.PrivateChannels()
if err == nil {
return c, nil
}
c, err = s.Session.PrivateChannels()
if err != nil {
return nil, err
}
for _, ch := range c {
ch := ch
if err := s.Store.ChannelSet(&ch); err != nil {
return nil, err
}
}
return c, nil
}
////
func (s *State) Emoji(
guildID, emojiID discord.Snowflake) (*discord.Emoji, error) {
e, err := s.Store.Emoji(guildID, emojiID)
if err == nil {
return e, nil
}
es, err := s.Session.Emojis(guildID)
if err != nil {
return nil, err
}
if err := s.Store.EmojiSet(guildID, es); err != nil {
return nil, err
}
for _, e := range es {
if e.ID == emojiID {
return &e, nil
}
}
return nil, ErrStoreNotFound
}
func (s *State) Emojis(guildID discord.Snowflake) ([]discord.Emoji, error) {
e, err := s.Store.Emojis(guildID)
if err == nil {
return e, nil
}
es, err := s.Session.Emojis(guildID)
if err != nil {
return nil, err
}
return es, s.Store.EmojiSet(guildID, es)
}
////
func (s *State) Guild(id discord.Snowflake) (*discord.Guild, error) {
c, err := s.Store.Guild(id)
if err == nil {
return c, nil
}
c, err = s.Session.Guild(id)
if err != nil {
return nil, err
}
return c, s.Store.GuildSet(c)
}
// Guilds will only fill a maximum of 100 guilds from the API.
func (s *State) Guilds() ([]discord.Guild, error) {
c, err := s.Store.Guilds()
if err == nil {
return c, nil
}
c, err = s.Session.Guilds(MaxFetchGuilds)
if err != nil {
return nil, err
}
for _, ch := range c {
ch := ch
if err := s.Store.GuildSet(&ch); err != nil {
return nil, err
}
}
return c, nil
}
////
func (s *State) Member(
guildID, userID discord.Snowflake) (*discord.Member, error) {
m, err := s.Store.Member(guildID, userID)
if err == nil {
return m, nil
}
m, err = s.Session.Member(guildID, userID)
if err != nil {
return nil, err
}
return m, s.Store.MemberSet(guildID, m)
}
func (s *State) Members(guildID discord.Snowflake) ([]discord.Member, error) {
ms, err := s.Store.Members(guildID)
if err == nil {
return ms, nil
}
ms, err = s.Session.Members(guildID, MaxFetchMembers)
if err != nil {
return nil, err
}
for _, m := range ms {
if err := s.Store.MemberSet(guildID, &m); err != nil {
return nil, err
}
}
return ms, s.Gateway.RequestGuildMembers(gateway.RequestGuildMembersData{
GuildID: []discord.Snowflake{guildID},
Presences: true,
})
}
////
func (s *State) Message(
channelID, messageID discord.Snowflake) (*discord.Message, error) {
m, err := s.Store.Message(channelID, messageID)
if err == nil {
return m, nil
}
m, err = s.Session.Message(channelID, messageID)
if err != nil {
return nil, err
}
// Fill the GuildID, because Discord doesn't do it for us.
c, err := s.Channel(channelID)
if err == nil {
// If it's 0, it's 0 anyway. We don't need a check here.
m.GuildID = c.GuildID
}
return m, s.Store.MessageSet(m)
}
// Messages fetches maximum 100 messages from the API, if it has to. There is no
// limit if it's from the State storage.
func (s *State) Messages(channelID discord.Snowflake) ([]discord.Message, error) {
// TODO: Think of a design that doesn't rely on MaxMessages().
var maxMsgs = s.MaxMessages()
ms, err := s.Store.Messages(channelID)
if err == nil {
// If the state already has as many messages as it can, skip the API.
if maxMsgs <= len(ms) {
return ms, nil
}
// Is the channel tiny?
s.fewMutex.Lock()
if _, ok := s.fewMessages[channelID]; ok {
s.fewMutex.Unlock()
return ms, nil
}
// No, fetch from the state.
s.fewMutex.Unlock()
}
ms, err = s.Session.Messages(channelID, uint(maxMsgs))
if err != nil {
return nil, err
}
// New messages fetched weirdly does not have GuildID filled. We'll try and
// get it for consistency with incoming message creates.
var guildID discord.Snowflake
// A bit too convoluted, but whatever.
c, err := s.Channel(channelID)
if err == nil {
// If it's 0, it's 0 anyway. We don't need a check here.
guildID = c.GuildID
}
for i := range ms {
// Set the guild ID, fine if it's 0 (it's already 0 anyway).
ms[i].GuildID = guildID
if err := s.Store.MessageSet(&ms[i]); err != nil {
return nil, err
}
}
if len(ms) < maxMsgs {
// Tiny channel, store this.
s.fewMutex.Lock()
s.fewMessages[channelID] = struct{}{}
s.fewMutex.Unlock()
return ms, nil
}
// Since the latest messages are at the end and we already know the maxMsgs,
// we could slice this right away.
return ms[:maxMsgs], nil
}
////
// Presence checks the state for user presences. If no guildID is given, it will
// look for the presence in all guilds.
func (s *State) Presence(guildID, userID discord.Snowflake) (*discord.Presence, error) {
p, err := s.Store.Presence(guildID, userID)
if err == nil {
return p, nil
}
// If there's no guild ID, look in all guilds
if !guildID.Valid() {
g, err := s.Guilds()
if err != nil {
return nil, err
}
for _, g := range g {
if p, err := s.Store.Presence(g.ID, userID); err == nil {
return p, nil
}
}
}
return nil, err
}
////
func (s *State) Role(guildID, roleID discord.Snowflake) (*discord.Role, error) {
r, err := s.Store.Role(guildID, roleID)
if err == nil {
return r, nil
}
rs, err := s.Session.Roles(guildID)
if err != nil {
return nil, err
}
var role *discord.Role
for _, r := range rs {
r := r
if r.ID == roleID {
role = &r
}
if err := s.RoleSet(guildID, &r); err != nil {
return role, err
}
}
return role, nil
}
func (s *State) Roles(guildID discord.Snowflake) ([]discord.Role, error) {
rs, err := s.Store.Roles(guildID)
if err == nil {
return rs, nil
}
rs, err = s.Session.Roles(guildID)
if err != nil {
return nil, err
}
for _, r := range rs {
r := r
if err := s.RoleSet(guildID, &r); err != nil {
return rs, err
}
}
return rs, nil
}