~evanj/cms

ref: 26671b0ca2b523aebded55a95b2f6601db011825 cms/internal/c/content/content.go -rw-r--r-- 12.6 KiB
26671b0cEvan J Feat(file.go): Upload files concurrently complete. Fixed bug in E3 path 2 months ago
                                                                                
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
package content

import (
	"context"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"

	"git.sr.ht/~evanj/cms/internal/c"
	"git.sr.ht/~evanj/cms/internal/m/content"
	"git.sr.ht/~evanj/cms/internal/m/contenttype"
	"git.sr.ht/~evanj/cms/internal/m/space"
	"git.sr.ht/~evanj/cms/internal/m/user"
	"git.sr.ht/~evanj/cms/internal/m/valuetype"
	"git.sr.ht/~evanj/cms/internal/s/db"
	webhook "git.sr.ht/~evanj/cms/internal/s/hook"
	"git.sr.ht/~evanj/cms/internal/v"
	"github.com/pkg/errors"
)

var (
	contentHTML = v.MustParse("html/content.html")

	ErrNoLogin = c.ErrNoLogin
	ErrNoSpace = errors.New("failed to find required space")
	ErrNoCT    = errors.New("failed to find required contenttype")
	ErrNoC     = errors.New("failed to find desired content")
)

// bgctx is used to send requests to external servers outside of
// request/response handling. External server requests have a timeout of ten
// seconds.
func bgctx() context.Context {
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	return ctx
}

type Content struct {
	*c.Controller
	log     *log.Logger
	db      dber
	e3      E3er
	hook    Hooker
	baseURL string
}

type dber interface {
	UserGet(ctx context.Context, username, password string) (user.User, error)
	UserGetFromToken(ctx context.Context, token string) (user.User, error)
	SpaceGet(ctx context.Context, user user.User, spaceID string) (space.Space, error)
	ContentTypeGet(ctx context.Context, u user.User, space space.Space, contenttypeID string) (contenttype.ContentType, error)
	ContentNew(ctx context.Context, u user.User, space space.Space, ct contenttype.ContentType, params []db.ContentNewParam) (content.Content, error)
	ContentGet(ctx context.Context, u user.User, space space.Space, ct contenttype.ContentType, contentID string) (content.Content, error)
	ContentUpdate(ctx context.Context, u user.User, space space.Space, ct contenttype.ContentType, c content.Content, newParams []db.ContentNewParam, updateParams []db.ContentUpdateParam) (content.Content, error)
	ContentDelete(ctx context.Context, u user.User, space space.Space, ct contenttype.ContentType, c content.Content) error
	ContentSearch(ctx context.Context, u user.User, space space.Space, ct contenttype.ContentType, name, query string, before int) (content.ContentList, error)
}

type E3er interface {
	Upload(ctx context.Context, public bool, filename string, file io.Reader) (string, error)
}

type Hooker interface {
	Do(ctx context.Context, user user.User, space space.Space, content content.Content, ht webhook.HookType)
}

func New(c *c.Controller, log *log.Logger, db dber, e3 E3er, hook Hooker, baseURL string) *Content {
	return &Content{
		c,
		log,
		db,
		e3,
		hook,
		baseURL,
	}
}

type fileSet struct {
	key, url string
}

func upload(ctx context.Context, e3 E3er, r *http.Request, file multipart.File, header *multipart.FileHeader, baseURL, key string, c chan fileSet, e chan error) {
	raw, err := e3.Upload(ctx, false, header.Filename, file)
	if err != nil {
		e <- fmt.Errorf("failed to upload file: %w", err)
		return
	}

	val, err := url.Parse(raw)
	if err != nil {
		e <- fmt.Errorf("failed to upload file: %w", err)
		return
	}

	url := baseURL + "/file" + val.Path

	c <- fileSet{key, url}
}

func uploadFileSets(e3 E3er, baseURL string, r *http.Request, u user.User) ([]fileSet, error) {
	_, _, _ = r.FormFile("") // Dummy read, loads internal r.MulitpartForm state.

	if r.MultipartForm == nil {
		// No work to do.
		return []fileSet{}, nil
	}

	var (
		fs  []fileSet
		ctx = r.Context()
		l   = len(r.MultipartForm.File)
		c   = make(chan fileSet, l)
		e   = make(chan error, l)
	)

	for key := range r.MultipartForm.File {
		file, header, err := r.FormFile(key)
		if err != nil {
			return []fileSet{}, err
		}
		go upload(ctx, e3, r, file, header, baseURL, key, c, e)
	}

	for {
		select {
		case <-ctx.Done():
			return []fileSet{}, ctx.Err()
		case err := <-e:
			return []fileSet{}, err
		case f := <-c:
			fs = append(fs, f)
			if len(fs) == l {
				// Done.
				return fs, nil
			}
		}
	}
}

