-
Notifications
You must be signed in to change notification settings - Fork 940
/
plugin_web.go
316 lines (251 loc) · 8.61 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
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
package serverstats
import (
"context"
"fmt"
"html/template"
"net/http"
"os"
"strconv"
"strings"
"time"
"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/volatiletech/null"
"github.com/volatiletech/sqlboiler/boil"
"goji.io"
"goji.io/pat"
)
var WebStatsCache = rcache.New(cacheChartFetcher, time.Minute)
var WebConfigCache = rcache.NewInt(cacheConfigFetcher, time.Minute)
type FormData struct {
Public bool
IgnoreChannels []int64 `valid:"channel,false"`
}
func (p *Plugin) InitWeb() {
web.LoadHTMLTemplate("../../serverstats/assets/serverstats.html", "templates/plugins/serverstats.html")
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
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)
}
WebConfigCache.Delete(int(ag.ID))
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 := GetConfigWeb(activeGuild.ID)
if conf == nil {
w.WriteHeader(http.StatusInternalServerError)
return nil
}
if !conf.Public && isPublicAccess {
return nil
}
stats, err := RetrieveDailyStats(time.Now(), 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"`
Data []*ChartDataPeriod `json:"data"`
}
func HandleStatsCharts(w http.ResponseWriter, r *http.Request, isPublicAccess bool) interface{} {
activeGuild, _ := web.GetBaseCPContextData(r.Context())
conf := GetConfigWeb(activeGuild.ID)
if conf == nil {
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, r.Context())
return stats
}
func emptyChartData() *ChartResponse {
return &ChartResponse{
Days: 0,
Data: []*ChartDataPeriod{},
}
}
func CacheGetCharts(guildID int64, days int, ctx context.Context) *ChartResponse {
if os.Getenv("YAGPDB_SERVERSTATS_DISABLE_SERVERSTATS") != "" {
return emptyChartData()
}
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 emptyChartData()
}
stats := statsInterface.(*ChartResponse)
cop := *stats
if fetchDays != days && days != -1 && len(cop.Data) > days {
cop.Data = cop.Data[:days]
cop.Days = days
}
return &cop
}
func cacheChartFetcher(key string) interface{} {
split := strings.Split(key, ":")
if len(split) < 3 {
logger.Error("invalid cache key: ", key)
return nil
}
guildID, _ := strconv.ParseInt(split[1], 10, 64)
days, _ := strconv.Atoi(split[2])
periods, err := RetrieveChartDataPeriods(context.Background(), guildID, time.Now(), days)
if err != nil {
logger.WithError(err).WithField("cache_key", key).Error("failed retrieving chart data")
return nil
}
return &ChartResponse{
Days: days,
Data: periods,
}
}
func GetConfigWeb(guildID int64) *ServerStatsConfig {
config := WebConfigCache.Get(int(guildID))
if config == nil {
return nil
}
return config.(*ServerStatsConfig)
}
func cacheConfigFetcher(key int) interface{} {
config, err := GetConfig(context.Background(), int64(key))
if err != nil {
logger.WithError(err).WithField("cache_key", key).Error("failed retrieving stats config")
return nil
}
return config
}
var _ web.PluginWithServerHomeWidget = (*Plugin)(nil)
func (p *Plugin) LoadServerHomeWidget(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
activeGuild, templateData := web.GetBaseCPContextData(r.Context())
templateData["WidgetTitle"] = "Server Stats"
templateData["SettingsPath"] = "/stats"
templateData["WidgetEnabled"] = true
config, err := GetConfig(r.Context(), activeGuild.ID)
if err != nil {
return templateData, common.ErrWithCaller(err)
}
const format = `<ul>
<li>Public stats: %s</li>
<li>Blacklisted channnels: <code>%d</code></li>
</ul>`
templateData["WidgetBody"] = template.HTML(fmt.Sprintf(format, web.EnabledDisabledSpanStatus(config.Public), len(config.ParsedChannels)))
return templateData, nil
}