forked from andersfylling/disgord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
guild.go
613 lines (523 loc) · 16 KB
/
guild.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
package resource
import (
"encoding/json"
"errors"
"sort"
"sync"
. "github.com/andersfylling/snowflake"
)
// consts inspired by: https://github.com/bwmarrin/discordgo/blob/master/structs.go
// Constants for the different bit offsets of text channel permissions
const (
ReadMessagesPermission = 1 << (iota + 10)
SendMessagesPermission
SendTTSMessagesPermission
ManageMessagesPermission
EmbedLinksPermission
AttachFilesPermission
ReadMessageHistoryPermission
MentionEveryonePermission
UseExternalEmojisPermission
)
// Constants for the different bit offsets of voice permissions
const (
VoiceConnectPermission = 1 << (iota + 20)
VoiceSpeakPermission
VoiceMuteMembersPermission
VoiceDeafenMembersPermission
VoiceMoveMembersPermission
VoiceUseVADPermission
)
// Constants for general management.
const (
ChangeNicknamePermission = 1 << (iota + 26)
ManageNicknamesPermission
ManageRolesPermission
ManageWebhooksPermission
ManageEmojisPermission
)
// Constants for the different bit offsets of general permissions
const (
CreateInstantInvitePermission = 1 << iota
KickMembersPermission
BanMembersPermission
AdministratorPermission
ManageChannelsPermission
ManageServerPermission
AddReactionsPermission
ViewAuditLogsPermission
AllTextPermission = ReadMessagesPermission |
SendMessagesPermission |
SendTTSMessagesPermission |
ManageMessagesPermission |
EmbedLinksPermission |
AttachFilesPermission |
ReadMessageHistoryPermission |
MentionEveryonePermission
AllVoicePermission = VoiceConnectPermission |
VoiceSpeakPermission |
VoiceMuteMembersPermission |
VoiceDeafenMembersPermission |
VoiceMoveMembersPermission |
VoiceUseVADPermission
AllChannelPermission = AllTextPermission |
AllVoicePermission |
CreateInstantInvitePermission |
ManageRolesPermission |
ManageChannelsPermission |
AddReactionsPermission |
ViewAuditLogsPermission
AllPermission = AllChannelPermission |
KickMembersPermission |
BanMembersPermission |
ManageServerPermission |
AdministratorPermission
)
func NewGuild() *Guild {
return &Guild{}
}
func NewGuildFromJSON(data []byte) *Guild {
guild := &Guild{
Roles: []*Role{},
Emojis: []*Emoji{},
Features: []string{},
VoiceStates: []*VoiceState{},
Members: []*Member{},
Channels: []*Channel{},
Presences: []*UserPresence{},
}
err := json.Unmarshal(data, guild)
if err != nil {
panic(err)
}
return guild
}
func NewPartialGuild(ID Snowflake) *Guild {
return &Guild{
ID: ID,
Unavailable: true,
Roles: []*Role{},
Emojis: []*Emoji{},
Features: []string{},
VoiceStates: []*VoiceState{},
Members: []*Member{},
Channels: []*Channel{},
Presences: []*UserPresence{},
}
}
func NewGuildFromUnavailable(gu *GuildUnavailable) *Guild {
return NewPartialGuild(gu.ID)
}
func NewGuildUnavailable(ID Snowflake) *GuildUnavailable {
gu := &GuildUnavailable{
ID: ID,
Unavailable: true,
}
return gu
}
type GuildUnavailable struct {
ID Snowflake `json:"id"`
Unavailable bool `json:"unavailable"` // ?*|
sync.RWMutex `json:"-"`
}
type GuildInterface interface {
Channel(ID Snowflake)
}
// if loading is deactivated, then check state, then do a request.
// if loading is activated, check state only.
// type Members interface {
// Member(userID snowflake.Snowflake) *Member
// MembersWithName( /*username*/ name string) map[snowflake.Snowflake]*Member
// MemberByUsername( /*username#discriminator*/ username string) *Member
// MemberByAlias(alias string) *Member
// EverythingInMemory() bool
// }
// Guild Guilds in Discord represent an isolated collection of users and channels,
// and are often referred to as "servers" in the UI.
// https://discordapp.com/developers/docs/resources/guild#guild-object
// Fields with `*` are only sent within the GUILD_CREATE event
// TODO: lazyload everything
// reviewed: 2018-08-25
type PartialGuild = Guild
type Guild struct {
ID Snowflake `json:"id"`
ApplicationID *Snowflake `json:"application_id"` // |?
Name string `json:"name"`
Icon *string `json:"icon"` // |?, icon hash
Splash *string `json:"splash"` // |?, image hash
Owner bool `json:"owner,omitempty"` // ?|
OwnerID Snowflake `json:"owner_id"`
Permissions uint64 `json:"permissions,omitempty"` // ?|, permission flags for connected user `/users/@me/guilds`
Region string `json:"region"`
AfkChannelID *Snowflake `json:"afk_channel_id"` // |?
AfkTimeout uint `json:"afk_timeout"`
EmbedEnabled bool `json:"embed_enabled,omit_empty"`
EmbedChannelID Snowflake `json:"embed_channel_id,omit_empty"`
VerificationLevel VerificationLvl `json:"verification_level"`
DefaultMessageNotifications DefaultMessageNotificationLvl `json:"default_message_notifications"`
ExplicitContentFilter ExplicitContentFilterLvl `json:"explicit_content_filter"`
Roles []*Role `json:"roles"`
Emojis []*Emoji `json:"emojis"`
Features []string `json:"features"`
MFALevel MFALvl `json:"mfa_level"`
WidgetEnabled bool `json:"widget_enabled,omit_empty"` // |
WidgetChannelID Snowflake `json:"widget_channel_id,omit_empty"` // |
SystemChannelID *Snowflake `json:"system_channel_id,omitempty"` // |?
// JoinedAt must be a pointer, as we can't hide non-nil structs
JoinedAt *Timestamp `json:"joined_at,omitempty"` // ?*|
Large bool `json:"large,omitempty"` // ?*|
Unavailable bool `json:"unavailable"` // ?*| omitempty?
MemberCount uint `json:"member_count,omitempty"` // ?*|
VoiceStates []*VoiceState `json:"voice_states,omitempty"` // ?*|
Members []*Member `json:"members,omitempty"` // ?*|
Channels []*Channel `json:"channels,omitempty"` // ?*|
Presences []*UserPresence `json:"presences,omitempty"` // ?*|
PresencesMutex sync.RWMutex `json:"-"`
mu sync.RWMutex
}
//func (g *Guild) EverythingInMemory() bool {
// return false
//}
// Compare two guild objects
func (g *Guild) Compare(other *Guild) bool {
// TODO: this is shit..
return (g == nil && other == nil) || (other != nil && g.ID == other.ID)
}
// func (g *Guild) UnmarshalJSON(data []byte) (err error) {
// return json.Unmarshal(data, &g.guildJSON)
// }
// TODO: fix copying of mutex lock
func (g *Guild) MarshalJSON() ([]byte, error) {
var jsonData []byte
var err error
if g.Unavailable {
guildUnavailable := NewGuildUnavailable(g.ID)
jsonData, err = json.Marshal(guildUnavailable)
if err != nil {
return []byte(""), nil
}
} else {
jsonData, err = json.Marshal(Guild(*g))
if err != nil {
return []byte(""), nil
}
}
return jsonData, nil
}
// sortChannels Only while in lock
func (g *Guild) sortChannels() {
sort.Slice(g.Channels, func(i, j int) bool {
return g.Channels[i].ID < g.Channels[j].ID
})
}
func (g *Guild) AddChannel(c *Channel) error {
g.Channels = append(g.Channels, c)
g.sortChannels()
return nil
}
func (g *Guild) DeleteChannel(c *Channel) error {
return g.DeleteChannelByID(c.ID)
}
func (g *Guild) DeleteChannelByID(ID Snowflake) error {
index := -1
for i, c := range g.Channels {
if c.ID == ID {
index = i
}
}
if index == -1 {
return errors.New("channel with Snowflake{" + ID.String() + "} does not exist in cache")
}
// delete the entry
g.Channels[index] = g.Channels[len(g.Channels)-1]
g.Channels[len(g.Channels)-1] = nil
g.Channels = g.Channels[:len(g.Channels)-1]
g.sortChannels()
return nil
}
func (g *Guild) AddMember(member *Member) error {
// TODO: implement sorting for faster searching later
g.Members = append(g.Members, member)
return nil
}
func (g *Guild) AddRole(role *Role) error {
// TODO: implement sorting for faster searching later
g.Roles = append(g.Roles, role)
return nil
}
// Member return a member by his/her userid
func (g *Guild) Member(id Snowflake) (*Member, error) {
for _, member := range g.Members {
if member.User.ID == id {
return member, nil
}
}
return nil, errors.New("member not found in guild")
}
// MemberByName retrieve a slice of members with same username or nickname
func (g *Guild) MemberByName(name string) ([]*Member, error) {
var members []*Member
for _, member := range g.Members {
if member.Nick == name || member.User.Username == name {
members = append(members, member)
}
}
if len(members) == 0 {
return nil, errors.New("no members with that nick or username was found in guild")
}
return members, nil
}
// Role retrieve a role based on role id
func (g *Guild) Role(id Snowflake) (*Role, error) {
for _, role := range g.Roles {
if role.ID == id {
return role, nil
}
}
return nil, errors.New("role not found in guild")
}
func (g *Guild) UpdateRole(r *Role) {
for _, role := range g.Roles {
if role.ID == r.ID {
*role = *r
break
}
}
}
func (g *Guild) DeleteRoleByID(ID Snowflake) {
index := -1
for i, r := range g.Roles {
if r.ID == ID {
index = i
break
}
}
if index != -1 {
// delete the entry
g.Roles[index] = g.Roles[len(g.Roles)-1]
g.Roles[len(g.Roles)-1] = nil
g.Roles = g.Roles[:len(g.Roles)-1]
}
}
// RoleByTitle retrieves a slice of roles with same name
func (g *Guild) RoleByName(name string) ([]*Role, error) {
var roles []*Role
for _, role := range g.Roles {
if role.Name == name {
roles = append(roles, role)
}
}
if len(roles) == 0 {
return nil, errors.New("no roles were found in guild")
}
return roles, nil
}
func (g *Guild) Channel(id Snowflake) (*Channel, error) {
for _, channel := range g.Channels {
if channel.ID == id {
return channel, nil
}
}
return nil, errors.New("channel not found in guild")
}
func (g *Guild) UpdatePresence(p *UserPresence) {
g.PresencesMutex.RLock()
index := -1
for i, presence := range g.Presences {
if presence.User.ID == p.User.ID {
index = i
break
}
}
g.PresencesMutex.RUnlock()
if index != -1 {
// update
return
}
// otherwise add
g.PresencesMutex.Lock()
g.Presences = append(g.Presences, p) // TODO: update the user pointer?
g.PresencesMutex.Unlock()
}
// Update update the reference content
func (g *Guild) Update(new *Guild) {
// must have same Snowflake
if g.ID != new.ID {
return
}
// must not be the same pointer as it causes a deadlock
if g == new {
return
}
g.mu.Lock()
new.mu.RLock()
// if it's a unavailable guild object, don't update the remaining fields
if new.Unavailable {
g.Unavailable = true
} else {
// normal update
// TODO
}
g.mu.Unlock()
new.mu.RUnlock()
}
// Clear all the pointers
func (g *Guild) Clear() {
g.mu.Lock() // what if another process tries to read this, but awais while locked for clearing?
defer g.mu.Unlock()
//g.Icon = nil // should this be cleared?
//g.Splash = nil // should this be cleared?
for _, r := range g.Roles {
r.Clear()
r = nil
}
g.Roles = nil
for _, e := range g.Emojis {
e.Clear()
e = nil
}
g.Emojis = nil
for _, vst := range g.VoiceStates {
vst.Clear()
vst = nil
}
g.VoiceStates = nil
var deletedUsers []Snowflake
for _, m := range g.Members {
deletedUsers = append(deletedUsers, m.Clear())
m = nil
}
g.Members = nil
for _, c := range g.Channels {
c.Clear()
c = nil
}
g.Channels = nil
for _, p := range g.Presences {
p.Clear()
p = nil
}
g.Presences = nil
}
func (g *Guild) DeepCopy() *Guild {
guild := NewGuild()
g.mu.RLock()
// TODO-guild: handle string pointers
guild.ID = g.ID
guild.ApplicationID = g.ApplicationID
guild.Name = g.Name
guild.Icon = g.Icon
guild.Splash = g.Splash
guild.Owner = g.Owner
guild.OwnerID = g.OwnerID
guild.Permissions = g.Permissions
guild.Region = g.Region
guild.AfkChannelID = g.AfkChannelID
guild.AfkTimeout = g.AfkTimeout
guild.EmbedEnabled = g.EmbedEnabled
guild.EmbedChannelID = g.EmbedChannelID
guild.VerificationLevel = g.VerificationLevel
guild.DefaultMessageNotifications = g.DefaultMessageNotifications
guild.ExplicitContentFilter = g.ExplicitContentFilter
guild.MFALevel = g.MFALevel
guild.WidgetEnabled = g.WidgetEnabled
guild.WidgetChannelID = g.WidgetChannelID
guild.SystemChannelID = g.SystemChannelID
guild.JoinedAt = g.JoinedAt
guild.Large = g.Large
guild.Unavailable = g.Unavailable
guild.MemberCount = g.MemberCount
//guild.PresencesMutex = g.PresencesMutex // TODO: do not copy lock value
// handle deep copy of slices
//TODO-guild: implement deep copying for fields
guild.Roles = g.Roles
guild.Emojis = g.Emojis
guild.Features = g.Features
guild.VoiceStates = g.VoiceStates
guild.Members = g.Members
guild.Channels = g.Channels
guild.Presences = g.Presences
g.mu.RUnlock()
return guild
}
// --------------
// Ban https://discordapp.com/developers/docs/resources/guild#ban-object
type Ban struct {
Reason string `json:"reason"`
User *User `json:"user"`
}
// ------------
// GuildEmbed https://discordapp.com/developers/docs/resources/guild#guild-embed-object
type GuildEmbed struct {
Enabled bool `json:"enabled"`
ChannelID Snowflake `json:"channel_id"`
}
// -------
// Integration https://discordapp.com/developers/docs/resources/guild#integration-object
type Integration struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Enabled bool `json:"enabled"`
Syncing bool `json:"syncing"`
RoleID Snowflake `json:"role_id"`
ExpireBehavior int `json:"expire_behavior"`
ExpireGracePeriod int `json:"expire_grace_period"`
User *User `json:"user"`
Account *IntegrationAccount `json:"account"`
}
// IntegrationAccount https://discordapp.com/developers/docs/resources/guild#integration-account-object
type IntegrationAccount struct {
ID string `json:"id"` // id of the account
Name string `json:"name"` // name of the account
}
// -------
// Member https://discordapp.com/developers/docs/resources/guild#guild-member-object
type Member struct {
GuildID Snowflake `json:"guild_id,omitempty"`
User *User `json:"user"`
Nick string `json:"nick,omitempty"` // ?|
Roles []Snowflake `json:"roles"`
JoinedAt Timestamp `json:"joined_at,omitempty"`
Deaf bool `json:"deaf"`
Mute bool `json:"mute"`
sync.RWMutex `json:"-"`
}
func (m *Member) Clear() Snowflake {
// do i want to delete user?.. what if there is a PM?
// Check for user id in DM's
// or.. since the user object is sent on channel_create events, the user can be reintialized when needed.
// but should be properly removed from other arrays.
m.User.Clear()
id := m.User.ID
m.User = nil
// use this Snowflake to check in other places. To avoid pointing to random memory spaces
return id
}
func (m *Member) Update(new *Member) (err error) {
if m.User.ID != new.User.ID || m.GuildID != new.GuildID {
err = errors.New("cannot update user when the new struct has a different Snowflake")
return
}
// make sure that new is not the same pointer!
if m == new {
err = errors.New("cannot update user when the new struct points to the same memory space")
return
}
m.Lock()
new.RLock()
m.Nick = new.Nick
m.Roles = new.Roles
m.JoinedAt = new.JoinedAt
m.Deaf = new.Deaf
m.Mute = new.Mute
new.RUnlock()
m.Unlock()
return
}
const (
EndpointGuild = "/guilds/"
)
type GuildPruneCount struct {
Pruned int `json:"pruned"`
}