func (c *Content) tree(w http.ResponseWriter, r *http.Request, spaceID, contenttypeID, contentID string) (user.User, space.Space, contenttype.ContentType, content.Content, error) {
	user, err := c.GetCookieUser(w, r)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	space, err := c.db.SpaceGet(r.Context(), user, spaceID)
	if err != nil {
		return nil, nil, nil, nil, ErrNoSpace
	}

	ct, err := c.db.ContentTypeGet(r.Context(), user, space, contenttypeID)
	if err != nil {
		return nil, nil, nil, nil, ErrNoCT
	}

	content, err := c.db.ContentGet(r.Context(), user, space, ct, contentID)
	if err != nil {
		return nil, nil, nil, nil, ErrNoC
	}

	return user, space, ct, content, nil
}

func (c *Content) create(w http.ResponseWriter, r *http.Request) {
	spaceID := r.FormValue("space")
	contenttypeID := r.FormValue("contenttype")

	user, err := c.GetCookieUser(w, r)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, err)
		return
	}

	space, err := c.db.SpaceGet(r.Context(), user, spaceID)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, errors.Wrap(err, ErrNoSpace.Error()))
		return
	}

	ct, err := c.db.ContentTypeGet(r.Context(), user, space, contenttypeID)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, errors.Wrap(err, ErrNoCT.Error()))
		return
	}

	var params []db.ContentNewParam
	for key := range r.Form {
		if key == "space" || key == "contenttype" || key == "method" {
			continue
		}

		parts := strings.Split(key, "-")
		if len(parts) < 2 {
			c.Error(w, r, http.StatusInternalServerError, errors.New("invalid name field for value"))
			return
		}

		typ, name, val := parts[0], parts[1], r.FormValue(key)
		if typ == valuetype.File {
			continue
		}

		params = append(params, db.ContentNewParam{
			Type:  typ,
			Name:  name,
			Value: val,
		})
	}

	// Upload files concurrently.
	fileSets, err := uploadFileSets(c.e3, c.baseURL, r, user)
	if err != nil {
		c.Error(w, r, http.StatusInternalServerError, err)
		return
	}
	for _, fileSet := range fileSets {
		parts := strings.Split(fileSet.key, "-")
		if len(parts) < 2 {
			c.Error(w, r, http.StatusInternalServerError, errors.New("invalid name field for value"))
			return
		}
		params = append(params, db.ContentNewParam{
			Type:  parts[0],
			Name:  parts[1],
			Value: fileSet.url,
		})
	}

	content, err := c.db.ContentNew(r.Context(), user, space, ct, params)
	if err != nil {
		c.Error(w, r, http.StatusInternalServerError, err)
		return
	}

	go c.hook.Do(bgctx(), user, space, content, webhook.HookNew)

	url := fmt.Sprintf("/content/%s/%s/%s", space.ID(), ct.ID(), content.ID())
	c.Redirect(w, r, url)
}

func (c *Content) serve(w http.ResponseWriter, r *http.Request) {
	spaceID := r.FormValue("space")
	contenttypeID := r.FormValue("contenttype")
	contentID := r.FormValue("content")

	parts := strings.Split(r.URL.Path, "/")
	if len(parts) > 4 {
		spaceID = parts[2]
		contenttypeID = parts[3]
		contentID = parts[4]
	}

	user, err := c.GetCookieUser(w, r)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, err)
		return
	}

	space, err := c.db.SpaceGet(r.Context(), user, spaceID)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, errors.Wrap(err, ErrNoSpace.Error()))
		return
	}

	ct, err := c.db.ContentTypeGet(r.Context(), user, space, contenttypeID)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, errors.Wrap(err, ErrNoCT.Error()))
		return
	}

	content, err := c.db.ContentGet(r.Context(), user, space, ct, contentID)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, errors.Wrap(err, ErrNoC.Error()))
		return
	}

	c.HTML(w, r, contentHTML, map[string]interface{}{
		"User":        user,
		"Space":       space,
		"ContentType": ct,
		"Content":     content,
	})
}

