-
Notifications
You must be signed in to change notification settings - Fork 910
/
web.go
303 lines (249 loc) · 7.6 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
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
package soundboard
import (
"emperror.dev/errors"
"fmt"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/soundboard/models"
"github.com/jonas747/yagpdb/web"
"github.com/volatiletech/sqlboiler/boil"
"github.com/volatiletech/sqlboiler/queries/qm"
"goji.io"
"goji.io/pat"
"html/template"
"io"
"mime/multipart"
"net/http"
"os"
"strconv"
"strings"
)
type PostForm struct {
ID int
Name string `valid:",100"`
RequiredRoles []int64 `valid:"role"`
BlacklistedRoles []int64 `valid:"role"`
}
func (pf *PostForm) ToDBModel() *models.SoundboardSound {
return &models.SoundboardSound{
ID: pf.ID,
Name: pf.Name,
RequiredRoles: pf.RequiredRoles,
BlacklistedRoles: pf.BlacklistedRoles,
}
}
func (p *Plugin) InitWeb() {
tmplPath := "templates/plugins/soundboard.html"
if common.Testing {
tmplPath = "../../soundboard/assets/soundboard.html"
}
web.Templates = template.Must(web.Templates.ParseFiles(tmplPath))
cpMux := goji.SubMux()
web.CPMux.Handle(pat.New("/soundboard/*"), cpMux)
web.CPMux.Handle(pat.New("/soundboard"), cpMux)
cpMux.Use(web.RequireBotMemberMW)
getHandler := web.ControllerHandler(HandleGetCP, "cp_soundboard")
cpMux.Handle(pat.Get("/"), getHandler)
//cpMux.Handle(pat.Get(""), getHandler)
cpMux.Handle(pat.Post("/new"), web.ControllerPostHandler(HandleNew, getHandler, PostForm{}, "Added a new sound to the soundboard"))
cpMux.Handle(pat.Post("/update"), web.ControllerPostHandler(HandleUpdate, getHandler, PostForm{}, "Updated a soundboard sound"))
cpMux.Handle(pat.Post("/delete"), web.ControllerPostHandler(HandleDelete, getHandler, PostForm{}, "Removed a sound from the soundboard"))
}
func HandleGetCP(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, tmpl := web.GetBaseCPContextData(ctx)
sounds, err := GetSoundboardSounds(g.ID, ctx)
if err != nil {
return tmpl, err
}
tmpl["SoundboardSounds"] = sounds
return tmpl, nil
}
func HandleNew(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, tmpl := web.GetBaseCPContextData(ctx)
isDCA := false
var file multipart.File
if r.FormValue("SoundURL") == "" {
f, header, err := r.FormFile("Sound")
if err != nil {
return tmpl, err
}
file = f
if strings.HasSuffix(header.Filename, ".dca") {
isDCA = true
}
}
data := ctx.Value(common.ContextKeyParsedForm).(*PostForm)
dbModel := data.ToDBModel()
dbModel.Status = int(TranscodingStatusQueued)
if isDCA {
dbModel.Status = int(TranscodingStatusReady)
}
dbModel.GuildID = g.ID
// check for name conflict
nameConflict, err := models.SoundboardSounds(qm.Where("guild_id=? AND name=?", g.ID, data.Name)).ExistsG(r.Context())
if err != nil {
return tmpl, err
}
if nameConflict {
tmpl.AddAlerts(web.ErrorAlert("Name already used"))
return tmpl, nil
}
// check sound limit
count, err := models.SoundboardSounds(qm.Where("guild_id=?", g.ID)).CountG(r.Context())
if err != nil {
return tmpl, err
}
if count >= int64(MaxSoundsForContext(ctx)) {
tmpl.AddAlerts(web.ErrorAlert(fmt.Sprintf("Max %d sounds allowed (%d for premium servers)", MaxGuildSounds, MaxGuildSoundsPremium)))
return tmpl, nil
}
err = dbModel.InsertG(r.Context(), boil.Infer())
if err != nil {
return tmpl, err
}
// Lock it
locked, err := common.TryLockRedisKey(KeySoundLock(dbModel.ID), 60)
if err != nil || !locked {
if !locked {
tmpl.AddAlerts(web.ErrorAlert("Uh oh failed locking"))
}
return tmpl, err
}
defer common.UnlockRedisKey(KeySoundLock(dbModel.ID))
//logrus.Error("CREAte errror:", err)
fname := "soundboard/queue/" + strconv.Itoa(int(dbModel.ID))
if isDCA {
fname += ".dca"
}
destFile, err := os.Create(fname)
if err != nil {
return tmpl, err
}
tooBig := false
if file != nil {
tooBig, err = DownloadNewSoundFile(file, destFile, 10000000)
} else if r.FormValue("SoundURL") != "" {
var resp *http.Response
resp, err = http.Get(r.FormValue("SoundURL"))
if err != nil {
tmpl.AddAlerts(web.ErrorAlert("Failed downloading sound: " + err.Error()))
destFile.Close()
} else {
defer resp.Body.Close()
tooBig, err = DownloadNewSoundFile(resp.Body, destFile, 10000000)
}
} else {
err = errors.New("No sound!?")
}
destFile.Close()
if tooBig || err != nil {
os.Remove(fname)
if tooBig {
tmpl.AddAlerts(web.ErrorAlert("Max 10MB files allowed"))
}
dbModel.DeleteG(ctx)
return tmpl, err
}
return tmpl, err
}
func DownloadNewSoundFile(r io.Reader, w io.Writer, limit int) (tooBig bool, err error) {
soundSize := 0
for {
buf := make([]byte, 1024)
n := 0
n, err = r.Read(buf)
if n > 0 {
buf = buf[:n]
soundSize += len(buf)
if soundSize > limit {
tooBig = true
break
}
_, writeErr := w.Write(buf)
if writeErr != nil {
err = writeErr
break
}
}
if err != nil {
if err == io.EOF {
err = nil
}
break
}
}
return
}
func HandleUpdate(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, tmpl := web.GetBaseCPContextData(ctx)
data := ctx.Value(common.ContextKeyParsedForm).(*PostForm)
dbModel, err := models.SoundboardSounds(qm.Where("guild_id = ? AND id = ?", g.ID, data.ID)).OneG(ctx)
if err != nil {
return tmpl.AddAlerts(web.ErrorAlert("Error retrieiving sound")), errors.WrapIf(err, "unknown sound")
}
nameConflict, err := models.SoundboardSounds(qm.Where("guild_id = ? AND name = ? AND id != ?", g.ID, data.Name, data.ID)).ExistsG(r.Context())
if err != nil {
return tmpl, err
}
if nameConflict {
tmpl.AddAlerts(web.ErrorAlert("Name already used"))
return tmpl, nil
}
dbModel.Name = data.Name
dbModel.RequiredRoles = data.RequiredRoles
dbModel.BlacklistedRoles = data.BlacklistedRoles
_, err = dbModel.UpdateG(ctx, boil.Whitelist("name", "required_roles", "blacklisted_roles", "updated_at"))
return tmpl, err
}
func HandleDelete(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ctx := r.Context()
g, tmpl := web.GetBaseCPContextData(ctx)
data := ctx.Value(common.ContextKeyParsedForm).(*PostForm)
locked, err := common.TryLockRedisKey(KeySoundLock(data.ID), 10)
if err != nil {
return tmpl, err
}
if !locked {
tmpl.AddAlerts(web.ErrorAlert("This sound is busy, try again in a minute and if it's still busy contact support"))
return tmpl, nil
}
defer common.UnlockRedisKey(KeySoundLock(data.ID))
storedSound, err := models.SoundboardSounds(qm.Where("guild_id = ? AND id = ?", g.ID, data.ID)).OneG(ctx)
if err != nil {
return tmpl, err
}
switch TranscodingStatus(storedSound.Status) {
case TranscodingStatusQueued, TranscodingStatusReady:
err = os.Remove(SoundFilePath(data.ID, TranscodingStatus(storedSound.Status)))
case TranscodingStatusTranscoding:
tmpl.AddAlerts(web.ErrorAlert("This sound is busy? try again in a minute and if its still busy contact support"))
return tmpl, nil
}
if err != nil {
if !os.IsNotExist(err) {
return tmpl, err
}
}
_, err = storedSound.DeleteG(ctx)
return tmpl, err
}
var _ web.PluginWithServerHomeWidget = (*Plugin)(nil)
func (p *Plugin) LoadServerHomeWidget(w http.ResponseWriter, r *http.Request) (web.TemplateData, error) {
ag, templateData := web.GetBaseCPContextData(r.Context())
templateData["WidgetTitle"] = "Soundboard"
templateData["SettingsPath"] = "/soundboard/"
sounds, err := GetSoundboardSounds(ag.ID, r.Context())
if err != nil {
return templateData, err
}
if len(sounds) > 0 {
templateData["WidgetEnabled"] = true
} else {
templateData["WidgetDisabled"] = true
}
const format = `<p>Soundboard sounds: <code>%d</code></p>`
templateData["WidgetBody"] = template.HTML(fmt.Sprintf(format, len(sounds)))
return templateData, nil
}