~evanj/cms

ref: 41bddf091e571b359b94d1f4287ccb471fb29d03 cms/internal/c/contenttype/contenttype.go -rw-r--r-- 9.9 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
package contenttype

import (
	"fmt"
	"log"
	"net/http"
	"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/s/db"
	"git.sr.ht/~evanj/cms/internal/s/tmpl"
)

var (
	contenttypeHTML = tmpl.MustParse("html/contenttype.html")
)

type ContentType struct {
	*c.Controller
	log *log.Logger
	db  dber
}

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)
	ContentTypeNew(space space.Space, name string, params []db.ContentTypeNewParam) (contenttype.ContentType, error)
	ContentTypeGet(space space.Space, contenttypeID string) (contenttype.ContentType, error)
	ContentTypeUpdate(space space.Space, contenttype contenttype.ContentType, name string, newParams []db.ContentTypeNewParam, updateParams []db.ContentTypeUpdateParam) (contenttype.ContentType, error)
	ContentTypeDelete(space space.Space, ct contenttype.ContentType) error
	ContentTypeSearch(space space.Space, query string, perPage, before, after int) (contenttype.ContentTypeList, error)
	ContentPerContentType(space space.Space, ct contenttype.ContentType, perPage, before, after int, order db.OrderType, sortField string) (content.ContentList, error)
}

func New(log *log.Logger, db dber) *ContentType {
	return &ContentType{c.New(log, db), log, db}
}

func (c *ContentType) tree(w http.ResponseWriter, r *http.Request) (user.User, space.Space, error) {
	user, err := c.GetCookieUser(w, r)
	if err != nil {
		return nil, nil, fmt.Errorf("must be logged in to perform this action")
	}

	spaceID := r.FormValue("space")
	space, err := c.db.SpaceGet(user, spaceID)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to retrieve space for id %s", spaceID)
	}

	return user, space, nil
}

func (c *ContentType) create(w http.ResponseWriter, r *http.Request) {
	name := r.FormValue("name")

	i := 1
	for key := range r.Form {
		if strings.Contains(key, "field_type_") || strings.Contains(key, "field_name_") {
			i++
		}
	}

	var params []db.ContentTypeNewParam
	for e := 0; e < (i / 2); e++ {
		keyName := fmt.Sprintf("field_name_%d", e+1)
		keyType := fmt.Sprintf("field_type_%d", e+1)
		valName := r.FormValue(keyName)
		valType := r.FormValue(keyType)
		if valName == "" || valType == "" {
			c.Error(w, r, http.StatusBadRequest, "form has malformed data")
			return
		}
		params = append(params, db.ContentTypeNewParam{
			Name: valName,
			Type: valType,
		})
	}

	if len(params) < 1 {
		c.Error(w, r, http.StatusBadRequest, "contenttype must have at least one field")
		return
	}

	// Enforce content always has a value for value type of "name"
	hasName := false
	for _, p := range params {
		if p.Name == "name" {
			hasName = true
		}
	}
	if !hasName {
		c.Error(w, r, http.StatusInternalServerError, "must have field of \"name\" for searchability")
		return
	}

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

	ct, err := c.db.ContentTypeNew(space, name, params)
	if err != nil {
		c.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, "failed to create contenttype")
		return
	}

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

func (c *ContentType) update(w http.ResponseWriter, r *http.Request) {
	name := r.FormValue("name")
	ctID := r.FormValue("contenttype")

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

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

	// Gather new params.

	i := 1
	for key := range r.Form {
		if strings.Contains(key, "field_type_") || strings.Contains(key, "field_name_") {
			i++
		}
	}

	var newParams []db.ContentTypeNewParam
	for e := 0; e < (i / 2); e++ {
		keyName := fmt.Sprintf("field_name_%d", e+2)
		keyType := fmt.Sprintf("field_type_%d", e+2)
		valName := r.FormValue(keyName)
		valType := r.FormValue(keyType)
		if valName == "" || valType == "" {
			c.Error(w, r, http.StatusBadRequest, "form has malformed data")
			return
		}
		newParams = append(newParams, db.ContentTypeNewParam{
			Name: valName,
			Type: valType,
		})
	}

	// Gather updated params.

	var updateParams []db.ContentTypeUpdateParam
	for e := 0; e < len(old.Fields()); e++ {
		keyID := fmt.Sprintf("field_update_id_%d", e+1)
		keyName := fmt.Sprintf("field_update_name_%d", e+1)
		keyType := fmt.Sprintf("field_update_type_%d", e+1)
		valID := r.FormValue(keyID)
		valName := r.FormValue(keyName)
		valType := r.FormValue(keyType)

		if valName == "" && valType == "" && valID == "" {
			continue // We're removing a field.
		}

		if valName == "" || valType == "" || valID == "" {
			c.Error(w, r, http.StatusBadRequest, "form has malformed data")
			return
		}

		updateParams = append(updateParams, db.ContentTypeUpdateParam{
			ID:   valID,
			Name: valName,
			Type: valType,
		})
	}

	if len(updateParams) < 1 {
		c.Error(w, r, http.StatusBadRequest, "contenttype must have at least one field")
		return
	}

	// Enforce content always has a value for value type of "name"
	hasName := false
	for _, p := range updateParams {
		if p.Name == "name" {
			hasName = true
		}
	}
	if !hasName {
		c.Error(w, r, http.StatusInternalServerError, "must have field of \"name\" for searchability")
		return
	}

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

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

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

func (c *ContentType) serve(w http.ResponseWriter, r *http.Request, spaceID, contenttypeID string) {
	user, err := c.GetCookieUser(w, r)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, "must be logged in")
		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 desired contenttype")
		return
	}

	// How to order by.
	var o db.OrderType
	switch r.FormValue("order") {
	case "asc":
		o = db.OrderAsc
	case "desc":
		o = db.OrderDesc
	case "":
		o = db.OrderAsc
	default:
		c.Error(w, r, http.StatusBadRequest, "invalid order value")
		return
	}

	// Order by this field.
	f := r.FormValue("field")
	if f == "" {
		f = "name" // All guaranteed to have.
	}

	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.ContentPerContentType(space, ct, perpage, before, after, o, f)
	if err != nil {
		c.log.Println(err)
		c.Error(w, r, http.StatusInternalServerError, "failed to find content for contenttype")
		return
	}

	c.HTML(w, r, contenttypeHTML, map[string]interface{}{
		"User":        user,
		"Space":       space,
		"ContentType": ct,
		"ContentList": list,
	})
}

func (c *ContentType) delete(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, "must be logged in to create contenttype")
		return
	}

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

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

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

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

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

	user, err := c.GetCookieUser(w, r)
	if err != nil {
		c.Error(w, r, http.StatusBadRequest, "must be logged in to create contenttype")
		return
	}

	space, err := c.db.SpaceGet(user, spaceID)
	if err != nil {
		c.Error(w, r, http.StatusInternalServerError, "failed to find desired space")
		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.ContentTypeSearch(space, query, perpage, before, after)
	if err != nil {
		c.Error(w, r, http.StatusInternalServerError, "failed to find desired contenttype")
		return
	}

	c.JSON(w, r, list)
}

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

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

	http.NotFound(w, r)
}