/
colorlistener.go
281 lines (239 loc) · 7.73 KB
/
colorlistener.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
package listeners
import (
"encoding/base64"
"fmt"
"image/color"
"regexp"
"strings"
"time"
"github.com/bwmarrin/discordgo"
"github.com/sarulabs/di/v2"
"github.com/zekroTJA/colorname"
"github.com/zekroTJA/shinpuru/internal/services/config"
"github.com/zekroTJA/shinpuru/internal/services/database"
"github.com/zekroTJA/shinpuru/internal/services/guildlog"
"github.com/zekroTJA/shinpuru/internal/services/permissions"
"github.com/zekroTJA/shinpuru/internal/util/static"
"github.com/zekroTJA/shinpuru/pkg/colors"
"github.com/zekroTJA/timedmap"
"github.com/zekrotja/dgrs"
"github.com/zekrotja/rogu"
"github.com/zekrotja/rogu/log"
)
const (
colorMatchesCap = 5
)
var (
rxColorHex = regexp.MustCompile(`^#?[\dA-Fa-f]{6,8}$`)
)
type ColorListener struct {
db database.Database
gl guildlog.Logger
pmw *permissions.Permissions
st *dgrs.State
log rogu.Logger
publicAddr string
emojiCache *timedmap.TimedMap
}
func NewColorListener(container di.Container) *ColorListener {
cfg := container.Get(static.DiConfig).(config.Provider)
return &ColorListener{
db: container.Get(static.DiDatabase).(database.Database),
gl: container.Get(static.DiGuildLog).(guildlog.Logger).Section("colorlistener"),
pmw: container.Get(static.DiPermissions).(*permissions.Permissions),
st: container.Get(static.DiState).(*dgrs.State),
log: log.Tagged("ColorListener"),
publicAddr: cfg.Config().WebServer.PublicAddr,
emojiCache: timedmap.New(1 * time.Minute),
}
}
func (l *ColorListener) HandlerMessageCreate(s *discordgo.Session, e *discordgo.MessageCreate) {
l.process(s, e.Message, false)
}
func (l *ColorListener) HandlerMessageEdit(s *discordgo.Session, e *discordgo.MessageUpdate) {
l.process(s, e.Message, true)
}
func (l *ColorListener) HandlerMessageReaction(s *discordgo.Session, e *discordgo.MessageReactionAdd) {
self, err := l.st.SelfUser()
if err != nil {
return
}
if e.MessageReaction.UserID == self.ID {
return
}
cacheKey := e.MessageID + e.Emoji.ID
if !l.emojiCache.Contains(cacheKey) {
return
}
clr, ok := l.emojiCache.GetValue(cacheKey).(*color.RGBA)
if !ok {
return
}
allowed, _, _ := l.pmw.CheckPermissions(s, e.GuildID, e.UserID, "sp.chat.colorreactions")
if !allowed {
s.MessageReactionRemove(e.ChannelID, e.MessageID, e.Emoji.APIName(), e.UserID)
return
}
user, err := l.st.User(e.UserID)
if err != nil {
return
}
hexClr := colors.ToHex(clr)
intClr := colors.ToInt(clr)
cC, cM, cY, cK := color.RGBToCMYK(clr.R, clr.G, clr.B)
yY, yCb, yCr := color.RGBToYCbCr(clr.R, clr.G, clr.B)
colorName := "*could not be fetched*"
matches := colorname.FindRGBA(clr)
if len(matches) > 0 {
precision := (1 - matches[0].AvgDiff/255) * 100
colorName = fmt.Sprintf("**%s** *(%0.1f%%)*", matches[0].Name, precision)
}
desc := fmt.Sprintf(
"%s\n\n```\n"+
"Hex: #%s\n"+
"Int: %d\n"+
"RGBA: %03d, %03d, %03d, %03d\n"+
"CMYK: %03d, %03d, %03d, %03d\n"+
"YCbCr: %03d, %03d, %03d\n"+
"```",
colorName,
hexClr,
intClr,
clr.R, clr.G, clr.B, clr.A,
cC, cM, cY, cK,
yY, yCb, yCr,
)
emb := &discordgo.MessageEmbed{
Color: intClr,
Title: "#" + hexClr,
Description: desc,
Footer: &discordgo.MessageEmbedFooter{
Text: "Activated by " + user.String(),
},
Thumbnail: &discordgo.MessageEmbedThumbnail{
URL: fmt.Sprintf("%s/api/util/color/%s?size=64", l.publicAddr, hexClr),
},
}
_, err = s.ChannelMessageSendComplex(e.ChannelID, &discordgo.MessageSend{
Embed: emb,
Reference: &discordgo.MessageReference{
MessageID: e.MessageID,
ChannelID: e.ChannelID,
GuildID: e.GuildID,
},
})
if err != nil {
l.log.Error().Err(err).Msg("Could not send embed message")
l.gl.Errorf(e.GuildID, "Failed sending embed message: %s", err.Error())
}
l.emojiCache.Remove(cacheKey)
}
func (l *ColorListener) process(s *discordgo.Session, m *discordgo.Message, removeReactions bool) {
if len(m.Content) < 6 {
return
}
matches := make([]string, 0)
content := strings.ReplaceAll(m.Content, "\n", " ")
// Find color hex in message content using
// predefined regex.
for _, v := range strings.Split(content, " ") {
if rxColorHex.MatchString(v) {
matches = appendIfUnique(matches, v)
}
}
// Get color reaction enabled guild setting
// and return when disabled
active, err := l.db.GetGuildColorReaction(m.GuildID)
if err != nil && !database.IsErrDatabaseNotFound(err) {
l.log.Error().Err(err).Msg("Could not get setting from database")
l.gl.Errorf(m.GuildID, "Could not get setting from database: %s", err.Error())
return
}
if !active {
return
}
cMatches := len(matches)
// Cancel when no matches were found
if cMatches == 0 {
return
}
// Cap matches count to colorMatchesCap
if cMatches > colorMatchesCap {
matches = matches[:colorMatchesCap]
}
if removeReactions {
if err := s.MessageReactionsRemoveAll(m.ChannelID, m.ID); err != nil {
l.log.Error().Err(err).Msg("Could not remove previous color reactions")
l.gl.Errorf(m.GuildID, "Could not remove previous color reactions: %s", err.Error())
}
}
// Execute reaction for each match
for _, hexClr := range matches {
l.createReaction(s, m, hexClr)
}
}
func (l *ColorListener) createReaction(s *discordgo.Session, m *discordgo.Message, hexClr string) {
// Remove trailing '#' from color code,
// when existent
hexClr = strings.TrimPrefix(hexClr, "#")
// Parse hex color code to color.RGBA object
clr, err := colors.FromHex(hexClr)
if err != nil {
l.log.Error().Err(err).Msg("Failed parsing color code")
l.gl.Errorf(m.GuildID, "Failed parsing color code: %s", err.Error())
return
}
// Create a 24x24 px image with the parsed color
// rendered as PNG into a buffer
buff, err := colors.CreateImage(clr, 24, 24)
if err != nil {
l.log.Error().Err(err).Msg("Failed generating image data")
l.gl.Errorf(m.GuildID, "Failed generating color image data: %s", err.Error())
return
}
// Encode the raw image data to a base64 string
b64Data := base64.StdEncoding.EncodeToString(buff.Bytes())
// Envelope the base64 data into data uri format
dataUri := fmt.Sprintf("data:image/png;base64,%s", b64Data)
// Upload guild emote
emoji, err := s.GuildEmojiCreate(m.GuildID, &discordgo.EmojiParams{
Name: hexClr,
Image: dataUri,
})
if err != nil {
l.log.Error().Err(err).Msg("Failed uploading emoji")
l.gl.Errorf(m.GuildID, "Failed uploading emoji: %s", err.Error())
return
}
// Delete the uploaded emote after 5 seconds
// to give discords caching or whatever some
// time to save the emoji.
defer time.AfterFunc(5*time.Second, func() {
if err = s.GuildEmojiDelete(m.GuildID, emoji.ID); err != nil {
l.log.Error().Err(err).Msg("Failed deleting emoji")
l.gl.Errorf(m.GuildID, "Failed deleting emoji: %s", err.Error())
}
})
// Add reaction of the uploaded emote to the message
err = s.MessageReactionAdd(m.ChannelID, m.ID, emoji.APIName())
if err != nil {
l.log.Error().Err(err).Msg("Failed creating message reaction")
l.gl.Errorf(m.GuildID, "Failed creating message reaction: %s", err.Error())
return
}
// Set messageID + emojiID with RGBA color object
// to emojiCache
l.emojiCache.Set(m.ID+emoji.ID, clr, 24*time.Hour)
}
// appendIfUnique appends the given elem to the
// passed slice only if the elem is not already
// contained in slice. Otherwise, slice will
// be returned unchanged.
func appendIfUnique(slice []string, elem string) []string {
for _, m := range slice {
if m == elem {
return slice
}
}
return append(slice, elem)
}