web.go (view raw)
1//
2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
3//
4// Permission to use, copy, modify, and distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
16package main
17
18import (
19 "bytes"
20 "database/sql"
21 "fmt"
22 "html"
23 "html/template"
24 "io"
25 "log"
26 notrand "math/rand"
27 "net/http"
28 "net/url"
29 "os"
30 "sort"
31 "strconv"
32 "strings"
33 "time"
34
35 "github.com/gorilla/mux"
36 "humungus.tedunangst.com/r/webs/css"
37 "humungus.tedunangst.com/r/webs/htfilter"
38 "humungus.tedunangst.com/r/webs/httpsig"
39 "humungus.tedunangst.com/r/webs/image"
40 "humungus.tedunangst.com/r/webs/junk"
41 "humungus.tedunangst.com/r/webs/login"
42 "humungus.tedunangst.com/r/webs/rss"
43 "humungus.tedunangst.com/r/webs/templates"
44)
45
46var readviews *templates.Template
47
48var userSep = "u"
49var honkSep = "h"
50
51func getuserstyle(u *login.UserInfo) template.CSS {
52 if u == nil {
53 return ""
54 }
55 user, _ := butwhatabout(u.Username)
56 if user.SkinnyCSS {
57 return "main { max-width: 700px; }"
58 }
59 return ""
60}
61
62func getInfo(r *http.Request) map[string]interface{} {
63 u := login.GetUserInfo(r)
64 templinfo := make(map[string]interface{})
65 templinfo["StyleParam"] = getassetparam("views/style.css")
66 templinfo["LocalStyleParam"] = getassetparam("views/local.css")
67 templinfo["JSParam"] = getassetparam("views/honkpage.js")
68 templinfo["UserStyle"] = getuserstyle(u)
69 templinfo["ServerName"] = serverName
70 templinfo["IconName"] = iconName
71 templinfo["UserInfo"] = u
72 templinfo["UserSep"] = userSep
73 if u != nil {
74 var combos []string
75 combocache.Get(u.UserID, &combos)
76 templinfo["Combos"] = combos
77 }
78 return templinfo
79}
80
81func homepage(w http.ResponseWriter, r *http.Request) {
82 templinfo := getInfo(r)
83 u := login.GetUserInfo(r)
84 var honks []*Honk
85 var userid int64 = -1
86 if r.URL.Path == "/front" || u == nil {
87 honks = getpublichonks()
88 } else {
89 userid = u.UserID
90 if r.URL.Path == "/atme" {
91 templinfo["PageName"] = "atme"
92 honks = gethonksforme(userid)
93 } else if r.URL.Path == "/first" {
94 templinfo["PageName"] = "first"
95 honks = gethonksforuser(userid)
96 honks = osmosis(honks, userid)
97 } else {
98 templinfo["PageName"] = "home"
99 honks = gethonksforuser(userid)
100 honks = osmosis(honks, userid)
101 }
102 if len(honks) > 0 {
103 templinfo["TopXID"] = honks[0].XID
104 }
105 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
106 }
107
108 templinfo["ShowRSS"] = true
109 templinfo["ServerMessage"] = serverMsg
110 honkpage(w, u, honks, templinfo)
111}
112
113func showfunzone(w http.ResponseWriter, r *http.Request) {
114 var emunames, memenames []string
115 dir, err := os.Open("emus")
116 if err == nil {
117 emunames, _ = dir.Readdirnames(0)
118 dir.Close()
119 }
120 for i, e := range emunames {
121 if len(e) > 4 {
122 emunames[i] = e[:len(e)-4]
123 }
124 }
125 dir, err = os.Open("memes")
126 if err == nil {
127 memenames, _ = dir.Readdirnames(0)
128 dir.Close()
129 }
130 templinfo := getInfo(r)
131 templinfo["Emus"] = emunames
132 templinfo["Memes"] = memenames
133 err = readviews.Execute(w, "funzone.html", templinfo)
134 if err != nil {
135 log.Print(err)
136 }
137}
138
139func showrss(w http.ResponseWriter, r *http.Request) {
140 name := mux.Vars(r)["name"]
141
142 var honks []*Honk
143 if name != "" {
144 honks = gethonksbyuser(name, false)
145 } else {
146 honks = getpublichonks()
147 }
148 if len(honks) > 20 {
149 honks = honks[0:20]
150 }
151 reverbolate(-1, honks)
152
153 home := fmt.Sprintf("https://%s/", serverName)
154 base := home
155 if name != "" {
156 home += "u/" + name
157 name += " "
158 }
159 feed := rss.Feed{
160 Title: name + "honk",
161 Link: home,
162 Description: name + "honk rss",
163 Image: &rss.Image{
164 URL: base + "icon.png",
165 Title: name + "honk rss",
166 Link: home,
167 },
168 }
169 var modtime time.Time
170 for _, honk := range honks {
171 if !firstclass(honk) {
172 continue
173 }
174 desc := string(honk.HTML)
175 if t := honk.Time; t != nil {
176 desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM EDT Mon Jan 02"))
177 if t.Duration != 0 {
178 desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
179 }
180 }
181 if p := honk.Place; p != nil {
182 desc += fmt.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
183 html.EscapeString(p.Url), html.EscapeString(p.Name), p.Latitude, p.Longitude)
184 }
185 for _, d := range honk.Donks {
186 desc += fmt.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
187 d.URL, html.EscapeString(d.Name))
188 }
189
190 feed.Items = append(feed.Items, &rss.Item{
191 Title: fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
192 Description: rss.CData{Data: desc},
193 Link: honk.URL,
194 PubDate: honk.Date.Format(time.RFC1123),
195 Guid: &rss.Guid{IsPermaLink: true, Value: honk.URL},
196 })
197 if honk.Date.After(modtime) {
198 modtime = honk.Date
199 }
200 }
201 w.Header().Set("Cache-Control", "max-age=300")
202 w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
203
204 err := feed.Write(w)
205 if err != nil {
206 log.Printf("error writing rss: %s", err)
207 }
208}
209
210func crappola(j junk.Junk) bool {
211 t, _ := j.GetString("type")
212 a, _ := j.GetString("actor")
213 o, _ := j.GetString("object")
214 if t == "Delete" && a == o {
215 log.Printf("crappola from %s", a)
216 return true
217 }
218 return false
219}
220
221func ping(user *WhatAbout, who string) {
222 box, err := getboxes(who)
223 if err != nil {
224 log.Printf("no inbox for ping: %s", err)
225 return
226 }
227 j := junk.New()
228 j["@context"] = itiswhatitis
229 j["type"] = "Ping"
230 j["id"] = user.URL + "/ping/" + xfiltrate()
231 j["actor"] = user.URL
232 j["to"] = who
233 keyname, key := ziggy(user.Name)
234 err = PostJunk(keyname, key, box.In, j)
235 if err != nil {
236 log.Printf("can't send ping: %s", err)
237 return
238 }
239 log.Printf("sent ping to %s: %s", who, j["id"])
240}
241
242func pong(user *WhatAbout, who string, obj string) {
243 box, err := getboxes(who)
244 if err != nil {
245 log.Printf("no inbox for pong %s : %s", who, err)
246 return
247 }
248 j := junk.New()
249 j["@context"] = itiswhatitis
250 j["type"] = "Pong"
251 j["id"] = user.URL + "/pong/" + xfiltrate()
252 j["actor"] = user.URL
253 j["to"] = who
254 j["object"] = obj
255 keyname, key := ziggy(user.Name)
256 err = PostJunk(keyname, key, box.In, j)
257 if err != nil {
258 log.Printf("can't send pong: %s", err)
259 return
260 }
261}
262
263func inbox(w http.ResponseWriter, r *http.Request) {
264 name := mux.Vars(r)["name"]
265 user, err := butwhatabout(name)
266 if err != nil {
267 http.NotFound(w, r)
268 return
269 }
270 if stealthmode(user.ID, r) {
271 http.NotFound(w, r)
272 return
273 }
274 var buf bytes.Buffer
275 io.Copy(&buf, r.Body)
276 payload := buf.Bytes()
277 j, err := junk.Read(bytes.NewReader(payload))
278 if err != nil {
279 log.Printf("bad payload: %s", err)
280 io.WriteString(os.Stdout, "bad payload\n")
281 os.Stdout.Write(payload)
282 io.WriteString(os.Stdout, "\n")
283 return
284 }
285 if crappola(j) {
286 return
287 }
288 keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
289 if err != nil {
290 log.Printf("inbox message failed signature: %s", err)
291 if keyname != "" {
292 keyname, err = makeitworksomehowwithoutregardforkeycontinuity(keyname, r, payload)
293 if err != nil {
294 log.Printf("still failed: %s", err)
295 }
296 }
297 if err != nil {
298 return
299 }
300 }
301 what, _ := j.GetString("type")
302 if what == "Like" {
303 return
304 }
305 who, _ := j.GetString("actor")
306 origin := keymatch(keyname, who)
307 if origin == "" {
308 log.Printf("keyname actor mismatch: %s <> %s", keyname, who)
309 return
310 }
311 if rejectactor(user.ID, who) {
312 return
313 }
314 switch what {
315 case "Ping":
316 obj, _ := j.GetString("id")
317 log.Printf("ping from %s: %s", who, obj)
318 pong(user, who, obj)
319 case "Pong":
320 obj, _ := j.GetString("object")
321 log.Printf("pong from %s: %s", who, obj)
322 case "Follow":
323 obj, _ := j.GetString("object")
324 if obj == user.URL {
325 log.Printf("updating honker follow: %s", who)
326
327 db := opendatabase()
328 row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('dub', 'undub')", who, user.ID)
329 var x string
330 err = row.Scan(&x)
331 if err != sql.ErrNoRows {
332 log.Printf("duplicate follow request: %s", who)
333 _, err = stmtUpdateFlavor.Exec("dub", user.ID, who, "undub")
334 if err != nil {
335 log.Printf("error updating honker: %s", err)
336 }
337 } else {
338 stmtSaveDub.Exec(user.ID, who, who, "dub")
339 }
340 go rubadubdub(user, j)
341 } else {
342 log.Printf("can't follow %s", obj)
343 }
344 case "Accept":
345 log.Printf("updating honker accept: %s", who)
346 _, err = stmtUpdateFlavor.Exec("sub", user.ID, who, "presub")
347 if err != nil {
348 log.Printf("error updating honker: %s", err)
349 return
350 }
351 case "Update":
352 obj, ok := j.GetMap("object")
353 if ok {
354 what, _ := obj.GetString("type")
355 switch what {
356 case "Person":
357 return
358 case "Question":
359 return
360 case "Note":
361 go xonksaver(user, j, origin)
362 return
363 }
364 }
365 log.Printf("unknown Update activity")
366 fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
367 j.Write(fd)
368 io.WriteString(fd, "\n")
369 fd.Close()
370
371 case "Undo":
372 obj, ok := j.GetMap("object")
373 if !ok {
374 log.Printf("unknown undo no object")
375 } else {
376 what, _ := obj.GetString("type")
377 switch what {
378 case "Follow":
379 log.Printf("updating honker undo: %s", who)
380 _, err = stmtUpdateFlavor.Exec("undub", user.ID, who, "dub")
381 if err != nil {
382 log.Printf("error updating honker: %s", err)
383 return
384 }
385 case "Announce":
386 xid, _ := obj.GetString("object")
387 log.Printf("undo announce: %s", xid)
388 case "Like":
389 default:
390 log.Printf("unknown undo: %s", what)
391 }
392 }
393 default:
394 go xonksaver(user, j, origin)
395 }
396}
397
398func ximport(w http.ResponseWriter, r *http.Request) {
399 u := login.GetUserInfo(r)
400 xid := r.FormValue("xid")
401 xonk := getxonk(u.UserID, xid)
402 if xonk == nil {
403 p, _ := investigate(xid)
404 if p != nil {
405 xid = p.XID
406 }
407 j, err := GetJunk(xid)
408 if err != nil {
409 http.Error(w, "error getting external object", http.StatusInternalServerError)
410 log.Printf("error getting external object: %s", err)
411 return
412 }
413 log.Printf("importing %s", xid)
414 user, _ := butwhatabout(u.Username)
415
416 what, _ := j.GetString("type")
417 if isactor(what) {
418 outbox, _ := j.GetString("outbox")
419 gimmexonks(user, outbox)
420 http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
421 return
422 }
423 xonk = xonksaver(user, j, originate(xid))
424 }
425 convoy := ""
426 if xonk != nil {
427 convoy = xonk.Convoy
428 }
429 http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
430}
431
432func xzone(w http.ResponseWriter, r *http.Request) {
433 u := login.GetUserInfo(r)
434 rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
435 if err != nil {
436 log.Printf("query err: %s", err)
437 return
438 }
439 defer rows.Close()
440 var honkers []Honker
441 for rows.Next() {
442 var xid string
443 rows.Scan(&xid)
444 honkers = append(honkers, Honker{XID: xid})
445 }
446 rows.Close()
447 for i, _ := range honkers {
448 _, honkers[i].Handle = handles(honkers[i].XID)
449 }
450 templinfo := getInfo(r)
451 templinfo["XCSRF"] = login.GetCSRF("ximport", r)
452 templinfo["Honkers"] = honkers
453 err = readviews.Execute(w, "xzone.html", templinfo)
454 if err != nil {
455 log.Print(err)
456 }
457}
458
459func outbox(w http.ResponseWriter, r *http.Request) {
460 name := mux.Vars(r)["name"]
461 user, err := butwhatabout(name)
462 if err != nil {
463 http.NotFound(w, r)
464 return
465 }
466 if stealthmode(user.ID, r) {
467 http.NotFound(w, r)
468 return
469 }
470
471 honks := gethonksbyuser(name, false)
472 if len(honks) > 20 {
473 honks = honks[0:20]
474 }
475
476 var jonks []junk.Junk
477 for _, h := range honks {
478 j, _ := jonkjonk(user, h)
479 jonks = append(jonks, j)
480 }
481
482 j := junk.New()
483 j["@context"] = itiswhatitis
484 j["id"] = user.URL + "/outbox"
485 j["type"] = "OrderedCollection"
486 j["totalItems"] = len(jonks)
487 j["orderedItems"] = jonks
488
489 w.Header().Set("Content-Type", theonetruename)
490 j.Write(w)
491}
492
493func emptiness(w http.ResponseWriter, r *http.Request) {
494 name := mux.Vars(r)["name"]
495 user, err := butwhatabout(name)
496 if err != nil {
497 http.NotFound(w, r)
498 return
499 }
500 if stealthmode(user.ID, r) {
501 http.NotFound(w, r)
502 return
503 }
504 colname := "/followers"
505 if strings.HasSuffix(r.URL.Path, "/following") {
506 colname = "/following"
507 }
508 j := junk.New()
509 j["@context"] = itiswhatitis
510 j["id"] = user.URL + colname
511 j["type"] = "OrderedCollection"
512 j["totalItems"] = 0
513 j["orderedItems"] = []junk.Junk{}
514
515 w.Header().Set("Content-Type", theonetruename)
516 j.Write(w)
517}
518
519func showuser(w http.ResponseWriter, r *http.Request) {
520 name := mux.Vars(r)["name"]
521 user, err := butwhatabout(name)
522 if err != nil {
523 log.Printf("user not found %s: %s", name, err)
524 http.NotFound(w, r)
525 return
526 }
527 if stealthmode(user.ID, r) {
528 http.NotFound(w, r)
529 return
530 }
531 if friendorfoe(r.Header.Get("Accept")) {
532 j := asjonker(user)
533 w.Header().Set("Content-Type", theonetruename)
534 j.Write(w)
535 return
536 }
537 u := login.GetUserInfo(r)
538 honks := gethonksbyuser(name, u != nil && u.Username == name)
539 templinfo := getInfo(r)
540 filt := htfilter.New()
541 templinfo["Name"] = user.Name
542 whatabout := user.About
543 whatabout = markitzero(user.About)
544 templinfo["WhatAbout"], _ = filt.String(whatabout)
545 templinfo["ServerMessage"] = ""
546 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
547 honkpage(w, u, honks, templinfo)
548}
549
550func showhonker(w http.ResponseWriter, r *http.Request) {
551 u := login.GetUserInfo(r)
552 name := mux.Vars(r)["name"]
553 var honks []*Honk
554 if name == "" {
555 name = r.FormValue("xid")
556 honks = gethonksbyxonker(u.UserID, name)
557 } else {
558 honks = gethonksbyhonker(u.UserID, name)
559 }
560 name = html.EscapeString(name)
561 msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, name, name)
562 templinfo := getInfo(r)
563 templinfo["PageName"] = "honker"
564 templinfo["ServerMessage"] = template.HTML(msg)
565 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
566 honkpage(w, u, honks, templinfo)
567}
568
569func showcombo(w http.ResponseWriter, r *http.Request) {
570 name := mux.Vars(r)["name"]
571 u := login.GetUserInfo(r)
572 honks := gethonksbycombo(u.UserID, name)
573 honks = osmosis(honks, u.UserID)
574 templinfo := getInfo(r)
575 templinfo["PageName"] = "combo"
576 templinfo["PageArg"] = "name"
577 templinfo["ServerMessage"] = "honks by combo: " + name
578 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
579 if len(honks) > 0 {
580 templinfo["TopXID"] = honks[0].XID
581 }
582 honkpage(w, u, honks, templinfo)
583}
584func showconvoy(w http.ResponseWriter, r *http.Request) {
585 c := r.FormValue("c")
586 u := login.GetUserInfo(r)
587 honks := gethonksbyconvoy(u.UserID, c)
588 templinfo := getInfo(r)
589 templinfo["ServerMessage"] = "honks in convoy: " + c
590 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
591 honkpage(w, u, honks, templinfo)
592}
593func showsearch(w http.ResponseWriter, r *http.Request) {
594 q := r.FormValue("q")
595 u := login.GetUserInfo(r)
596 honks := gethonksbysearch(u.UserID, q)
597 templinfo := getInfo(r)
598 templinfo["ServerMessage"] = "honks for search: " + q
599 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
600 honkpage(w, u, honks, templinfo)
601}
602func showontology(w http.ResponseWriter, r *http.Request) {
603 name := mux.Vars(r)["name"]
604 u := login.GetUserInfo(r)
605 var userid int64 = -1
606 if u != nil {
607 userid = u.UserID
608 }
609 honks := gethonksbyontology(userid, "#"+name)
610 templinfo := getInfo(r)
611 templinfo["ServerMessage"] = "honks by ontology: " + name
612 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
613 honkpage(w, u, honks, templinfo)
614}
615
616func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
617 u := login.GetUserInfo(r)
618 var userid int64 = -1
619 if u != nil {
620 userid = u.UserID
621 }
622 rows, err := stmtSelectOnts.Query(userid)
623 if err != nil {
624 log.Printf("selection error: %s", err)
625 return
626 }
627 defer rows.Close()
628 var onts [][]string
629 for rows.Next() {
630 var o string
631 err := rows.Scan(&o)
632 if err != nil {
633 log.Printf("error scanning ont: %s", err)
634 continue
635 }
636 onts = append(onts, []string{o, o[1:]})
637 }
638 if u == nil {
639 w.Header().Set("Cache-Control", "max-age=300")
640 }
641 templinfo := getInfo(r)
642 templinfo["Onts"] = onts
643 err = readviews.Execute(w, "onts.html", templinfo)
644 if err != nil {
645 log.Print(err)
646 }
647}
648
649func showhonk(w http.ResponseWriter, r *http.Request) {
650 name := mux.Vars(r)["name"]
651 user, err := butwhatabout(name)
652 if err != nil {
653 http.NotFound(w, r)
654 return
655 }
656 if stealthmode(user.ID, r) {
657 http.NotFound(w, r)
658 return
659 }
660
661 xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
662 honk := getxonk(user.ID, xid)
663 if honk == nil {
664 http.NotFound(w, r)
665 return
666 }
667 u := login.GetUserInfo(r)
668 if u != nil && u.UserID != user.ID {
669 u = nil
670 }
671 if !honk.Public {
672 if u == nil {
673 http.NotFound(w, r)
674 return
675
676 }
677 templinfo := getInfo(r)
678 templinfo["ServerMessage"] = "one honk maybe more"
679 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
680 honkpage(w, u, []*Honk{honk}, templinfo)
681 return
682 }
683 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
684 if friendorfoe(r.Header.Get("Accept")) {
685 for _, h := range rawhonks {
686 if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
687 honk.Replies = append(honk.Replies, h)
688 }
689 }
690 donksforhonks([]*Honk{honk})
691 _, j := jonkjonk(user, honk)
692 j["@context"] = itiswhatitis
693 w.Header().Set("Content-Type", theonetruename)
694 j.Write(w)
695 return
696 }
697 var honks []*Honk
698 for _, h := range rawhonks {
699 if h.Public && (h.Whofore == 2 || h.IsAcked()) {
700 honks = append(honks, h)
701 }
702 }
703
704 templinfo := getInfo(r)
705 templinfo["ServerMessage"] = "one honk maybe more"
706 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
707 honkpage(w, u, honks, templinfo)
708}
709
710func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
711 var userid int64 = -1
712 if u != nil {
713 userid = u.UserID
714 }
715 if u == nil {
716 w.Header().Set("Cache-Control", "max-age=60")
717 }
718 reverbolate(userid, honks)
719 templinfo["Honks"] = honks
720 err := readviews.Execute(w, "honkpage.html", templinfo)
721 if err != nil {
722 log.Print(err)
723 }
724}
725
726func saveuser(w http.ResponseWriter, r *http.Request) {
727 whatabout := r.FormValue("whatabout")
728 u := login.GetUserInfo(r)
729 db := opendatabase()
730 options := ""
731 if r.FormValue("skinny") == "skinny" {
732 options += " skinny "
733 }
734 _, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
735 if err != nil {
736 log.Printf("error bouting what: %s", err)
737 }
738
739 http.Redirect(w, r, "/account", http.StatusSeeOther)
740}
741
742func submitbonk(w http.ResponseWriter, r *http.Request) {
743 xid := r.FormValue("xid")
744 userinfo := login.GetUserInfo(r)
745 user, _ := butwhatabout(userinfo.Username)
746
747 log.Printf("bonking %s", xid)
748
749 xonk := getxonk(userinfo.UserID, xid)
750 if xonk == nil {
751 return
752 }
753 if !xonk.Public {
754 return
755 }
756 donksforhonks([]*Honk{xonk})
757
758 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
759 if err != nil {
760 log.Printf("error acking bonk: %s", err)
761 }
762
763 oonker := xonk.Oonker
764 if oonker == "" {
765 oonker = xonk.Honker
766 }
767 dt := time.Now().UTC()
768 bonk := Honk{
769 UserID: userinfo.UserID,
770 Username: userinfo.Username,
771 What: "bonk",
772 Honker: user.URL,
773 Oonker: oonker,
774 XID: xonk.XID,
775 RID: xonk.RID,
776 Noise: xonk.Noise,
777 Precis: xonk.Precis,
778 URL: xonk.URL,
779 Date: dt,
780 Donks: xonk.Donks,
781 Whofore: 2,
782 Convoy: xonk.Convoy,
783 Audience: []string{thewholeworld, oonker},
784 Public: true,
785 }
786
787 bonk.Format = "html"
788
789 err = savehonk(&bonk)
790 if err != nil {
791 log.Printf("uh oh")
792 return
793 }
794
795 go honkworldwide(user, &bonk)
796}
797
798func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
799 zonk := Honk{
800 What: what,
801 XID: xonk.XID,
802 Date: time.Now().UTC(),
803 Audience: oneofakind(xonk.Audience),
804 }
805 zonk.Public = !keepitquiet(zonk.Audience)
806
807 log.Printf("announcing %sed honk: %s", what, xonk.XID)
808 go honkworldwide(user, &zonk)
809}
810
811func zonkit(w http.ResponseWriter, r *http.Request) {
812 wherefore := r.FormValue("wherefore")
813 what := r.FormValue("what")
814 userinfo := login.GetUserInfo(r)
815 user, _ := butwhatabout(userinfo.Username)
816
817 if wherefore == "ack" {
818 xonk := getxonk(userinfo.UserID, what)
819 if xonk != nil {
820 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
821 if err != nil {
822 log.Printf("error acking: %s", err)
823 }
824 sendzonkofsorts(xonk, user, "ack")
825 }
826 return
827 }
828
829 if wherefore == "deack" {
830 xonk := getxonk(userinfo.UserID, what)
831 if xonk != nil {
832 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
833 if err != nil {
834 log.Printf("error deacking: %s", err)
835 }
836 sendzonkofsorts(xonk, user, "deack")
837 }
838 return
839 }
840
841 if wherefore == "unbonk" {
842 xonk := getbonk(userinfo.UserID, what)
843 if xonk != nil {
844 deletehonk(xonk.ID)
845 xonk = getxonk(userinfo.UserID, what)
846 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
847 if err != nil {
848 log.Printf("error unbonking: %s", err)
849 }
850 sendzonkofsorts(xonk, user, "unbonk")
851 }
852 return
853 }
854
855 log.Printf("zonking %s %s", wherefore, what)
856 if wherefore == "zonk" {
857 xonk := getxonk(userinfo.UserID, what)
858 if xonk != nil {
859 deletehonk(xonk.ID)
860 if xonk.Whofore == 2 || xonk.Whofore == 3 {
861 sendzonkofsorts(xonk, user, "zonk")
862 }
863 }
864 }
865 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
866 if err != nil {
867 log.Printf("error saving zonker: %s", err)
868 return
869 }
870}
871
872func edithonkpage(w http.ResponseWriter, r *http.Request) {
873 u := login.GetUserInfo(r)
874 user, _ := butwhatabout(u.Username)
875 xid := r.FormValue("xid")
876 honk := getxonk(u.UserID, xid)
877 if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
878 log.Printf("no edit")
879 return
880 }
881
882 noise := honk.Noise
883 if honk.Precis != "" {
884 noise = honk.Precis + "\n\n" + noise
885 }
886
887 honks := []*Honk{honk}
888 donksforhonks(honks)
889 reverbolate(u.UserID, honks)
890 templinfo := getInfo(r)
891 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
892 templinfo["Honks"] = honks
893 templinfo["Noise"] = noise
894 templinfo["ServerMessage"] = "honk edit"
895 templinfo["UpdateXID"] = honk.XID
896 if len(honk.Donks) > 0 {
897 templinfo["SavedFile"] = honk.Donks[0].XID
898 }
899 err := readviews.Execute(w, "honkpage.html", templinfo)
900 if err != nil {
901 log.Print(err)
902 }
903}
904
905// what a hot mess this function is
906func submithonk(w http.ResponseWriter, r *http.Request) {
907 rid := r.FormValue("rid")
908 noise := r.FormValue("noise")
909
910 userinfo := login.GetUserInfo(r)
911 user, _ := butwhatabout(userinfo.Username)
912
913 dt := time.Now().UTC()
914 updatexid := r.FormValue("updatexid")
915 var honk *Honk
916 if updatexid != "" {
917 honk = getxonk(userinfo.UserID, updatexid)
918 if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
919 log.Printf("not saving edit")
920 return
921 }
922 honk.Date = dt
923 honk.What = "update"
924 honk.Format = "markdown"
925 } else {
926 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
927 what := "honk"
928 if rid != "" {
929 what = "tonk"
930 }
931 honk = &Honk{
932 UserID: userinfo.UserID,
933 Username: userinfo.Username,
934 What: what,
935 Honker: user.URL,
936 XID: xid,
937 Date: dt,
938 Format: "markdown",
939 }
940 }
941
942 noise = hooterize(noise)
943 honk.Noise = noise
944 translate(honk)
945
946 var convoy string
947 if rid != "" {
948 xonk := getxonk(userinfo.UserID, rid)
949 if xonk != nil {
950 if xonk.Public {
951 honk.Audience = append(honk.Audience, xonk.Audience...)
952 }
953 convoy = xonk.Convoy
954 } else {
955 xonkaud, c := whosthere(rid)
956 honk.Audience = append(honk.Audience, xonkaud...)
957 convoy = c
958 }
959 for i, a := range honk.Audience {
960 if a == thewholeworld {
961 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
962 break
963 }
964 }
965 honk.RID = rid
966 } else {
967 honk.Audience = []string{thewholeworld}
968 }
969 if honk.Noise != "" && honk.Noise[0] == '@' {
970 honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
971 } else {
972 honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
973 }
974
975 if convoy == "" {
976 convoy = "data:,electrichonkytonk-" + xfiltrate()
977 }
978 butnottooloud(honk.Audience)
979 honk.Audience = oneofakind(honk.Audience)
980 if len(honk.Audience) == 0 {
981 log.Printf("honk to nowhere")
982 http.Error(w, "honk to nowhere...", http.StatusNotFound)
983 return
984 }
985 honk.Public = !keepitquiet(honk.Audience)
986 honk.Convoy = convoy
987
988 donkxid := r.FormValue("donkxid")
989 if donkxid == "" {
990 file, filehdr, err := r.FormFile("donk")
991 if err == nil {
992 var buf bytes.Buffer
993 io.Copy(&buf, file)
994 file.Close()
995 data := buf.Bytes()
996 xid := xfiltrate()
997 var media, name string
998 img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
999 if err == nil {
1000 data = img.Data
1001 format := img.Format
1002 media = "image/" + format
1003 if format == "jpeg" {
1004 format = "jpg"
1005 }
1006 name = xid + "." + format
1007 xid = name
1008 } else {
1009 maxsize := 100000
1010 if len(data) > maxsize {
1011 log.Printf("bad image: %s too much text: %d", err, len(data))
1012 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1013 return
1014 }
1015 for i := 0; i < len(data); i++ {
1016 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1017 log.Printf("bad image: %s not text: %d", err, data[i])
1018 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1019 return
1020 }
1021 }
1022 media = "text/plain"
1023 name = filehdr.Filename
1024 if name == "" {
1025 name = xid + ".txt"
1026 }
1027 xid += ".txt"
1028 }
1029 desc := r.FormValue("donkdesc")
1030 if desc == "" {
1031 desc = name
1032 }
1033 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1034 fileid, err := savefile(xid, name, desc, url, media, true, data)
1035 if err != nil {
1036 log.Printf("unable to save image: %s", err)
1037 return
1038 }
1039 var d Donk
1040 d.FileID = fileid
1041 honk.Donks = append(honk.Donks, &d)
1042 donkxid = d.XID
1043 }
1044 } else {
1045 xid := donkxid
1046 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1047 donk := finddonk(url)
1048 if donk != nil {
1049 honk.Donks = append(honk.Donks, donk)
1050 } else {
1051 log.Printf("can't find file: %s", xid)
1052 }
1053 }
1054 herd := herdofemus(honk.Noise)
1055 for _, e := range herd {
1056 donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1057 if donk != nil {
1058 donk.Name = e.Name
1059 honk.Donks = append(honk.Donks, donk)
1060 }
1061 }
1062 memetize(honk)
1063
1064 placename := r.FormValue("placename")
1065 placelat := r.FormValue("placelat")
1066 placelong := r.FormValue("placelong")
1067 if placename != "" || placelat != "" || placelong != "" {
1068 p := new(Place)
1069 p.Name = placename
1070 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1071 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1072 p.Url = r.FormValue("placeurl")
1073 honk.Place = p
1074 }
1075 timestart := r.FormValue("timestart")
1076 if timestart != "" {
1077 t := new(Time)
1078 now := time.Now().Local()
1079 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1080 start, err := time.ParseInLocation(layout, timestart, now.Location())
1081 if err == nil {
1082 if start.Year() == 0 {
1083 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1084 }
1085 t.StartTime = start
1086 break
1087 }
1088 }
1089 timeend := r.FormValue("timeend")
1090 dur, err := time.ParseDuration(timeend)
1091 if err == nil {
1092 t.Duration = Duration(dur)
1093 }
1094 if !t.StartTime.IsZero() {
1095 honk.What = "event"
1096 honk.Time = t
1097 }
1098 }
1099
1100 if honk.Public {
1101 honk.Whofore = 2
1102 } else {
1103 honk.Whofore = 3
1104 }
1105
1106 // back to markdown
1107 honk.Noise = noise
1108
1109 if r.FormValue("preview") == "preview" {
1110 honks := []*Honk{honk}
1111 reverbolate(userinfo.UserID, honks)
1112 templinfo := getInfo(r)
1113 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1114 templinfo["Honks"] = honks
1115 templinfo["InReplyTo"] = r.FormValue("rid")
1116 templinfo["Noise"] = r.FormValue("noise")
1117 templinfo["SavedFile"] = donkxid
1118 templinfo["ServerMessage"] = "honk preview"
1119 err := readviews.Execute(w, "honkpage.html", templinfo)
1120 if err != nil {
1121 log.Print(err)
1122 }
1123 return
1124 }
1125
1126 if updatexid != "" {
1127 updatehonk(honk)
1128 } else {
1129 err := savehonk(honk)
1130 if err != nil {
1131 log.Printf("uh oh")
1132 return
1133 }
1134 }
1135
1136 // reload for consistency
1137 honk.Donks = nil
1138 donksforhonks([]*Honk{honk})
1139
1140 go honkworldwide(user, honk)
1141
1142 http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1143}
1144
1145func showhonkers(w http.ResponseWriter, r *http.Request) {
1146 userinfo := login.GetUserInfo(r)
1147 templinfo := getInfo(r)
1148 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1149 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1150 err := readviews.Execute(w, "honkers.html", templinfo)
1151 if err != nil {
1152 log.Print(err)
1153 }
1154}
1155
1156var combocache = cacheNew(func(userid int64) ([]string, bool) {
1157 honkers := gethonkers(userid)
1158 var combos []string
1159 for _, h := range honkers {
1160 combos = append(combos, h.Combos...)
1161 }
1162 for i, c := range combos {
1163 if c == "-" {
1164 combos[i] = ""
1165 }
1166 }
1167 combos = oneofakind(combos)
1168 sort.Strings(combos)
1169 return combos, true
1170})
1171
1172func showcombos(w http.ResponseWriter, r *http.Request) {
1173 userinfo := login.GetUserInfo(r)
1174 var combos []string
1175 combocache.Get(userinfo.UserID, &combos)
1176 templinfo := getInfo(r)
1177 err := readviews.Execute(w, "combos.html", templinfo)
1178 if err != nil {
1179 log.Print(err)
1180 }
1181}
1182
1183func submithonker(w http.ResponseWriter, r *http.Request) {
1184 u := login.GetUserInfo(r)
1185 name := r.FormValue("name")
1186 url := r.FormValue("url")
1187 peep := r.FormValue("peep")
1188 combos := r.FormValue("combos")
1189 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1190
1191 defer combocache.Clear(u.UserID)
1192
1193 if honkerid > 0 {
1194 goodbye := r.FormValue("goodbye")
1195 if goodbye == "F" {
1196 db := opendatabase()
1197 row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1198 honkerid, u.UserID)
1199 err := row.Scan(&url)
1200 if err != nil {
1201 log.Printf("can't get honker xid: %s", err)
1202 return
1203 }
1204 log.Printf("unsubscribing from %s", url)
1205 user, _ := butwhatabout(u.Username)
1206 _, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, "sub")
1207 if err != nil {
1208 log.Printf("error updating honker: %s", err)
1209 return
1210 }
1211 go itakeitallback(user, url)
1212
1213 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1214 return
1215 }
1216 if goodbye == "X" {
1217 db := opendatabase()
1218 row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1219 honkerid, u.UserID)
1220 err := row.Scan(&url)
1221 if err != nil {
1222 log.Printf("can't get honker xid: %s", err)
1223 return
1224 }
1225 log.Printf("resubscribing to %s", url)
1226 user, _ := butwhatabout(u.Username)
1227 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "unsub")
1228 if err == nil {
1229 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "peep")
1230 }
1231 if err != nil {
1232 log.Printf("error updating honker: %s", err)
1233 return
1234 }
1235 go subsub(user, url)
1236
1237 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1238 return
1239 }
1240 combos = " " + strings.TrimSpace(combos) + " "
1241 _, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1242 if err != nil {
1243 log.Printf("update honker err: %s", err)
1244 return
1245 }
1246 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1247 return
1248 }
1249
1250 flavor := "presub"
1251 if peep == "peep" {
1252 flavor = "peep"
1253 }
1254 p, err := investigate(url)
1255 if err != nil {
1256 http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1257 log.Printf("failed to investigate honker: %s", err)
1258 return
1259 }
1260 url = p.XID
1261
1262 db := opendatabase()
1263 row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1264 var x string
1265 err = row.Scan(&x)
1266 if err != sql.ErrNoRows {
1267 http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1268 if err != nil {
1269 log.Printf("honker scan err: %s", err)
1270 }
1271 return
1272 }
1273
1274 if name == "" {
1275 name = p.Handle
1276 }
1277 _, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1278 if err != nil {
1279 log.Print(err)
1280 return
1281 }
1282 if flavor == "presub" {
1283 user, _ := butwhatabout(u.Username)
1284 go subsub(user, url)
1285 }
1286 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1287}
1288
1289func hfcspage(w http.ResponseWriter, r *http.Request) {
1290 userinfo := login.GetUserInfo(r)
1291
1292 filters := getfilters(userinfo.UserID, filtAny)
1293
1294 templinfo := getInfo(r)
1295 templinfo["Filters"] = filters
1296 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1297 err := readviews.Execute(w, "hfcs.html", templinfo)
1298 if err != nil {
1299 log.Print(err)
1300 }
1301}
1302
1303func savehfcs(w http.ResponseWriter, r *http.Request) {
1304 userinfo := login.GetUserInfo(r)
1305 itsok := r.FormValue("itsok")
1306 if itsok == "iforgiveyou" {
1307 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1308 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1309 if err != nil {
1310 log.Printf("error deleting filter: %s", err)
1311 }
1312 filtcache.Clear(userinfo.UserID)
1313 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1314 return
1315 }
1316
1317 filt := new(Filter)
1318 filt.Name = r.FormValue("name")
1319 filt.Date = time.Now().UTC()
1320 filt.Actor = r.FormValue("actor")
1321 filt.IncludeAudience = r.FormValue("incaud") == "yes"
1322 filt.Text = r.FormValue("filttext")
1323 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1324 filt.AnnounceOf = r.FormValue("announceof")
1325 filt.Reject = r.FormValue("doreject") == "yes"
1326 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1327 filt.Hide = r.FormValue("dohide") == "yes"
1328 filt.Collapse = r.FormValue("docollapse") == "yes"
1329 filt.Rewrite = r.FormValue("filtrewrite")
1330 filt.Replace = r.FormValue("filtreplace")
1331
1332 if filt.Actor == "" && filt.Text == "" {
1333 log.Printf("blank filter")
1334 return
1335 }
1336
1337 j, err := jsonify(filt)
1338 if err == nil {
1339 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1340 }
1341 if err != nil {
1342 log.Printf("error saving filter: %s", err)
1343 }
1344
1345 filtcache.Clear(userinfo.UserID)
1346 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1347}
1348
1349func accountpage(w http.ResponseWriter, r *http.Request) {
1350 u := login.GetUserInfo(r)
1351 user, _ := butwhatabout(u.Username)
1352 templinfo := getInfo(r)
1353 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1354 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1355 templinfo["User"] = user
1356 err := readviews.Execute(w, "account.html", templinfo)
1357 if err != nil {
1358 log.Print(err)
1359 }
1360}
1361
1362func dochpass(w http.ResponseWriter, r *http.Request) {
1363 err := login.ChangePassword(w, r)
1364 if err != nil {
1365 log.Printf("error changing password: %s", err)
1366 }
1367 http.Redirect(w, r, "/account", http.StatusSeeOther)
1368}
1369
1370func fingerlicker(w http.ResponseWriter, r *http.Request) {
1371 orig := r.FormValue("resource")
1372
1373 log.Printf("finger lick: %s", orig)
1374
1375 if strings.HasPrefix(orig, "acct:") {
1376 orig = orig[5:]
1377 }
1378
1379 name := orig
1380 idx := strings.LastIndexByte(name, '/')
1381 if idx != -1 {
1382 name = name[idx+1:]
1383 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1384 log.Printf("foreign request rejected")
1385 name = ""
1386 }
1387 } else {
1388 idx = strings.IndexByte(name, '@')
1389 if idx != -1 {
1390 name = name[:idx]
1391 if name+"@"+serverName != orig {
1392 log.Printf("foreign request rejected")
1393 name = ""
1394 }
1395 }
1396 }
1397 user, err := butwhatabout(name)
1398 if err != nil {
1399 http.NotFound(w, r)
1400 return
1401 }
1402 if stealthmode(user.ID, r) {
1403 http.NotFound(w, r)
1404 return
1405 }
1406
1407 j := junk.New()
1408 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1409 j["aliases"] = []string{user.URL}
1410 var links []junk.Junk
1411 l := junk.New()
1412 l["rel"] = "self"
1413 l["type"] = `application/activity+json`
1414 l["href"] = user.URL
1415 links = append(links, l)
1416 j["links"] = links
1417
1418 w.Header().Set("Cache-Control", "max-age=3600")
1419 w.Header().Set("Content-Type", "application/jrd+json")
1420 j.Write(w)
1421}
1422
1423func somedays() string {
1424 secs := 432000 + notrand.Int63n(432000)
1425 return fmt.Sprintf("%d", secs)
1426}
1427
1428func avatate(w http.ResponseWriter, r *http.Request) {
1429 n := r.FormValue("a")
1430 a := avatar(n)
1431 w.Header().Set("Cache-Control", "max-age="+somedays())
1432 w.Write(a)
1433}
1434
1435func servecss(w http.ResponseWriter, r *http.Request) {
1436 fd, err := os.Open("views" + r.URL.Path)
1437 if err != nil {
1438 http.NotFound(w, r)
1439 return
1440 }
1441 w.Header().Set("Cache-Control", "max-age=0")
1442 w.Header().Set("Content-Type", "text/css; charset=utf-8")
1443 err = css.Filter(fd, w)
1444 if err != nil {
1445 log.Printf("error filtering css: %s", err)
1446 }
1447}
1448func serveasset(w http.ResponseWriter, r *http.Request) {
1449 w.Header().Set("Cache-Control", "max-age=7776000")
1450 http.ServeFile(w, r, "views"+r.URL.Path)
1451}
1452func servehtml(w http.ResponseWriter, r *http.Request) {
1453 templinfo := getInfo(r)
1454 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1455 if err != nil {
1456 log.Print(err)
1457 }
1458}
1459func serveemu(w http.ResponseWriter, r *http.Request) {
1460 xid := mux.Vars(r)["xid"]
1461 w.Header().Set("Cache-Control", "max-age="+somedays())
1462 http.ServeFile(w, r, "emus/"+xid)
1463}
1464func servememe(w http.ResponseWriter, r *http.Request) {
1465 xid := mux.Vars(r)["xid"]
1466 w.Header().Set("Cache-Control", "max-age="+somedays())
1467 http.ServeFile(w, r, "memes/"+xid)
1468}
1469
1470func servefile(w http.ResponseWriter, r *http.Request) {
1471 xid := mux.Vars(r)["xid"]
1472 row := stmtGetFileData.QueryRow(xid)
1473 var media string
1474 var data []byte
1475 err := row.Scan(&media, &data)
1476 if err != nil {
1477 log.Printf("error loading file: %s", err)
1478 http.NotFound(w, r)
1479 return
1480 }
1481 w.Header().Set("Content-Type", media)
1482 w.Header().Set("X-Content-Type-Options", "nosniff")
1483 w.Header().Set("Cache-Control", "max-age="+somedays())
1484 w.Write(data)
1485}
1486
1487func nomoroboto(w http.ResponseWriter, r *http.Request) {
1488 io.WriteString(w, "User-agent: *\n")
1489 io.WriteString(w, "Disallow: /a\n")
1490 io.WriteString(w, "Disallow: /d\n")
1491 io.WriteString(w, "Disallow: /meme\n")
1492 for _, u := range allusers() {
1493 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1494 }
1495}
1496
1497func webhydra(w http.ResponseWriter, r *http.Request) {
1498 u := login.GetUserInfo(r)
1499 userid := u.UserID
1500 templinfo := getInfo(r)
1501 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1502 page := r.FormValue("page")
1503 var honks []*Honk
1504 switch page {
1505 case "atme":
1506 honks = gethonksforme(userid)
1507 case "home":
1508 honks = gethonksforuser(userid)
1509 honks = osmosis(honks, userid)
1510 case "first":
1511 honks = gethonksforuserfirstclass(userid)
1512 honks = osmosis(honks, userid)
1513 case "combo":
1514 c := r.FormValue("c")
1515 honks = gethonksbycombo(userid, c)
1516 case "convoy":
1517 c := r.FormValue("c")
1518 honks = gethonksbyconvoy(userid, c)
1519 case "honker":
1520 xid := r.FormValue("xid")
1521 if strings.IndexByte(xid, '@') != -1 {
1522 xid = gofish(xid)
1523 }
1524 honks = gethonksbyxonker(userid, xid)
1525 default:
1526 http.NotFound(w, r)
1527 }
1528 if len(honks) > 0 {
1529 templinfo["TopXID"] = honks[0].XID
1530 }
1531 if topxid := r.FormValue("topxid"); topxid != "" {
1532 for i, h := range honks {
1533 if h.XID == topxid {
1534 honks = honks[0:i]
1535 break
1536 }
1537 }
1538 log.Printf("topxid %d frags", len(honks))
1539 }
1540 reverbolate(userid, honks)
1541 templinfo["Honks"] = honks
1542 w.Header().Set("Content-Type", "text/html; charset=utf-8")
1543 err := readviews.Execute(w, "honkfrags.html", templinfo)
1544 if err != nil {
1545 log.Printf("frag error: %s", err)
1546 }
1547}
1548
1549func serve() {
1550 db := opendatabase()
1551 login.Init(db)
1552
1553 listener, err := openListener()
1554 if err != nil {
1555 log.Fatal(err)
1556 }
1557 go redeliverator()
1558
1559 debug := false
1560 getconfig("debug", &debug)
1561 readviews = templates.Load(debug,
1562 "views/honkpage.html",
1563 "views/honkfrags.html",
1564 "views/honkers.html",
1565 "views/hfcs.html",
1566 "views/combos.html",
1567 "views/honkform.html",
1568 "views/honk.html",
1569 "views/account.html",
1570 "views/about.html",
1571 "views/funzone.html",
1572 "views/login.html",
1573 "views/xzone.html",
1574 "views/header.html",
1575 "views/onts.html",
1576 "views/honkpage.js",
1577 )
1578 if !debug {
1579 assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1580 for _, s := range assets {
1581 savedassetparams[s] = getassetparam(s)
1582 }
1583 }
1584
1585 mux := mux.NewRouter()
1586 mux.Use(login.Checker)
1587
1588 posters := mux.Methods("POST").Subrouter()
1589 getters := mux.Methods("GET").Subrouter()
1590
1591 getters.HandleFunc("/", homepage)
1592 getters.HandleFunc("/home", homepage)
1593 getters.HandleFunc("/front", homepage)
1594 getters.HandleFunc("/robots.txt", nomoroboto)
1595 getters.HandleFunc("/rss", showrss)
1596 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1597 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1598 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1599 posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1600 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1601 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1602 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1603 getters.HandleFunc("/a", avatate)
1604 getters.HandleFunc("/o", thelistingoftheontologies)
1605 getters.HandleFunc("/o/{name:.+}", showontology)
1606 getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1607 getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1608 getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1609 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1610
1611 getters.HandleFunc("/style.css", servecss)
1612 getters.HandleFunc("/local.css", servecss)
1613 getters.HandleFunc("/honkpage.js", serveasset)
1614 getters.HandleFunc("/about", servehtml)
1615 getters.HandleFunc("/login", servehtml)
1616 posters.HandleFunc("/dologin", login.LoginFunc)
1617 getters.HandleFunc("/logout", login.LogoutFunc)
1618
1619 loggedin := mux.NewRoute().Subrouter()
1620 loggedin.Use(login.Required)
1621 loggedin.HandleFunc("/account", accountpage)
1622 loggedin.HandleFunc("/funzone", showfunzone)
1623 loggedin.HandleFunc("/chpass", dochpass)
1624 loggedin.HandleFunc("/atme", homepage)
1625 loggedin.HandleFunc("/hfcs", hfcspage)
1626 loggedin.HandleFunc("/xzone", xzone)
1627 loggedin.HandleFunc("/edit", edithonkpage)
1628 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1629 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1630 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1631 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
1632 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1633 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1634 loggedin.HandleFunc("/honkers", showhonkers)
1635 loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1636 loggedin.HandleFunc("/h", showhonker)
1637 loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1638 loggedin.HandleFunc("/c", showcombos)
1639 loggedin.HandleFunc("/t", showconvoy)
1640 loggedin.HandleFunc("/q", showsearch)
1641 loggedin.HandleFunc("/hydra", webhydra)
1642 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1643
1644 err = http.Serve(listener, mux)
1645 if err != nil {
1646 log.Fatal(err)
1647 }
1648}