forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
automod_web.go
847 lines (679 loc) · 25.5 KB
/
automod_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
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
package automod
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"html/template"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"github.com/botlabs-gg/yagpdb/v2/automod/models"
"github.com/botlabs-gg/yagpdb/v2/common"
"github.com/botlabs-gg/yagpdb/v2/common/cplogs"
"github.com/botlabs-gg/yagpdb/v2/common/featureflags"
"github.com/botlabs-gg/yagpdb/v2/common/pubsub"
"github.com/botlabs-gg/yagpdb/v2/lib/discordgo"
"github.com/botlabs-gg/yagpdb/v2/lib/dstate"
"github.com/botlabs-gg/yagpdb/v2/moderation"
"github.com/botlabs-gg/yagpdb/v2/web"
"github.com/fatih/structs"
"github.com/gorilla/schema"
"github.com/volatiletech/sqlboiler/v4/boil"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
"goji.io"
"goji.io/pat"
)
//go:embed assets/automod.html
var PageHTML string
type CtxKey int
const (
CtxKeyCurrentRuleset CtxKey = iota
)
var _ web.Plugin = (*Plugin)(nil)
var (
panelLogKeyNewList = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "automodv2_new_list", FormatString: "Updated automod: Created a new ChannelOverride"})
panelLogKeyUpdatedList = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "automodv2_updated_list", FormatString: "Updated automod: Updated a ChannelOverride"})
panelLogKeyRemovedList = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "automodv2_removed_list", FormatString: "Updated automod: Removed a ChannelOverride"})
panelLogKeyNewRuleset = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "automodv2_new_ruleset", FormatString: "Updated automod: Created a new ruleset"})
panelLogKeyUpdatedRuleset = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "automodv2_updated_ruleset", FormatString: "Updated automod: Updated a ruleset"})
panelLogKeyRemovedRuleset = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "automodv2_removed_ruleset", FormatString: "Updated automod: Removed a ruleset"})
panelLogKeyNewRule = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "automodv2_new_rule", FormatString: "Updated automod: Created a new rule"})
panelLogKeyUpdatedRule = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "automodv2_updated_rule", FormatString: "Updated automod: Updated a rule"})
panelLogKeyRemovedRule = cplogs.RegisterActionFormat(&cplogs.ActionFormat{Key: "automodv2_removed_rule", FormatString: "Updated automod: Removed a rule"})
)
func (p *Plugin) InitWeb() {
web.AddHTMLTemplate("automod/assets/automod.html", PageHTML)
web.AddSidebarItem(web.SidebarCategoryModeration, &web.SidebarItem{
Name: "Advanced Automoderator",
URL: "automod",
Icon: "fas fa-robot",
})
muxer := goji.SubMux()
web.CPMux.Handle(pat.New("/automod"), muxer)
web.CPMux.Handle(pat.New("/automod/*"), muxer)
// All handlers here require guild channels present
muxer.Use(web.RequireBotMemberMW)
muxer.Use(web.RequirePermMW(discordgo.PermissionManageRoles, discordgo.PermissionKickMembers, discordgo.PermissionBanMembers, discordgo.PermissionManageMessages, discordgo.PermissionManageServer, discordgo.PermissionModerateMembers))
getIndexHandler := web.ControllerHandler(p.handleGetAutomodIndex, "automod_index")
muxer.Handle(pat.Get("/"), getIndexHandler)
muxer.Handle(pat.Get(""), getIndexHandler)
muxer.Handle(pat.Get("/logs"), web.ControllerHandler(p.handleGetLogs, "automod_index"))
muxer.Handle(pat.Post("/new_ruleset"), web.ControllerPostHandler(p.handlePostAutomodCreateRuleset, getIndexHandler, CreateRulesetData{}))
// List handlers
muxer.Handle(pat.Post("/new_list"), web.ControllerPostHandler(p.handlePostAutomodCreateList, getIndexHandler, CreateListData{}))
muxer.Handle(pat.Post("/list/:listID/update"), web.ControllerPostHandler(p.handlePostAutomodUpdateList, getIndexHandler, UpdateListData{}))
muxer.Handle(pat.Post("/list/:listID/delete"), web.ControllerPostHandler(p.handlePostAutomodDeleteList, getIndexHandler, nil))
// Ruleset specific handlers
rulesetMuxer := goji.SubMux()
muxer.Handle(pat.New("/ruleset/:rulesetID"), rulesetMuxer)
muxer.Handle(pat.New("/ruleset/:rulesetID/*"), rulesetMuxer)
rulesetMuxer.Use(p.currentRulesetMW(getIndexHandler))
getRulesetHandler := web.ControllerHandler(p.handleGetAutomodRuleset, "automod_index")
rulesetMuxer.Handle(pat.Get(""), getRulesetHandler)
rulesetMuxer.Handle(pat.Get("/"), getRulesetHandler)
rulesetMuxer.Handle(pat.Post("/update"), web.ControllerPostHandler(p.handlePostAutomodUpdateRuleset, getRulesetHandler, UpdateRulesetData{}))
rulesetMuxer.Handle(pat.Post("/delete"), web.ControllerPostHandler(p.handlePostAutomodDeleteRuleset, getIndexHandler, nil))
rulesetMuxer.Handle(pat.Post("/new_rule"), web.ControllerPostHandler(p.handlePostAutomodCreateRule, getRulesetHandler, CreateRuleData{}))
rulesetMuxer.Handle(pat.Post("/rule/:ruleID/delete"), web.ControllerPostHandler(p.handlePostAutomodDeleteRule, getRulesetHandler, nil))
rulesetMuxer.Handle(pat.Post("/rule/:ruleID/update"), web.ControllerPostHandler(p.handlePostAutomodUpdateRule, getRulesetHandler, UpdateRuleData{}))
}
func (p *Plugin) handleGetAutomodIndex(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, tmpl := web.GetBaseCPContextData(r.Context())
rulesets, err := models.AutomodRulesets(qm.Where("guild_id = ?", g.ID), qm.OrderBy("id asc")).AllG(r.Context())
if err != nil {
return tmpl, err
}
lists, err := models.AutomodLists(qm.Where("guild_id=?", g.ID), qm.OrderBy("id asc")).AllG(r.Context())
if err != nil {
return tmpl, err
}
tmpl["AutomodLists"] = lists
tmpl["AutomodRulesets"] = rulesets
tmpl["PartMap"] = RulePartMap
tmpl["PartList"] = RulePartList
return tmpl, nil
}
func (p *Plugin) handleGetLogs(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, tmpl := web.GetBaseCPContextData(r.Context())
tmpl["InLogs"] = true
before := r.URL.Query().Get("before")
after := r.URL.Query().Get("after")
var beforeParsed int
var afterParsed int
if before != "" {
beforeParsed, _ = strconv.Atoi(before)
} else if after != "" {
afterParsed, _ = strconv.Atoi(after)
}
qms := []qm.QueryMod{qm.Where("guild_id=?", g.ID), qm.OrderBy("id desc"), qm.Limit(100)}
if beforeParsed != 0 {
qms = append(qms, qm.Where("id < ?", beforeParsed))
} else if afterParsed != 0 {
qms = append(qms, qm.Where("id > ?", afterParsed))
}
entries, err := models.AutomodTriggeredRules(qms...).AllG(r.Context())
if err != nil {
return tmpl, err
}
tmpl["AutomodLogEntries"] = entries
return p.handleGetAutomodIndex(w, r)
}
type CreateRulesetData struct {
Name string `valid:",1,100"`
}
func (p *Plugin) handlePostAutomodCreateRuleset(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, tmpl := web.GetBaseCPContextData(r.Context())
currentCount, err := models.AutomodRulesets(qm.Where("guild_id=?", g.ID)).CountG(r.Context())
if err != nil {
return tmpl, err
}
if currentCount >= int64(GuildMaxRulesets(g.ID)) {
tmpl.AddAlerts(web.ErrorAlert("Reached max number of rulesets, ", MaxRulesets))
return tmpl, nil
}
data := r.Context().Value(common.ContextKeyParsedForm).(*CreateRulesetData)
rs := &models.AutomodRuleset{
Name: data.Name,
GuildID: g.ID,
Enabled: true,
}
err = rs.InsertG(r.Context(), boil.Infer())
if err == nil {
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyNewRuleset))
}
return tmpl, err
}
type CreateListData struct {
Name string `valid:",1,50"`
}
func (p *Plugin) handlePostAutomodCreateList(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, tmpl := web.GetBaseCPContextData(r.Context())
totalLists, err := models.AutomodLists(qm.Where("guild_id = ? ", g.ID)).CountG(r.Context())
if err != nil {
return tmpl, err
}
if totalLists >= int64(GuildMaxLists(g.ID)) {
tmpl.AddAlerts(web.ErrorAlert(fmt.Sprintf("Reached max number of lists, %d for normal servers and %d for premium servers", MaxLists, MaxListsPremium)))
return tmpl, nil
}
data := r.Context().Value(common.ContextKeyParsedForm).(*CreateListData)
list := &models.AutomodList{
Name: data.Name,
GuildID: g.ID,
Content: []string{},
}
err = list.InsertG(r.Context(), boil.Infer())
if err == nil {
pubsub.EvictCacheSet(cachedLists, g.ID)
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyNewList))
}
return tmpl, err
}
type UpdateListData struct {
Name string `valid:",1,50"`
Content string `valid:",0,5000"`
}
func (p *Plugin) handlePostAutomodUpdateList(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, tmpl := web.GetBaseCPContextData(r.Context())
data := r.Context().Value(common.ContextKeyParsedForm).(*UpdateListData)
id := pat.Param(r, "listID")
list, err := models.AutomodLists(qm.Where("guild_id=? AND id=?", g.ID, id)).OneG(r.Context())
if err != nil {
return nil, err
}
list.Name = data.Name
list.Content = strings.Fields(data.Content)
_, err = list.UpdateG(r.Context(), boil.Whitelist("name", "content"))
if err == nil {
pubsub.EvictCacheSet(cachedLists, g.ID)
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyUpdatedList))
}
return tmpl, err
}
func (p *Plugin) handlePostAutomodDeleteList(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, tmpl := web.GetBaseCPContextData(r.Context())
id := pat.Param(r, "listID")
list, err := models.AutomodLists(qm.Where("guild_id=? AND id=?", g.ID, id)).OneG(r.Context())
if err != nil {
return nil, err
}
_, err = list.DeleteG(r.Context())
if err == nil {
pubsub.EvictCacheSet(cachedLists, g.ID)
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyRemovedList))
}
return tmpl, err
}
func (p *Plugin) currentRulesetMW(backupHandler http.Handler) func(http.Handler) http.Handler {
return func(inner http.Handler) http.Handler {
mw := func(w http.ResponseWriter, r *http.Request) {
g, tmpl := web.GetBaseCPContextData(r.Context())
idStr := pat.Param(r, "rulesetID")
parsed, _ := strconv.ParseInt(idStr, 10, 64)
ruleset, err := models.AutomodRulesets(qm.Where("guild_id=? AND id=?", g.ID, parsed),
qm.Load("RulesetAutomodRules.RuleAutomodRuleData"), qm.Load("RulesetAutomodRulesetConditions")).OneG(r.Context())
if err != nil {
tmpl.AddAlerts(web.ErrorAlert("Failed retrieving ruleset, maybe it was deleted?"))
backupHandler.ServeHTTP(w, r)
web.CtxLogger(r.Context()).WithError(err).Error("Failed retrieving automod ruleset")
return
}
sort.Slice(ruleset.R.RulesetAutomodRules, func(i, j int) bool {
return ruleset.R.RulesetAutomodRules[i].ID < ruleset.R.RulesetAutomodRules[j].ID
})
tmpl["CurrentRuleset"] = ruleset
WebLoadRuleSettings(r, tmpl, ruleset)
r = r.WithContext(context.WithValue(r.Context(), CtxKeyCurrentRuleset, ruleset))
inner.ServeHTTP(w, r)
}
return http.HandlerFunc(mw)
}
}
func (p *Plugin) handleGetAutomodRuleset(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
return p.handleGetAutomodIndex(w, r)
}
type CreateRuleData struct {
Name string `valid:",1,50"`
}
func (p *Plugin) handlePostAutomodCreateRule(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, tmpl := web.GetBaseCPContextData(r.Context())
ruleset := r.Context().Value(CtxKeyCurrentRuleset).(*models.AutomodRuleset)
totalRules, err := models.AutomodRules(qm.Where("guild_id = ? ", g.ID)).CountG(r.Context())
if err != nil {
return tmpl, err
}
if totalRules >= int64(GuildMaxTotalRules(g.ID)) {
tmpl.AddAlerts(web.ErrorAlert(fmt.Sprintf("Reached max number of rules, %d for normal servers and %d for premium servers", MaxTotalRules, MaxTotalRulesPremium)))
return tmpl, nil
}
data := r.Context().Value(common.ContextKeyParsedForm).(*CreateRuleData)
rule := &models.AutomodRule{
GuildID: g.ID,
RulesetID: ruleset.ID,
Name: data.Name,
}
err = rule.InsertG(r.Context(), boil.Infer())
if err == nil {
ruleset.R.RulesetAutomodRules = append(ruleset.R.RulesetAutomodRules, rule)
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyNewRule))
}
return tmpl, err
}
type UpdateRulesetData struct {
Name string `valid:",1,50"`
Enabled bool
Conditions []RuleRowData
}
func (p *Plugin) handlePostAutomodUpdateRuleset(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, tmpl := web.GetBaseCPContextData(r.Context())
data := r.Context().Value(common.ContextKeyParsedForm).(*UpdateRulesetData)
// The form parsing utility dosen't take care of maps, so manually do that parsing for now
conditions, validatedOK, err := ReadRuleRowData(g, tmpl, data.Conditions, r.Form, "Conditions")
if err != nil || !validatedOK {
return tmpl, err
}
ruleset := r.Context().Value(CtxKeyCurrentRuleset).(*models.AutomodRuleset)
tx, err := common.PQ.BeginTx(r.Context(), nil)
if err != nil {
return tmpl, err
}
// First wipe all previous rule data
_, err = models.AutomodRulesetConditions(qm.Where("guild_id = ? AND ruleset_id = ?", g.ID, ruleset.ID)).DeleteAll(r.Context(), tx)
if err != nil {
tx.Rollback()
return tmpl, err
}
properConditions := make([]*models.AutomodRulesetCondition, len(conditions))
// Insert the new data
for i, cond := range conditions {
proper := &models.AutomodRulesetCondition{
GuildID: g.ID,
RulesetID: ruleset.ID,
Kind: cond.Kind,
TypeID: cond.TypeID,
Settings: cond.Settings,
}
properConditions[i] = proper
err := proper.Insert(r.Context(), tx, boil.Infer())
if err != nil {
tx.Rollback()
return tmpl, err
}
}
// Update the ruleset model itself
ruleset.Name = data.Name
ruleset.Enabled = data.Enabled
_, err = ruleset.Update(r.Context(), tx, boil.Whitelist("name", "enabled"))
if err != nil {
tx.Rollback()
return tmpl, err
}
// All done
err = tx.Commit()
if err != nil {
return tmpl, err
}
pubsub.EvictCacheSet(cachedRulesets, g.ID)
featureflags.MarkGuildDirty(g.ID)
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyUpdatedRuleset))
// Reload the conditions now
ruleset.R.RulesetAutomodRulesetConditions = properConditions
WebLoadRuleSettings(r, tmpl, ruleset)
return tmpl, err
}
func (p *Plugin) handlePostAutomodDeleteRuleset(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, tmpl := web.GetBaseCPContextData(r.Context())
ruleset := r.Context().Value(CtxKeyCurrentRuleset).(*models.AutomodRuleset)
rows, err := ruleset.DeleteG(r.Context())
if err != nil {
return tmpl, err
}
delete(tmpl, "CurrentRuleset")
if rows > 0 {
pubsub.EvictCacheSet(cachedRulesets, g.ID)
featureflags.MarkGuildDirty(g.ID)
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyRemovedRuleset))
}
return tmpl, err
}
type UpdateRuleData struct {
Name string `valid:",1,50"`
Triggers []RuleRowData
Conditions []RuleRowData
Effects []RuleRowData
}
type RuleRowData struct {
Type int
Data map[string][]string
}
func (p *Plugin) handlePostAutomodUpdateRule(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, tmpl := web.GetBaseCPContextData(r.Context())
data := r.Context().Value(common.ContextKeyParsedForm).(*UpdateRuleData)
combinedParts := make([]*models.AutomodRuleDatum, 0, 10)
// The form parsing utility dosen't take care of maps, so manually do that parsing for now
triggers, validatedOK, err := ReadRuleRowData(g, tmpl, data.Triggers, r.Form, "Triggers")
if err != nil || !validatedOK {
return tmpl, err
}
combinedParts = append(combinedParts, triggers...)
conditions, validatedOK, err := ReadRuleRowData(g, tmpl, data.Conditions, r.Form, "Conditions")
if err != nil || !validatedOK {
return tmpl, err
}
combinedParts = append(combinedParts, conditions...)
effects, validatedOK, err := ReadRuleRowData(g, tmpl, data.Effects, r.Form, "Effects")
if err != nil || !validatedOK {
return tmpl, err
}
combinedParts = append(combinedParts, effects...)
// retrieve the ruleset and the rule were working on
ruleSet := r.Context().Value(CtxKeyCurrentRuleset).(*models.AutomodRuleset)
ruleIDStr := pat.Param(r, "ruleID")
parsedRuleID, _ := strconv.ParseInt(ruleIDStr, 10, 64)
var currentRule *models.AutomodRule
for _, v := range ruleSet.R.RulesetAutomodRules {
if v.ID == parsedRuleID {
currentRule = v
break
}
}
if currentRule == nil {
return tmpl.AddAlerts(web.ErrorAlert("Unknown rule, maybe someone else deleted it in the meantime?")), nil
}
// Check limits
combinedParts, ok, err := CheckLimits(common.PQ, currentRule, tmpl, combinedParts)
if !ok || err != nil {
return tmpl, err
}
tx, err := common.PQ.BeginTx(r.Context(), nil)
if err != nil {
return tmpl, err
}
anyMute := false
for _, effect := range effects {
if effect.TypeID == 304 {
anyMute = true
break
}
}
if anyMute {
conf, err := moderation.GetConfig(g.ID)
if err != nil || conf.MuteRole == "" {
tx.Rollback()
tmpl.AddAlerts(web.ErrorAlert("No mute role set, please configure one."))
return tmpl, nil
}
}
// First wipe all previous rule data
_, err = models.AutomodRuleData(qm.Where("guild_id = ? AND rule_id = ?", g.ID, currentRule.ID)).DeleteAll(r.Context(), tx)
if err != nil {
tx.Rollback()
return tmpl, err
}
// Then insert the new data
for _, part := range combinedParts {
part.GuildID = g.ID
part.RuleID = currentRule.ID
err := part.Insert(r.Context(), tx, boil.Infer())
if err != nil {
tx.Rollback()
return tmpl, err
}
}
currentRule.Name = data.Name
_, err = currentRule.Update(r.Context(), tx, boil.Whitelist("name"))
if err != nil {
tx.Rollback()
return tmpl, err
}
// All done
err = tx.Commit()
if err != nil {
return tmpl, err
}
// Reload the rules now
currentRule.R.RuleAutomodRuleData = combinedParts
WebLoadRuleSettings(r, tmpl, ruleSet)
pubsub.EvictCacheSet(cachedRulesets, g.ID)
featureflags.MarkGuildDirty(g.ID)
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyUpdatedRule))
return tmpl, err
}
func CheckLimits(exec boil.ContextExecutor, rule *models.AutomodRule, tmpl web.TemplateData, parts []*models.AutomodRuleDatum) (newParts []*models.AutomodRuleDatum, ok bool, err error) {
// truncate to 20
newParts = parts
if len(newParts) > MaxRuleParts {
newParts = newParts[:MaxRuleParts]
tmpl.AddAlerts(web.WarningAlert("Truncated rule down to 20 triggers/conditions/effects, thats the max per rule."))
}
// Check number of message triggers and violation triggers
numMessageTriggers := 0
numViolationTriggers := 0
for _, v := range newParts {
for _, p := range RulePartList {
if p.ID != v.TypeID {
continue
}
if _, ok := p.Part.(MessageTrigger); ok {
numMessageTriggers++
break
}
if _, ok := p.Part.(ViolationListener); ok {
numViolationTriggers++
break
}
}
}
maxTotalMT := GuildMaxMessageTriggers(rule.GuildID)
maxTotalVT := GuildMaxViolationTriggers(rule.GuildID)
allParts, err := models.AutomodRuleData(qm.Where("guild_id = ? AND rule_id != ?", rule.GuildID, rule.ID)).All(context.Background(), exec)
if err != nil {
return
}
for _, v := range allParts {
for _, p := range RulePartList {
if p.ID != v.TypeID {
continue
}
if _, ok := p.Part.(MessageTrigger); ok {
numMessageTriggers++
break
}
if _, ok := p.Part.(ViolationListener); ok {
numViolationTriggers++
break
}
}
}
ok = true
if numMessageTriggers > maxTotalMT {
tmpl.AddAlerts(web.ErrorAlert(fmt.Sprintf("Max message based triggers reached (%d for normal and %d for premium)", MaxMessageTriggers, MaxMessageTriggersPremium)))
ok = false
}
if numViolationTriggers > maxTotalVT {
tmpl.AddAlerts(web.ErrorAlert(fmt.Sprintf("Max violation based triggers reached (%d for normal and %d for premium)", MaxViolationTriggers, MaxViolationTriggersPremium)))
ok = false
}
return
}
func ReadRuleRowData(guild *dstate.GuildSet, tmpl web.TemplateData, rawData []RuleRowData, form url.Values, namePrefix string) (result []*models.AutomodRuleDatum, validationOK bool, err error) {
parsedSettings := make([]*ParsedPart, 0, len(rawData))
for i, entry := range rawData {
for k, fv := range form {
if strings.HasPrefix(k, namePrefix+"."+strconv.Itoa(i)+".Data.") {
dataKey := strings.TrimPrefix(k, namePrefix+"."+strconv.Itoa(i)+".Data.")
if entry.Data == nil {
entry.Data = make(map[string][]string)
}
entry.Data[dataKey] = fv
}
}
pType, ok := RulePartMap[entry.Type]
if !ok {
continue // Ignore unknown rules
}
parsed := &ParsedPart{
Part: pType,
}
// Process the settings for this part type if it has any
dst := pType.DataType()
if dst != nil {
// Decode map[string][]string into the struct
dec := schema.NewDecoder()
dec.IgnoreUnknownKeys(true)
err = dec.Decode(dst, entry.Data)
if err != nil {
return nil, false, err
}
// Perform the validation
validationOK = web.ValidateForm(guild, tmpl, dst)
if !validationOK {
return nil, false, nil
}
parsed.ParsedSettings = dst
}
parsedSettings = append(parsedSettings, parsed)
}
// merge the duplicate parts
deDuplicated := make([]*ParsedPart, 0, len(parsedSettings))
OUTER:
for _, parsedPart := range parsedSettings {
mergeable, ok := parsedPart.Part.(MergeableRulePart)
if !ok {
// not mergeable, continue as normal
deDuplicated = append(deDuplicated, parsedPart)
continue
}
for _, d := range deDuplicated {
if parsedPart.Part == d.Part {
// already merged before, skip
continue OUTER
}
}
dupes := []interface{}{parsedPart.ParsedSettings}
// find duplicate types
for _, v := range parsedSettings {
if v.Part == parsedPart.Part && v != parsedPart {
dupes = append(dupes, v.ParsedSettings)
}
}
if len(dupes) > 1 {
merged := mergeable.MergeDuplicates(dupes)
parsedPart.ParsedSettings = merged
}
deDuplicated = append(deDuplicated, parsedPart)
}
// finally make proper db models
result = make([]*models.AutomodRuleDatum, len(deDuplicated))
for i, v := range deDuplicated {
model := &models.AutomodRuleDatum{
GuildID: guild.ID,
Kind: int(v.Part.Kind()),
TypeID: InverseRulePartMap[v.Part],
}
if v.ParsedSettings != nil {
// Serialize it back to store in the database
serialized, err := json.Marshal(v.ParsedSettings)
if err != nil {
return result, false, err
}
model.Settings = serialized
} else {
model.Settings = []byte("{}")
}
result[i] = model
}
return result, true, nil
}
func (p *Plugin) handlePostAutomodDeleteRule(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g := web.ContextGuild(r.Context())
ruleset := r.Context().Value(CtxKeyCurrentRuleset).(*models.AutomodRuleset)
toDelete := pat.Param(r, "ruleID")
parsedRuleID, err := strconv.ParseInt(toDelete, 10, 64)
if err != nil {
return nil, err
}
for k, v := range ruleset.R.RulesetAutomodRules {
if v.ID == parsedRuleID {
_, err := v.DeleteG(r.Context())
if err == nil {
ruleset.R.RulesetAutomodRules = append(ruleset.R.RulesetAutomodRules[:k], ruleset.R.RulesetAutomodRules[k+1:]...)
pubsub.EvictCacheSet(cachedRulesets, g.ID)
featureflags.MarkGuildDirty(g.ID)
go cplogs.RetryAddEntry(web.NewLogEntryFromContext(r.Context(), panelLogKeyRemovedRule))
}
return nil, err
}
}
return nil, nil
}
func WebLoadRuleSettings(r *http.Request, tmpl web.TemplateData, ruleset *models.AutomodRuleset) {
// Parse the rule settings data
// 1st index: rule
// 2nd index: part
// keys: part data
parsedData := make([][]map[string]interface{}, len(ruleset.R.RulesetAutomodRules))
for i, rule := range ruleset.R.RulesetAutomodRules {
ruleData := make([]map[string]interface{}, len(rule.R.RuleAutomodRuleData))
for j, part := range rule.R.RuleAutomodRuleData {
dst := RulePartMap[part.TypeID].DataType()
if dst != nil {
// Parse the settings into the relevant struct
err := json.Unmarshal(part.Settings, dst)
if err != nil {
web.CtxLogger(r.Context()).WithError(err).Error("failed parsing rule part data")
continue
}
// Convert to map for ease of use with index, can't unmarshal directly into interface{} because then it will use float64 for the snowflakes
m := structs.Map(dst)
ruleData[j] = m
}
}
parsedData[i] = ruleData
}
// The ruleset scoped conditions
parsedRSData := make([]map[string]interface{}, len(ruleset.R.RulesetAutomodRulesetConditions))
for i, part := range ruleset.R.RulesetAutomodRulesetConditions {
dst := RulePartMap[part.TypeID].DataType()
if dst != nil {
// Parse the settings into the relevant struct
err := json.Unmarshal(part.Settings, dst)
if err != nil {
web.CtxLogger(r.Context()).WithError(err).Error("failed parsing ruleset condition part data")
continue
}
// Convert to map for ease of use with index, can't unmarshal directly into interface{} because then it will use float64 for the snowflakes
m := structs.Map(dst)
parsedRSData[i] = m
}
}
tmpl["RulePartData"] = parsedData
tmpl["RSPartData"] = parsedRSData
}
var _ web.PluginWithServerHomeWidget = (*Plugin)(nil)
func (p *Plugin) LoadServerHomeWidget(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
g, templateData := web.GetBaseCPContextData(r.Context())
templateData["WidgetTitle"] = "Advanced Automoderator"
templateData["SettingsPath"] = "/automod"
rulesets, err := models.AutomodRulesets(qm.Where("guild_id = ?", g.ID), qm.Where("enabled = true")).CountG(r.Context())
if err != nil {
return templateData, err
}
rules, err := models.AutomodRules(qm.Where("guild_id = ?", g.ID)).CountG(r.Context())
if err != nil {
return templateData, err
}
templateData["WidgetBody"] = template.HTML(fmt.Sprintf(`<ul>
<li>Active and enabled Rulesets: <code>%d</code></li>
<li>Total rules: <code>%d</code></li>
</ul>`, rulesets, rules))
if rulesets > 0 {
templateData["WidgetEnabled"] = true
} else {
templateData["WidgetDisabled"] = true
}
return templateData, nil
}