-
Notifications
You must be signed in to change notification settings - Fork 927
/
plugin_web.go
274 lines (207 loc) · 7.62 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
package premium
import (
"context"
"database/sql"
_ "embed"
"fmt"
"html"
"html/template"
"net/http"
"strconv"
"strings"
"time"
"github.com/botlabs-gg/yagpdb/common"
"github.com/botlabs-gg/yagpdb/premium/models"
"github.com/botlabs-gg/yagpdb/web"
"github.com/didip/tollbooth"
"github.com/didip/tollbooth/limiter"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
"goji.io"
"goji.io/pat"
)
//go:embed assets/premium.html
var PageHTML string
type CtxKey int
var (
CtxKeyIsPremium CtxKey = 1
CtxKeyPremiumTier CtxKey = 2
)
var _ web.Plugin = (*Plugin)(nil)
func (p *Plugin) InitWeb() {
web.AddHTMLTemplate("premium/assets/premium.html", PageHTML)
web.CPMux.Use(PremiumGuildMW)
web.ServerPublicMux.Use(PremiumGuildMW)
submux := goji.SubMux()
web.RootMux.Handle(pat.New("/premium"), submux)
web.RootMux.Handle(pat.New("/premium/*"), submux)
submux.Use(web.RequireSessionMiddleware)
mainHandler := web.ControllerHandler(HandleGetPremiumMainPage, "premium_user_setup")
submux.Handle(pat.Get("/"), mainHandler)
submux.Handle(pat.Get(""), mainHandler)
limiter := tollbooth.NewLimiter(1, &limiter.ExpirableOptions{DefaultExpirationTTL: time.Hour})
limiter.SetIPLookups([]string{"CF-Connecting-IP", "X-Forwarded-For", "RemoteAddr", "X-Real-IP"})
submux.Handle(pat.Post("/lookupcode"), tollbooth.LimitHandler(limiter, web.ControllerPostHandler(HandlePostLookupCode, mainHandler, nil)))
submux.Handle(pat.Post("/redeemcode"), tollbooth.LimitHandler(limiter, web.ControllerPostHandler(HandlePostRedeemCode, mainHandler, nil)))
submux.Handle(pat.Post("/updateslot/:slotID"), web.ControllerPostHandler(HandlePostUpdateSlot, mainHandler, UpdateData{}))
web.CPMux.Handle(pat.Post("/premium/detach"), web.ControllerPostHandler(HandlePostDetachGuildSlot, web.RenderHandler(nil, "cp_premium_detach"), nil))
}
// PremiumGuildMW adds premium data to context and tmpl vars
func PremiumGuildMW(inner http.Handler) http.Handler {
mw := func(w http.ResponseWriter, r *http.Request) {
guild, tmpl := web.GetBaseCPContextData(r.Context())
isPremium, err := IsGuildPremium(guild.ID)
if err != nil {
web.CtxLogger(r.Context()).WithError(err).Error("Failed checking if guild is premium")
}
ctx := r.Context()
ctx = context.WithValue(ctx, CtxKeyIsPremium, isPremium)
tmpl["IsGuildPremium"] = isPremium
if isPremium {
tier, err := GuildPremiumTier(guild.ID)
if err != nil {
web.CtxLogger(ctx).WithError(err).Error("Failed retrieving guild premium tier")
}
tmpl["GuildPremiumTier"] = tier
ctx = context.WithValue(ctx, CtxKeyPremiumTier, tier)
}
inner.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(mw)
}
func HandleGetPremiumMainPage(w http.ResponseWriter, r *http.Request) (tmpl web.TemplateData, err error) {
_, tmpl = web.GetCreateTemplateData(r.Context())
user := web.ContextUser(r.Context())
slots, err := UserPremiumSlots(r.Context(), user.ID)
if err != nil {
return tmpl, err
}
guilds, _ := web.GetUserGuilds(r.Context())
tmpl["UserGuilds"] = guilds
tmpl["PremiumSlotDurationRemaining"] = SlotDurationLeft
tmpl["PremiumSlots"] = slots
return tmpl, nil
}
func HandlePostLookupCode(w http.ResponseWriter, r *http.Request) (tmpl web.TemplateData, err error) {
_, tmpl = web.GetCreateTemplateData(r.Context())
code := r.FormValue("code")
if code == "" {
return tmpl.AddAlerts(web.ErrorAlert("No code provided")), nil
}
codeModel, err := LookupCode(r.Context(), code)
if err != nil {
if err == ErrCodeNotFound {
return tmpl.AddAlerts(web.ErrorAlert("Code not found")), nil
}
return tmpl, err
}
if codeModel.UserID.Valid {
return tmpl.AddAlerts(web.ErrorAlert("That code is already redeemed")), nil
}
tmpl["QueriedCode"] = codeModel
return tmpl, nil
}
func HandlePostRedeemCode(w http.ResponseWriter, r *http.Request) (tmpl web.TemplateData, err error) {
_, tmpl = web.GetCreateTemplateData(r.Context())
user := web.ContextUser(r.Context())
code := r.FormValue("code")
if code == "" {
return tmpl.AddAlerts(web.ErrorAlert("No code provided")), nil
}
err = RedeemCode(r.Context(), code, user.ID)
return tmpl, err
}
type UpdateData struct {
GuildID int64
}
func HandlePostUpdateSlot(w http.ResponseWriter, r *http.Request) (tmpl web.TemplateData, err error) {
_, tmpl = web.GetCreateTemplateData(r.Context())
data := r.Context().Value(common.ContextKeyParsedForm).(*UpdateData)
user := web.ContextUser(r.Context())
strSlotID := pat.Param(r, "slotID")
parsedSlotID, _ := strconv.ParseInt(strSlotID, 10, 64)
err = DetachSlotFromGuild(r.Context(), parsedSlotID, user.ID)
if err != nil {
return tmpl, err
}
if data.GuildID != 0 {
err = AttachSlotToGuild(r.Context(), parsedSlotID, user.ID, data.GuildID)
if err == ErrGuildAlreadyPremium {
tmpl.AddAlerts(web.ErrorAlert("Server already has premium from another slot (possibly from another user)"))
}
}
return tmpl, err
}
func ContextPremium(ctx context.Context) bool {
if v := ctx.Value(CtxKeyIsPremium); v != nil {
return v.(bool)
}
return false
}
func ContextPremiumTier(ctx context.Context) PremiumTier {
if v := ctx.Value(CtxKeyPremiumTier); v != nil {
return v.(PremiumTier)
}
return PremiumTierNone
}
var _ web.PluginWithServerHomeWidget = (*Plugin)(nil)
var _ web.ServerHomeWidgetWithOrder = (*Plugin)(nil)
func (p *Plugin) LoadServerHomeWidget(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ag, templateData := web.GetBaseCPContextData(r.Context())
templateData["WidgetTitle"] = "Premium Status"
footer := "<p><a href=\"/premium\">Manage your user premium slots</a></p>"
if ContextPremium(r.Context()) {
body := strings.Builder{}
for _, v := range GuildPremiumSources {
tier, status, err := v.GuildPremiumDetails(ag.ID)
if err != nil {
return nil, err
}
if tier <= PremiumTierNone {
continue
}
if _, ok := v.(*SlotGuildPremiumSource); ok {
// special handling for this since i was a bit lazy
username := ""
discrim := ""
premiumBy, err := PremiumProvidedBy(ag.ID)
if err != nil {
return templateData, err
}
user, err := common.BotSession.User(premiumBy)
if err == nil {
username = user.Username
discrim = user.Discriminator
}
detForm := fmt.Sprintf(`<form data-async-form action="/manage/%d/premium/detach">
<button type="submit" class="btn btn-danger">Detach premium slot</button>
</form>`, ag.ID)
body.WriteString(fmt.Sprintf("<p>Premium tier <b>%s</b> active and provided by user <code>%s#%s (%d)</p></code>\n\n%s", tier.String(), html.EscapeString(username), html.EscapeString(discrim), premiumBy, detForm))
} else {
body.WriteString(fmt.Sprintf("<p class=\"mt-3\">Premium tier <b>%s</b> active and provided by %s: %s</p>", tier.String(), v.Name(), status))
}
}
templateData["WidgetEnabled"] = true
templateData["WidgetBody"] = template.HTML(body.String() + footer)
return templateData, nil
} else {
templateData["WidgetDisabled"] = true
templateData["WidgetBody"] = template.HTML(fmt.Sprintf("<p>Premium not active on this server :(</p>\n\n%s", footer))
}
return templateData, nil
}
func (p *Plugin) ServerHomeWidgetOrder() int {
return 10
}
func HandlePostDetachGuildSlot(w http.ResponseWriter, r *http.Request) (tmpl web.TemplateData, err error) {
activeGuild, templateData := web.GetBaseCPContextData(r.Context())
slot, err := models.PremiumSlots(qm.Where("guild_id = ?", activeGuild.ID)).OneG(r.Context())
if err != nil {
if err == sql.ErrNoRows {
templateData.AddAlerts(web.ErrorAlert("No premium slot attached to this server"))
return templateData, nil
}
return templateData, err
}
err = DetachSlotFromGuild(r.Context(), slot.ID, slot.UserID)
return templateData, err
}