This repository has been archived by the owner on Oct 11, 2021. It is now read-only.
/
web.go
451 lines (397 loc) · 11.5 KB
/
web.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
446
447
448
449
450
451
package main
import (
"database/sql"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/hoisie/mustache"
"github.com/moovweb/gokogiri/html"
"github.com/moovweb/gokogiri/xml"
"log"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
func authedForHeader(authHeader string) (bool, error) {
if !strings.HasPrefix(authHeader, "Basic ") {
return false, nil
}
logr.Debugln("Yay, client gave a Basic auth header")
userpass, err := base64.StdEncoding.DecodeString(authHeader[6:])
if err != nil {
logr.Debugln("Oops, error decoding the client's Basic auth header:", err.Error())
// but report it as Unauthorized, not an error
return false, nil
}
userpassParts := strings.SplitN(string(userpass), ":", 2)
username, pass := userpassParts[0], userpassParts[1]
account, err := AccountByName(username)
if err == sql.ErrNoRows {
logr.Debugln("No such account %s", username)
return false, nil
} else if err != nil {
return false, err
}
return account.HasPassword(pass), nil
}
func IsAuthed(w http.ResponseWriter, r *http.Request) (authed bool) {
authHeader := r.Header.Get("Authorization")
authed, err := authedForHeader(authHeader)
if err != nil {
logr.Errln("Error checking auth information:", err.Error())
http.Error(w, "error loading auth information", http.StatusInternalServerError)
} else if !authed {
w.Header().Set("WWW-Authenticate", "Basic realm=\"cares\"")
http.Error(w, "authorization required", http.StatusUnauthorized)
}
return
}
func WriteRssForPosts(w http.ResponseWriter, r *http.Request, posts []*Post, titleFormat string) (err error) {
var host string
var port string
if strings.Contains(r.Host, ":") {
host, port, err = net.SplitHostPort(r.Host)
if err != nil {
return
}
} else {
host = r.Host
// TODO: set port appropriately if we're on HTTPS
port = "80"
}
owner := AccountForOwner()
firstPost, err := FirstPost()
if err != nil {
return
}
// TODO: somehow determine if we're on HTTPS or no?
baseurlUrl := url.URL{"http", "", nil, r.Host, "/", "", ""}
baseurl := strings.TrimRight(baseurlUrl.String(), "/")
data := map[string]interface{}{
"posts": posts,
"OwnerName": owner.DisplayName,
"Title": fmt.Sprintf(titleFormat, owner.DisplayName),
"baseurl": baseurl,
"host": host,
"port": port,
"FirstPost": firstPost,
}
logr.Debugln("Rendering RSS with baseurl of", baseurl)
xml := mustache.RenderFile("html/rss.xml", data)
w.Header().Set("Content-Type", "application/rss+xml")
w.Write([]byte(xml))
return
}
func rss(w http.ResponseWriter, r *http.Request) {
posts, err := RecentPosts(20)
if err != nil {
logr.Errln("Error loading posts for RSS feed:", err.Error())
http.Error(w, "error finding recent posts", http.StatusInternalServerError)
return
}
err = WriteRssForPosts(w, r, posts, "%s")
if err != nil {
logr.Errln("Error building RSS for recent posts:", err.Error())
http.Error(w, "error generating rss for recent posts", http.StatusInternalServerError)
}
}
func archive(w http.ResponseWriter, r *http.Request) {
// /archive/2012/09/06/rss.xml
// 0 1 2 3 4 5
pathParts := strings.SplitN(r.URL.Path, "/", 6)
if len(pathParts) != 6 {
http.NotFound(w, r)
return
}
var year, month, day int
var err error
year, err = strconv.Atoi(pathParts[2])
if err == nil {
month, err = strconv.Atoi(pathParts[3])
}
if err == nil {
day, err = strconv.Atoi(pathParts[4])
}
if err != nil {
http.NotFound(w, r)
return
}
// TODO: support HTML archives too
if pathParts[5] != "rss.xml" {
http.NotFound(w, r)
return
}
archiveDate := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
posts, err := PostsOnDay(archiveDate)
if err != nil {
logr.Errln("Error getting posts for day", archiveDate, "from database:", err.Error())
http.Error(w, "error finding posts for day", http.StatusInternalServerError)
return
}
err = WriteRssForPosts(w, r, posts, archiveDate.Format("%s for _2 Jan 2006"))
if err != nil {
logr.Errln("Error generating RSS for date", archiveDate, ":", err.Error())
http.Error(w, "error generating rss for date", http.StatusInternalServerError)
}
}
func AtomForPosts(r *http.Request, posts []*Post, titleFormat string) string {
// TODO: somehow determine if we're on HTTPS or no?
baseurlUrl := url.URL{"http", "", nil, r.Host, "/", "", ""}
baseurl := strings.TrimRight(baseurlUrl.String(), "/")
var lastPost *Post = nil
if len(posts) > 0 {
lastPost = posts[0]
}
owner := AccountForOwner()
data := map[string]interface{}{
"Posts": posts,
"OwnerName": owner.DisplayName,
"Title": fmt.Sprintf(titleFormat, owner.DisplayName),
"baseurl": baseurl,
"LastPost": lastPost,
}
logr.Debugln("Rendering Atom with baseurl of", baseurl)
xml := mustache.RenderFile("html/atom.xml", data)
return xml
}
func atom(w http.ResponseWriter, r *http.Request) {
posts, err := RecentPosts(20)
if err != nil {
logr.Errln("Error loading posts for Atom feed:", err.Error())
http.Error(w, "error finding recent posts", http.StatusInternalServerError)
return
}
xml := AtomForPosts(r, posts, "%s")
w.Header().Set("Content-Type", "application/atom+xml")
w.Write([]byte(xml))
return
}
func activity(w http.ResponseWriter, r *http.Request) {
// TODO: somehow determine if we're on HTTPS or no?
baseurlUrl := url.URL{"http", "", nil, r.Host, "/", "", ""}
baseurl := strings.TrimRight(baseurlUrl.String(), "/")
owner := AccountForOwner()
actorData := map[string]interface{}{
"objectType": "person",
"url": baseurl + "/",
"id": baseurl + "/",
"displayName": owner.DisplayName,
"image": map[string]interface{}{
"url": baseurl + "/static/avatar-250.jpg",
"width": 250,
"height": 250,
},
}
targetData := map[string]interface{}{
"objectType": "blog",
"url": baseurl + "/",
"id": baseurl + "/",
"displayName": owner.DisplayName,
}
items, err := RecentPosts(20)
if err != nil {
logr.Errln("error finding recent posts for activity stream:", err.Error())
http.Error(w, "error finding recent activity", http.StatusInternalServerError)
return
}
itemData := make([]map[string]interface{}, len(items))
for i, item := range items {
itemData[i] = map[string]interface{}{
"verb": "post",
"actor": actorData,
"target": targetData,
"published": item.Posted,
"object": map[string]interface{}{
"content": item.Html,
"url": baseurl + item.Permalink(),
"id": baseurl + item.Permalink(),
"published": item.Posted,
},
}
}
streamData := map[string]interface{}{
"items": itemData,
}
streamBytes, err := json.Marshal(streamData)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(streamBytes)
}
func stream(w http.ResponseWriter, r *http.Request) {
before := r.FormValue("before")
beforeTime, err := time.Parse(time.RFC3339, before)
if err != nil {
http.Error(w, fmt.Sprintf("invalid timestamp %s", before), http.StatusBadRequest)
return
}
posts, err := PostsBefore(beforeTime, 20)
if err != nil {
logr.Errln("Error finding posts older than", before, ":", err.Error())
http.Error(w, "error finding posts", http.StatusInternalServerError)
return
}
ret, err := json.Marshal(posts)
if err != nil {
logr.Errln("Error serializing posts older than", before, ":", err.Error())
http.Error(w, "error serializing requested posts", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(ret)
}
func index(w http.ResponseWriter, r *http.Request) {
posts, err := RecentPosts(20)
if err != nil {
logr.Errln("Error loading recent posts for home page:", err.Error())
}
owner := AccountForOwner()
data := map[string]interface{}{
"posts": posts,
"OwnerName": owner.DisplayName,
}
if len(posts) > 0 {
data["LastPost"] = posts[len(posts)-1]
}
html := mustache.RenderFile("html/index.html", data)
w.Write([]byte(html))
}
func permalink(w http.ResponseWriter, r *http.Request) {
idstr := r.URL.Path[len("/post/"):]
post, err := PostBySlug(idstr)
if err != nil {
http.Error(w, fmt.Sprintf("invalid post %s: %s", idstr, err.Error()), http.StatusBadRequest)
return
}
if r.Method == "DELETE" {
if !IsAuthed(w, r) {
return
}
post.MarkDeleted()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNoContent)
w.Write([]byte("{\"ok\":true}"))
return
}
owner := AccountForOwner()
data := map[string]interface{}{
"post": post,
"OwnerName": owner.DisplayName,
}
html := mustache.RenderFile("html/permalink.html", data)
w.Write([]byte(html))
}
func removeNonAnchorElements(node xml.Node) {
var next xml.Node
for n := node.FirstChild(); n != nil; n = next {
next = n.NextSibling()
if n.NodeType() == xml.XML_ELEMENT_NODE {
removeNonAnchorElements(n)
if strings.ToLower(n.Name()) != "a" {
var chNext xml.Node
for ch := n.FirstChild(); ch != nil; ch = chNext {
chNext = ch.NextSibling()
ch.Unlink()
n.InsertBefore(ch)
}
n.Remove()
}
}
}
}
func CleanHTML(inhtml string) (string, error) {
frag, err := html.ParseFragment([]byte(inhtml), html.DefaultEncodingBytes, []byte{},
html.DefaultParseOption, html.DefaultEncodingBytes)
if err != nil {
return "", err
}
removeNonAnchorElements(frag)
return frag.String(), nil
}
func post(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.Header().Set("Allow", "POST")
http.Error(w, "POST is required", http.StatusMethodNotAllowed)
return
}
if !IsAuthed(w, r) {
return
}
post := NewPost()
// TODO: use the site owner's author id
post.AuthorId = 1
html := r.FormValue("html")
if html == "" {
http.Error(w, "html value is required", http.StatusBadRequest)
return
}
html, err := CleanHTML(html)
if err != nil {
http.Error(w, "error parsing HTML: "+err.Error(), http.StatusBadRequest)
return
}
post.Html = html
err = post.Save()
if err != nil {
http.Error(w, "error saving post to database", http.StatusInternalServerError)
logr.Errln("Error saving new Post:", err.Error())
return
}
ws := NewWritestream()
ws.PostId = post.Id
ws.Posted = post.Posted
err = ws.Save()
if err != nil {
http.Error(w, "error saving post to database", http.StatusInternalServerError)
logr.Errln("Error saving Writestream for new post:", err.Error())
return
}
// TODO: use proper scheme
go NotifyRssCloud(fmt.Sprintf("http://%s/rss", r.Host))
go NotifySubscribers(AtomForPosts(r, []*Post{post}, "%s"))
ret, err := json.Marshal(post)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(ret)
}
func static(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path[1:]
logr.Debugln("Serving static file", path)
http.ServeFile(w, r, path)
}
func indexOr404(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Path) > 1 {
// Actually some other unhandled URL, so 404.
http.NotFound(w, r)
return
}
index(w, r)
}
func ServeWeb(port int) {
err := LoadAccountForOwner()
if err != nil {
logr.Errln("Error loading site owner:", err.Error())
return
}
http.HandleFunc("/static/", static)
http.HandleFunc("/rss", rss)
http.HandleFunc("/rssCloud", rssCloud)
http.HandleFunc("/atom", atom)
http.HandleFunc("/hub", hub)
http.HandleFunc("/post", post)
http.HandleFunc("/activity", activity)
http.HandleFunc("/stream", stream)
http.HandleFunc("/archive/", archive)
http.HandleFunc("/post/", permalink)
http.HandleFunc("/", indexOr404)
logr.Debugln("Ohai web servin'")
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}