forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin_web.go
279 lines (227 loc) · 8.07 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
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
package serverstats
import (
"github.com/jonas747/discordgo"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/pubsub"
"github.com/jonas747/yagpdb/premium"
"github.com/jonas747/yagpdb/serverstats/models"
"github.com/jonas747/yagpdb/web"
"github.com/karlseguin/rcache"
"github.com/sirupsen/logrus"
"github.com/volatiletech/null"
"github.com/volatiletech/sqlboiler/boil"
"goji.io"
"goji.io/pat"
"html/template"
"net/http"
"strconv"
"strings"
"time"
)
var WebStatsCache = rcache.New(cacheChartFetcher, time.Minute)
type FormData struct {
Public bool
IgnoreChannels []int64 `valid:"channel,false"`
}
func (p *Plugin) InitWeb() {
tmplPath := "templates/plugins/serverstats.html"
if common.Testing {
tmplPath = "../../serverstats/assets/serverstats.html"
}
web.Templates = template.Must(web.Templates.ParseFiles(tmplPath))
statsCPMux := goji.SubMux()
web.CPMux.Handle(pat.New("/stats"), statsCPMux)
web.CPMux.Handle(pat.New("/stats/*"), statsCPMux)
statsCPMux.Use(web.RequireGuildChannelsMiddleware)
cpGetHandler := web.ControllerHandler(publicHandler(HandleStatsHtml, false), "cp_serverstats")
statsCPMux.Handle(pat.Get(""), cpGetHandler)
statsCPMux.Handle(pat.Get("/"), cpGetHandler)
statsCPMux.Handle(pat.Post("/settings"), web.ControllerPostHandler(HandleSaveStatsSettings, cpGetHandler, FormData{}, "Updated serverstats settings"))
statsCPMux.Handle(pat.Get("/daily_json"), web.APIHandler(publicHandlerJson(HandleStatsJson, false)))
statsCPMux.Handle(pat.Get("/charts"), web.APIHandler(publicHandlerJson(HandleStatsCharts, false)))
// Public
web.ServerPublicMux.Handle(pat.Get("/stats"), web.RequireGuildChannelsMiddleware(web.ControllerHandler(publicHandler(HandleStatsHtml, true), "cp_serverstats")))
web.ServerPublicMux.Handle(pat.Get("/stats/daily_json"), web.RequireGuildChannelsMiddleware(web.APIHandler(publicHandlerJson(HandleStatsJson, true))))
web.ServerPublicMux.Handle(pat.Get("/stats/charts"), web.RequireGuildChannelsMiddleware(web.APIHandler(publicHandlerJson(HandleStatsCharts, true))))
}
type publicHandlerFunc func(w http.ResponseWriter, r *http.Request, publicAccess bool) (web.TemplateData, error)
func publicHandler(inner publicHandlerFunc, public bool) web.ControllerHandlerFunc {
mw := func(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
return inner(w, r.WithContext(web.SetContextTemplateData(r.Context(), map[string]interface{}{"Public": public})), public)
}
return mw
}
// Somewhat dirty - should clean up this mess sometime
func HandleStatsHtml(w http.ResponseWriter, r *http.Request, isPublicAccess bool) (web.TemplateData, error) {
activeGuild, templateData := web.GetBaseCPContextData(r.Context())
config, err := GetConfig(r.Context(), activeGuild.ID)
if err != nil {
return templateData, common.ErrWithCaller(err)
}
templateData["Config"] = config
templateData["ExtraHead"] = template.HTML(`
<link rel="stylesheet" href="/static/vendor/morris/morris.css" />
<link rel="stylesheet" href="/static/vendor/chartist/chartist.min.css" />
`)
return templateData, nil
}
func HandleSaveStatsSettings(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ag, templateData := web.GetBaseCPContextData(r.Context())
formData := r.Context().Value(common.ContextKeyParsedForm).(*FormData)
stringedChannels := ""
alreadyAdded := make([]int64, 0, len(formData.IgnoreChannels))
OUTER:
for i, v := range formData.IgnoreChannels {
// only add each once
for _, ad := range alreadyAdded {
if ad == v {
continue OUTER
}
}
// make sure the channel exists
channelExists := false
for _, ec := range ag.Channels {
if ec.ID == v {
channelExists = true
break
}
}
if !channelExists {
continue
}
if i != 0 {
stringedChannels += ","
}
alreadyAdded = append(alreadyAdded, v)
stringedChannels += strconv.FormatInt(v, 10)
}
model := &models.ServerStatsConfig{
GuildID: ag.ID,
Public: null.BoolFrom(formData.Public),
IgnoreChannels: null.StringFrom(stringedChannels),
CreatedAt: null.TimeFrom(time.Now()),
}
err := model.UpsertG(r.Context(), true, []string{"guild_id"}, boil.Whitelist("public", "ignore_channels"), boil.Infer())
if err == nil {
go pubsub.Publish("server_stats_invalidate_cache", ag.ID, nil)
}
return templateData, err
}
type publicHandlerFuncJson func(w http.ResponseWriter, r *http.Request, publicAccess bool) interface{}
func publicHandlerJson(inner publicHandlerFuncJson, public bool) web.CustomHandlerFunc {
mw := func(w http.ResponseWriter, r *http.Request) interface{} {
return inner(w, r.WithContext(web.SetContextTemplateData(r.Context(), map[string]interface{}{"Public": public})), public)
}
return mw
}
func HandleStatsJson(w http.ResponseWriter, r *http.Request, isPublicAccess bool) interface{} {
activeGuild, _ := web.GetBaseCPContextData(r.Context())
conf, err := GetConfig(r.Context(), activeGuild.ID)
if err != nil {
web.CtxLogger(r.Context()).WithError(err).Error("Failed retrieving stats config")
w.WriteHeader(http.StatusInternalServerError)
return nil
}
if !conf.Public && isPublicAccess {
return nil
}
stats, err := RetrieveDailyStats(activeGuild.ID)
if err != nil {
web.CtxLogger(r.Context()).WithError(err).Error("Failed retrieving stats")
w.WriteHeader(http.StatusInternalServerError)
return nil
}
// Update the names to human readable ones, leave the ids in the name fields for the ones not available
for _, cs := range stats.ChannelMessages {
for _, channel := range activeGuild.Channels {
if discordgo.StrID(channel.ID) == cs.Name {
cs.Name = channel.Name
break
}
}
}
return stats
}
type ChartResponse struct {
Days int `json:"days"`
MemberData []*MemberChartDataPeriod `json:"member_chart_data"`
MessageData []*MessageChartDataPeriod `json:"message_chart_data"`
}
func HandleStatsCharts(w http.ResponseWriter, r *http.Request, isPublicAccess bool) interface{} {
activeGuild, _ := web.GetBaseCPContextData(r.Context())
conf, err := GetConfig(r.Context(), activeGuild.ID)
if err != nil {
web.CtxLogger(r.Context()).WithError(err).Error("Failed retrieving stats config")
w.WriteHeader(http.StatusInternalServerError)
return nil
}
if !conf.Public && isPublicAccess {
return nil
}
numDays := 7
if r.URL.Query().Get("days") != "" {
numDays, _ = strconv.Atoi(r.URL.Query().Get("days"))
if numDays > 365 {
numDays = 365
}
}
if !premium.ContextPremium(r.Context()) && (numDays > 7 || numDays <= 0) {
numDays = 7
}
stats := CacheGetCharts(activeGuild.ID, numDays)
return stats
}
func CacheGetCharts(guildID int64, days int) *ChartResponse {
fetchDays := days
if days < 7 {
fetchDays = 7
}
// default to full time stats
if days != 30 && days != 365 && days > 7 {
fetchDays = -1
days = -1
} else if days < 1 {
days = -1
fetchDays = -1
}
key := "charts:" + strconv.FormatInt(guildID, 10) + ":" + strconv.FormatInt(int64(fetchDays), 10)
statsInterface := WebStatsCache.Get(key)
if statsInterface == nil {
return &ChartResponse{
MemberData: make([]*MemberChartDataPeriod, 0),
MessageData: make([]*MessageChartDataPeriod, 0),
}
}
stats := statsInterface.(*ChartResponse)
cop := *stats
if fetchDays != days && days != -1 && len(cop.MemberData) > days {
cop.MemberData = cop.MemberData[:days]
cop.MessageData = cop.MessageData[:days]
cop.Days = days
}
return &cop
}
func cacheChartFetcher(key string) interface{} {
split := strings.Split(key, ":")
if len(split) < 3 {
logrus.Error("[serverstats] invalid cache key: ", key)
return nil
}
guildID, _ := strconv.ParseInt(split[1], 10, 64)
days, _ := strconv.Atoi(split[2])
memberData, err := RetrieveMemberChartStats(guildID, days)
if err != nil {
logrus.WithError(err).WithField("cache_key", key).Error("failed retrieving member chart data")
return nil
}
messageData, err := RetrieveMessageChartData(guildID, days)
if err != nil {
logrus.WithError(err).WithField("cache_key", key).Error("failed retrieving message chart data")
return nil
}
return &ChartResponse{
Days: days,
MemberData: memberData,
MessageData: messageData,
}
}