forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
255 lines (208 loc) · 7.29 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
package logs
import (
"errors"
"github.com/jonas747/discordgo"
"github.com/jonas747/yagpdb/bot/botrest"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/configstore"
"github.com/jonas747/yagpdb/web"
"github.com/sirupsen/logrus"
"goji.io"
"goji.io/pat"
"html/template"
"net/http"
"strconv"
"strings"
)
var AuthorColors = []string{
"7c7cff", // blue-ish
"529fb7", // lighter blue
"4aa085", // dark-green
"7ea04a", // lighter green
"a0824a", // brown
"a04a4a", // red
"a04a89", // purple?
}
type DeleteData struct {
ID string
}
type GeneralFormData struct {
UsernameLoggingEnabled bool
NicknameLoggingEnabled bool
ManageMessagesCanViewDeleted bool
EveryoneCanViewDeleted bool
BlacklistedChannels []string
}
func (lp *Plugin) InitWeb() {
tmplPathSettings := "templates/plugins/logs_control_panel.html"
tmplPathView := "templates/plugins/logs_view.html"
if common.Testing {
tmplPathSettings = "../../logs/assets/logs_control_panel.html"
tmplPathView = "../../logs/assets/logs_view.html"
}
web.Templates = template.Must(web.Templates.ParseFiles(tmplPathSettings, tmplPathView))
web.ServerPublicMux.Handle(pat.Get("/logs/:id"), web.RenderHandler(HandleLogsHTML, "public_server_logs"))
web.ServerPublicMux.Handle(pat.Get("/logs/:id/"), web.RenderHandler(HandleLogsHTML, "public_server_logs"))
logCPMux := goji.SubMux()
web.CPMux.Handle(pat.New("/logging"), logCPMux)
web.CPMux.Handle(pat.New("/logging/*"), logCPMux)
logCPMux.Use(web.RequireGuildChannelsMiddleware)
cpGetHandler := web.ControllerHandler(HandleLogsCP, "cp_logging")
logCPMux.Handle(pat.Get("/"), cpGetHandler)
logCPMux.Handle(pat.Get(""), cpGetHandler)
saveHandler := web.ControllerPostHandler(HandleLogsCPSaveGeneral, cpGetHandler, GeneralFormData{}, "Updated logging config")
fullDeleteHandler := web.ControllerPostHandler(HandleLogsCPDelete, cpGetHandler, DeleteData{}, "Deleted a channel log")
msgDeleteHandler := web.APIHandler(HandleDeleteMessageJson)
logCPMux.Handle(pat.Post("/"), saveHandler)
logCPMux.Handle(pat.Post(""), saveHandler)
logCPMux.Handle(pat.Post("/fulldelete"), fullDeleteHandler)
logCPMux.Handle(pat.Post("/msgdelete"), msgDeleteHandler)
}
func HandleLogsCP(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, tmpl := web.GetBaseCPContextData(ctx)
beforeID := 0
beforeStr := r.URL.Query().Get("before")
if beforeStr != "" {
beforeId64, err := strconv.ParseInt(beforeStr, 10, 32)
if err != nil {
tmpl.AddAlerts(web.ErrorAlert("Failed parsing before id"))
}
beforeID = int(beforeId64)
} else {
tmpl["FirstPage"] = true
}
afterID := 0
afterStr := r.URL.Query().Get("after")
if afterStr != "" {
id64, err := strconv.ParseInt(afterStr, 10, 32)
if err != nil {
tmpl.AddAlerts(web.ErrorAlert("Failed parsing before id"))
}
afterID = int(id64)
tmpl["FirstPage"] = false
}
serverLogs, err := GetGuilLogs(g.ID, beforeID, afterID, 20)
web.CheckErr(tmpl, err, "Failed retrieving logs", web.CtxLogger(ctx).Error)
if err == nil {
tmpl["Logs"] = serverLogs
if len(serverLogs) > 0 {
tmpl["Oldest"] = serverLogs[len(serverLogs)-1].ID
tmpl["Newest"] = serverLogs[0].ID
}
}
general, err := GetConfig(g.ID)
if err != nil {
return nil, err
}
tmpl["Config"] = general
return tmpl, nil
}
func HandleLogsCPSaveGeneral(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, tmpl := web.GetBaseCPContextData(ctx)
form := ctx.Value(common.ContextKeyParsedForm).(*GeneralFormData)
config := &GuildLoggingConfig{
GuildConfigModel: configstore.GuildConfigModel{
GuildID: g.ID,
},
NicknameLoggingEnabled: form.NicknameLoggingEnabled,
UsernameLoggingEnabled: form.UsernameLoggingEnabled,
BlacklistedChannels: strings.Join(form.BlacklistedChannels, ","),
EveryoneCanViewDeleted: form.EveryoneCanViewDeleted,
ManageMessagesCanViewDeleted: form.ManageMessagesCanViewDeleted,
}
err := configstore.SQL.SetGuildConfig(ctx, config)
return tmpl, err
}
func HandleLogsCPDelete(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, tmpl := web.GetBaseCPContextData(ctx)
data := ctx.Value(common.ContextKeyParsedForm).(*DeleteData)
if data.ID == "" {
return tmpl, errors.New("ID is blank!")
}
result := common.GORM.Where("id = ? AND guild_id = ?", data.ID, g.ID).Delete(MessageLog{})
if result.Error != nil {
return tmpl, result.Error
}
if result.RowsAffected < 1 {
tmpl.AddAlerts(web.ErrorAlert("Ahhhhh did nothing??"))
return tmpl, nil
}
logrus.Println(result.RowsAffected)
err := common.GORM.Where("message_log_id = ?", data.ID).Delete(Message{}).Error
return tmpl, err
}
func HandleLogsHTML(w http.ResponseWriter, r *http.Request) interface{} {
g, tmpl := web.GetBaseCPContextData(r.Context())
idString := pat.Param(r, "id")
parsed, err := strconv.ParseInt(idString, 10, 64)
if web.CheckErr(tmpl, err, "Thats's not a real log id", nil) {
return tmpl
}
config, err := GetConfig(g.ID)
if web.CheckErr(tmpl, err, "Error retrieving config for this server", web.CtxLogger(r.Context()).Error) {
return tmpl
}
canViewDeleted := web.IsAdminRequest(r.Context(), r)
if config.EveryoneCanViewDeleted {
canViewDeleted = true
} else if config.ManageMessagesCanViewDeleted && !canViewDeleted {
canViewDeleted = web.HasPermissionCTX(r.Context(), discordgo.PermissionManageMessages)
}
tmpl["CanViewDeleted"] = canViewDeleted
msgLogs, err := GetChannelLogs(parsed)
if web.CheckErr(tmpl, err, "Failed retrieving message logs", web.CtxLogger(r.Context()).Error) {
return tmpl
}
if msgLogs.GuildID != discordgo.StrID(g.ID) {
return tmpl.AddAlerts(web.ErrorAlert("Couldn't find the logs im so sorry please dont hurt me i have a family D:"))
}
// Fetch the role colors if possible
users := make([]int64, 0, 50)
for _, v := range msgLogs.Messages {
parsedAuthor, _ := strconv.ParseInt(v.AuthorID, 10, 64)
if !common.ContainsInt64Slice(users, parsedAuthor) {
users = append(users, parsedAuthor)
}
}
roleColors, _ := botrest.GetMemberColors(g.ID, users...)
const TimeFormat = "2006 Jan 02 15:04"
for k, v := range msgLogs.Messages {
parsed, err := discordgo.Timestamp(v.Timestamp).Parse()
if err != nil {
logrus.WithError(err).Error("Failed parsing logged message timestamp")
continue
}
ts := parsed.UTC().Format(TimeFormat)
msgLogs.Messages[k].Timestamp = ts
if roleColors != nil {
if c, ok := roleColors[v.AuthorID]; ok {
msgLogs.Messages[k].Color = strconv.FormatInt(int64(c), 16)
}
}
}
tmpl["Logs"] = msgLogs
return tmpl
}
func HandleDeleteMessageJson(w http.ResponseWriter, r *http.Request) interface{} {
g, _ := web.GetBaseCPContextData(r.Context())
logsId := r.FormValue("LogID")
msgID := r.FormValue("MessageID")
if logsId == "" || msgID == "" {
return web.NewPublicError("Empty id")
}
var logContainer MessageLog
err := common.GORM.Where("id = ?", logsId).First(&logContainer).Error
if err != nil {
return err
}
if logContainer.GuildID != discordgo.StrID(g.ID) {
return err
}
err = common.GORM.Model(&Message{}).Where("message_log_id = ? AND id = ?", logsId, msgID).Update("deleted", true).Error
user := r.Context().Value(common.ContextKeyUser).(*discordgo.User)
common.AddCPLogEntry(user, g.ID, "Deleted a message from log #"+logsId)
return err
}