func (c *Content) update(w http.ResponseWriter, r *http.Request) {
	spaceID := r.FormValue("space")
	contenttypeID := r.FormValue("contenttype")
	contentID := r.FormValue("content")

	user, space, ct, content, err := c.tree(w, r, spaceID, contenttypeID, contentID)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, err)
		return
	}

	var newParams []db.ContentNewParam
	var updateParams []db.ContentUpdateParam

	for key := range r.Form {
		if key == "space" || key == "contenttype" || key == "content" || key == "method" {
			continue
		}

		// Man, there must be a better way.
		// All this form nonsense is driving me insane.

		// Check if new param of update param
		if strings.Contains(key, "value_update_") {

			parts := strings.Split(strings.ReplaceAll(key, "value_update_", ""), "-")
			if len(parts) < 2 {
				c.Error(w, r, http.StatusInternalServerError, errors.New("invalid name field for value"))
				return
			}

			typ, id, val := parts[0], parts[1], r.FormValue(key)
			if typ == valuetype.File && strings.TrimSpace(val) == "" {
				// Don't update empty file fields.
				continue
			}

			updateParams = append(updateParams, db.ContentUpdateParam{
				ID:    id,
				Type:  typ,
				Value: val,
			})

			continue
		}

		// Now we're a new value.

		parts := strings.Split(key, "-")
		if len(parts) < 2 {
			c.Error(w, r, http.StatusInternalServerError, errors.New("invalid name field for value"))
			return
		}

		typ, name, val := parts[0], parts[1], r.FormValue(key)
		if typ == valuetype.File {
			continue
		}

		newParams = append(newParams, db.ContentNewParam{
			Type:  typ,
			Name:  name,
			Value: val,
		})
	}

	// Upload files concurrently.
	fileSets, err := uploadFileSets(c.e3, c.baseURL, r, user)
	if err != nil {
		c.Error(w, r, http.StatusInternalServerError, err)
		return
	}
	for _, fileSet := range fileSets {
		// Check if we're update file value.
		if strings.Contains(fileSet.key, "value_update_") {
			parts := strings.Split(strings.ReplaceAll(fileSet.key, "value_update_", ""), "-")
			if len(parts) < 2 {
				c.Error(w, r, http.StatusInternalServerError, errors.New("invalid name field for value"))
				return
			}
			updateParams = append(updateParams, db.ContentUpdateParam{
				ID:    parts[1], // ID
				Type:  valuetype.File,
				Value: fileSet.url,
			})
			continue
		}
		// This is a new file value.
		parts := strings.Split(fileSet.key, "-")
		if len(parts) < 2 {
			c.Error(w, r, http.StatusInternalServerError, errors.New("invalid name field for value"))
			return
		}
		newParams = append(newParams, db.ContentNewParam{
			Type:  parts[0],
			Name:  parts[1],
			Value: fileSet.url,
		})
	}

	content, err = c.db.ContentUpdate(r.Context(), user, space, ct, content, newParams, updateParams)
	if err != nil {
		c.Error(w, r, http.StatusInternalServerError, fmt.Errorf("failed to update content: %w", err))
		return
	}

	go c.hook.Do(bgctx(), user, space, content, webhook.HookUpdate)

	url := fmt.Sprintf("/content/%s/%s/%s", space.ID(), ct.ID(), content.ID())
	c.Redirect(w, r, url)
}

func (c *Content) delete(w http.ResponseWriter, r *http.Request) {
	spaceID := r.FormValue("space")
	contenttypeID := r.FormValue("contenttype")
	contentID := r.FormValue("content")

	user, space, ct, content, err := c.tree(w, r, spaceID, contenttypeID, contentID)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, err)
		return
	}

	if err := c.db.ContentDelete(r.Context(), user, space, ct, content); err != nil {
		c.Error(w, r, http.StatusInternalServerError, fmt.Errorf("failed to delete content: %w", err))
		return
	}

	go c.hook.Do(bgctx(), user, space, content, webhook.HookDelete)

	url := fmt.Sprintf("/contenttype/%s/%s", space.ID(), ct.ID())
	c.Redirect(w, r, url)
}

func (c *Content) search(w http.ResponseWriter, r *http.Request) {
	spaceID := r.FormValue("space")
	contenttypeID := r.FormValue("contenttype")
	query := r.FormValue("query")
	field := r.FormValue("field")

	if field == "" {
		field = "name"
	}

	user, err := c.GetCookieUser(w, r)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, err)
		return
	}

	space, err := c.db.SpaceGet(r.Context(), user, spaceID)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, errors.Wrap(err, ErrNoSpace.Error()))
		return
	}

	ct, err := c.db.ContentTypeGet(r.Context(), user, space, contenttypeID)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, errors.Wrap(err, ErrNoCT.Error()))
		return
	}

	before, _ := strconv.Atoi(r.URL.Query().Get("before"))
	list, err := c.db.ContentSearch(r.Context(), user, space, ct, field, query, before)
	if err != nil {
		return
	}

	c.JSON(w, r, list)
}

func (c *Content) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch c.Method(r) {
	case "POST":
		c.create(w, r)
		return
	case "PATCH":
		c.update(w, r)
		return
	case "DELETE":
		c.delete(w, r)
		return
	case "GET":
		// Either want to serve a contenttype or search for a contenttype... Decide
		// what to do on presence of FormValue.
		if r.FormValue("query") != "" {
			c.search(w, r)
			return
		}
		c.serve(w, r)
		return
	}

	http.NotFound(w, r)
}