~evanj/cms

ref: 41bddf091e571b359b94d1f4287ccb471fb29d03 cms/internal/c/content/content.go -rw-r--r-- 12.0 KiB
41bddf09Evan M Jones WIP(perPage/after): Testing to see if this is viable. 4 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
package content

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"strings"

	"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/s/tmpl"
)

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

	ErrNoLogin = errors.New("must be logged in")
)

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

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

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

type Hooker interface {
	Do(space space.Space, content content.Content, ht webhook.HookType)
}

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

func (c *Content) upload(ctx context.Context, filename string, file io.Reader) (string, error) {
	raw, err := c.e3.Upload(ctx, false, filename, file)
	if err != nil {
		return "", err
	}

	val, err := url.Parse(raw)
	if err != nil {
		return "", err
	}

	return c.baseURL + "/file" + val.Path, 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, ErrNoLogin
	}

	space, err := c.db.SpaceGet(user, spaceID)
	if err != nil {
		return nil, nil, nil, nil, fmt.Errorf("failed to find required space")
	}

	ct, err := c.db.ContentTypeGet(space, contenttypeID)
	if err != nil {
		return nil, nil, nil, nil, fmt.Errorf("failed to find required contenttype")
	}

	content, err := c.db.ContentGet(space, ct, contentID)
	if err != nil {
		return nil, nil, nil, nil, fmt.Errorf("failed to find required content")
	}

	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, ErrNoLogin.Error())
		return
	}

	space, err := c.db.SpaceGet(user, spaceID)
	if err != nil {
		c.Error(w, r, http.StatusInternalServerError, "failed to find required space")
		return
	}

	ct, err := c.db.ContentTypeGet(space, contenttypeID)
	if err != nil {
		c.Error(w, r, http.StatusInternalServerError, "failed to find required contenttype")
		return
	}

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

		parts := strings.Split(key, "-")
		if len(parts) < 2 {
			c.Error(w, r, http.StatusInternalServerError, "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,
		})
	}

	// TODO: Upload concurrently.
	_, _, _ = r.FormFile("") // Dummy read, loads internal r.MulitpartForm state.
	for key := range r.MultipartForm.File {
		file, header, err := r.FormFile(key)
		if err != nil {
			c.Error(w, r, http.StatusInternalServerError, "failed to retreive file")
			return
		}

		url, err := c.upload(r.Context(), header.Filename, file)
		if err != nil {
			c.log.Println("failed to upload file", err)
			c.Error(w, r, http.StatusInternalServerError, "failed to upload file")
			return
		}

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

		typ, name := parts[0], parts[1]

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

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

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

	url := fmt.Sprintf("/content/%s/%s/%s", space.ID(), ct.ID(), content.ID())
	c.log.Println("successfully created new content for user", user.Name(), "in space", space.Name(), "for contenttype", ct.Name(), "redirecting to", url)
	http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

func (c *Content) serve(w http.ResponseWriter, r *http.Request, spaceID, contenttypeID, contentID string) {
	user, err := c.GetCookieUser(w, r)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, ErrNoLogin.Error())
		return
	}

	space, err := c.db.SpaceGet(user, spaceID)
	if err != nil {
		c.Error(w, r, http.StatusInternalServerError, "failed to find required space")
		return
	}

	ct, err := c.db.ContentTypeGet(space, contenttypeID)
	if err != nil {
		c.Error(w, r, http.StatusInternalServerError, "failed to find required contenttype")
		return
	}

	content, err := c.db.ContentGet(space, ct, contentID)
	if err != nil {
		c.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, "failed to find desired content")
		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.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, err.Error())
		return
	}

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

	for key := range r.Form {
		if key == "space" || key == "contenttype" || key == "content" {
			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, "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, "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,
		})
	}

	// TODO: Upload concurrently.
	_, _, _ = r.FormFile("") // Dummy read, loads internal r.MulitpartForm state.
	for key := range r.MultipartForm.File {
		file, header, err := r.FormFile(key)
		if err != nil {
			c.Error(w, r, http.StatusInternalServerError, "failed to retreive file")
			return
		}

		url, err := c.upload(r.Context(), header.Filename, file)
		if err != nil {
			c.log.Println("failed to upload file", err)
			c.Error(w, r, http.StatusInternalServerError, "failed to upload file")
			return
		}

		// Check if we're update image value.
		if strings.Contains(key, "value_update_") {

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

			_, id := parts[0], parts[1]

			updateParams = append(updateParams, db.ContentUpdateParam{
				ID:    id,
				Type:  valuetype.File,
				Value: url,
			})

			continue
		}

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

		typ, name := parts[0], parts[1]

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

	content, err = c.db.ContentUpdate(space, ct, content, newParams, updateParams)
	if err != nil {
		c.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, "failed to update content")
		return
	}

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

	url := fmt.Sprintf("/content/%s/%s/%s", space.ID(), ct.ID(), content.ID())
	c.log.Println("successfully updated content for user", user.Name(), "in space", space.Name(), "for contenttype", ct.Name(), "redirecting to", url)
	http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

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.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, err.Error())
		return
	}

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

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

	url := fmt.Sprintf("/contenttype/%s/%s", space.ID(), ct.ID())
	c.log.Println("successfully deleted content for user", user.Name(), "in space", space.Name(), "for contenttype", ct.Name(), "redirecting to", url)
	http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

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.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, ErrNoLogin.Error())
		return
	}

	space, err := c.db.SpaceGet(user, spaceID)
	if err != nil {
		c.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, "failed to find required space")
		return
	}

	ct, err := c.db.ContentTypeGet(space, contenttypeID)
	if err != nil {
		c.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, "failed to find required contenttype")
		return
	}

	perpage, _ := strconv.Atoi(r.URL.Query().Get("perpage"))
	before, _ := strconv.Atoi(r.URL.Query().Get("before"))
	after, _ := strconv.Atoi(r.URL.Query().Get("after"))

	list, err := c.db.ContentSearch(space, ct, field, query, perpage, before, after)
	if err != nil {
		c.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, "failed to find desired content")
		return
	}

	c.JSON(w, r, list)
}

func (c *Content) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch r.URL.Path {
	case "/content/new":
		c.create(w, r)
		return
	case "/content/update":
		c.update(w, r)
		return
	case "/content/delete":
		c.delete(w, r)
		return
	case "/content/search":
		c.search(w, r)
		return
	}

	parts := strings.Split(r.URL.Path, "/")
	if len(parts) > 4 {
		c.serve(w, r, parts[2], parts[3], parts[4])
		return
	}

	http.NotFound(w, r)
}