forked from mrdoob/glsl-sandbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
548 lines (464 loc) · 11.8 KB
/
server.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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package server
import (
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"io"
"net/http"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/labstack/gommon/log"
"github.com/mrdoob/glsl-sandbox/server/store"
"golang.org/x/crypto/acme/autocert"
)
const (
pathGallery = "./server/assets/gallery.html"
pathThumbs = "thumbs"
pathCerts = "certs"
perPage = 50
)
var (
ErrInvalidData = fmt.Errorf("invalid data")
)
type Template struct {
templates *template.Template
}
func prepareTemplate() (*template.Template, error) {
tpl := template.New("")
tpl = tpl.Funcs(template.FuncMap{
"checkboxID": func(id int) string {
return fmt.Sprintf("hidden_%d", id)
},
"checked": func(b bool) string {
if b {
return "checked"
}
return ""
},
})
tpl, err := tpl.ParseFiles(pathGallery)
if err != nil {
fmt.Println("template error", err.Error())
return nil, err
}
return tpl, nil
}
func (t *Template) Render(
w io.Writer, name string, data interface{}, c echo.Context,
) error {
tpl := t.templates
if tpl == nil {
var err error
tpl, err = prepareTemplate()
if err != nil {
return err
}
}
return tpl.ExecuteTemplate(w, name, data)
}
type Server struct {
addr string
tlsAddr string
domains []string
echo *echo.Echo
template *Template
effects *store.Effects
auth *Auth
dataPath string
}
func New(
addr string,
tlsAddr string,
domains string,
e *store.Effects,
auth *Auth,
dataPath string,
dev bool,
) (*Server, error) {
var tpl *template.Template
if !dev {
var err error
tpl, err = prepareTemplate()
if err != nil {
return nil, err
}
}
if tlsAddr != "" && domains == "" {
return nil, fmt.Errorf("cannot specify TLS_ADDR without DOMAINS")
}
return &Server{
addr: addr,
tlsAddr: tlsAddr,
domains: strings.Split(domains, ","),
echo: echo.New(),
template: &Template{
templates: tpl,
},
effects: e,
auth: auth,
dataPath: dataPath,
}, nil
}
func (s *Server) Start() error {
err := s.setup()
if err != nil {
return err
}
if s.tlsAddr != "" {
go func() {
err := s.echo.Start(s.addr)
s.echo.Logger.Errorf("could not create http server: %s", err.Error())
}()
return s.echo.StartAutoTLS(s.tlsAddr)
}
return s.echo.Start(s.addr)
}
func (s *Server) setup() error {
if s.tlsAddr != "" {
certs := filepath.Join(s.dataPath, pathCerts)
err := os.MkdirAll(certs, 0750)
if err != nil {
return fmt.Errorf("could not create certs directory: %w", err)
}
s.echo.AutoTLSManager.Cache = autocert.DirCache(certs)
s.echo.AutoTLSManager.HostPolicy = autocert.HostWhitelist(s.domains...)
s.echo.Pre(middleware.HTTPSRedirect())
}
s.echo.Use(middleware.Recover())
s.echo.Renderer = s.template
s.echo.Logger.SetLevel(log.DEBUG)
s.echo.Use(middleware.Logger())
s.routes()
return nil
}
func (s *Server) routes() {
s.echo.GET("/", s.indexHandler)
s.echo.GET("/e", s.effectHandler)
s.echo.POST("/e", s.saveHandler)
s.echo.GET("/item/:id", s.itemHandler)
s.echo.Static("/thumbs", filepath.Join(s.dataPath, pathThumbs))
s.echo.Static("/css", "./server/assets/css")
s.echo.Static("/js", "./server/assets/js")
s.echo.File("/diff", "./server/assets/diff.html")
s.echo.File("/login", "./server/assets/login.html")
s.echo.POST("/login", s.loginHandler)
admin := s.echo.Group("/admin")
admin.Use(s.auth.Middleware(func(err error, c echo.Context) error {
c.Logger().Errorf("not authorized: %s", err.Error())
return c.Redirect(http.StatusSeeOther, "/login")
}))
admin.GET("", s.adminHandler)
admin.POST("", s.adminPostHandler)
}
func (s *Server) indexHandler(c echo.Context) error {
return s.indexRender(c, false)
}
func (s *Server) adminHandler(c echo.Context) error {
return s.indexRender(c, true)
}
// galleryEffect has information about each effect displayed in the gallery.
type galleryEffect struct {
// ID is the effect identifyier.
ID int
// Version is the latest effect version.
Version int
// Image holds the thumbnail name.
Image string
// Hidden tells if the effect has been moderated.
Hidden bool
}
// galleryData has information about the current gallery page.
type galleryData struct {
// Effects is an array with all the effects for the page.
Effects []galleryEffect
// URL is the path of the gallery. Can be "/" or "/admin".
URL string
// Page holds the current page number.
Page int
// IsPrevious is true if there is a previous page.
IsPrevious bool
// PreviousPage is the previous page number.
PreviousPage string
// IsNext is true if there is a next page.
IsNext bool
// NextPage is the next page number.
NextPage string
// Admin is true when accessing "/admin" path.
Admin bool
}
func (s *Server) indexRender(c echo.Context, admin bool) error {
pString := c.QueryParam("page")
if pString == "" {
pString = "0"
}
page, err := strconv.Atoi(pString)
if err != nil {
page = 0
}
parent := -1
if c.QueryParam("parent") != "" {
parent, err = strconv.Atoi(c.QueryParam("parent"))
if err != nil {
parent = -1
}
}
var p []store.Effect
if parent > 0 {
p, err = s.effects.PageSiblings(page, perPage, parent)
} else {
p, err = s.effects.Page(page, perPage, admin)
}
if err != nil {
return c.String(http.StatusInternalServerError, "error")
}
effects := make([]galleryEffect, len(p))
for i, e := range p {
effects[i] = galleryEffect{
ID: e.ID,
Version: len(e.Versions) - 1,
Image: path.Join("/thumbs", e.ImageName()),
Hidden: e.Hidden,
}
}
url := "/"
if admin {
url = "/admin"
}
nextPage := fmt.Sprintf("%s?page=%d", url, page+1)
previousPage := fmt.Sprintf("%s?page=%d", url, page-1)
if parent > 0 {
nextPage = fmt.Sprintf("%s&parent=%d", nextPage, parent)
previousPage = fmt.Sprintf("%s&parent=%d", previousPage, parent)
}
d := galleryData{
Effects: effects,
URL: url,
Page: page,
IsNext: len(effects) == perPage,
NextPage: nextPage,
IsPrevious: page > 0,
PreviousPage: previousPage,
Admin: admin,
}
err = c.Render(http.StatusOK, "gallery", d)
if err != nil {
panic(err)
}
return err
}
func (s *Server) effectHandler(c echo.Context) error {
return c.File("./static/index.html")
}
type itemResponse struct {
Code string `json:"code"`
User string `json:"user"`
Parent string `json:"parent,omitempty"`
}
func (s *Server) itemHandler(c echo.Context) error {
param := c.Param("id")
id, version, err := idVersion(param)
if err != nil {
return c.String(http.StatusBadRequest, "{}")
}
effect, err := s.effects.Effect(id)
if err != nil {
return c.String(http.StatusBadRequest, "{}")
}
if version >= len(effect.Versions) || version < 0 {
return c.String(http.StatusNotFound, "{}")
}
parent := ""
if effect.Parent > 0 {
parent = fmt.Sprintf("/e#%d.%d", effect.Parent, effect.ParentVersion)
}
item := itemResponse{
Code: effect.Versions[version].Code,
User: effect.User,
Parent: parent,
}
data, err := json.Marshal(item)
if err != nil {
return c.String(http.StatusInternalServerError, "{}")
}
return c.Blob(http.StatusOK, "application/json", data)
}
type saveQuery struct {
Code string `json:"code"`
Image string `json:"image"`
User string `json:"user"`
CodeID string `json:"code_id"`
Parent string `json:"parent"`
}
func (s *Server) saveHandler(c echo.Context) error {
if c.Request().Body == nil {
c.Logger().Errorf("empty body")
return c.String(http.StatusBadRequest, "")
}
data, err := io.ReadAll(c.Request().Body)
if err != nil {
c.Logger().Errorf("could not read body: %s", err.Error())
return c.String(http.StatusInternalServerError, "")
}
var save saveQuery
err = json.Unmarshal(data, &save)
if err != nil {
c.Logger().Errorf("could not parse json: %s", err.Error())
return c.String(http.StatusBadRequest, "")
}
parts := strings.Split(save.Image, ",")
if len(parts) != 2 {
c.Logger().Errorf("malformed encoded image")
return c.String(http.StatusBadRequest, "")
}
imgData := parts[1]
img, err := base64.StdEncoding.DecodeString(imgData)
if err != nil {
c.Logger().Errorf("could not decode image: %s", err.Error())
return c.String(http.StatusBadRequest, "")
}
var id, version int
if save.CodeID == "" {
parent, parentVersion, err := idVersion(save.Parent)
if err != nil {
parent, parentVersion = -1, -1
}
id, err = s.effects.Add(parent, parentVersion, save.User, save.Code)
if err != nil {
c.Logger().Errorf("could not save new effect: %s", err.Error())
return c.String(http.StatusInternalServerError, "")
}
} else {
parts := strings.Split(save.CodeID, ".")
if len(parts) < 1 {
c.Logger().Errorf("malformed code id: %s", err.Error())
return c.String(http.StatusBadRequest, "")
}
id, err = strconv.Atoi(parts[0])
if err != nil {
c.Logger().Errorf("malformed code id: %s", err.Error())
return c.String(http.StatusBadRequest, "")
}
version, err = s.effects.AddVersion(id, save.Code)
if err != nil {
c.Logger().Errorf("could not save new version: %s", err.Error())
return c.String(http.StatusInternalServerError, "")
}
}
err = saveImage(thumbPath(s.dataPath, id), img)
if err != nil {
c.Logger().Errorf("could not save image: %s", err.Error())
return c.String(http.StatusInternalServerError, "")
}
answer := fmt.Sprintf("%d.%d", id, version)
return c.String(http.StatusOK, answer)
}
func (s *Server) adminPostHandler(c echo.Context) error {
pageTxt := c.FormValue("page")
// TODO(jfontan): check error?
page, _ := strconv.Atoi(pageTxt)
url := fmt.Sprintf("/admin?page=%d", page)
values, err := c.FormParams()
if err != nil {
c.Logger().Errorf("malformed form: %s", err.Error())
return c.Redirect(http.StatusSeeOther, url)
}
on := make(map[int]struct{})
for n, v := range values {
if !strings.HasPrefix(n, "hidden_") {
continue
}
if len(v) != 1 || v[0] != "on" {
continue
}
parts := strings.Split(n, "_")
if len(parts) != 2 {
continue
}
id, err := strconv.Atoi(parts[1])
if err != nil {
continue
}
on[id] = struct{}{}
err = s.effects.Hide(id, true)
if err != nil {
c.Logger().Errorf("could not hide effect: %s", err.Error())
}
}
e := values["effects"]
for _, d := range e {
id, err := strconv.Atoi(d)
if err != nil {
continue
}
if _, ok := on[id]; ok {
continue
}
err = s.effects.Hide(id, false)
if err != nil {
c.Logger().Errorf("could not unhide effect: %s", err.Error())
}
}
return c.Redirect(http.StatusSeeOther, url)
}
type loginData struct {
Name string `form:"name"`
Password string `form:"password"`
}
func (s *Server) loginHandler(c echo.Context) error {
log := c.Logger()
var l loginData
err := c.Bind(&l)
if err != nil {
log.Errorf("malformed form: %s", err.Error())
return c.Redirect(http.StatusSeeOther, "/login")
}
err = s.auth.Login(c, l.Name, l.Password)
if err != nil {
log.Errorf("could not authenticate: %s", err.Error())
return c.Redirect(http.StatusSeeOther, "/login")
}
return c.Redirect(http.StatusSeeOther, "/admin")
}
func thumbPath(dataPath string, id int) string {
return filepath.Join(dataPath, pathThumbs, fmt.Sprintf("%d.png", id))
}
func saveImage(path string, data []byte) error {
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("cannot create thumbnail: %w", err)
}
defer f.Close()
_, err = f.Write(data)
if err != nil {
return fmt.Errorf("cannot write thumbnail: %w", err)
}
return nil
}
func idVersion(param string) (int, int, error) {
var idString, versionString string
parts := strings.Split(strings.TrimPrefix(param, "#"), ".")
switch len(parts) {
case 1:
idString = parts[0]
case 2:
idString = parts[0]
versionString = parts[1]
default:
return 0, 0, ErrInvalidData
}
id, err := strconv.Atoi(idString)
if err != nil {
return 0, 0, ErrInvalidData
}
version, err := strconv.Atoi(versionString)
if err != nil {
return 0, 0, ErrInvalidData
}
return id, version, nil
}