forked from andersfylling/disgord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
202 lines (175 loc) · 5.24 KB
/
utils.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
package disgord
import (
"errors"
"os"
"os/signal"
"strings"
"syscall"
"github.com/andersfylling/disgord/internal/disgorderr"
"github.com/andersfylling/disgord/internal/gateway"
)
// ShardID calculate the shard id for a given guild.
// https://discord.com/developers/docs/topics/gateway#sharding-sharding-formula
func ShardID(guildID Snowflake, nrOfShards uint) uint {
return gateway.GetShardForGuildID(guildID, nrOfShards)
}
//////////////////////////////////////////////////////
//
// Validators
//
//////////////////////////////////////////////////////
func ValidateHandlerInputs(inputs ...interface{}) (err error) {
var i int
var ok bool
// make sure that middlewares are only at beginning
for j := i; j < len(inputs); j++ {
if _, ok = inputs[j].(Middleware); ok {
if j != i {
return disgorderr.NewHandlerSpecErr(
disgorderr.HandlerSpecErrCodeUnexpectedMiddleware,
"middlewares can only be in the beginning. Grouped together")
}
i++
}
}
// there should now be N handlers, 0 < N.
if len(inputs) <= i {
return disgorderr.NewHandlerSpecErr(
disgorderr.HandlerSpecErrCodeMissingHandler, "missing handler(s)")
}
for j := i; j < len(inputs); j++ {
if _, ok = inputs[j].(HandlerCtrl); ok {
// first element after middlewares and last in inputs
if j == i && len(inputs)-1 == j {
return disgorderr.NewHandlerSpecErr(
disgorderr.HandlerSpecErrCodeMissingHandler, "missing handler(s)")
}
// not last
if len(inputs)-1 != j {
return disgorderr.NewHandlerSpecErr(
disgorderr.HandlerSpecErrCodeUnexpectedCtrl,
"a handlerCtrl's can only be at the end of the definition and only one")
}
break
}
if _, ok = inputs[j].(Ctrl); ok {
return disgorderr.NewHandlerSpecErr(
disgorderr.HandlerSpecErrCodeNotHandlerCtrlImpl,
"does not implement disgord.HandlerCtrl. Try to use &disgord.Ctrl instead of disgord.Ctrl")
}
if !isHandler(inputs[j]) {
return disgorderr.NewHandlerSpecErr(
disgorderr.HandlerSpecErrCodeUnknownHandlerSignature,
"invalid handler signature. General tip: no handlers can use the param type `*disgord.Session`, try `disgord.Session` instead")
}
}
return nil
}
// https://discord.com/developers/docs/resources/user#avatar-data
func validAvatarPrefix(avatar string) (valid bool) {
if avatar == "" {
return false
}
construct := func(encoding string) string {
return "data:image/" + encoding + ";base64,"
}
if len(avatar) < len(construct("X")) {
return false // missing base64 declaration
}
encodings := []string{
"jpeg", "png", "gif",
}
for _, encoding := range encodings {
prefix := construct(encoding)
if strings.HasPrefix(avatar, prefix) {
valid = len(avatar)-len(prefix) > 0 // it has content
break
}
}
return true
}
// ValidateUsername uses Discords rule-set to verify user-names and nicknames
// https://discord.com/developers/docs/resources/user#usernames-and-nicknames
//
// Note that not all the rules are listed in the docs:
// There are other rules and restrictions not shared here for the sake of spam and abuse mitigation, but the
// majority of users won't encounter them. It's important to properly handle all error messages returned by
// Discord when editing or updating names.
func ValidateUsername(name string) (err error) {
if name == "" {
return errors.New("empty")
}
// attributes
length := len(name)
// Names must be between 2 and 32 characters long.
if length < 2 {
err = errors.New("name is too short")
} else if length > 32 {
err = errors.New("name is too long")
}
if err != nil {
return err
}
// Names are sanitized and trimmed of leading, trailing, and excessive internal whitespace.
if name[0] == ' ' {
err = errors.New("contains whitespace prefix")
} else if name[length-1] == ' ' {
err = errors.New("contains whitespace suffix")
} else {
last := name[1]
for i := 2; i < length-1; i++ {
if name[i] == ' ' && last == name[i] {
err = errors.New("contains excessive internal whitespace")
break
}
last = name[i]
}
}
if err != nil {
return err
}
// Names cannot contain the following substrings: '@', '#', ':', '```'
illegalChars := []string{
"@", "#", ":", "```",
}
for _, illegalChar := range illegalChars {
if strings.Contains(name, illegalChar) {
err = errors.New("can not contain the character " + illegalChar)
return err
}
}
// Names cannot be: 'discordtag', 'everyone', 'here'
illegalNames := []string{
"discordtag", "everyone", "here",
}
for _, illegalName := range illegalNames {
if name == illegalName {
err = errors.New("the given username is illegal")
return err
}
}
return nil
}
func validateChannelName(name string) (err error) {
if name == "" {
return errors.New("empty")
}
// attributes
length := len(name)
// Names must be of length of minimum 2 and maximum 100 characters long.
if length < 2 {
err = errors.New("name is too short")
} else if length > 100 {
err = errors.New("name is too long")
}
if err != nil {
return err
}
return nil
}
// CreateTermSigListener create a channel to listen for termination signals (graceful shutdown)
func CreateTermSigListener() <-chan os.Signal {
termSignal := make(chan os.Signal, 1)
signal.Notify(termSignal, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
return termSignal
}