-
Notifications
You must be signed in to change notification settings - Fork 907
/
web.go
577 lines (453 loc) · 18.6 KB
/
web.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
package customcommands
import (
"context"
_ "embed"
"fmt"
"html/template"
"net/http"
"strconv"
"strings"
"unicode/utf8"
"emperror.dev/errors"
"github.com/jonas747/discordgo/v2"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/cplogs"
"github.com/jonas747/yagpdb/common/featureflags"
"github.com/jonas747/yagpdb/common/pubsub"
yagtemplate "github.com/jonas747/yagpdb/common/templates"
"github.com/jonas747/yagpdb/customcommands/models"
"github.com/jonas747/yagpdb/web"
"github.com/mediocregopher/radix/v3"
"github.com/volatiletech/null"
"github.com/volatiletech/sqlboiler/boil"
"github.com/volatiletech/sqlboiler/queries/qm"
"goji.io"
"goji.io/pat"
)
//go:embed assets/customcommands-editcmd.html
var PageHTMLEditCmd string
//go:embed assets/customcommands.html
var PageHTMLMain string
// GroupForm is the form bindings used when creating or updating groups
type GroupForm struct {
ID int64
Name string `valid:",100"`
WhitelistChannels []int64 `valid:"channel,true"`
BlacklistChannels []int64 `valid:"channel,true"`
WhitelistRoles []int64 `valid:"role,true"`
BlacklistRoles []int64 `valid:"role,true"`
}
var (
panelLogKeyNewCommand = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "customcommands_new_command", FormatString: "Created a new custom command: %d"})
panelLogKeyUpdatedCommand = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "customcommands_updated_command", FormatString: "Updated custom command: %d"})
panelLogKeyRemovedCommand = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "customcommands_removed_command", FormatString: "Removed custom command: %d"})
panelLogKeyNewGroup = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "customcommands_new_group", FormatString: "Created a new custom command group: %s"})
panelLogKeyUpdatedGroup = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "customcommands_updated_group", FormatString: "Updated custom command group: %s"})
panelLogKeyRemovedGroup = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "customcommands_removed_group", FormatString: "Removed custom command group: %d"})
)
// InitWeb implements web.Plugin
func (p *Plugin) InitWeb() {
web.AddHTMLTemplate("customcommands/assets/customcommands.html", PageHTMLMain)
web.AddHTMLTemplate("customcommands/assets/customcommands-editcmd.html", PageHTMLEditCmd)
web.AddSidebarItem(web.SidebarCategoryCore, &web.SidebarItem{
Name: "Custom commands",
URL: "customcommands",
Icon: "fas fa-closed-captioning",
})
getHandler := web.ControllerHandler(handleCommands, "cp_custom_commands")
getCmdHandler := web.ControllerHandler(handleGetCommand, "cp_custom_commands_edit_cmd")
getGroupHandler := web.ControllerHandler(handleGetCommandsGroup, "cp_custom_commands")
subMux := goji.SubMux()
web.CPMux.Handle(pat.New("/customcommands"), subMux)
web.CPMux.Handle(pat.New("/customcommands/*"), subMux)
subMux.Use(func(inner http.Handler) http.Handler {
h := func(w http.ResponseWriter, r *http.Request) {
_, templateData := web.GetBaseCPContextData(r.Context())
strTriggerTypes := map[int]string{}
for k, v := range triggerStrings {
strTriggerTypes[int(k)] = v
}
templateData["CCTriggerTypes"] = strTriggerTypes
inner.ServeHTTP(w, r)
}
return http.HandlerFunc(h)
})
subMux.Handle(pat.Get(""), getHandler)
subMux.Handle(pat.Get("/"), getHandler)
subMux.Handle(pat.Get("/commands/:cmd/"), getCmdHandler)
subMux.Handle(pat.Get("/groups/:group/"), web.ControllerHandler(handleGetCommandsGroup, "cp_custom_commands"))
subMux.Handle(pat.Get("/groups/:group"), web.ControllerHandler(handleGetCommandsGroup, "cp_custom_commands"))
newCommandHandler := web.ControllerPostHandler(handleNewCommand, nil, nil)
subMux.Handle(pat.Post("/commands/new"), newCommandHandler)
subMux.Handle(pat.Post("/commands/:cmd/update"), web.ControllerPostHandler(handleUpdateCommand, getCmdHandler, CustomCommand{}))
subMux.Handle(pat.Post("/commands/:cmd/delete"), web.ControllerPostHandler(handleDeleteCommand, getHandler, nil))
subMux.Handle(pat.Post("/commands/:cmd/run_now"), web.ControllerPostHandler(handleRunCommandNow, getCmdHandler, nil))
subMux.Handle(pat.Post("/creategroup"), web.ControllerPostHandler(handleNewGroup, getHandler, GroupForm{}))
subMux.Handle(pat.Post("/groups/:group/update"), web.ControllerPostHandler(handleUpdateGroup, getGroupHandler, GroupForm{}))
subMux.Handle(pat.Post("/groups/:group/delete"), web.ControllerPostHandler(handleDeleteGroup, getHandler, nil))
}
func handleCommands(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
activeGuild, templateData := web.GetBaseCPContextData(r.Context())
groupID := int64(0)
if v, ok := templateData["CurrentGroupID"]; ok {
groupID = v.(int64)
}
var langBuiltins strings.Builder
for k := range yagtemplate.StandardFuncMap {
langBuiltins.WriteString(" " + k)
}
templateData["HLJSBuiltins"] = langBuiltins.String()
return serveGroupSelected(r, templateData, groupID, activeGuild.ID)
}
func handleGetCommand(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
activeGuild, templateData := web.GetBaseCPContextData(r.Context())
ccID, err := strconv.ParseInt(pat.Param(r, "cmd"), 10, 64)
if err != nil {
return templateData, errors.WithStackIf(err)
}
cc, err := models.CustomCommands(
models.CustomCommandWhere.GuildID.EQ(activeGuild.ID),
models.CustomCommandWhere.LocalID.EQ(ccID)).OneG(r.Context())
if err != nil {
return templateData, errors.WithStackIf(err)
}
templateData["CC"] = cc
templateData["Commands"] = true
return serveGroupSelected(r, templateData, cc.GroupID.Int64, activeGuild.ID)
}
func handleGetCommandsGroup(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
activeGuild, templateData := web.GetBaseCPContextData(r.Context())
groupID, _ := strconv.ParseInt(pat.Param(r, "group"), 10, 64)
return serveGroupSelected(r, templateData, groupID, activeGuild.ID)
}
func serveGroupSelected(r *http.Request, templateData web.TemplateData, groupID int64, guildID int64) (web.TemplateData, error) {
templateData["GetCCIntervalType"] = tmplGetCCIntervalTriggerType
templateData["GetCCInterval"] = tmplGetCCInterval
_, ok := templateData["CustomCommands"]
if !ok {
var err error
var commands []*models.CustomCommand
if groupID == 0 {
commands, err = models.CustomCommands(qm.Where("guild_id = ? AND group_id IS NULL", guildID), qm.OrderBy("local_id asc")).AllG(r.Context())
} else {
commands, err = models.CustomCommands(qm.Where("guild_id = ? AND group_id = ?", guildID, groupID), qm.OrderBy("local_id asc")).AllG(r.Context())
}
if err != nil {
return templateData, err
}
templateData["CustomCommands"] = commands
}
commandsGroups, err := models.CustomCommandGroups(qm.Where("guild_id = ?", guildID), qm.OrderBy("id asc")).AllG(r.Context())
if err != nil {
return templateData, err
}
for _, v := range commandsGroups {
if v.ID == groupID {
templateData["CurrentCommandGroup"] = v
break
}
}
templateData["CommandGroups"] = commandsGroups
return templateData, nil
}
func handleNewCommand(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
groupID, _ := strconv.ParseInt(r.FormValue("GroupID"), 10, 64)
if groupID != 0 {
// make sure we aren't trying to pull any tricks with the group id
c, err := models.CustomCommandGroups(qm.Where("guild_id = ? AND id = ?", activeGuild.ID, groupID)).CountG(ctx)
if err != nil {
return templateData, err
}
if c < 1 {
return templateData.AddAlerts(web.ErrorAlert("Unknown group")), nil
}
templateData["CurrentGroupID"] = groupID
}
c, err := models.CustomCommands(qm.Where("guild_id = ?", activeGuild.ID)).CountG(ctx)
if err != nil {
return templateData, err
}
if int(c) >= MaxCommandsForContext(ctx) {
return templateData, web.NewPublicError(fmt.Sprintf("Max %d custom commands allowed (or %d for premium servers)", MaxCommands, MaxCommandsPremium))
}
localID, err := common.GenLocalIncrID(activeGuild.ID, "custom_command")
if err != nil {
return templateData, errors.WrapIf(err, "error generating local id")
}
dbModel := &models.CustomCommand{
GuildID: activeGuild.ID,
LocalID: localID,
Disabled: true,
ShowErrors: true,
TimeTriggerExcludingDays: []int64{},
TimeTriggerExcludingHours: []int64{},
Responses: []string{"Edit this to change the output of the custom command {{.CCID}}!"},
}
if groupID != 0 {
dbModel.GroupID = null.Int64From(groupID)
}
err = dbModel.InsertG(ctx, boil.Infer())
if err != nil {
return templateData, err
}
featureflags.MarkGuildDirty(activeGuild.ID)
http.Redirect(w, r, fmt.Sprintf("/manage/%d/customcommands/commands/%d/", activeGuild.ID, localID), http.StatusSeeOther)
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyNewCommand, &cplogs.Param{Type: cplogs.ParamTypeInt, Value: dbModel.LocalID}))
pubsub.EvictCacheSet(cachedCommandsMessage, activeGuild.ID)
return templateData, nil
}
func handleUpdateCommand(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
cmd := ctx.Value(common.ContextKeyParsedForm).(*CustomCommand)
// ensure that the group specified is owned by this guild
if cmd.GroupID != 0 {
c, err := models.CustomCommandGroups(qm.Where("guild_id = ? AND id = ?", activeGuild.ID, cmd.GroupID)).CountG(ctx)
if err != nil {
return templateData, err
}
if c < 1 {
return templateData.AddAlerts(web.ErrorAlert("Unknown group")), nil
}
}
dbModel := cmd.ToDBModel()
templateData["CurrentGroupID"] = dbModel.GroupID.Int64
dbModel.GuildID = activeGuild.ID
dbModel.LocalID = cmd.ID
dbModel.TriggerType = int(triggerTypeFromForm(cmd.TriggerTypeForm))
// check low interval limits
if dbModel.TriggerType == int(CommandTriggerInterval) && dbModel.TimeTriggerInterval <= 10 {
if dbModel.TimeTriggerInterval < 5 {
dbModel.TimeTriggerInterval = 5
}
ok, err := checkIntervalLimits(ctx, activeGuild.ID, dbModel.LocalID, templateData)
if err != nil || !ok {
return templateData, err
}
}
_, err := dbModel.UpdateG(ctx, boil.Blacklist("last_run", "next_run", "local_id", "guild_id", "last_error", "last_error_time", "run_count"))
if err != nil {
return templateData, nil
}
// create, update or remove the next run time and scheduled event
if dbModel.TriggerType == int(CommandTriggerInterval) {
// need the last run time
fullModel, err := models.CustomCommands(qm.Where("guild_id = ? AND local_id = ?", activeGuild.ID, dbModel.LocalID)).OneG(ctx)
if err != nil {
web.CtxLogger(ctx).WithError(err).Error("failed retrieving full model")
} else {
err = UpdateCommandNextRunTime(fullModel, true, true)
}
} else {
err = DelNextRunEvent(activeGuild.ID, dbModel.LocalID)
}
if err != nil {
web.CtxLogger(ctx).WithError(err).WithField("guild", dbModel.GuildID).Error("failed updating next custom command run time")
}
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyUpdatedCommand, &cplogs.Param{Type: cplogs.ParamTypeInt, Value: dbModel.LocalID}))
pubsub.EvictCacheSet(cachedCommandsMessage, activeGuild.ID)
return templateData, err
}
func handleDeleteCommand(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
cmdID, err := strconv.ParseInt(pat.Param(r, "cmd"), 10, 64)
if err != nil {
return templateData, err
}
cmd, err := models.CustomCommands(qm.Where("guild_id = ? AND local_id = ?", activeGuild.ID, cmdID)).OneG(ctx)
if err != nil {
return templateData, err
}
groupID := cmd.GroupID.Int64
if groupID != 0 {
templateData["CurrentGroupID"] = groupID
}
_, err = cmd.DeleteG(ctx)
if err != nil {
return templateData, err
}
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyRemovedCommand, &cplogs.Param{Type: cplogs.ParamTypeInt, Value: cmd.LocalID}))
err = DelNextRunEvent(cmd.GuildID, cmd.LocalID)
featureflags.MarkGuildDirty(activeGuild.ID)
pubsub.EvictCacheSet(cachedCommandsMessage, activeGuild.ID)
return templateData, err
}
const RunCmdCooldownSeconds = 5
func keyRunCmdCooldown(guildID, userID int64) string {
return "custom_command_run_now_cooldown:" + discordgo.StrID(guildID) + ":" + discordgo.StrID(userID)
}
func checkSetCooldown(guildID, userID int64) (bool, error) {
var resp string
err := common.RedisPool.Do(radix.FlatCmd(&resp, "SET", keyRunCmdCooldown(guildID, userID), true, "EX", RunCmdCooldownSeconds, "NX"))
if err != nil {
return false, err
}
return resp == "OK", nil
}
func handleRunCommandNow(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
member := web.ContextMember(ctx)
if member == nil {
templateData.AddAlerts()
return templateData, nil
}
cmdID, err := strconv.ParseInt(pat.Param(r, "cmd"), 10, 64)
if err != nil {
return templateData, err
}
// only interval commands can be ran from the dashboard currently
cmd, err := models.CustomCommands(qm.Where("guild_id = ? AND local_id = ? AND trigger_type = 5", activeGuild.ID, cmdID)).OneG(context.Background())
if err != nil {
return templateData, err
}
ok, err := checkSetCooldown(activeGuild.ID, member.User.ID)
if err != nil {
return templateData, err
}
if !ok {
templateData.AddAlerts(web.ErrorAlert("You're on cooldown, wait before trying again"))
return templateData, nil
}
go pubsub.Publish("custom_commands_run_now", activeGuild.ID, cmd)
return templateData, nil
}
// allow for max 5 triggers with intervals of less than 10 minutes
func checkIntervalLimits(ctx context.Context, guildID int64, cmdID int64, templateData web.TemplateData) (ok bool, err error) {
num, err := models.CustomCommands(qm.Where("guild_id = ? AND local_id != ? AND trigger_type = 5 AND time_trigger_interval <= 10", guildID, cmdID)).CountG(ctx)
if err != nil {
return false, err
}
if num < 5 {
return true, nil
}
templateData.AddAlerts(web.ErrorAlert("You can have max 5 triggers on less than 10 minute intervals"))
return false, nil
}
func handleNewGroup(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
newGroup := ctx.Value(common.ContextKeyParsedForm).(*GroupForm)
numCurrentGroups, err := models.CustomCommandGroups(qm.Where("guild_id = ?", activeGuild.ID)).CountG(ctx)
if err != nil {
return templateData, err
}
if numCurrentGroups >= MaxGroups {
return templateData, web.NewPublicError(fmt.Sprintf("Max %d custom command groups", MaxGroups))
}
dbModel := &models.CustomCommandGroup{
GuildID: activeGuild.ID,
Name: newGroup.Name,
}
err = dbModel.InsertG(ctx, boil.Infer())
if err != nil {
return templateData, err
}
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyNewGroup, &cplogs.Param{Type: cplogs.ParamTypeString, Value: newGroup.Name}))
templateData["CurrentGroupID"] = dbModel.ID
pubsub.EvictCacheSet(cachedCommandsMessage, activeGuild.ID)
return templateData, nil
}
func handleUpdateGroup(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
groupForm := ctx.Value(common.ContextKeyParsedForm).(*GroupForm)
id, _ := strconv.ParseInt(pat.Param(r, "group"), 10, 64)
model, err := models.CustomCommandGroups(qm.Where("guild_id = ? AND id = ?", activeGuild.ID, id)).OneG(ctx)
if err != nil {
return templateData, err
}
model.WhitelistChannels = groupForm.WhitelistChannels
model.IgnoreChannels = groupForm.BlacklistChannels
model.WhitelistRoles = groupForm.WhitelistRoles
model.IgnoreRoles = groupForm.BlacklistRoles
model.Name = groupForm.Name
_, err = model.UpdateG(ctx, boil.Infer())
if err == nil {
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyUpdatedGroup, &cplogs.Param{Type: cplogs.ParamTypeString, Value: model.Name}))
}
pubsub.EvictCacheSet(cachedCommandsMessage, activeGuild.ID)
return templateData, err
}
func handleDeleteGroup(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
id, err := strconv.ParseInt(pat.Param(r, "group"), 10, 64)
if err != nil {
return templateData, err
}
rows, err := models.CustomCommandGroups(qm.Where("guild_id = ? AND id = ?", activeGuild.ID, id)).DeleteAll(ctx, common.PQ)
if err != nil {
return templateData, err
}
if rows > 0 {
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyRemovedGroup, &cplogs.Param{Type: cplogs.ParamTypeInt, Value: id}))
}
pubsub.EvictCacheSet(cachedCommandsMessage, activeGuild.ID)
return templateData, err
}
func triggerTypeFromForm(str string) CommandTriggerType {
switch str {
case "none":
return CommandTriggerNone
case "prefix":
return CommandTriggerStartsWith
case "regex":
return CommandTriggerRegex
case "contains":
return CommandTriggerContains
case "exact":
return CommandTriggerExact
case "command":
return CommandTriggerCommand
case "reaction":
return CommandTriggerReaction
case "interval_minutes", "interval_hours":
return CommandTriggerInterval
default:
return CommandTriggerCommand
}
}
func CheckLimits(in ...string) bool {
for _, v := range in {
if utf8.RuneCountInString(v) > 2000 {
return false
}
}
return true
}
// returns 1 for hours, 0 for minutes, -1 otherwise
func tmplGetCCIntervalTriggerType(cc *models.CustomCommand) int {
if cc.TriggerType != int(CommandTriggerInterval) {
return -1
}
if (cc.TimeTriggerInterval % 60) == 0 {
return 1
}
return 0
}
// returns the proper interval number dispalyed, depending on if it can be rounded to hours or not
func tmplGetCCInterval(cc *models.CustomCommand) int {
if tmplGetCCIntervalTriggerType(cc) == 1 {
return cc.TimeTriggerInterval / 60
}
return cc.TimeTriggerInterval
}
var _ web.PluginWithServerHomeWidget = (*Plugin)(nil)
func (p *Plugin) LoadServerHomeWidget(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ag, templateData := web.GetBaseCPContextData(r.Context())
templateData["WidgetTitle"] = "Custom Commands"
templateData["SettingsPath"] = "/customcommands"
numCustomCommands, err := models.CustomCommands(qm.Where("guild_id = ?", ag.ID)).CountG(r.Context())
format := `<p>Number of custom commands: <code>%d</code></p>`
templateData["WidgetBody"] = template.HTML(fmt.Sprintf(format, numCustomCommands))
if numCustomCommands > 0 {
templateData["WidgetEnabled"] = true
} else {
templateData["WidgetDisabled"] = true
}
return templateData, err
}