-
Notifications
You must be signed in to change notification settings - Fork 4
/
handlers.go
500 lines (424 loc) · 13 KB
/
handlers.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package http
import (
"errors"
"fmt"
"image/color"
"image/png"
"math"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"goji.io/v3/pat"
log "github.com/sirupsen/logrus"
"github.com/BattlesnakeOfficial/exporter/engine"
"github.com/BattlesnakeOfficial/exporter/media"
"github.com/BattlesnakeOfficial/exporter/parse"
"github.com/BattlesnakeOfficial/exporter/render"
)
// maxGIFResolution is the maximum resolution of GIF that we want to support.
// This is an important limit to set, because the GIF rendering takes a lot more
// IO, CPU and memory resources for larger resolutions.
// This resolution was chosen as a safe upper-limit after which the rendering starts
// to get really slow and the GIF sizes start to get too big.
const maxGIFResolution = 504 * 504
// allowedPixelsPerSquare is a list of resolutions that the API will allow.
var allowedPixelsPerSquare = []int{10, 20, 30, 40}
var errBadRequest = fmt.Errorf("bad request")
var errBadColor = fmt.Errorf("color parameter should have the format #FFFFFF")
var reCustomizationParam = regexp.MustCompile(`^[A-Za-z-0-9#]{1,32}$`)
var reColorParam = regexp.MustCompile(`^#?[A-Fa-f0-9]{6}$`)
func handleVersion(w http.ResponseWriter, r *http.Request) {
version := os.Getenv("APP_VERSION")
if len(version) == 0 {
version = "unknown"
}
fmt.Fprint(w, version)
}
var reAvatarParams = regexp.MustCompile(`^/(?:[a-z-]{1,32}:[A-Za-z-0-9#]{0,32}/)*(?P<width>[0-9]{2,4})x(?P<height>[0-9]{2,4}).(?P<ext>[a-z]{3,4})$`)
var reAvatarCustomizations = regexp.MustCompile(`(?P<key>[a-z-]{1,32}):(?P<value>[A-Za-z-0-9#]{0,32})`)
func handleAvatar(w http.ResponseWriter, r *http.Request) {
subPath := strings.TrimPrefix(r.URL.Path, "/avatars")
avatarSettings := render.AvatarSettings{}
// Extract width, height, and filetype
reParamsResult := reAvatarParams.FindStringSubmatch(subPath)
if len(reParamsResult) != 4 {
handleBadRequest(w, r, errBadRequest)
return
}
pWidth, err := strconv.Atoi(reParamsResult[1])
if err != nil {
handleBadRequest(w, r, errBadRequest)
return
}
avatarSettings.Width = pWidth
pHeight, err := strconv.Atoi(reParamsResult[2])
if err != nil {
handleBadRequest(w, r, errBadRequest)
return
}
avatarSettings.Height = pHeight
pExt := reParamsResult[3]
if pExt != "svg" && pExt != "png" {
handleBadRequest(w, r, errBadRequest)
return
}
// Extract customization params
reCustomizationResults := reAvatarCustomizations.FindAllStringSubmatch(subPath, -1)
for _, match := range reCustomizationResults {
cKey, cValue := match[1], match[2]
if cValue == "" {
// ignore empty values
continue
}
switch cKey {
case "head":
avatarSettings.HeadSVG, err = media.GetHeadSVG(cValue)
if err != nil {
if errors.Is(err, media.ErrNotFound) {
handleBadRequest(w, r, errBadRequest)
} else {
handleError(w, r, err, http.StatusInternalServerError)
}
return
}
case "tail":
avatarSettings.TailSVG, err = media.GetTailSVG(cValue)
if err != nil {
if errors.Is(err, media.ErrNotFound) {
handleBadRequest(w, r, errBadRequest)
} else {
handleError(w, r, err, http.StatusInternalServerError)
}
return
}
case "color":
if !reColorParam.MatchString(cValue) {
handleBadRequest(w, r, errBadRequest)
return
}
avatarSettings.Color = cValue
default:
handleBadRequest(w, r, errBadRequest)
return
}
}
// Render SVG
avatarSVG, err := render.AvatarSVG(avatarSettings)
if err != nil {
if errors.Is(err, render.ErrInvalidAvatarSettings) {
handleBadRequest(w, r, errBadRequest)
} else {
handleError(w, r, err, http.StatusInternalServerError)
}
return
}
if pExt == "png" {
image, err := media.ConvertSVGStringToPNG(avatarSVG, avatarSettings.Width, avatarSettings.Height)
if err != nil {
handleError(w, r, err, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "image/png")
if err := png.Encode(w, image); err != nil {
log.WithError(err).Error("unable to write PNG to response stream")
}
return
}
w.Header().Set("Content-Type", "image/svg+xml")
fmt.Fprint(w, avatarSVG)
}
func handleCustomization(w http.ResponseWriter, r *http.Request) {
customizationType := pat.Param(r, "type")
customizationName := pat.Param(r, "name")
ext := pat.Param(r, "ext")
if ext != "svg" {
handleBadRequest(w, r, errBadRequest)
return
}
if customizationType != "head" && customizationType != "tail" {
handleBadRequest(w, r, errBadRequest)
return
}
if !reCustomizationParam.MatchString(customizationName) {
handleBadRequest(w, r, errBadRequest)
return
}
var customizationColor color.Color = color.Black
colorParam := r.URL.Query().Get("color")
if colorParam != "" {
if !reColorParam.MatchString(colorParam) {
handleBadRequest(w, r, errBadColor)
return
}
customizationColor = parse.HexColor(colorParam)
}
flippedParam := r.URL.Query().Get("flipped") != ""
var svg string
var err error
var shouldFlip bool
switch customizationType {
case "head":
svg, err = media.GetHeadSVG(customizationName)
shouldFlip = flippedParam
case "tail":
svg, err = media.GetTailSVG(customizationName)
shouldFlip = !flippedParam
}
if err != nil {
if err == media.ErrNotFound {
handleError(w, r, err, http.StatusNotFound)
} else {
handleError(w, r, err, http.StatusInternalServerError)
}
return
}
svg = media.CustomizeSnakeSVG(svg, customizationColor, shouldFlip)
w.Header().Set("Content-Type", "image/svg+xml")
fmt.Fprint(w, svg)
}
func handleASCIIFrame(w http.ResponseWriter, r *http.Request) {
gameID := pat.Param(r, "game")
engineURL := r.URL.Query().Get("engine_url")
frameID, err := strconv.Atoi(pat.Param(r, "frame"))
if err != nil {
handleBadRequest(w, r, err)
return
}
game, err := engine.GetGame(gameID, engineURL)
if err != nil {
if errors.Is(err, engine.ErrNotFound) {
handleError(w, r, err, http.StatusNotFound)
} else {
handleError(w, r, err, http.StatusInternalServerError)
}
return
}
gameFrame, err := engine.GetGameFrame(game.ID, engineURL, frameID)
if err != nil {
if errors.Is(err, engine.ErrNotFound) {
handleError(w, r, err, http.StatusNotFound)
} else {
handleError(w, r, err, http.StatusInternalServerError)
}
return
}
if err = render.GameFrameToASCII(w, game, gameFrame); err != nil {
handleError(w, r, err, http.StatusInternalServerError)
return
}
}
// validateDimensionsForBoard checks whether the width/height is valid for the given board width/height.
func validateDimensionsForBoard(game *engine.Game, w, h int) error {
// handle the legacy case where w/h are 0
if w == 0 || h == 0 {
return nil
}
b := int(render.BoardBorder * 2)
options := make([]string, 0, len(allowedPixelsPerSquare)) // used to build a helpful error message
for _, r := range allowedPixelsPerSquare {
// should match one of the allowed resolutions
aw := (game.Width*r + b)
ah := (game.Height*r + b)
options = append(options, fmt.Sprintf("%dx%d", aw, ah))
if aw == w && ah == h {
return nil
}
}
return fmt.Errorf("Dimensions %dx%d invalid - valid options are: %s", w, h, strings.Join(options, ", "))
}
func handleGIFFrameDimensions(w http.ResponseWriter, r *http.Request) {
width, height, err := getGameDimensions(r)
if err != nil {
handleBadRequest(w, r, err)
return
}
handleGIFFrameCommon(w, r, width, height)
}
func handleGIFFrame(w http.ResponseWriter, r *http.Request) {
handleGIFFrameCommon(w, r, 0, 0)
}
func handleGIFFrameCommon(w http.ResponseWriter, r *http.Request, width, height int) {
gameID := pat.Param(r, "game")
frameID, err := strconv.Atoi(pat.Param(r, "frame"))
if err != nil {
handleBadRequest(w, r, err)
return
}
log.Infof("exporting frame %s:%d", gameID, frameID)
engineURL := r.URL.Query().Get("engine_url")
game, err := engine.GetGame(gameID, engineURL)
if err != nil {
if errors.Is(err, engine.ErrNotFound) {
handleError(w, r, err, http.StatusNotFound)
} else {
handleError(w, r, err, http.StatusInternalServerError)
}
return
}
err = validateDimensionsForBoard(game, width, height)
if err != nil {
handleBadRequest(w, r, err)
return
}
gameFrame, err := engine.GetGameFrame(game.ID, engineURL, frameID)
if err != nil {
if errors.Is(err, engine.ErrNotFound) {
handleError(w, r, err, http.StatusNotFound)
} else {
handleError(w, r, err, http.StatusInternalServerError)
}
return
}
w.Header().Set("Content-Type", "image/gif")
if err = render.GameFrameToGIF(w, game, gameFrame, width, height); err != nil {
handleError(w, r, err, http.StatusInternalServerError)
return
}
}
func getGameDimensions(r *http.Request) (int, int, error) {
sizeParam := pat.Param(r, "size")
width, height, err := parseSizeParam(sizeParam)
if err != nil {
return 0, 0, err
}
// ensure width/height are within allowable limits
err = validateGIFSize(width, height)
if err != nil {
return 0, 0, err
}
return width, height, nil
}
func handleGIFGameDimensions(w http.ResponseWriter, r *http.Request) {
width, height, err := getGameDimensions(r)
if err != nil {
handleBadRequest(w, r, err)
return
}
handleCommonGIFGame(w, r, width, height)
}
func handleGIFGame(w http.ResponseWriter, r *http.Request) {
handleCommonGIFGame(w, r, 0, 0)
}
func handleCommonGIFGame(w http.ResponseWriter, r *http.Request, width, height int) {
gameID := pat.Param(r, "game")
engineURL := r.URL.Query().Get("engine_url")
log.WithField("game", gameID).WithField("engine_url", engineURL).Info("rendering gif for game")
game, err := engine.GetGame(gameID, engineURL)
if err != nil {
if errors.Is(err, engine.ErrNotFound) {
handleError(w, r, err, http.StatusNotFound)
} else {
handleError(w, r, err, http.StatusInternalServerError)
}
return
}
err = validateDimensionsForBoard(game, width, height)
if err != nil {
handleBadRequest(w, r, err)
return
}
offset := 0
limit := math.MaxInt32
frames := strings.Split(r.URL.Query().Get("frames"), "-")
if len(frames) == 2 {
valOne, errOne := strconv.Atoi(frames[0])
valTwo, errTwo := strconv.Atoi(frames[1])
if errOne != nil || errTwo != nil {
handleBadRequest(w, r, fmt.Errorf("invalid frames parameter: %s", r.URL.Query().Get("frames")))
}
offset = valOne
limit = valTwo - valOne + 1
}
gameFrames, err := engine.GetGameFrames(game.ID, engineURL, offset, limit)
if err != nil {
if errors.Is(err, engine.ErrNotFound) {
handleError(w, r, err, http.StatusNotFound)
} else {
handleError(w, r, err, http.StatusInternalServerError)
}
return
}
frameDelay, err := strconv.Atoi(r.URL.Query().Get("frameDelay"))
if err != nil {
frameDelay = render.GIFFrameDelay
}
loopDelay, err := strconv.Atoi(r.URL.Query().Get("loopDelay"))
if err != nil {
loopDelay = render.GIFLoopDelay
}
w.Header().Set("Content-Type", "image/gif")
err = render.GameFramesToAnimatedGIF(w, game, gameFrames, frameDelay, loopDelay, width, height)
if err != nil {
handleError(w, r, err, http.StatusInternalServerError)
return
}
}
func handleBadRequest(w http.ResponseWriter, r *http.Request, e error) {
w.WriteHeader(http.StatusBadRequest)
_, err := w.Write([]byte(e.Error()))
if err != nil {
log.WithError(err).Error("unable to write to response stream")
}
}
func handleError(w http.ResponseWriter, r *http.Request, err error, statusCode int) {
log.WithError(err).
WithFields(log.Fields{
"httpRequest": map[string]interface{}{
"method": r.Method,
"url": r.URL.String(),
"userAgent": r.Header.Get("User-Agent"),
"referrer": r.Header.Get("Referer"),
},
}).Error("unable to process request")
w.WriteHeader(statusCode)
if _, err := w.Write([]byte(err.Error())); err != nil {
log.WithError(err).Error("unable to write to response stream")
}
}
func handleAlive(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "alive")
}
func handleReady(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "ready")
}
var sizeRegex = regexp.MustCompile(`^(\d+)x(\d+)$`)
// validateGIFSize checks that the dimension of the GIF is within a safe range that we can allow.
func validateGIFSize(w, h int) error {
// ensure the max resolution is not exceeded
res := w * h
if res > maxGIFResolution {
return fmt.Errorf(`Too many pixels! Dimensions %dx%d having resolution %d exceeds maximum allowable resolution of %d.`, w, h, res, maxGIFResolution)
}
// ensure the minimum dimensions are met
if w < 0 {
return fmt.Errorf(`Invalid width %d: cannot be < 0.`, w)
}
// ensure the minimum dimensions are met
if h < 0 {
return fmt.Errorf(`Invalid height %d: cannot be < 0`, h)
}
return nil
}
// parseSizeParam parses a path parameter that is expected to be in the form "<WIDTH>x<HEIGHT>".
// If the size param is empty, 0,0 is returned.
func parseSizeParam(param string) (int, int, error) {
// check for legacy case where size params are not included
if param == "" {
return 0, 0, nil
}
m := sizeRegex.FindStringSubmatch(param)
if len(m) != 3 {
return 0, 0, fmt.Errorf(`Invalid dimensions: "%s" not of the format <WIDTH>x<HEIGHT>.`, param)
}
w, err := strconv.Atoi(m[1])
if err != nil {
return 0, 0, err
}
h, err := strconv.Atoi(m[2])
if err != nil {
return 0, 0, err
}
return w, h, nil
}