/
utils.go
525 lines (417 loc) · 12.8 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
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
package welcomer
import (
"context"
"fmt"
"image/color"
"math/rand"
"net"
"net/url"
"strconv"
"strings"
"time"
"github.com/WelcomerTeam/Discord/discord"
protobuf "github.com/WelcomerTeam/Sandwich-Daemon/protobuf"
"github.com/WelcomerTeam/Welcomer/welcomer-core/database"
urlverifier "github.com/davidmytton/url-verifier"
"github.com/jackc/pgtype"
jsoniter "github.com/json-iterator/go"
"github.com/rs/zerolog"
)
var (
True = true
False = false
)
const (
hexBase = 16
int64Base = 10
int64BitSize = 64
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
UserAgent = "WelcomerService (https://github.com/WelcomerTeam/Welcomer)"
)
func Itoa(v int64) string {
return strconv.FormatInt(v, int64Base)
}
func Atoi(s string) (int64, error) {
return strconv.ParseInt(s, int64Base, int64BitSize)
}
func RandStringBytesRmndr(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Int63()%int64(len(letterBytes))]
}
return string(b)
}
var verifier = urlverifier.NewVerifier()
func CheckGuildMemberships(memberships []*database.GetUserMembershipsByGuildIDRow) (hasWelcomerPro bool, hasCustomBackgrounds bool) {
for _, membership := range memberships {
switch database.MembershipType(membership.MembershipType) {
case database.MembershipTypeLegacyCustomBackgrounds,
database.MembershipTypeCustomBackgrounds:
hasCustomBackgrounds = true
case database.MembershipTypeLegacyWelcomerPro1,
database.MembershipTypeLegacyWelcomerPro3,
database.MembershipTypeLegacyWelcomerPro5,
database.MembershipTypeWelcomerPro:
hasWelcomerPro = true
}
}
return
}
// StringToJsonLiteral converts a string to a jsoniter.RawMessage.
func StringToJsonLiteral(s string) jsoniter.RawMessage {
return jsoniter.RawMessage([]byte(`"` + s + `"`))
}
func ToPointer[K any](k K) *K {
return &k
}
func FormatTextStroke(v bool) int {
if v {
return 4
}
return 0
}
func SetupJSONB(jsonb pgtype.JSONB) pgtype.JSONB {
if jsonb.Status == pgtype.Undefined || len(jsonb.Bytes) == 0 {
jsonb.Status = pgtype.Present
jsonb.Bytes = []byte{123, 125} // {}
}
return jsonb
}
func ConvertToRGBA(int32Color int64) color.RGBA {
alpha := uint8(int32Color >> 24 & 0xFF)
red := uint8(int32Color >> 16 & 0xFF)
green := uint8(int32Color >> 8 & 0xFF)
blue := uint8(int32Color & 0xFF)
return color.RGBA{R: red, G: green, B: blue, A: alpha}
}
func TryParseBool(str string) bool {
boolean, _ := strconv.ParseBool(str)
return boolean
}
func TryParseInt(str string) int {
integer, _ := strconv.ParseInt(str, int64Base, int64BitSize)
return int(integer)
}
func TryParseFloat(str string) float64 {
float, _ := strconv.ParseFloat(str, int64BitSize)
return float
}
func IsValidUnsplashID(str string) bool {
return unsplashRegex.MatchString(str)
}
func IsValidColour(str string) bool {
_, err := ParseColour(str, "")
return err == nil
}
func IsValidInteger(str string) bool {
_, err := strconv.ParseInt(str, int64Base, int64BitSize)
return err == nil
}
func IsValidHex(str string, allowAlpha bool) bool {
if len(str) != 6 && (!allowAlpha || len(str) != 8) {
return false
}
_, err := strconv.ParseUint(str, hexBase, int64BitSize)
return err == nil
}
func IsValidBackground(s string) bool {
_, err := ParseBackground(s)
return err == nil
}
func IsValidEmbed(s string) bool {
var upe UserProvidedEmbed
err := jsoniter.UnmarshalFromString(s, &upe)
return err == nil
}
func IsValidImageAlignment(value string) bool {
_, err := ParseImageAlignment(value)
return err == nil
}
func IsValidImageTheme(value string) bool {
_, err := ParseImageTheme(value)
return err == nil
}
func IsValidImageProfileBorderType(value string) bool {
_, err := ParseImageProfileBorderType(value)
return err == nil
}
// Validates a URL and prevents SSRF.
func IsValidURL(url string) (*url.URL, bool) {
result, err := verifier.Verify(url)
if err != nil {
return nil, false
}
if !result.IsURL || !result.IsRFC3986URL {
return nil, false
}
if !isValidHostname(result.URLComponents.Hostname()) {
return nil, false
}
return result.URLComponents, true
}
func isValidHostname(host string) bool {
ips, err := net.LookupIP(host)
if err != nil {
return false
}
// Check each IP to see if it is an internal IP
for _, ip := range ips {
if ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsInterfaceLocalMulticast() || ip.IsUnspecified() {
return false
}
}
return true
}
// ParseColour parses a colour and returns RGBA.
// Expected formats:
// #FFAAAA
// #FFAAAAFF
// RGBA(255, 255, 255, 0.1)
// RGB(255, 255, 255)
func ParseColour(str string, defaultValue string) (*color.RGBA, error) {
str = strings.TrimSpace(str)
if str == "" {
if defaultValue == "" {
str = fallbackColour
} else {
str = defaultValue
}
}
switch {
case strings.HasPrefix(str, RGBPrefix):
if strings.HasPrefix(str, RGBAPrefix) {
// Validate against RGBA regex
if RGBARegex.MatchString(str) {
str = strings.TrimPrefix(str, RGBAPrefix) // (255, 255, 255, 0.1)
str = strings.TrimPrefix(str, "(") // 255, 255, 255, 0.1)
str = strings.TrimSuffix(str, ")") // 255, 255, 255, 0.1
values := strings.Split(str, ",") // ["255", " 255", " 255, " 0.1"]
alphaString := strings.TrimSpace(values[3]) // 0.1
alphaFloat, err := strconv.ParseFloat(alphaString, int64BitSize)
if err == nil {
var alphaInt uint8
// If our float is above one, we will assume alpha max is 255 instead of 1.
// We store all values as 255 so we multiply the float by 255 if it is not max 1.
if alphaFloat > 1 {
alphaInt = uint8(alphaFloat)
} else {
alphaInt = uint8(alphaFloat * 255)
}
// We can assume these values are ints due to our regex only allowing numerical values.
colourR, _ := strconv.ParseInt(strings.TrimSpace(values[0]), int64Base, int64BitSize)
colourG, _ := strconv.ParseInt(strings.TrimSpace(values[1]), int64Base, int64BitSize)
colourB, _ := strconv.ParseInt(strings.TrimSpace(values[2]), int64Base, int64BitSize)
if colourR > 255 || colourR < 0 {
return nil, ErrInvalidColour
}
if colourG > 255 || colourG < 0 {
return nil, ErrInvalidColour
}
if colourB > 255 || colourB < 0 {
return nil, ErrInvalidColour
}
return &color.RGBA{uint8(colourR), uint8(colourG), uint8(colourB), alphaInt}, nil
}
}
} else {
// Validate against RGB regex
if RGBRegex.MatchString(str) {
str = strings.TrimPrefix(str, RGBPrefix) // (255, 255, 255)
str = strings.TrimPrefix(str, "(") // 255, 255, 255)
str = strings.TrimSuffix(str, ")") // 255, 255, 255
values := strings.Split(str, ",") // ["255", " 255", " 255]
// We can assume these values are ints due to our regex only allowing numerical values.
colourR, _ := strconv.ParseInt(strings.TrimSpace(values[0]), int64Base, int64BitSize)
colourG, _ := strconv.ParseInt(strings.TrimSpace(values[1]), int64Base, int64BitSize)
colourB, _ := strconv.ParseInt(strings.TrimSpace(values[2]), int64Base, int64BitSize)
if colourR > 255 || colourR < 0 {
return nil, ErrInvalidColour
}
if colourG > 255 || colourG < 0 {
return nil, ErrInvalidColour
}
if colourB > 255 || colourB < 0 {
return nil, ErrInvalidColour
}
return &color.RGBA{uint8(colourR), uint8(colourG), uint8(colourB), 255}, nil
}
}
default:
str = strings.TrimPrefix(str, "#")
if IsValidHex(str, true) {
// We can assume these values are ints due to isValidHex.
colourR, _ := strconv.ParseInt(strings.TrimSpace(str[0:2]), hexBase, int64BitSize)
colourG, _ := strconv.ParseInt(strings.TrimSpace(str[2:4]), hexBase, int64BitSize)
colourB, _ := strconv.ParseInt(strings.TrimSpace(str[4:6]), hexBase, int64BitSize)
var colourA int64
if len(str) == 8 {
colourA, _ = strconv.ParseInt(strings.TrimSpace(str[6:8]), hexBase, int64BitSize)
} else {
colourA = 255
}
if colourR > 255 || colourR < 0 {
return nil, ErrInvalidColour
}
if colourG > 255 || colourG < 0 {
return nil, ErrInvalidColour
}
if colourB > 255 || colourB < 0 {
return nil, ErrInvalidColour
}
return &color.RGBA{uint8(colourR), uint8(colourG), uint8(colourB), uint8(colourA)}, nil
}
}
return nil, ErrInvalidColour
}
// IsJSONBEmpty checks if a byte slice is empty or is a JSON empty object.
func IsJSONBEmpty(b []byte) bool {
return len(b) == 0 || (len(b) == 2 && b[0] == '{' && b[1] == '}')
}
// IsMessageParamsEmpty checks if the given message parameters are empty.
// It returns true if the content and all the fields in the embeds are empty, otherwise it returns false.
func IsMessageParamsEmpty(m discord.MessageParams) bool {
if m.Content != "" {
return false
}
if len(m.Files) > 0 {
return false
}
if len(m.Embeds) == 0 {
return true
}
for _, embed := range m.Embeds {
if embed.Title != "" || embed.Description != "" || embed.URL != "" || len(embed.Fields) > 0 || embed.Color != 0 {
return false
}
// Check each field in the embed
for _, field := range embed.Fields {
if field.Name != "" || field.Value != "" || field.Inline {
return false
}
}
}
return true
}
func FilterAssignableTimeRoles(ctx context.Context, sandwichClient protobuf.SandwichClient, logger zerolog.Logger, guildID int64, applicationID int64, timeRoles []GuildSettingsTimeRolesRole) (out []GuildSettingsTimeRolesRole, err error) {
roleIDs := make([]int64, len(timeRoles))
for i, timeRole := range timeRoles {
roleIDs[i] = int64(timeRole.Role)
}
assignableRoleIDs, err := FilterAssignableRoles(ctx, sandwichClient, logger, guildID, applicationID, roleIDs)
if err != nil {
return nil, err
}
for _, timeRole := range timeRoles {
for _, assignableRoleID := range assignableRoleIDs {
if timeRole.Role == assignableRoleID {
out = append(out, timeRole)
break
}
}
}
return out, nil
}
func FilterAssignableRoles(ctx context.Context, sandwichClient protobuf.SandwichClient, logger zerolog.Logger, guildID int64, applicationID int64, roleIDs []int64) (out []discord.Snowflake, err error) {
guildRoles, err := sandwichClient.FetchGuildRoles(ctx, &protobuf.FetchGuildRolesRequest{
GuildID: int64(guildID),
})
if err != nil {
logger.Error().Err(err).
Int64("guild_id", int64(guildID)).
Msg("Failed to fetch guild roles.")
return nil, err
}
guildMember, err := sandwichClient.FetchGuildMembers(ctx, &protobuf.FetchGuildMembersRequest{
GuildID: int64(guildID),
UserIDs: []int64{int64(applicationID)},
})
if err != nil {
logger.Error().Err(err).
Int64("guild_id", int64(guildID)).
Int64("user_id", int64(applicationID)).
Msg("Failed to fetch application guild member.")
}
// Get the guild member of the application.
applicationUser, ok := guildMember.GuildMembers[int64(applicationID)]
if !ok {
logger.Error().Err(err).
Int64("guild_id", int64(guildID)).
Int64("user_id", int64(applicationID)).
Msg("Application guild member not present in response.")
return nil, ErrMissingApplicationUser
}
// Get the top role position of the application user.
var applicationUserTopRolePosition int32
for _, roleID := range applicationUser.Roles {
role, ok := guildRoles.GuildRoles[roleID]
if ok && role.Position > applicationUserTopRolePosition {
applicationUserTopRolePosition = role.Position
}
}
// Filter out any roles that are not in cache or are above the application user's top role position.
for _, roleID := range roleIDs {
role, ok := guildRoles.GuildRoles[roleID]
if ok {
if role.Position < applicationUserTopRolePosition {
out = append(out, discord.Snowflake(roleID))
}
}
}
return out, nil
}
func HumanizeDuration(seconds int) string {
duration := time.Duration(seconds) * time.Second
years := int(duration.Hours() / 24 / 365)
days := int(duration.Hours()/24) % 365
hours := int(duration.Hours()) % 24
minutes := int(duration.Minutes()) % 60
var result strings.Builder
if years > 0 {
result.WriteString(fmt.Sprintf("%d year", years))
if years > 1 {
result.WriteString("s")
}
}
if days > 0 {
if result.Len() > 0 {
result.WriteString(", ")
}
result.WriteString(fmt.Sprintf("%d day", days))
if days > 1 {
result.WriteString("s")
}
}
if hours > 0 {
if result.Len() > 0 {
result.WriteString(", ")
}
result.WriteString(fmt.Sprintf("%d hour", hours))
if hours > 1 {
result.WriteString("s")
}
}
if minutes > 0 {
if result.Len() > 0 {
result.WriteString(" and ")
}
result.WriteString(fmt.Sprintf("%d minute", minutes))
if minutes > 1 {
result.WriteString("s")
}
}
return result.String()
}
func If[T any](condition bool, trueValue, falseValue T) T {
if condition {
return trueValue
}
return falseValue
}
func SliceContains[T comparable](slice []T, value T) bool {
for _, v := range slice {
if v == value {
return true
}
}
return false
}