-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin_web.go
247 lines (198 loc) · 7.58 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
package reddit
import (
"context"
"fmt"
"github.com/jonas747/discordgo"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/reddit/models"
"github.com/jonas747/yagpdb/web"
"github.com/volatiletech/sqlboiler/boil"
"goji.io"
"goji.io/pat"
"html/template"
"net/http"
"os"
"sort"
"strconv"
"strings"
)
type CtxKey int
const (
CurrentConfig CtxKey = iota
)
type CreateForm struct {
Subreddit string `schema:"subreddit" valid:",1,100"`
Slow bool `schema:"slow"`
Channel int64 `schema:"channel" valid:"channel,false`
ID int64 `schema:"id"`
UseEmbeds bool `schema:"use_embeds"`
NSFWMode int `schema:"nsfw_filter"`
MinUpvotes int `schema:"min_upvotes"`
}
type UpdateForm struct {
Channel int64 `schema:"channel" valid:"channel,false`
ID int64 `schema:"id"`
UseEmbeds bool `schema:"use_embeds"`
NSFWMode int `schema:"nsfw_filter"`
MinUpvotes int `schema:"min_upvotes"`
}
func (p *Plugin) InitWeb() {
if os.Getenv("YAGPDB_REDDIT_DISABLE_REDIS_PQ_MIGRATION") == "" {
go migrateLegacyRedisFormatToPostgres()
}
tmplPathSettings := "templates/plugins/reddit.html"
if common.Testing {
tmplPathSettings = "../../reddit/assets/reddit.html"
}
web.Templates = template.Must(web.Templates.ParseFiles(tmplPathSettings))
redditMux := goji.SubMux()
web.CPMux.Handle(pat.New("/reddit/*"), redditMux)
web.CPMux.Handle(pat.New("/reddit"), redditMux)
// Alll handlers here require guild channels present
redditMux.Use(web.RequireGuildChannelsMiddleware)
redditMux.Use(web.RequireFullGuildMW)
redditMux.Use(web.RequireBotMemberMW)
redditMux.Use(web.RequirePermMW(discordgo.PermissionManageWebhooks))
redditMux.Use(baseData)
redditMux.Handle(pat.Get("/"), web.RenderHandler(HandleReddit, "cp_reddit"))
redditMux.Handle(pat.Get(""), web.RenderHandler(HandleReddit, "cp_reddit"))
// If only html forms allowed patch and delete.. if only
redditMux.Handle(pat.Post(""), web.FormParserMW(web.RenderHandler(HandleNew, "cp_reddit"), CreateForm{}))
redditMux.Handle(pat.Post("/"), web.FormParserMW(web.RenderHandler(HandleNew, "cp_reddit"), CreateForm{}))
redditMux.Handle(pat.Post("/:item/update"), web.FormParserMW(web.RenderHandler(HandleModify, "cp_reddit"), UpdateForm{}))
redditMux.Handle(pat.Post("/:item/delete"), web.RenderHandler(HandleRemove, "cp_reddit"))
}
// Adds the current config to the context
func baseData(inner http.Handler) http.Handler {
mw := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
templateData["VisibleURL"] = "/manage/" + discordgo.StrID(activeGuild.ID) + "/reddit/"
feeds, err := models.RedditFeeds(models.RedditFeedWhere.GuildID.EQ(activeGuild.ID)).AllG(ctx)
if web.CheckErr(templateData, err, "Failed retrieving config, message support in the yagpdb server", web.CtxLogger(ctx).Error) {
web.LogIgnoreErr(web.Templates.ExecuteTemplate(w, "cp_reddit", templateData))
} else {
sort.Slice(feeds, func(i, j int) bool {
return feeds[i].Subreddit < feeds[j].Subreddit
})
}
inner.ServeHTTP(w, r.WithContext(context.WithValue(ctx, CurrentConfig, feeds)))
}
return http.HandlerFunc(mw)
}
func HandleReddit(w http.ResponseWriter, r *http.Request) interface{} {
ctx := r.Context()
_, templateData := web.GetBaseCPContextData(ctx)
currentConfig := ctx.Value(CurrentConfig).(models.RedditFeedSlice)
templateData["RedditConfig"] = currentConfig
return templateData
}
func HandleNew(w http.ResponseWriter, r *http.Request) interface{} {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
currentConfig := ctx.Value(CurrentConfig).(models.RedditFeedSlice)
templateData["RedditConfig"] = currentConfig
newElem := ctx.Value(common.ContextKeyParsedForm).(*CreateForm)
ok := ctx.Value(common.ContextKeyFormOk).(bool)
if !ok {
return templateData
}
maxFeeds := MaxFeedForCtx(ctx)
if len(currentConfig) >= maxFeeds {
return templateData.AddAlerts(web.ErrorAlert(fmt.Sprintf("Max %d feeds allowed (or %d for premium servers)", GuildMaxFeedsNormal, GuildMaxFeedsPremium)))
}
watchItem := &models.RedditFeed{
GuildID: activeGuild.ID,
ChannelID: newElem.Channel,
Subreddit: strings.ToLower(strings.TrimSpace(newElem.Subreddit)),
UseEmbeds: newElem.UseEmbeds,
FilterNSFW: newElem.NSFWMode,
}
if newElem.Slow {
watchItem.Slow = true
watchItem.MinUpvotes = newElem.MinUpvotes
}
err := watchItem.InsertG(ctx, boil.Infer())
if web.CheckErr(templateData, err, "Failed saving item :'(", web.CtxLogger(ctx).Error) {
return templateData
}
currentConfig = append(currentConfig, watchItem)
sort.Slice(currentConfig, func(i, j int) bool {
return currentConfig[i].Subreddit < currentConfig[j].Subreddit
})
templateData["RedditConfig"] = currentConfig
templateData.AddAlerts(web.SucessAlert("Sucessfully added subreddit feed for /r/" + watchItem.Subreddit))
// Log
user := ctx.Value(common.ContextKeyUser).(*discordgo.User)
go common.AddCPLogEntry(user, activeGuild.ID, "Added reddit feed from /r/"+newElem.Subreddit)
return templateData
}
func HandleModify(w http.ResponseWriter, r *http.Request) interface{} {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
currentConfig := ctx.Value(CurrentConfig).(models.RedditFeedSlice)
templateData["RedditConfig"] = currentConfig
updated := ctx.Value(common.ContextKeyParsedForm).(*UpdateForm)
ok := ctx.Value(common.ContextKeyFormOk).(bool)
if !ok {
return templateData
}
item := FindFeed(currentConfig, updated.ID)
if item == nil {
return templateData.AddAlerts(web.ErrorAlert("Unknown id"))
}
item.ChannelID = updated.Channel
item.UseEmbeds = updated.UseEmbeds
item.FilterNSFW = updated.NSFWMode
item.Disabled = false
if item.Slow {
item.MinUpvotes = updated.MinUpvotes
}
_, err := item.UpdateG(ctx, boil.Whitelist("channel_id", "use_embeds", "filter_nsfw", "min_upvotes", "disabled"))
if web.CheckErr(templateData, err, "Failed saving item :'(", web.CtxLogger(ctx).Error) {
return templateData
}
templateData.AddAlerts(web.SucessAlert("Sucessfully updated reddit feed! :D"))
user := ctx.Value(common.ContextKeyUser).(*discordgo.User)
common.AddCPLogEntry(user, activeGuild.ID, "Modified a feed to /r/"+item.Subreddit)
return templateData
}
func HandleRemove(w http.ResponseWriter, r *http.Request) interface{} {
ctx := r.Context()
activeGuild, templateData := web.GetBaseCPContextData(ctx)
currentConfig := ctx.Value(CurrentConfig).(models.RedditFeedSlice)
templateData["RedditConfig"] = currentConfig
id := pat.Param(r, "item")
idInt, err := strconv.ParseInt(id, 10, 32)
if err != nil {
return templateData.AddAlerts(web.ErrorAlert("Failed parsing id", err))
}
// Get tha actual watch item from the config
item := FindFeed(currentConfig, idInt)
if item == nil {
return templateData.AddAlerts(web.ErrorAlert("Unknown id"))
}
_, err = item.DeleteG(ctx)
if web.CheckErr(templateData, err, "Failed removing item :'(", web.CtxLogger(ctx).Error) {
return templateData
}
templateData.AddAlerts(web.SucessAlert("Sucessfully removed subreddit feed for /r/" + item.Subreddit))
// Remove it form the displayed list
for k, c := range currentConfig {
if c.ID == idInt {
currentConfig = append(currentConfig[:k], currentConfig[k+1:]...)
}
}
templateData["RedditConfig"] = currentConfig
user := ctx.Value(common.ContextKeyUser).(*discordgo.User)
go common.AddCPLogEntry(user, activeGuild.ID, "Removed feed from /r/"+item.Subreddit)
return templateData
}
func FindFeed(feeds []*models.RedditFeed, id int64) *models.RedditFeed {
for _, v := range feeds {
if v.ID == id {
return v
}
}
return nil
}