-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlecontent.go
358 lines (303 loc) · 7.93 KB
/
handlecontent.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
package handler
import (
"context"
"encoding/json"
"fmt"
"github.com/gohugonet/hugoverse/internal/domain/content"
"github.com/gohugonet/hugoverse/internal/interfaces/api/query"
"github.com/gohugonet/hugoverse/pkg/db"
"github.com/gohugonet/hugoverse/pkg/form"
"github.com/gohugonet/hugoverse/pkg/timestamp"
"github.com/gorilla/schema"
"log"
"net/http"
"strings"
)
func (s *Handler) ApiContentsHandler(res http.ResponseWriter, req *http.Request) {
q := req.URL.Query()
t := q.Get("type")
if t == "" {
res.WriteHeader(http.StatusBadRequest)
return
}
it, ok := s.contentApp.AllContentTypes()[t]
if !ok {
res.WriteHeader(http.StatusNotFound)
return
}
if hide(res, req, it()) {
return
}
count, err := query.Count(req)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
offset, err := query.Offset(req)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
order := query.Order(req)
opts := db.QueryOptions{
Count: count,
Offset: offset,
Order: order,
}
_, bb := db.Query(t+"__sorted", opts)
var result []json.RawMessage
for i := range bb {
result = append(result, bb[i])
}
j, err := s.res.FmtJSON(result...)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
j, err = omit(res, req, it(), j)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
// assert hookable
get := it()
hook, ok := get.(content.Hookable)
if !ok {
log.Println("[Response] error: Type", t, "does not implement item.Hookable or embed item.Item.")
res.WriteHeader(http.StatusBadRequest)
return
}
// hook before response
j, err = hook.BeforeAPIResponse(res, req, j)
if err != nil {
log.Println("[Response] error calling BeforeAPIResponse:", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
s.res.Json(res, j)
// hook after response
err = hook.AfterAPIResponse(res, req, j)
if err != nil {
log.Println("[Response] error calling AfterAPIResponse:", err)
return
}
}
func (s *Handler) ContentHandler(res http.ResponseWriter, req *http.Request) {
q := req.URL.Query()
id := q.Get("id")
t := q.Get("type")
status := q.Get("status")
if t == "" || id == "" {
res.WriteHeader(http.StatusBadRequest)
return
}
pt, ok := s.contentApp.GetContentCreator(t)
if !ok {
res.WriteHeader(http.StatusNotFound)
return
}
post, err := s.contentApp.GetContent(t, id, status)
if err != nil {
s.log.Errorf("Error getting content: %v", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
if post == nil {
res.WriteHeader(http.StatusNotFound)
s.log.Printf("Content not found: %s %s %s", t, id, status)
return
}
p := pt()
err = json.Unmarshal(post, p)
if err != nil {
s.log.Errorf("Error unmarshalling content: %v", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
if hide(res, req, p) {
return
}
push(res, req, p, post)
j, err := s.res.FmtJSON(json.RawMessage(post))
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
j, err = omit(res, req, p, j)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
// assert hookable
get := p
hook, ok := get.(content.Hookable)
if !ok {
log.Println("[Response] error: Type", t, "does not implement item.Hookable or embed item.Item.")
res.WriteHeader(http.StatusBadRequest)
return
}
// hook before response
j, err = hook.BeforeAPIResponse(res, req, j)
if err != nil {
log.Println("[Response] error calling BeforeAPIResponse:", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
s.res.Json(res, j)
// hook after response
err = hook.AfterAPIResponse(res, req, j)
if err != nil {
log.Println("[Response] error calling AfterAPIResponse:", err)
return
}
}
func (s *Handler) CreateContentHandler(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
res.WriteHeader(http.StatusMethodNotAllowed)
return
}
err := req.ParseMultipartForm(1024 * 1024 * 4) // maxMemory 4MB
if err != nil {
s.log.Errorf("Error parsing multipart form: %v", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
t := req.URL.Query().Get("type")
if t == "" {
res.WriteHeader(http.StatusBadRequest)
return
}
p, found := s.contentApp.AllContentTypes()[t]
if !found {
s.log.Printf("Attempt to submit unknown type: %s from %s", t, req.RemoteAddr)
res.WriteHeader(http.StatusNotFound)
return
}
post := p()
ext, ok := post.(content.Createable)
if !ok {
s.log.Printf("Attempt to create non-createable type: %s from %s", t, req.RemoteAddr)
res.WriteHeader(http.StatusBadRequest)
return
}
ts := timestamp.Now()
req.PostForm.Set("timestamp", ts)
req.PostForm.Set("updated", ts)
urlPaths, err := s.StoreFiles(req)
if err != nil {
s.log.Errorf("Error storing files: %v", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
for name, urlPath := range urlPaths {
req.PostForm.Set(name, urlPath)
}
req.PostForm, err = form.Convert(req.PostForm)
if err != nil {
s.log.Errorf("Error converting form: %v", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
hook, ok := post.(content.Hookable)
if !ok {
s.log.Printf("Attempt to create non-hookable type: %s from %s", t, req.RemoteAddr)
res.WriteHeader(http.StatusBadRequest)
return
}
// Let's be nice and make a proper item for the Hookable methods
dec := schema.NewDecoder()
dec.IgnoreUnknownKeys(true)
dec.SetAliasTag("json")
err = dec.Decode(post, req.PostForm)
if err != nil {
s.log.Printf("Error decoding post form for edit %s handler: %v", t, err)
res.WriteHeader(http.StatusBadRequest)
return
}
err = hook.BeforeAPICreate(res, req)
if err != nil {
s.log.Errorf("Error calling BeforeCreate: %v", err)
return
}
err = ext.Create(res, req)
if err != nil {
s.log.Errorf("Error calling Accept: %v", err)
return
}
err = hook.BeforeSave(res, req)
if err != nil {
s.log.Errorf("Error calling BeforeSave: %v", err)
return
}
// set specifier for db bucket in case content is/isn't Trustable
var spec string
// check if the content is Trustable should be auto-approved, if so the
// content is immediately added to the public content API. If not, then it
// is added to a "pending" list, only visible to Admins in the CMS and only
// if the type implements editor.Mergable
trusted, ok := post.(content.Trustable)
if ok {
err := trusted.AutoApprove(res, req)
if err != nil {
s.log.Errorf("Error calling AutoApprove: %v", err)
return
}
} else {
spec = "__pending"
req.PostForm.Set("status", string(content.Pending))
}
req.PostForm.Set("namespace", t)
s.log.Printf("PostForm: %+v", req.PostForm)
id, err := s.contentApp.NewContent(t, req.PostForm)
if err != nil {
s.log.Errorf("Error calling SetContent: %v", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
// set the target in the context so user can get saved value from db in hook
ctx := context.WithValue(req.Context(), "target", fmt.Sprintf("%s:%s", t, id))
req = req.WithContext(ctx)
err = hook.AfterSave(res, req)
if err != nil {
s.log.Errorf("Error calling AfterSave: %v", err)
return
}
err = hook.AfterAPICreate(res, req)
if err != nil {
s.log.Errorf("Error calling AfterAccept: %v", err)
return
}
// create JSON response to send data back to client
var data map[string]interface{}
if spec != "" {
spec = strings.TrimPrefix(spec, "__")
data = map[string]interface{}{
"status": spec,
"type": t,
}
} else {
spec = "public"
data = map[string]interface{}{
"id": id,
"status": spec,
"type": t,
}
}
resp := map[string]interface{}{
"data": []map[string]interface{}{
data,
},
}
j, err := json.Marshal(resp)
if err != nil {
s.log.Errorf("Error marshalling response to JSON: %v", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
res.Header().Set("Content-Type", "application/json")
_, err = res.Write(j)
if err != nil {
s.log.Errorf("Error writing response: %v", err)
return
}
}