forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin_web.go
238 lines (191 loc) · 7.26 KB
/
plugin_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
package reputation
import (
"fmt"
"github.com/jonas747/discordgo"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/reputation/models"
"github.com/jonas747/yagpdb/web"
"github.com/volatiletech/sqlboiler/boil"
"github.com/volatiletech/sqlboiler/queries/qm"
"goji.io"
"goji.io/pat"
"html"
"html/template"
"net/http"
"strconv"
)
type PostConfigForm struct {
Enabled bool
EnableThanksDetection bool
PointsName string `valid:",50"`
Cooldown int `valid:"0,86401"` // One day
MaxGiveAmount int64
MaxRemoveAmount int64
RequiredGiveRoles []int64 `valid:"role,true"`
RequiredReceiveRoles []int64 `valid:"role,true"`
BlacklistedGiveRoles []int64 `valid:"role,true"`
BlacklistedReceiveRoles []int64 `valid:"role,true"`
AdminRoles []int64 `valid:"role,true"`
}
func (p PostConfigForm) RepConfig() *models.ReputationConfig {
return &models.ReputationConfig{
PointsName: p.PointsName,
Enabled: p.Enabled,
Cooldown: p.Cooldown,
MaxGiveAmount: p.MaxGiveAmount,
MaxRemoveAmount: p.MaxRemoveAmount,
RequiredGiveRoles: p.RequiredGiveRoles,
RequiredReceiveRoles: p.RequiredReceiveRoles,
BlacklistedGiveRoles: p.BlacklistedGiveRoles,
BlacklistedReceiveRoles: p.BlacklistedReceiveRoles,
AdminRoles: p.AdminRoles,
DisableThanksDetection: !p.EnableThanksDetection,
}
}
func (p *Plugin) InitWeb() {
tmplPathSettings := "templates/plugins/reputation_settings.html"
tmplPathLeaderboard := "templates/plugins/reputation_leaderboard.html"
if common.Testing {
tmplPathSettings = "../../reputation/assets/reputation_settings.html"
tmplPathLeaderboard = "../../reputation/assets/reputation_leaderboard.html"
}
web.Templates = template.Must(web.Templates.ParseFiles(tmplPathSettings, tmplPathLeaderboard))
subMux := goji.SubMux()
web.CPMux.Handle(pat.New("/reputation"), subMux)
web.CPMux.Handle(pat.New("/reputation/*"), subMux)
mainGetHandler := web.RenderHandler(HandleGetReputation, "cp_reputation_settings")
subMux.Handle(pat.Get(""), mainGetHandler)
subMux.Handle(pat.Get("/"), mainGetHandler)
subMux.Handle(pat.Post(""), web.ControllerPostHandler(HandlePostReputation, mainGetHandler, PostConfigForm{}, "Updated reputation config"))
subMux.Handle(pat.Post("/"), web.ControllerPostHandler(HandlePostReputation, mainGetHandler, PostConfigForm{}, "Updated reputation config"))
subMux.Handle(pat.Post("/reset_users"), web.ControllerPostHandler(HandleResetReputation, mainGetHandler, nil, "Reset reputation"))
subMux.Handle(pat.Get("/logs"), web.APIHandler(HandleLogsJson))
web.ServerPublicMux.Handle(pat.Get("/reputation/leaderboard"), web.RenderHandler(HandleGetReputation, "cp_reputation_leaderboard"))
web.ServerPubliAPIMux.Handle(pat.Get("/reputation/leaderboard"), web.APIHandler(HandleLeaderboardJson))
}
func HandleGetReputation(w http.ResponseWriter, r *http.Request) interface{} {
activeGuild, templateData := web.GetBaseCPContextData(r.Context())
if _, ok := templateData["RepSettings"]; !ok {
settings, err := GetConfig(r.Context(), activeGuild.ID)
if !web.CheckErr(templateData, err, "Failed retrieving settings", web.CtxLogger(r.Context()).Error) {
templateData["RepSettings"] = settings
}
}
return templateData
}
func HandlePostReputation(w http.ResponseWriter, r *http.Request) (templateData web.TemplateData, err error) {
activeGuild, templateData := web.GetBaseCPContextData(r.Context())
templateData["VisibleURL"] = "/manage/" + discordgo.StrID(activeGuild.ID) + "/reputation"
form := r.Context().Value(common.ContextKeyParsedForm).(*PostConfigForm)
conf := form.RepConfig()
conf.GuildID = activeGuild.ID
templateData["RepSettings"] = conf
err = conf.UpsertG(r.Context(), true, []string{"guild_id"}, boil.Whitelist(
"points_name",
"enabled",
"cooldown",
"max_give_amount",
"max_remove_amount",
"required_give_roles",
"required_receive_roles",
"blacklisted_give_roles",
"blacklisted_receive_roles",
"admin_roles",
"disable_thanks_detection",
), boil.Infer())
return
}
func HandleResetReputation(w http.ResponseWriter, r *http.Request) (templateData web.TemplateData, err error) {
activeGuild, templateData := web.GetBaseCPContextData(r.Context())
templateData["VisibleURL"] = "/manage/" + discordgo.StrID(activeGuild.ID) + "/reputation"
_, err = models.ReputationUsers(qm.Where("guild_id = ?", activeGuild.ID)).DeleteAll(r.Context(), common.PQ)
return templateData, err
}
func HandleLeaderboardJson(w http.ResponseWriter, r *http.Request) interface{} {
activeGuild, _ := web.GetBaseCPContextData(r.Context())
conf, err := GetConfig(r.Context(), activeGuild.ID)
if err != nil {
return err
}
if !conf.Enabled {
return web.NewPublicError("Reputation not enabled")
}
query := r.URL.Query()
offsetStr := query.Get("offset")
offset := 0
if offsetStr != "" {
offset, err = strconv.Atoi(offsetStr)
if err != nil {
web.CtxLogger(r.Context()).WithError(err).WithField("raw", offsetStr).Error("Failed parsing offset")
}
}
limitStr := query.Get("limit")
limit := 0
if limitStr != "" {
limit, err = strconv.Atoi(limitStr)
if err != nil {
web.CtxLogger(r.Context()).WithError(err).WithField("raw", limitStr).Error("Failed parsing limit")
}
}
if limit > 100 || limit < 0 {
limit = 10
}
top, err := TopUsers(activeGuild.ID, offset, limit)
if err != nil {
return err
}
entries, err := DetailedLeaderboardEntries(activeGuild.ID, top)
if err != nil {
return err
}
return entries
}
func HandleLogsJson(W http.ResponseWriter, r *http.Request) interface{} {
activeGuild, _ := web.GetBaseCPContextData(r.Context())
query := r.URL.Query()
after, _ := strconv.ParseInt(query.Get("after"), 10, 64)
before, _ := strconv.ParseInt(query.Get("before"), 10, 64)
// usernameQuery := query.Get("username")
idQuery, _ := strconv.ParseInt(query.Get("user_id"), 10, 64)
var result []*models.ReputationLog
if idQuery == 0 {
return result
}
clauses := make([]qm.QueryMod, 4, 5)
clauses[0] = qm.Where("guild_id = ?", activeGuild.ID)
clauses[1] = qm.Where("(receiver_id = ? OR sender_id = ?)", idQuery, idQuery)
clauses[2] = qm.OrderBy("id desc")
clauses[3] = qm.Limit(100)
if after != 0 {
clauses = append(clauses, qm.Where("id > ?", after))
} else if before != 0 {
clauses = append(clauses, qm.Where("id < ?", before))
}
result, err := models.ReputationLogs(clauses...).AllG(r.Context())
if err != nil {
return err
}
return result
}
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"] = "Reputation"
templateData["SettingsPath"] = "/reputation"
settings, err := GetConfig(r.Context(), ag.ID)
if err != nil {
return templateData, err
}
const format = `<ul>
<li>Repuatation is: %s</li>
<li>Repuatation name: <code>%s</code></li>
</ul>`
name := html.EscapeString(settings.PointsName)
if settings.Enabled {
templateData["WidgetEnabled"] = true
} else {
templateData["WidgetDisabled"] = true
}
templateData["WidgetBody"] = template.HTML(fmt.Sprintf(format, web.EnabledDisabledSpanStatus(settings.Enabled), name))
return templateData, nil
}