/
posts.go
445 lines (408 loc) · 13.4 KB
/
posts.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
package routes
import (
"bufio"
"errors"
"log"
"net/http"
"strings"
. "github.com/toldjuuso/vertigo/databases/sqlx"
"github.com/toldjuuso/vertigo/render"
. "github.com/toldjuuso/vertigo/session"
"github.com/gorilla/context"
"github.com/husobee/vestigo"
"github.com/toldjuuso/go-jaro-winkler-distance"
)
// GetPost() returns binded Post from POST data
func GetPost(r *http.Request) (Post, error) {
rv, ok := context.GetOk(r, "post")
if !ok {
return Post{}, errors.New("context not set")
}
return rv.(Post), nil
}
// GetSearch() returns binded Search from POST data
func GetSearch(r *http.Request) (Search, error) {
rv, ok := context.GetOk(r, "search")
if !ok {
return Search{}, errors.New("context not set")
}
return rv.(Search), nil
}
// Homepage route fetches all posts from database and renders them according to "home.tmpl".
// Normally you'd use this function as your "/" route.
func Homepage(w http.ResponseWriter, r *http.Request) {
if Settings.Firstrun {
render.R.HTML(w, 200, "installation/wizard", nil)
return
}
var post Post
posts, err := post.GetAll()
if err != nil {
log.Println("route Homepage, post.GetAll:", err)
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
render.R.HTML(w, 200, "home", posts)
}
// Search struct is basically just a type check to make sure people don't add anything nasty to
// on-site search queries.
type Search struct {
Query string `json:"query" form:"query" binding:"required"`
Score float64
Posts []Post
}
// Get or search.Get returns all posts which contain parameter search.Query in either
// post.Title or post.Content.
// Returns []Post and error object.
func (search Search) Get() (Search, error) {
var post Post
posts, err := post.GetAll()
if err != nil {
return search, err
}
for _, post := range posts {
if post.Published {
// posts are searched for a match in both content and title, so here
// we declare two scanners for them
content := bufio.NewScanner(strings.NewReader(post.Markdown))
title := bufio.NewScanner(strings.NewReader(post.Title))
// Blackfriday makes smartypants corrections some characters, which break the search
content.Split(bufio.ScanWords)
title.Split(bufio.ScanWords)
// content is scanned trough Jaro-Winkler distance with
// quite strict matching score of 0.9/1
// matching score this high would most likely catch only different
// capitalization and small typos
//
// since we are already in a for loop, we have to break the
// iteration here by going to label End to avoid showing a
// duplicate search result
//
// the condition after the OR operator limits searches to words basically
// for example, searching for foobarbarbar would match foobar, but for now
// we want to limit the searches to contain only the word foobar
for content.Scan() {
if jwd.Calculate(content.Text(), search.Query) >= 0.9 || strings.Contains(search.Query, content.Text()+" ") {
search.Posts = append(search.Posts, post)
goto End
}
}
for title.Scan() {
if jwd.Calculate(title.Text(), search.Query) >= 0.9 || strings.Contains(search.Query, title.Text()+" ") {
search.Posts = append(search.Posts, post)
goto End
}
}
}
End:
}
if len(search.Posts) == 0 {
search.Posts = make([]Post, 0)
}
return search, nil
}
// SearchPost is a route which returns all posts and aggregates the ones which contain
// the POSTed search query in either Title or Content field.
func SearchPost(w http.ResponseWriter, r *http.Request) {
search, err := GetSearch(r)
if err != nil {
log.Println("route SearchPost, context GetSearch:", err)
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
search, err = search.Get()
if err != nil {
log.Println("route SearchPost, search.Get:", err)
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
switch Root(r) {
case "api":
render.R.JSON(w, 200, search.Posts)
case "posts":
render.R.HTML(w, 200, "search", search.Posts)
}
}
// CreatePost is a route which creates a new post according to the posted data.
// API renderponse contains the created post object and normal request redirects to "/user" page.
// Does not publish the post automatically. See PublishPost for more.
func CreatePost(w http.ResponseWriter, r *http.Request) {
post, err := GetPost(r)
if err != nil {
log.Println("route CreatePost, context GetPost:", err)
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
var user User
id, ok := SessionGetValue(r, "id")
if !ok {
log.Println("route CreatePost, SessionGetValue:", ok)
SessionDelete(w, r, "id")
render.R.HTML(w, 500, "error", "Session could not be fetched. Please log in again.")
return
}
user.ID = id
user, err = user.Get()
if err != nil {
log.Println("route CreatePost, user.Get:", err)
SessionDelete(w, r, "id")
render.R.HTML(w, 500, "error", err)
return
}
post, err = post.Insert(user)
if err != nil {
log.Println("route CreatePost, post.Insert:", err)
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
switch Root(r) {
case "api":
render.R.JSON(w, 200, post)
case "posts":
http.Redirect(w, r, "/user", 302)
}
}
// ReadPosts is a route which returns all posts without merged owner data (although the object does include author field)
// Not available on frontend, so therefore it only returns a JSON renderponse, hence the post iteration in Go.
func ReadPosts(w http.ResponseWriter, r *http.Request) {
var post Post
published := make([]Post, 0)
posts, err := post.GetAll()
if err != nil {
log.Println("route ReadPosts, post.GetAll:", err)
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
for _, post := range posts {
if post.Published {
published = append(published, post)
}
}
render.R.JSON(w, 200, published)
}
// ReadPost is a route which returns post with given post.Slug.
// Returns post data on JSON call and displays a formatted page on frontend.
func ReadPost(w http.ResponseWriter, r *http.Request) {
log.Println("url query:", r.URL.Query())
var post Post
if vestigo.Param(r, "slug") == "new" {
render.R.JSON(w, 400, map[string]interface{}{"error": "There can't be a post called 'new'."})
return
}
post.Slug = vestigo.Param(r, "slug")
post, err := post.Get()
if err != nil {
log.Println("route ReadPost, post.Get:", err)
if err.Error() == "not found" {
render.R.JSON(w, 404, map[string]interface{}{"error": "Not found"})
return
}
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
go post.Increment()
switch Root(r) {
case "api":
render.R.JSON(w, 200, post)
case "post":
render.R.HTML(w, 200, "post/display", post)
}
}
// EditPost is a route which returns a post object to be displayed and edited on frontend.
// Not available for JSON API.
// Analogous to ReadPost. Could be replaced at some point.
func EditPost(w http.ResponseWriter, r *http.Request) {
var post Post
post.Slug = vestigo.Param(r, "slug")
post, err := post.Get()
if err != nil {
log.Println("route EditPost, post.Get:", err)
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
render.R.HTML(w, 200, "post/edit", post)
}
// UpdatePost is a route which updates a post defined by martini parameter "title" with posted data.
// Requirender session cookie. JSON request returns the updated post object, frontend call will redirect to "/user".
func UpdatePost(w http.ResponseWriter, r *http.Request) {
var post Post
post.Slug = vestigo.Param(r, "slug")
post, err := post.Get()
if err != nil {
log.Println("route UpdatePost, post.Get:", err)
if err.Error() == "not found" {
render.R.JSON(w, 404, map[string]interface{}{"error": "Not found"})
return
}
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
id, ok := SessionGetValue(r, "id")
if !ok {
log.Println("route UpdatePost, SessionGetValue:", ok)
SessionDelete(w, r, "id")
render.R.HTML(w, 500, "error", "Session could not be fetched. Please log in again.")
return
}
if post.Author != id {
log.Println("route UpdatePost, post.Author and id mismatch")
render.R.JSON(w, 401, map[string]interface{}{"error": "Unauthorized"})
return
}
entry, err := GetPost(r)
if err != nil {
log.Println("route UpdatePost, context GetPost:", err)
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
post, err = post.Update(entry)
if err != nil {
log.Println("route UpdatePost, post.Update:", err)
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
switch Root(r) {
case "api":
render.R.JSON(w, 200, post)
case "post":
http.Redirect(w, r, "/user", 302)
}
}
// PublishPost is a route which publishes a post and therefore making it appear on frontpage and search.
// JSON request returns `HTTP 200 {"success": "Post published"}` on success. Frontend call will redirect to
// published page.
// Requirender active session cookie.
func PublishPost(w http.ResponseWriter, r *http.Request) {
var post Post
post.Slug = vestigo.Param(r, "slug")
post, err := post.Get()
if err != nil {
log.Println("route PublishPost, post.Get:", err)
if err.Error() == "not found" {
render.R.JSON(w, 404, map[string]interface{}{"error": "Not found"})
return
}
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
id, ok := SessionGetValue(r, "id")
if !ok {
log.Println("route PublishPost, SessionGetValue:", ok)
SessionDelete(w, r, "id")
render.R.HTML(w, 500, "error", "Session could not be fetched. Please log in again.")
return
}
if post.Author != id {
log.Println("route PublishPost, post.Author and id mismatch")
render.R.JSON(w, 401, map[string]interface{}{"error": "Unauthorized"})
return
}
var entry Post
entry = post
entry.Published = true
post, err = post.Update(entry)
if err != nil {
log.Println("route PublishPost, post.Update:", err)
if err.Error() == "unauthorized" {
render.R.JSON(w, 401, map[string]interface{}{"error": "Unauthorized"})
return
}
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
switch Root(r) {
case "api":
render.R.JSON(w, 200, map[string]interface{}{"success": "Post published"})
case "post":
http.Redirect(w, r, "/post/"+post.Slug, 302)
}
}
// UnpublishPost is a route which unpublishes a post and therefore making it disappear from frontpage and search.
// JSON request returns `HTTP 200 {"success": "Post unpublished"}` on success. Frontend call will redirect to
// user control panel.
// Requirender active session cookie.
// The route is anecdotal to route PublishPost().
func UnpublishPost(w http.ResponseWriter, r *http.Request) {
var post Post
post.Slug = vestigo.Param(r, "slug")
post, err := post.Get()
if err != nil {
log.Println("route UnpublishPost, post.Get:", err)
if err.Error() == "not found" {
render.R.JSON(w, 404, map[string]interface{}{"error": "Not found"})
return
}
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
id, ok := SessionGetValue(r, "id")
if !ok {
log.Println("route UnpublishPost, SessionGetValue:", ok)
SessionDelete(w, r, "id")
render.R.HTML(w, 500, "error", "Session could not be fetched. Please log in again.")
return
}
if post.Author != id {
log.Println("route UnpublishPost, author mismatch")
render.R.JSON(w, 401, map[string]interface{}{"error": "Unauthorized"})
return
}
err = post.Unpublish()
if err != nil {
log.Println("route UnpublishPost, post.Unpublish:", err)
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
switch Root(r) {
case "api":
render.R.JSON(w, 200, map[string]interface{}{"success": "Post unpublished"})
case "post":
http.Redirect(w, r, "/user", 302)
}
}
// DeletePost is a route which deletes a post according to martini parameter "title".
// JSON request returns `HTTP 200 {"success": "Post deleted"}` on success. Frontend call will redirect to
// "/user" page on successful request.
// Requirender active session cookie.
func DeletePost(w http.ResponseWriter, r *http.Request) {
var post Post
post.Slug = vestigo.Param(r, "slug")
post, err := post.Get()
if err != nil {
log.Println("route DeletePost, post.Get:", err)
if err.Error() == "not found" {
render.R.JSON(w, 404, map[string]interface{}{"error": "Not found"})
return
}
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
id, ok := SessionGetValue(r, "id")
if !ok {
log.Println("route DeletePost, SessionGetValue:", ok)
SessionDelete(w, r, "id")
render.R.HTML(w, 500, "error", "Session could not be fetched. Please log in again.")
return
}
if post.Author != id {
log.Println("route DeletePost, author mismatch")
render.R.JSON(w, 401, map[string]interface{}{"error": "Unauthorized"})
return
}
err = post.Delete()
if err != nil {
log.Println("route DeletePost, post.Delete:", err)
if err.Error() == "unauthorized" {
render.R.JSON(w, 401, map[string]interface{}{"error": "Unauthorized"})
return
}
render.R.JSON(w, 500, map[string]interface{}{"error": "Internal server error"})
return
}
switch Root(r) {
case "api":
render.R.JSON(w, 200, map[string]interface{}{"success": "Post deleted"})
case "post":
http.Redirect(w, r, "/user", 302)
}
}