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/template"
23 "io"
24 notrand "math/rand"
25 "mime/multipart"
26 "net/http"
27 "net/url"
28 "os"
29 "os/signal"
30 "regexp"
31 "sort"
32 "strconv"
33 "strings"
34 "syscall"
35 "time"
36 "unicode/utf8"
37
38 "github.com/gorilla/mux"
39 "humungus.tedunangst.com/r/webs/cache"
40 "humungus.tedunangst.com/r/webs/httpsig"
41 "humungus.tedunangst.com/r/webs/junk"
42 "humungus.tedunangst.com/r/webs/login"
43 "humungus.tedunangst.com/r/webs/rss"
44 "humungus.tedunangst.com/r/webs/templates"
45)
46
47var readviews *templates.Template
48
49var userSep = "u"
50var honkSep = "h"
51
52var develMode = false
53
54var allemus []Emu
55
56func getuserstyle(u *login.UserInfo) template.HTMLAttr {
57 if u == nil {
58 return ""
59 }
60 user, _ := butwhatabout(u.Username)
61 class := template.HTMLAttr("")
62 if user.Options.SkinnyCSS {
63 class += `class="skinny"`
64 }
65 return class
66}
67
68func getmaplink(u *login.UserInfo) string {
69 if u == nil {
70 return "osm"
71 }
72 user, _ := butwhatabout(u.Username)
73 ml := user.Options.MapLink
74 if ml == "" {
75 ml = "osm"
76 }
77 return ml
78}
79
80func getInfo(r *http.Request) map[string]interface{} {
81 templinfo := make(map[string]interface{})
82 templinfo["StyleParam"] = getassetparam(viewDir + "/views/style.css")
83 templinfo["LocalStyleParam"] = getassetparam(dataDir + "/views/local.css")
84 templinfo["JSParam"] = getassetparam(viewDir + "/views/honkpage.js")
85 templinfo["MiscJSParam"] = getassetparam(viewDir + "/views/misc.js")
86 templinfo["LocalJSParam"] = getassetparam(dataDir + "/views/local.js")
87 templinfo["ServerName"] = serverName
88 templinfo["IconName"] = iconName
89 templinfo["UserSep"] = userSep
90 if u := login.GetUserInfo(r); u != nil {
91 templinfo["UserInfo"], _ = butwhatabout(u.Username)
92 templinfo["UserStyle"] = getuserstyle(u)
93 var combos []string
94 combocache.Get(u.UserID, &combos)
95 templinfo["Combos"] = combos
96 }
97 return templinfo
98}
99
100func homepage(w http.ResponseWriter, r *http.Request) {
101 templinfo := getInfo(r)
102 u := login.GetUserInfo(r)
103 var honks []*Honk
104 var userid int64 = -1
105
106 templinfo["ServerMessage"] = serverMsg
107 if u == nil || r.URL.Path == "/front" {
108 switch r.URL.Path {
109 case "/events":
110 honks = geteventhonks(userid)
111 templinfo["ServerMessage"] = "some recent and upcoming events"
112 default:
113 templinfo["ShowRSS"] = true
114 honks = getpublichonks()
115 }
116 } else {
117 userid = u.UserID
118 switch r.URL.Path {
119 case "/atme":
120 templinfo["ServerMessage"] = "at me!"
121 templinfo["PageName"] = "atme"
122 honks = gethonksforme(userid, 0)
123 honks = osmosis(honks, userid, false)
124 menewnone(userid)
125 templinfo["UserInfo"], _ = butwhatabout(u.Username)
126 case "/longago":
127 templinfo["ServerMessage"] = "long ago and far away!"
128 templinfo["PageName"] = "longago"
129 honks = gethonksfromlongago(userid, 0)
130 honks = osmosis(honks, userid, false)
131 case "/events":
132 templinfo["ServerMessage"] = "some recent and upcoming events"
133 templinfo["PageName"] = "events"
134 honks = geteventhonks(userid)
135 honks = osmosis(honks, userid, true)
136 case "/first":
137 templinfo["PageName"] = "first"
138 honks = gethonksforuserfirstclass(userid, 0)
139 honks = osmosis(honks, userid, true)
140 case "/saved":
141 templinfo["ServerMessage"] = "saved honks"
142 templinfo["PageName"] = "saved"
143 honks = getsavedhonks(userid, 0)
144 default:
145 templinfo["PageName"] = "home"
146 honks = gethonksforuser(userid, 0)
147 honks = osmosis(honks, userid, true)
148 }
149 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
150 }
151
152 honkpage(w, u, honks, templinfo)
153}
154
155func showemus(w http.ResponseWriter, r *http.Request) {
156 templinfo := getInfo(r)
157 templinfo["Emus"] = allemus
158 err := readviews.Execute(w, "emus.html", templinfo)
159 if err != nil {
160 elog.Print(err)
161 }
162}
163
164func showfunzone(w http.ResponseWriter, r *http.Request) {
165 var emunames, memenames []string
166 emuext := make(map[string]string)
167 dir, err := os.Open(dataDir + "/emus")
168 if err == nil {
169 emunames, _ = dir.Readdirnames(0)
170 dir.Close()
171 }
172 for i, e := range emunames {
173 if len(e) > 4 {
174 emunames[i] = e[:len(e)-4]
175 emuext[emunames[i]] = e[len(e)-4:]
176 }
177 }
178 dir, err = os.Open(dataDir + "/memes")
179 if err == nil {
180 memenames, _ = dir.Readdirnames(0)
181 dir.Close()
182 }
183 sort.Strings(emunames)
184 sort.Strings(memenames)
185 templinfo := getInfo(r)
186 templinfo["Emus"] = emunames
187 templinfo["Emuext"] = emuext
188 templinfo["Memes"] = memenames
189 err = readviews.Execute(w, "funzone.html", templinfo)
190 if err != nil {
191 elog.Print(err)
192 }
193}
194
195func showrss(w http.ResponseWriter, r *http.Request) {
196 name := mux.Vars(r)["name"]
197
198 var honks []*Honk
199 if name != "" {
200 honks = gethonksbyuser(name, false, 0)
201 } else {
202 honks = getpublichonks()
203 }
204 reverbolate(-1, honks)
205
206 home := fmt.Sprintf("https://%s/", serverName)
207 base := home
208 if name != "" {
209 home += "u/" + name
210 name += " "
211 }
212 feed := rss.Feed{
213 Title: name + "honk",
214 Link: home,
215 Description: name + "honk rss",
216 Image: &rss.Image{
217 URL: base + "icon.png",
218 Title: name + "honk rss",
219 Link: home,
220 },
221 }
222 var modtime time.Time
223 for _, honk := range honks {
224 if !firstclass(honk) {
225 continue
226 }
227 desc := string(honk.HTML)
228 if t := honk.Time; t != nil {
229 desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM EDT Mon Jan 02"))
230 if t.Duration != 0 {
231 desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
232 }
233 }
234 if p := honk.Place; p != nil {
235 desc += string(templates.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
236 p.Url, p.Name, p.Latitude, p.Longitude))
237 }
238 for _, d := range honk.Donks {
239 desc += string(templates.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
240 d.URL, d.Desc))
241 if strings.HasPrefix(d.Media, "image") {
242 desc += string(templates.Sprintf(`<img src="%s">`, d.URL))
243 }
244 }
245
246 feed.Items = append(feed.Items, &rss.Item{
247 Title: fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
248 Description: rss.CData{Data: desc},
249 Link: honk.URL,
250 PubDate: honk.Date.Format(time.RFC1123),
251 Guid: &rss.Guid{IsPermaLink: true, Value: honk.URL},
252 })
253 if honk.Date.After(modtime) {
254 modtime = honk.Date
255 }
256 }
257 if !develMode {
258 w.Header().Set("Cache-Control", "max-age=300")
259 w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
260 }
261
262 err := feed.Write(w)
263 if err != nil {
264 elog.Printf("error writing rss: %s", err)
265 }
266}
267
268func crappola(j junk.Junk) bool {
269 t, _ := j.GetString("type")
270 a, _ := j.GetString("actor")
271 o, _ := j.GetString("object")
272 if t == "Delete" && a == o {
273 dlog.Printf("crappola from %s", a)
274 return true
275 }
276 return false
277}
278
279func ping(user *WhatAbout, who string) {
280 if targ := fullname(who, user.ID); targ != "" {
281 who = targ
282 }
283 if !strings.HasPrefix(who, "https:") {
284 who = gofish(who)
285 }
286 if who == "" {
287 ilog.Printf("nobody to ping!")
288 return
289 }
290 var box *Box
291 ok := boxofboxes.Get(who, &box)
292 if !ok {
293 ilog.Printf("no inbox to ping %s", who)
294 return
295 }
296 ilog.Printf("sending ping to %s", box.In)
297 j := junk.New()
298 j["@context"] = itiswhatitis
299 j["type"] = "Ping"
300 j["id"] = user.URL + "/ping/" + xfiltrate()
301 j["actor"] = user.URL
302 j["to"] = who
303 ki := ziggy(user.ID)
304 if ki == nil {
305 return
306 }
307 err := PostJunk(ki.keyname, ki.seckey, box.In, j)
308 if err != nil {
309 elog.Printf("can't send ping: %s", err)
310 return
311 }
312 ilog.Printf("sent ping to %s: %s", who, j["id"])
313}
314
315func pong(user *WhatAbout, who string, obj string) {
316 var box *Box
317 ok := boxofboxes.Get(who, &box)
318 if !ok {
319 ilog.Printf("no inbox to pong %s", who)
320 return
321 }
322 j := junk.New()
323 j["@context"] = itiswhatitis
324 j["type"] = "Pong"
325 j["id"] = user.URL + "/pong/" + xfiltrate()
326 j["actor"] = user.URL
327 j["to"] = who
328 j["object"] = obj
329 ki := ziggy(user.ID)
330 if ki == nil {
331 return
332 }
333 err := PostJunk(ki.keyname, ki.seckey, box.In, j)
334 if err != nil {
335 elog.Printf("can't send pong: %s", err)
336 return
337 }
338}
339
340func inbox(w http.ResponseWriter, r *http.Request) {
341 name := mux.Vars(r)["name"]
342 user, err := butwhatabout(name)
343 if err != nil {
344 http.NotFound(w, r)
345 return
346 }
347 if stealthmode(user.ID, r) {
348 http.NotFound(w, r)
349 return
350 }
351 var buf bytes.Buffer
352 limiter := io.LimitReader(r.Body, 1*1024*1024)
353 io.Copy(&buf, limiter)
354 payload := buf.Bytes()
355 j, err := junk.FromBytes(payload)
356 if err != nil {
357 ilog.Printf("bad payload: %s", err)
358 ilog.Writer().Write(payload)
359 ilog.Writer().Write([]byte{'\n'})
360 return
361 }
362
363 if crappola(j) {
364 return
365 }
366 what, _ := j.GetString("type")
367 obj, _ := j.GetString("object")
368 if what == "Like" || what == "Dislike" || (what == "EmojiReact" && originate(obj) != serverName) {
369 return
370 }
371 who, _ := j.GetString("actor")
372 if rejectactor(user.ID, who) {
373 return
374 }
375
376 keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
377 if err != nil && keyname != "" {
378 savingthrow(keyname)
379 keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
380 }
381 if err != nil {
382 ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
383 if keyname != "" {
384 ilog.Printf("bad signature from %s", keyname)
385 }
386 http.Error(w, "what did you call me?", http.StatusTeapot)
387 return
388 }
389 origin := keymatch(keyname, who)
390 if origin == "" {
391 ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
392 return
393 }
394
395 switch what {
396 case "Ping":
397 id, _ := j.GetString("id")
398 ilog.Printf("ping from %s: %s", who, id)
399 pong(user, who, id)
400 case "Pong":
401 ilog.Printf("pong from %s: %s", who, obj)
402 case "Follow":
403 if obj != user.URL {
404 ilog.Printf("can't follow %s", obj)
405 return
406 }
407 followme(user, who, who, j)
408 case "Accept":
409 followyou2(user, j)
410 case "Reject":
411 nofollowyou2(user, j)
412 case "Update":
413 obj, ok := j.GetMap("object")
414 if ok {
415 what, _ := obj.GetString("type")
416 switch what {
417 case "Service":
418 fallthrough
419 case "Person":
420 return
421 case "Question":
422 return
423 }
424 }
425 go xonksaver(user, j, origin)
426 case "Undo":
427 obj, ok := j.GetMap("object")
428 if !ok {
429 folxid, ok := j.GetString("object")
430 if ok && originate(folxid) == origin {
431 unfollowme(user, "", "", j)
432 }
433 return
434 }
435 what, _ := obj.GetString("type")
436 switch what {
437 case "Follow":
438 unfollowme(user, who, who, j)
439 case "Announce":
440 xid, _ := obj.GetString("object")
441 dlog.Printf("undo announce: %s", xid)
442 case "Like":
443 default:
444 ilog.Printf("unknown undo: %s", what)
445 }
446 case "EmojiReact":
447 obj, ok := j.GetString("object")
448 if ok {
449 content, _ := j.GetString("content")
450 addreaction(user, obj, who, content)
451 }
452 default:
453 go saveandcheck(user, j, origin)
454 }
455}
456
457func saveandcheck(user *WhatAbout, j junk.Junk, origin string) {
458 xonk := xonksaver(user, j, origin)
459 if xonk == nil {
460 return
461 }
462 if sname := shortname(user.ID, xonk.Honker); sname == "" {
463 dlog.Printf("received unexpected activity from %s", xonk.Honker)
464 if xonk.Whofore == 0 {
465 dlog.Printf("it's not even for me!")
466 }
467 }
468}
469
470func serverinbox(w http.ResponseWriter, r *http.Request) {
471 user := getserveruser()
472 if stealthmode(user.ID, r) {
473 http.NotFound(w, r)
474 return
475 }
476 var buf bytes.Buffer
477 io.Copy(&buf, r.Body)
478 payload := buf.Bytes()
479 j, err := junk.FromBytes(payload)
480 if err != nil {
481 ilog.Printf("bad payload: %s", err)
482 ilog.Writer().Write(payload)
483 ilog.Writer().Write([]byte{'\n'})
484 return
485 }
486 if crappola(j) {
487 return
488 }
489 keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
490 if err != nil && keyname != "" {
491 savingthrow(keyname)
492 keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
493 }
494 if err != nil {
495 ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
496 if keyname != "" {
497 ilog.Printf("bad signature from %s", keyname)
498 }
499 http.Error(w, "what did you call me?", http.StatusTeapot)
500 return
501 }
502 who, _ := j.GetString("actor")
503 origin := keymatch(keyname, who)
504 if origin == "" {
505 ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
506 return
507 }
508 if rejectactor(user.ID, who) {
509 return
510 }
511 re_ont := regexp.MustCompile("https://" + serverName + "/o/([\\pL[:digit:]]+)")
512 what, _ := j.GetString("type")
513 dlog.Printf("server got a %s", what)
514 switch what {
515 case "Follow":
516 obj, _ := j.GetString("object")
517 if obj == user.URL {
518 ilog.Printf("can't follow the server!")
519 return
520 }
521 m := re_ont.FindStringSubmatch(obj)
522 if len(m) != 2 {
523 ilog.Printf("not sure how to handle this")
524 return
525 }
526 ont := "#" + m[1]
527
528 followme(user, who, ont, j)
529 case "Undo":
530 obj, ok := j.GetMap("object")
531 if !ok {
532 ilog.Printf("unknown undo no object")
533 return
534 }
535 what, _ := obj.GetString("type")
536 if what != "Follow" {
537 ilog.Printf("unknown undo: %s", what)
538 return
539 }
540 targ, _ := obj.GetString("object")
541 m := re_ont.FindStringSubmatch(targ)
542 if len(m) != 2 {
543 ilog.Printf("not sure how to handle this")
544 return
545 }
546 ont := "#" + m[1]
547 unfollowme(user, who, ont, j)
548 default:
549 ilog.Printf("unhandled server activity: %s", what)
550 dumpactivity(j)
551 }
552}
553
554func serveractor(w http.ResponseWriter, r *http.Request) {
555 user := getserveruser()
556 if stealthmode(user.ID, r) {
557 http.NotFound(w, r)
558 return
559 }
560 j := junkuser(user)
561 j.Write(w)
562}
563
564func ximport(w http.ResponseWriter, r *http.Request) {
565 u := login.GetUserInfo(r)
566 xid := strings.TrimSpace(r.FormValue("q"))
567 xonk := getxonk(u.UserID, xid)
568 if xonk == nil {
569 p, _ := investigate(xid)
570 if p != nil {
571 xid = p.XID
572 }
573 j, err := GetJunk(u.UserID, xid)
574 if err != nil {
575 http.Error(w, "error getting external object", http.StatusInternalServerError)
576 ilog.Printf("error getting external object: %s", err)
577 return
578 }
579 allinjest(originate(xid), j)
580 dlog.Printf("importing %s", xid)
581 user, _ := butwhatabout(u.Username)
582
583 info, _ := somethingabout(j)
584 if info == nil {
585 xonk = xonksaver(user, j, originate(xid))
586 } else if info.What == SomeActor {
587 outbox, _ := j.GetString("outbox")
588 gimmexonks(user, outbox)
589 http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
590 return
591 } else if info.What == SomeCollection {
592 gimmexonks(user, xid)
593 http.Redirect(w, r, "/xzone", http.StatusSeeOther)
594 return
595 }
596 }
597 convoy := ""
598 if xonk != nil {
599 convoy = xonk.Convoy
600 }
601 http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
602}
603
604func xzone(w http.ResponseWriter, r *http.Request) {
605 u := login.GetUserInfo(r)
606 rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
607 if err != nil {
608 elog.Printf("query err: %s", err)
609 return
610 }
611 defer rows.Close()
612 var honkers []Honker
613 for rows.Next() {
614 var xid string
615 rows.Scan(&xid)
616 honkers = append(honkers, Honker{XID: xid})
617 }
618 rows.Close()
619 for i := range honkers {
620 _, honkers[i].Handle = handles(honkers[i].XID)
621 }
622 templinfo := getInfo(r)
623 templinfo["XCSRF"] = login.GetCSRF("ximport", r)
624 templinfo["Honkers"] = honkers
625 err = readviews.Execute(w, "xzone.html", templinfo)
626 if err != nil {
627 elog.Print(err)
628 }
629}
630
631var oldoutbox = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
632 user, err := butwhatabout(name)
633 if err != nil {
634 return nil, false
635 }
636 honks := gethonksbyuser(name, false, 0)
637 if len(honks) > 20 {
638 honks = honks[0:20]
639 }
640
641 var jonks []junk.Junk
642 for _, h := range honks {
643 j, _ := jonkjonk(user, h)
644 jonks = append(jonks, j)
645 }
646
647 j := junk.New()
648 j["@context"] = itiswhatitis
649 j["id"] = user.URL + "/outbox"
650 j["attributedTo"] = user.URL
651 j["type"] = "OrderedCollection"
652 j["totalItems"] = len(jonks)
653 j["orderedItems"] = jonks
654
655 return j.ToBytes(), true
656}, Duration: 1 * time.Minute})
657
658func outbox(w http.ResponseWriter, r *http.Request) {
659 name := mux.Vars(r)["name"]
660 user, err := butwhatabout(name)
661 if err != nil {
662 http.NotFound(w, r)
663 return
664 }
665 if stealthmode(user.ID, r) {
666 http.NotFound(w, r)
667 return
668 }
669 var j []byte
670 ok := oldoutbox.Get(name, &j)
671 if ok {
672 w.Header().Set("Content-Type", theonetruename)
673 w.Write(j)
674 } else {
675 http.NotFound(w, r)
676 }
677}
678
679var oldempties = cache.New(cache.Options{Filler: func(url string) ([]byte, bool) {
680 colname := "/followers"
681 if strings.HasSuffix(url, "/following") {
682 colname = "/following"
683 }
684 user := fmt.Sprintf("https://%s%s", serverName, url[:len(url)-10])
685 j := junk.New()
686 j["@context"] = itiswhatitis
687 j["id"] = user + colname
688 j["attributedTo"] = user
689 j["type"] = "OrderedCollection"
690 j["totalItems"] = 0
691 j["orderedItems"] = []junk.Junk{}
692
693 return j.ToBytes(), true
694}})
695
696func emptiness(w http.ResponseWriter, r *http.Request) {
697 name := mux.Vars(r)["name"]
698 user, err := butwhatabout(name)
699 if err != nil {
700 http.NotFound(w, r)
701 return
702 }
703 if stealthmode(user.ID, r) {
704 http.NotFound(w, r)
705 return
706 }
707 var j []byte
708 ok := oldempties.Get(r.URL.Path, &j)
709 if ok {
710 w.Header().Set("Content-Type", theonetruename)
711 w.Write(j)
712 } else {
713 http.NotFound(w, r)
714 }
715}
716
717func showuser(w http.ResponseWriter, r *http.Request) {
718 name := mux.Vars(r)["name"]
719 user, err := butwhatabout(name)
720 if err != nil {
721 ilog.Printf("user not found %s: %s", name, err)
722 http.NotFound(w, r)
723 return
724 }
725 if stealthmode(user.ID, r) {
726 http.NotFound(w, r)
727 return
728 }
729 if friendorfoe(r.Header.Get("Accept")) {
730 j, ok := asjonker(name)
731 if ok {
732 w.Header().Set("Content-Type", theonetruename)
733 w.Write(j)
734 } else {
735 http.NotFound(w, r)
736 }
737 return
738 }
739 u := login.GetUserInfo(r)
740 if u != nil && u.Username != name {
741 u = nil
742 }
743 honks := gethonksbyuser(name, u != nil, 0)
744 templinfo := getInfo(r)
745 templinfo["PageName"] = "user"
746 templinfo["PageArg"] = name
747 templinfo["Name"] = user.Name
748 templinfo["WhatAbout"] = user.HTAbout
749 templinfo["ServerMessage"] = ""
750 templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", user.URL)
751 if u != nil {
752 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
753 }
754 honkpage(w, u, honks, templinfo)
755}
756
757func showhonker(w http.ResponseWriter, r *http.Request) {
758 u := login.GetUserInfo(r)
759 name := mux.Vars(r)["name"]
760 var honks []*Honk
761 if name == "" {
762 name = r.FormValue("xid")
763 honks = gethonksbyxonker(u.UserID, name, 0)
764 } else {
765 honks = gethonksbyhonker(u.UserID, name, 0)
766 }
767 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
768<input type="hidden" name="CSRF" value="%s">
769<input type="hidden" name="url" value="%s">
770<button tabindex=1 name="add honker" value="add honker">add honker</button>
771</form>`, login.GetCSRF("submithonker", r), name)
772 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, name, name, miniform)
773 templinfo := getInfo(r)
774 templinfo["PageName"] = "honker"
775 templinfo["PageArg"] = name
776 templinfo["ServerMessage"] = msg
777 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
778 honkpage(w, u, honks, templinfo)
779}
780
781func showcombo(w http.ResponseWriter, r *http.Request) {
782 name := mux.Vars(r)["name"]
783 u := login.GetUserInfo(r)
784 honks := gethonksbycombo(u.UserID, name, 0)
785 honks = osmosis(honks, u.UserID, true)
786 templinfo := getInfo(r)
787 templinfo["PageName"] = "combo"
788 templinfo["PageArg"] = name
789 templinfo["ServerMessage"] = "honks by combo: " + name
790 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
791 honkpage(w, u, honks, templinfo)
792}
793func showconvoy(w http.ResponseWriter, r *http.Request) {
794 c := r.FormValue("c")
795 u := login.GetUserInfo(r)
796 honks := gethonksbyconvoy(u.UserID, c, 0)
797 templinfo := getInfo(r)
798 if len(honks) > 0 {
799 templinfo["TopHID"] = honks[0].ID
800 }
801 honks = osmosis(honks, u.UserID, false)
802 //reversehonks(honks)
803 honks = threadsort(honks)
804 templinfo["PageName"] = "convoy"
805 templinfo["PageArg"] = c
806 templinfo["ServerMessage"] = "honks in convoy: " + c
807 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
808 honkpage(w, u, honks, templinfo)
809}
810func showsearch(w http.ResponseWriter, r *http.Request) {
811 q := r.FormValue("q")
812 if strings.HasPrefix(q, "https://") {
813 ximport(w, r)
814 return
815 }
816 u := login.GetUserInfo(r)
817 honks := gethonksbysearch(u.UserID, q, 0)
818 templinfo := getInfo(r)
819 templinfo["PageName"] = "search"
820 templinfo["PageArg"] = q
821 templinfo["ServerMessage"] = "honks for search: " + q
822 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
823 honkpage(w, u, honks, templinfo)
824}
825func showontology(w http.ResponseWriter, r *http.Request) {
826 name := mux.Vars(r)["name"]
827 u := login.GetUserInfo(r)
828 var userid int64 = -1
829 if u != nil {
830 userid = u.UserID
831 }
832 honks := gethonksbyontology(userid, "#"+name, 0)
833 if friendorfoe(r.Header.Get("Accept")) {
834 if len(honks) > 40 {
835 honks = honks[0:40]
836 }
837
838 var xids []string
839 for _, h := range honks {
840 xids = append(xids, h.XID)
841 }
842
843 user := getserveruser()
844
845 j := junk.New()
846 j["@context"] = itiswhatitis
847 j["id"] = fmt.Sprintf("https://%s/o/%s", serverName, name)
848 j["name"] = "#" + name
849 j["attributedTo"] = user.URL
850 j["type"] = "OrderedCollection"
851 j["totalItems"] = len(xids)
852 j["orderedItems"] = xids
853
854 j.Write(w)
855 return
856 }
857
858 templinfo := getInfo(r)
859 templinfo["ServerMessage"] = "honks by ontology: " + name
860 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
861 honkpage(w, u, honks, templinfo)
862}
863
864type Ont struct {
865 Name string
866 Count int64
867}
868
869func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
870 u := login.GetUserInfo(r)
871 var userid int64 = -1
872 if u != nil {
873 userid = u.UserID
874 }
875 rows, err := stmtAllOnts.Query(userid)
876 if err != nil {
877 elog.Printf("selection error: %s", err)
878 return
879 }
880 defer rows.Close()
881 var onts []Ont
882 for rows.Next() {
883 var o Ont
884 err := rows.Scan(&o.Name, &o.Count)
885 if err != nil {
886 elog.Printf("error scanning ont: %s", err)
887 continue
888 }
889 if utf8.RuneCountInString(o.Name) > 24 {
890 continue
891 }
892 o.Name = o.Name[1:]
893 onts = append(onts, o)
894 }
895 sort.Slice(onts, func(i, j int) bool {
896 return onts[i].Name < onts[j].Name
897 })
898 if u == nil && !develMode {
899 w.Header().Set("Cache-Control", "max-age=300")
900 }
901 templinfo := getInfo(r)
902 templinfo["Onts"] = onts
903 templinfo["FirstRune"] = func(s string) rune { r, _ := utf8.DecodeRuneInString(s); return r }
904 err = readviews.Execute(w, "onts.html", templinfo)
905 if err != nil {
906 elog.Print(err)
907 }
908}
909
910type Track struct {
911 xid string
912 who string
913}
914
915func getbacktracks(xid string) []string {
916 c := make(chan bool)
917 dumptracks <- c
918 <-c
919 row := stmtGetTracks.QueryRow(xid)
920 var rawtracks string
921 err := row.Scan(&rawtracks)
922 if err != nil {
923 if err != sql.ErrNoRows {
924 elog.Printf("error scanning tracks: %s", err)
925 }
926 return nil
927 }
928 var rcpts []string
929 for _, f := range strings.Split(rawtracks, " ") {
930 idx := strings.LastIndexByte(f, '#')
931 if idx != -1 {
932 f = f[:idx]
933 }
934 if !strings.HasPrefix(f, "https://") {
935 f = fmt.Sprintf("%%https://%s/inbox", f)
936 }
937 rcpts = append(rcpts, f)
938 }
939 return rcpts
940}
941
942func savetracks(tracks map[string][]string) {
943 db := opendatabase()
944 tx, err := db.Begin()
945 if err != nil {
946 elog.Printf("savetracks begin error: %s", err)
947 return
948 }
949 defer func() {
950 err := tx.Commit()
951 if err != nil {
952 elog.Printf("savetracks commit error: %s", err)
953 }
954
955 }()
956 stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
957 if err != nil {
958 elog.Printf("savetracks error: %s", err)
959 return
960 }
961 stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
962 if err != nil {
963 elog.Printf("savetracks error: %s", err)
964 return
965 }
966 stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
967 if err != nil {
968 elog.Printf("savetracks error: %s", err)
969 return
970 }
971 count := 0
972 for xid, f := range tracks {
973 count += len(f)
974 var prev string
975 row := stmtGetTracks.QueryRow(xid)
976 err := row.Scan(&prev)
977 if err == sql.ErrNoRows {
978 f = oneofakind(f)
979 stmtNewTracks.Exec(xid, strings.Join(f, " "))
980 } else if err == nil {
981 all := append(strings.Split(prev, " "), f...)
982 all = oneofakind(all)
983 stmtUpdateTracks.Exec(strings.Join(all, " "))
984 } else {
985 elog.Printf("savetracks error: %s", err)
986 }
987 }
988 dlog.Printf("saved %d new fetches", count)
989}
990
991var trackchan = make(chan Track)
992var dumptracks = make(chan chan bool)
993
994func tracker() {
995 timeout := 4 * time.Minute
996 sleeper := time.NewTimer(timeout)
997 tracks := make(map[string][]string)
998 workinprogress++
999 for {
1000 select {
1001 case track := <-trackchan:
1002 tracks[track.xid] = append(tracks[track.xid], track.who)
1003 case <-sleeper.C:
1004 if len(tracks) > 0 {
1005 go savetracks(tracks)
1006 tracks = make(map[string][]string)
1007 }
1008 sleeper.Reset(timeout)
1009 case c := <-dumptracks:
1010 if len(tracks) > 0 {
1011 savetracks(tracks)
1012 }
1013 c <- true
1014 case <-endoftheworld:
1015 if len(tracks) > 0 {
1016 savetracks(tracks)
1017 }
1018 readyalready <- true
1019 return
1020 }
1021 }
1022}
1023
1024var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
1025
1026func trackback(xid string, r *http.Request) {
1027 agent := r.UserAgent()
1028 who := originate(agent)
1029 sig := r.Header.Get("Signature")
1030 if sig != "" {
1031 m := re_keyholder.FindStringSubmatch(sig)
1032 if len(m) == 2 {
1033 who = m[1]
1034 }
1035 }
1036 if who != "" {
1037 trackchan <- Track{xid: xid, who: who}
1038 }
1039}
1040
1041func sameperson(h1, h2 *Honk) bool {
1042 n1, n2 := h1.Honker, h2.Honker
1043 if h1.Oonker != "" {
1044 n1 = h1.Oonker
1045 }
1046 if h2.Oonker != "" {
1047 n2 = h2.Oonker
1048 }
1049 return n1 == n2
1050}
1051
1052func threadsort(honks []*Honk) []*Honk {
1053 sort.Slice(honks, func(i, j int) bool {
1054 return honks[i].Date.Before(honks[j].Date)
1055 })
1056 honkx := make(map[string]*Honk)
1057 kids := make(map[string][]*Honk)
1058 for _, h := range honks {
1059 honkx[h.XID] = h
1060 rid := h.RID
1061 kids[rid] = append(kids[rid], h)
1062 }
1063 done := make(map[*Honk]bool)
1064 var thread []*Honk
1065 var nextlevel func(p *Honk)
1066 level := 0
1067 nextlevel = func(p *Honk) {
1068 levelup := level < 4
1069 if pp := honkx[p.RID]; p.RID == "" || (pp != nil && sameperson(p, pp)) {
1070 levelup = false
1071 }
1072 if level > 0 && len(kids[p.RID]) == 1 {
1073 if pp := honkx[p.RID]; pp != nil && len(kids[pp.RID]) == 1 {
1074 levelup = false
1075 }
1076 }
1077 if levelup {
1078 level++
1079 }
1080 p.Style += fmt.Sprintf(" level%d", level)
1081 childs := kids[p.XID]
1082 if false {
1083 sort.SliceStable(childs, func(i, j int) bool {
1084 return sameperson(childs[i], p) && !sameperson(childs[j], p)
1085 })
1086 }
1087 if true {
1088 sort.SliceStable(childs, func(i, j int) bool {
1089 return !sameperson(childs[i], p) && sameperson(childs[j], p)
1090 })
1091 }
1092 for _, h := range childs {
1093 if !done[h] {
1094 done[h] = true
1095 thread = append(thread, h)
1096 nextlevel(h)
1097 }
1098 }
1099 if levelup {
1100 level--
1101 }
1102 }
1103 for _, h := range honks {
1104 if !done[h] && h.RID == "" {
1105 done[h] = true
1106 thread = append(thread, h)
1107 nextlevel(h)
1108 }
1109 }
1110 for _, h := range honks {
1111 if !done[h] {
1112 done[h] = true
1113 thread = append(thread, h)
1114 nextlevel(h)
1115 }
1116 }
1117 return thread
1118}
1119
1120func honkology(honk *Honk) template.HTML {
1121 var user *WhatAbout
1122 ok := somenumberedusers.Get(honk.UserID, &user)
1123 if !ok {
1124 return ""
1125 }
1126 title := fmt.Sprintf("%s: %s", user.Display, honk.Precis)
1127 imgurl := avatarURL(user)
1128 for _, d := range honk.Donks {
1129 if d.Local && strings.HasPrefix(d.Media, "image") {
1130 imgurl = d.URL
1131 break
1132 }
1133 }
1134 short := honk.Noise
1135 if len(short) > 160 {
1136 short = short[0:160] + "..."
1137 }
1138 return templates.Sprintf(
1139 `<meta property="og:title" content="%s" />
1140<meta property="og:type" content="article" />
1141<meta property="article:author" content="%s" />
1142<meta property="og:url" content="%s" />
1143<meta property="og:image" content="%s" />
1144<meta property="og:description" content="%s" />`,
1145 title, user.URL, honk.XID, imgurl, short)
1146}
1147
1148func showonehonk(w http.ResponseWriter, r *http.Request) {
1149 name := mux.Vars(r)["name"]
1150 user, err := butwhatabout(name)
1151 if err != nil {
1152 http.NotFound(w, r)
1153 return
1154 }
1155 if stealthmode(user.ID, r) {
1156 http.NotFound(w, r)
1157 return
1158 }
1159 xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1160
1161 if friendorfoe(r.Header.Get("Accept")) {
1162 j, ok := gimmejonk(xid)
1163 if ok {
1164 trackback(xid, r)
1165 w.Header().Set("Content-Type", theonetruename)
1166 w.Write(j)
1167 } else {
1168 http.NotFound(w, r)
1169 }
1170 return
1171 }
1172 honk := getxonk(user.ID, xid)
1173 if honk == nil {
1174 http.NotFound(w, r)
1175 return
1176 }
1177 u := login.GetUserInfo(r)
1178 if u != nil && u.UserID != user.ID {
1179 u = nil
1180 }
1181 if !honk.Public {
1182 if u == nil {
1183 http.NotFound(w, r)
1184 return
1185
1186 }
1187 honks := []*Honk{honk}
1188 donksforhonks(honks)
1189 templinfo := getInfo(r)
1190 templinfo["ServerMessage"] = "one honk maybe more"
1191 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1192 honkpage(w, u, honks, templinfo)
1193 return
1194 }
1195
1196 templinfo := getInfo(r)
1197 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1198 //reversehonks(rawhonks)
1199 rawhonks = threadsort(rawhonks)
1200 var honks []*Honk
1201 for _, h := range rawhonks {
1202 if h.XID == xid {
1203 templinfo["Honkology"] = honkology(h)
1204 if len(honks) != 0 {
1205 h.Style += " glow"
1206 }
1207 }
1208 if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1209 honks = append(honks, h)
1210 }
1211 }
1212
1213 templinfo["ServerMessage"] = "one honk maybe more"
1214 if u != nil {
1215 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1216 }
1217 templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1218 honkpage(w, u, honks, templinfo)
1219}
1220
1221func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1222 var userid int64 = -1
1223 if u != nil {
1224 userid = u.UserID
1225 templinfo["User"], _ = butwhatabout(u.Username)
1226 }
1227 reverbolate(userid, honks)
1228 templinfo["Honks"] = honks
1229 templinfo["MapLink"] = getmaplink(u)
1230 if templinfo["TopHID"] == nil {
1231 if len(honks) > 0 {
1232 templinfo["TopHID"] = honks[0].ID
1233 } else {
1234 templinfo["TopHID"] = 0
1235 }
1236 }
1237 if u == nil && !develMode {
1238 w.Header().Set("Cache-Control", "max-age=60")
1239 }
1240 err := readviews.Execute(w, "honkpage.html", templinfo)
1241 if err != nil {
1242 elog.Print(err)
1243 }
1244}
1245
1246func saveuser(w http.ResponseWriter, r *http.Request) {
1247 whatabout := r.FormValue("whatabout")
1248 whatabout = strings.Replace(whatabout, "\r", "", -1)
1249 u := login.GetUserInfo(r)
1250 user, _ := butwhatabout(u.Username)
1251 db := opendatabase()
1252
1253 options := user.Options
1254 if r.FormValue("skinny") == "skinny" {
1255 options.SkinnyCSS = true
1256 } else {
1257 options.SkinnyCSS = false
1258 }
1259 if r.FormValue("omitimages") == "omitimages" {
1260 options.OmitImages = true
1261 } else {
1262 options.OmitImages = false
1263 }
1264 if r.FormValue("mentionall") == "mentionall" {
1265 options.MentionAll = true
1266 } else {
1267 options.MentionAll = false
1268 }
1269 if r.FormValue("inlineqts") == "inlineqts" {
1270 options.InlineQuotes = true
1271 } else {
1272 options.InlineQuotes = false
1273 }
1274 if r.FormValue("maps") == "apple" {
1275 options.MapLink = "apple"
1276 } else {
1277 options.MapLink = ""
1278 }
1279 options.Reaction = r.FormValue("reaction")
1280
1281 sendupdate := false
1282 ava := re_avatar.FindString(whatabout)
1283 if ava != "" {
1284 whatabout = re_avatar.ReplaceAllString(whatabout, "")
1285 ava = ava[7:]
1286 if ava[0] == ' ' {
1287 ava = ava[1:]
1288 }
1289 ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1290 }
1291 if ava != options.Avatar {
1292 options.Avatar = ava
1293 sendupdate = true
1294 }
1295 ban := re_banner.FindString(whatabout)
1296 if ban != "" {
1297 whatabout = re_banner.ReplaceAllString(whatabout, "")
1298 ban = ban[7:]
1299 if ban[0] == ' ' {
1300 ban = ban[1:]
1301 }
1302 ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1303 }
1304 if ban != options.Banner {
1305 options.Banner = ban
1306 sendupdate = true
1307 }
1308 whatabout = strings.TrimSpace(whatabout)
1309 if whatabout != user.About {
1310 sendupdate = true
1311 }
1312 j, err := jsonify(options)
1313 if err == nil {
1314 _, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1315 }
1316 if err != nil {
1317 elog.Printf("error bouting what: %s", err)
1318 }
1319 somenamedusers.Clear(u.Username)
1320 somenumberedusers.Clear(u.UserID)
1321 oldjonkers.Clear(u.Username)
1322
1323 if sendupdate {
1324 updateMe(u.Username)
1325 }
1326
1327 http.Redirect(w, r, "/account", http.StatusSeeOther)
1328}
1329
1330func bonkit(xid string, user *WhatAbout) {
1331 dlog.Printf("bonking %s", xid)
1332
1333 xonk := getxonk(user.ID, xid)
1334 if xonk == nil {
1335 return
1336 }
1337 if !xonk.Public {
1338 return
1339 }
1340 if xonk.IsBonked() {
1341 return
1342 }
1343 donksforhonks([]*Honk{xonk})
1344
1345 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1346 if err != nil {
1347 elog.Printf("error acking bonk: %s", err)
1348 }
1349
1350 oonker := xonk.Oonker
1351 if oonker == "" {
1352 oonker = xonk.Honker
1353 }
1354 dt := time.Now().UTC()
1355 bonk := &Honk{
1356 UserID: user.ID,
1357 Username: user.Name,
1358 What: "bonk",
1359 Honker: user.URL,
1360 Oonker: oonker,
1361 XID: xonk.XID,
1362 RID: xonk.RID,
1363 Noise: xonk.Noise,
1364 Precis: xonk.Precis,
1365 URL: xonk.URL,
1366 Date: dt,
1367 Donks: xonk.Donks,
1368 Whofore: 2,
1369 Convoy: xonk.Convoy,
1370 Audience: []string{thewholeworld, oonker},
1371 Public: true,
1372 Format: xonk.Format,
1373 Place: xonk.Place,
1374 Onts: xonk.Onts,
1375 Time: xonk.Time,
1376 }
1377
1378 err = savehonk(bonk)
1379 if err != nil {
1380 elog.Printf("uh oh")
1381 return
1382 }
1383
1384 go honkworldwide(user, bonk)
1385}
1386
1387func submitbonk(w http.ResponseWriter, r *http.Request) {
1388 xid := r.FormValue("xid")
1389 userinfo := login.GetUserInfo(r)
1390 user, _ := butwhatabout(userinfo.Username)
1391
1392 bonkit(xid, user)
1393
1394 if r.FormValue("js") != "1" {
1395 templinfo := getInfo(r)
1396 templinfo["ServerMessage"] = "Bonked!"
1397 err := readviews.Execute(w, "msg.html", templinfo)
1398 if err != nil {
1399 elog.Print(err)
1400 }
1401 }
1402}
1403
1404func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1405 zonk := &Honk{
1406 What: what,
1407 XID: xonk.XID,
1408 Date: time.Now().UTC(),
1409 Audience: oneofakind(xonk.Audience),
1410 Noise: aux,
1411 }
1412 zonk.Public = loudandproud(zonk.Audience)
1413
1414 dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1415 go honkworldwide(user, zonk)
1416}
1417
1418func zonkit(w http.ResponseWriter, r *http.Request) {
1419 wherefore := r.FormValue("wherefore")
1420 what := r.FormValue("what")
1421 userinfo := login.GetUserInfo(r)
1422 user, _ := butwhatabout(userinfo.Username)
1423
1424 if wherefore == "save" {
1425 xonk := getxonk(userinfo.UserID, what)
1426 if xonk != nil {
1427 _, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1428 if err != nil {
1429 elog.Printf("error saving: %s", err)
1430 }
1431 }
1432 return
1433 }
1434
1435 if wherefore == "unsave" {
1436 xonk := getxonk(userinfo.UserID, what)
1437 if xonk != nil {
1438 _, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1439 if err != nil {
1440 elog.Printf("error unsaving: %s", err)
1441 }
1442 }
1443 return
1444 }
1445
1446 if wherefore == "react" {
1447 reaction := user.Options.Reaction
1448 if r2 := r.FormValue("reaction"); r2 != "" {
1449 reaction = r2
1450 }
1451 if reaction == "none" {
1452 return
1453 }
1454 xonk := getxonk(userinfo.UserID, what)
1455 if xonk != nil {
1456 _, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1457 if err != nil {
1458 elog.Printf("error saving: %s", err)
1459 }
1460 sendzonkofsorts(xonk, user, "react", reaction)
1461 }
1462 return
1463 }
1464
1465 // my hammer is too big, oh well
1466 defer oldjonks.Flush()
1467
1468 if wherefore == "ack" {
1469 xonk := getxonk(userinfo.UserID, what)
1470 if xonk != nil && !xonk.IsAcked() {
1471 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1472 if err != nil {
1473 elog.Printf("error acking: %s", err)
1474 }
1475 sendzonkofsorts(xonk, user, "ack", "")
1476 }
1477 return
1478 }
1479
1480 if wherefore == "deack" {
1481 xonk := getxonk(userinfo.UserID, what)
1482 if xonk != nil && xonk.IsAcked() {
1483 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1484 if err != nil {
1485 elog.Printf("error deacking: %s", err)
1486 }
1487 sendzonkofsorts(xonk, user, "deack", "")
1488 }
1489 return
1490 }
1491
1492 if wherefore == "bonk" {
1493 user, _ := butwhatabout(userinfo.Username)
1494 bonkit(what, user)
1495 return
1496 }
1497
1498 if wherefore == "unbonk" {
1499 xonk := getbonk(userinfo.UserID, what)
1500 if xonk != nil {
1501 deletehonk(xonk.ID)
1502 xonk = getxonk(userinfo.UserID, what)
1503 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1504 if err != nil {
1505 elog.Printf("error unbonking: %s", err)
1506 }
1507 sendzonkofsorts(xonk, user, "unbonk", "")
1508 }
1509 return
1510 }
1511
1512 if wherefore == "untag" {
1513 xonk := getxonk(userinfo.UserID, what)
1514 if xonk != nil {
1515 _, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1516 if err != nil {
1517 elog.Printf("error untagging: %s", err)
1518 }
1519 }
1520 var badparents map[string]bool
1521 untagged.GetAndLock(userinfo.UserID, &badparents)
1522 badparents[what] = true
1523 untagged.Unlock()
1524 return
1525 }
1526
1527 ilog.Printf("zonking %s %s", wherefore, what)
1528 if wherefore == "zonk" {
1529 xonk := getxonk(userinfo.UserID, what)
1530 if xonk != nil {
1531 deletehonk(xonk.ID)
1532 if xonk.Whofore == 2 || xonk.Whofore == 3 {
1533 sendzonkofsorts(xonk, user, "zonk", "")
1534 }
1535 }
1536 }
1537 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1538 if err != nil {
1539 elog.Printf("error saving zonker: %s", err)
1540 return
1541 }
1542}
1543
1544func edithonkpage(w http.ResponseWriter, r *http.Request) {
1545 u := login.GetUserInfo(r)
1546 user, _ := butwhatabout(u.Username)
1547 xid := r.FormValue("xid")
1548 honk := getxonk(u.UserID, xid)
1549 if !canedithonk(user, honk) {
1550 http.Error(w, "no editing that please", http.StatusInternalServerError)
1551 return
1552 }
1553
1554 noise := honk.Noise
1555
1556 honks := []*Honk{honk}
1557 donksforhonks(honks)
1558 reverbolate(u.UserID, honks)
1559 templinfo := getInfo(r)
1560 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1561 templinfo["Honks"] = honks
1562 templinfo["MapLink"] = getmaplink(u)
1563 templinfo["Noise"] = noise
1564 templinfo["SavedPlace"] = honk.Place
1565 if tm := honk.Time; tm != nil {
1566 templinfo["ShowTime"] = " "
1567 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1568 if tm.Duration != 0 {
1569 templinfo["Duration"] = tm.Duration
1570 }
1571 }
1572 templinfo["ServerMessage"] = "honk edit 2"
1573 templinfo["IsPreview"] = true
1574 templinfo["UpdateXID"] = honk.XID
1575 if len(honk.Donks) > 0 {
1576 templinfo["SavedFile"] = honk.Donks[0].XID
1577 }
1578 err := readviews.Execute(w, "honkpage.html", templinfo)
1579 if err != nil {
1580 elog.Print(err)
1581 }
1582}
1583
1584func newhonkpage(w http.ResponseWriter, r *http.Request) {
1585 u := login.GetUserInfo(r)
1586 rid := r.FormValue("rid")
1587 noise := ""
1588
1589 xonk := getxonk(u.UserID, rid)
1590 if xonk != nil {
1591 _, replto := handles(xonk.Honker)
1592 if replto != "" {
1593 noise = "@" + replto + " "
1594 }
1595 }
1596
1597 templinfo := getInfo(r)
1598 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1599 templinfo["InReplyTo"] = rid
1600 templinfo["Noise"] = noise
1601 templinfo["ServerMessage"] = "compose honk"
1602 templinfo["IsPreview"] = true
1603 err := readviews.Execute(w, "honkpage.html", templinfo)
1604 if err != nil {
1605 elog.Print(err)
1606 }
1607}
1608
1609func canedithonk(user *WhatAbout, honk *Honk) bool {
1610 if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1611 return false
1612 }
1613 return true
1614}
1615
1616func submitdonk(w http.ResponseWriter, r *http.Request) ([]*Donk, error) {
1617 if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1618 return nil, nil
1619 }
1620 var donks []*Donk
1621 for _, hdr := range r.MultipartForm.File["donk"] {
1622 donk, err := formtodonk(w, r, hdr)
1623 if err != nil {
1624 return nil, err
1625 }
1626 donks = append(donks, donk)
1627 }
1628 return donks, nil
1629}
1630
1631func formtodonk(w http.ResponseWriter, r *http.Request, filehdr *multipart.FileHeader) (*Donk, error) {
1632 file, err := filehdr.Open()
1633 if err != nil {
1634 if err == http.ErrMissingFile {
1635 return nil, nil
1636 }
1637 elog.Printf("error reading donk: %s", err)
1638 http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1639 return nil, err
1640 }
1641 var buf bytes.Buffer
1642 io.Copy(&buf, file)
1643 file.Close()
1644 data := buf.Bytes()
1645 var media, name string
1646 img, err := shrinkit(data)
1647 if err == nil {
1648 data = img.Data
1649 format := img.Format
1650 media = "image/" + format
1651 if format == "jpeg" {
1652 format = "jpg"
1653 }
1654 if format == "svg+xml" {
1655 format = "svg"
1656 }
1657 name = xfiltrate() + "." + format
1658 } else {
1659 ct := http.DetectContentType(data)
1660 switch ct {
1661 case "application/pdf":
1662 maxsize := 10000000
1663 if len(data) > maxsize {
1664 ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1665 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1666 return nil, err
1667 }
1668 media = ct
1669 name = filehdr.Filename
1670 if name == "" {
1671 name = xfiltrate() + ".pdf"
1672 }
1673 default:
1674 maxsize := 100000
1675 if len(data) > maxsize {
1676 ilog.Printf("bad image: %s too much text: %d", err, len(data))
1677 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1678 return nil, err
1679 }
1680 for i := 0; i < len(data); i++ {
1681 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1682 ilog.Printf("bad image: %s not text: %d", err, data[i])
1683 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1684 return nil, err
1685 }
1686 }
1687 media = "text/plain"
1688 name = filehdr.Filename
1689 if name == "" {
1690 name = xfiltrate() + ".txt"
1691 }
1692 }
1693 }
1694 desc := strings.TrimSpace(r.FormValue("donkdesc"))
1695 if desc == "" {
1696 desc = name
1697 }
1698 fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1699 if err != nil {
1700 elog.Printf("unable to save image: %s", err)
1701 http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1702 return nil, err
1703 }
1704 d := &Donk{
1705 FileID: fileid,
1706 XID: xid,
1707 Desc: desc,
1708 Local: true,
1709 }
1710 return d, nil
1711}
1712
1713func websubmithonk(w http.ResponseWriter, r *http.Request) {
1714 h := submithonk(w, r)
1715 if h == nil {
1716 return
1717 }
1718 http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1719}
1720
1721// what a hot mess this function is
1722func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1723 rid := r.FormValue("rid")
1724 noise := r.FormValue("noise")
1725 format := r.FormValue("format")
1726 if format == "" {
1727 format = "markdown"
1728 }
1729 if !(format == "markdown" || format == "html") {
1730 http.Error(w, "unknown format", 500)
1731 return nil
1732 }
1733
1734 userinfo := login.GetUserInfo(r)
1735 user, _ := butwhatabout(userinfo.Username)
1736
1737 dt := time.Now().UTC()
1738 updatexid := r.FormValue("updatexid")
1739 var honk *Honk
1740 if updatexid != "" {
1741 honk = getxonk(userinfo.UserID, updatexid)
1742 if !canedithonk(user, honk) {
1743 http.Error(w, "no editing that please", http.StatusInternalServerError)
1744 return nil
1745 }
1746 honk.Date = dt
1747 honk.What = "update"
1748 honk.Format = format
1749 } else {
1750 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1751 what := "honk"
1752 honk = &Honk{
1753 UserID: userinfo.UserID,
1754 Username: userinfo.Username,
1755 What: what,
1756 Honker: user.URL,
1757 XID: xid,
1758 Date: dt,
1759 Format: format,
1760 }
1761 }
1762
1763 var convoy string
1764 noise = strings.Replace(noise, "\r", "", -1)
1765 if updatexid == "" && rid == "" {
1766 noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1767 convoy = m[7:]
1768 convoy = strings.TrimSpace(convoy)
1769 if !re_convalidate.MatchString(convoy) {
1770 convoy = ""
1771 }
1772 return ""
1773 })
1774 }
1775 noise = quickrename(noise, userinfo.UserID)
1776 noise = hooterize(noise)
1777 honk.Noise = noise
1778 precipitate(honk)
1779 noise = honk.Noise
1780 recategorize(honk)
1781 translate(honk)
1782
1783 if rid != "" {
1784 xonk := getxonk(userinfo.UserID, rid)
1785 if xonk == nil {
1786 http.Error(w, "replyto disappeared", http.StatusNotFound)
1787 return nil
1788 }
1789 if xonk.Public {
1790 honk.Audience = append(honk.Audience, xonk.Audience...)
1791 }
1792 convoy = xonk.Convoy
1793 for i, a := range honk.Audience {
1794 if a == thewholeworld {
1795 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1796 break
1797 }
1798 }
1799 honk.RID = rid
1800 if xonk.Precis != "" && honk.Precis == "" {
1801 honk.Precis = xonk.Precis
1802 if !re_dangerous.MatchString(honk.Precis) {
1803 honk.Precis = "re: " + honk.Precis
1804 }
1805 }
1806 } else if updatexid == "" {
1807 honk.Audience = []string{thewholeworld}
1808 }
1809 if honk.Noise != "" && honk.Noise[0] == '@' {
1810 honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1811 } else {
1812 honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1813 }
1814
1815 if convoy == "" {
1816 convoy = "data:,electrichonkytonk-" + xfiltrate()
1817 }
1818 butnottooloud(honk.Audience)
1819 honk.Audience = oneofakind(honk.Audience)
1820 if len(honk.Audience) == 0 {
1821 ilog.Printf("honk to nowhere")
1822 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1823 return nil
1824 }
1825 honk.Public = loudandproud(honk.Audience)
1826 honk.Convoy = convoy
1827
1828 donkxid := r.FormValue("donkxid")
1829 if donkxid == "" {
1830 donks, err := submitdonk(w, r)
1831 if err != nil && err != http.ErrMissingFile {
1832 return nil
1833 }
1834 if len(donks) > 0 {
1835 honk.Donks = append(honk.Donks, donks...)
1836 d := donks[0]
1837 donkxid = fmt.Sprintf("%s:%d", d.XID, d.FileID)
1838 }
1839 } else {
1840 for _, xid := range r.Form["donkxid"] {
1841 p := strings.Split(xid, ":")
1842 xid = p[0]
1843 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1844 var donk *Donk
1845 if len(p) > 1 {
1846 fileid, _ := strconv.ParseInt(p[1], 10, 0)
1847 donk = finddonkid(fileid, url)
1848 } else {
1849 donk = finddonk(url)
1850 }
1851 if donk != nil {
1852 honk.Donks = append(honk.Donks, donk)
1853 } else {
1854 ilog.Printf("can't find file: %s", xid)
1855 }
1856 }
1857 }
1858 memetize(honk)
1859 imaginate(honk)
1860
1861 placename := strings.TrimSpace(r.FormValue("placename"))
1862 placelat := strings.TrimSpace(r.FormValue("placelat"))
1863 placelong := strings.TrimSpace(r.FormValue("placelong"))
1864 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1865 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1866 p := new(Place)
1867 p.Name = placename
1868 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1869 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1870 p.Url = placeurl
1871 honk.Place = p
1872 }
1873 timestart := strings.TrimSpace(r.FormValue("timestart"))
1874 if timestart != "" {
1875 t := new(Time)
1876 now := time.Now().Local()
1877 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1878 start, err := time.ParseInLocation(layout, timestart, now.Location())
1879 if err == nil {
1880 if start.Year() == 0 {
1881 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1882 }
1883 t.StartTime = start
1884 break
1885 }
1886 }
1887 timeend := r.FormValue("timeend")
1888 dur := parseDuration(timeend)
1889 if dur != 0 {
1890 t.Duration = Duration(dur)
1891 }
1892 if !t.StartTime.IsZero() {
1893 honk.What = "event"
1894 honk.Time = t
1895 }
1896 }
1897
1898 if honk.Public {
1899 honk.Whofore = 2
1900 } else {
1901 honk.Whofore = 3
1902 }
1903
1904 // back to markdown
1905 honk.Noise = noise
1906
1907 if r.FormValue("preview") == "preview" {
1908 honks := []*Honk{honk}
1909 reverbolate(userinfo.UserID, honks)
1910 templinfo := getInfo(r)
1911 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1912 templinfo["Honks"] = honks
1913 templinfo["MapLink"] = getmaplink(userinfo)
1914 templinfo["InReplyTo"] = r.FormValue("rid")
1915 templinfo["Noise"] = r.FormValue("noise")
1916 templinfo["SavedFile"] = donkxid
1917 if tm := honk.Time; tm != nil {
1918 templinfo["ShowTime"] = " "
1919 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1920 if tm.Duration != 0 {
1921 templinfo["Duration"] = tm.Duration
1922 }
1923 }
1924 templinfo["IsPreview"] = true
1925 templinfo["UpdateXID"] = updatexid
1926 templinfo["ServerMessage"] = "honk preview"
1927 err := readviews.Execute(w, "honkpage.html", templinfo)
1928 if err != nil {
1929 elog.Print(err)
1930 }
1931 return nil
1932 }
1933
1934 if updatexid != "" {
1935 updatehonk(honk)
1936 oldjonks.Clear(honk.XID)
1937 } else {
1938 err := savehonk(honk)
1939 if err != nil {
1940 elog.Printf("uh oh")
1941 return nil
1942 }
1943 }
1944
1945 // reload for consistency
1946 honk.Donks = nil
1947 donksforhonks([]*Honk{honk})
1948
1949 go honkworldwide(user, honk)
1950
1951 return honk
1952}
1953
1954func showhonkers(w http.ResponseWriter, r *http.Request) {
1955 userinfo := login.GetUserInfo(r)
1956 templinfo := getInfo(r)
1957 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1958 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1959 err := readviews.Execute(w, "honkers.html", templinfo)
1960 if err != nil {
1961 elog.Print(err)
1962 }
1963}
1964
1965func showchatter(w http.ResponseWriter, r *http.Request) {
1966 u := login.GetUserInfo(r)
1967 chatnewnone(u.UserID)
1968 chatter := loadchatter(u.UserID)
1969 for _, chat := range chatter {
1970 for _, ch := range chat.Chonks {
1971 filterchonk(ch)
1972 }
1973 }
1974
1975 templinfo := getInfo(r)
1976 templinfo["Chatter"] = chatter
1977 templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1978 err := readviews.Execute(w, "chatter.html", templinfo)
1979 if err != nil {
1980 elog.Print(err)
1981 }
1982}
1983
1984func submitchonk(w http.ResponseWriter, r *http.Request) {
1985 u := login.GetUserInfo(r)
1986 user, _ := butwhatabout(u.Username)
1987 noise := r.FormValue("noise")
1988 target := r.FormValue("target")
1989 format := "markdown"
1990 dt := time.Now().UTC()
1991 xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1992
1993 if !strings.HasPrefix(target, "https://") {
1994 target = fullname(target, u.UserID)
1995 }
1996 if target == "" {
1997 http.Error(w, "who is that?", http.StatusInternalServerError)
1998 return
1999 }
2000 ch := Chonk{
2001 UserID: u.UserID,
2002 XID: xid,
2003 Who: user.URL,
2004 Target: target,
2005 Date: dt,
2006 Noise: noise,
2007 Format: format,
2008 }
2009 donks, err := submitdonk(w, r)
2010 if err != nil && err != http.ErrMissingFile {
2011 return
2012 }
2013 if len(donks) > 0 {
2014 ch.Donks = append(ch.Donks, donks...)
2015 }
2016
2017 translatechonk(&ch)
2018 savechonk(&ch)
2019 // reload for consistency
2020 ch.Donks = nil
2021 donksforchonks([]*Chonk{&ch})
2022 go sendchonk(user, &ch)
2023
2024 http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2025}
2026
2027var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
2028 honkers := gethonkers(userid)
2029 var combos []string
2030 for _, h := range honkers {
2031 combos = append(combos, h.Combos...)
2032 }
2033 for i, c := range combos {
2034 if c == "-" {
2035 combos[i] = ""
2036 }
2037 }
2038 combos = oneofakind(combos)
2039 sort.Strings(combos)
2040 return combos, true
2041}, Invalidator: &honkerinvalidator})
2042
2043func showcombos(w http.ResponseWriter, r *http.Request) {
2044 userinfo := login.GetUserInfo(r)
2045 var combos []string
2046 combocache.Get(userinfo.UserID, &combos)
2047 templinfo := getInfo(r)
2048 err := readviews.Execute(w, "combos.html", templinfo)
2049 if err != nil {
2050 elog.Print(err)
2051 }
2052}
2053
2054func websubmithonker(w http.ResponseWriter, r *http.Request) {
2055 h := submithonker(w, r)
2056 if h == nil {
2057 return
2058 }
2059 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2060}
2061
2062func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2063 u := login.GetUserInfo(r)
2064 user, _ := butwhatabout(u.Username)
2065 name := strings.TrimSpace(r.FormValue("name"))
2066 url := strings.TrimSpace(r.FormValue("url"))
2067 peep := r.FormValue("peep")
2068 combos := strings.TrimSpace(r.FormValue("combos"))
2069 combos = " " + combos + " "
2070 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2071
2072 re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2073 if name != "" && !re_namecheck.MatchString(name) {
2074 http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2075 return nil
2076 }
2077
2078 var meta HonkerMeta
2079 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2080 mj, _ := jsonify(&meta)
2081
2082 defer honkerinvalidator.Clear(u.UserID)
2083
2084 // mostly dummy, fill in later...
2085 h := &Honker{
2086 ID: honkerid,
2087 }
2088
2089 if honkerid > 0 {
2090 if r.FormValue("delete") == "delete" {
2091 unfollowyou(user, honkerid, false)
2092 stmtDeleteHonker.Exec(honkerid)
2093 return h
2094 }
2095 if r.FormValue("unsub") == "unsub" {
2096 unfollowyou(user, honkerid, false)
2097 }
2098 if r.FormValue("sub") == "sub" {
2099 followyou(user, honkerid, false)
2100 }
2101 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2102 if err != nil {
2103 elog.Printf("update honker err: %s", err)
2104 return nil
2105 }
2106 return h
2107 }
2108
2109 if url == "" {
2110 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2111 return nil
2112 }
2113
2114 flavor := "presub"
2115 if peep == "peep" {
2116 flavor = "peep"
2117 }
2118
2119 var err error
2120 honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2121 if err != nil {
2122 http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2123 return nil
2124 }
2125 if flavor == "presub" {
2126 followyou(user, honkerid, false)
2127 }
2128 h.ID = honkerid
2129 return h
2130}
2131
2132func hfcspage(w http.ResponseWriter, r *http.Request) {
2133 userinfo := login.GetUserInfo(r)
2134
2135 filters := getfilters(userinfo.UserID, filtAny)
2136
2137 templinfo := getInfo(r)
2138 templinfo["Filters"] = filters
2139 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2140 err := readviews.Execute(w, "hfcs.html", templinfo)
2141 if err != nil {
2142 elog.Print(err)
2143 }
2144}
2145
2146func savehfcs(w http.ResponseWriter, r *http.Request) {
2147 userinfo := login.GetUserInfo(r)
2148 itsok := r.FormValue("itsok")
2149 if itsok == "iforgiveyou" {
2150 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2151 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2152 if err != nil {
2153 elog.Printf("error deleting filter: %s", err)
2154 }
2155 filtInvalidator.Clear(userinfo.UserID)
2156 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2157 return
2158 }
2159
2160 filt := new(Filter)
2161 filt.Name = strings.TrimSpace(r.FormValue("name"))
2162 filt.Date = time.Now().UTC()
2163 filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2164 filt.IncludeAudience = r.FormValue("incaud") == "yes"
2165 filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2166 filt.IsReply = r.FormValue("isreply") == "yes"
2167 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2168 filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2169 filt.Reject = r.FormValue("doreject") == "yes"
2170 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2171 filt.Hide = r.FormValue("dohide") == "yes"
2172 filt.Collapse = r.FormValue("docollapse") == "yes"
2173 filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2174 filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2175 if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2176 filt.Expiration = time.Now().UTC().Add(dur)
2177 }
2178 filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2179
2180 if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2181 ilog.Printf("blank filter")
2182 http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2183 return
2184 }
2185
2186 j, err := jsonify(filt)
2187 if err == nil {
2188 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2189 }
2190 if err != nil {
2191 elog.Printf("error saving filter: %s", err)
2192 }
2193
2194 filtInvalidator.Clear(userinfo.UserID)
2195 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2196}
2197
2198func accountpage(w http.ResponseWriter, r *http.Request) {
2199 u := login.GetUserInfo(r)
2200 user, _ := butwhatabout(u.Username)
2201 templinfo := getInfo(r)
2202 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2203 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2204 templinfo["User"] = user
2205 about := user.About
2206 if ava := user.Options.Avatar; ava != "" {
2207 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2208 }
2209 if ban := user.Options.Banner; ban != "" {
2210 about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2211 }
2212 templinfo["WhatAbout"] = about
2213 err := readviews.Execute(w, "account.html", templinfo)
2214 if err != nil {
2215 elog.Print(err)
2216 }
2217}
2218
2219func dochpass(w http.ResponseWriter, r *http.Request) {
2220 err := login.ChangePassword(w, r)
2221 if err != nil {
2222 elog.Printf("error changing password: %s", err)
2223 }
2224 http.Redirect(w, r, "/account", http.StatusSeeOther)
2225}
2226
2227var oldfingers = cache.New(cache.Options{Filler: func(orig string) ([]byte, bool) {
2228 if strings.HasPrefix(orig, "acct:") {
2229 orig = orig[5:]
2230 }
2231 name := orig
2232 idx := strings.LastIndexByte(name, '/')
2233 if idx != -1 {
2234 name = name[idx+1:]
2235 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2236 ilog.Printf("foreign request rejected")
2237 name = ""
2238 }
2239 } else {
2240 idx = strings.IndexByte(name, '@')
2241 if idx != -1 {
2242 name = name[:idx]
2243 if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2244 ilog.Printf("foreign request rejected")
2245 name = ""
2246 }
2247 }
2248 }
2249 user, err := butwhatabout(name)
2250 if err != nil {
2251 return nil, false
2252 }
2253
2254 j := junk.New()
2255 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2256 j["aliases"] = []string{user.URL}
2257 l := junk.New()
2258 l["rel"] = "self"
2259 l["type"] = `application/activity+json`
2260 l["href"] = user.URL
2261 j["links"] = []junk.Junk{l}
2262 return j.ToBytes(), true
2263}})
2264
2265func fingerlicker(w http.ResponseWriter, r *http.Request) {
2266 orig := r.FormValue("resource")
2267
2268 dlog.Printf("finger lick: %s", orig)
2269
2270 var j []byte
2271 ok := oldfingers.Get(orig, &j)
2272 if ok {
2273 w.Header().Set("Content-Type", "application/jrd+json")
2274 w.Write(j)
2275 } else {
2276 http.NotFound(w, r)
2277 }
2278}
2279
2280func somedays() string {
2281 secs := 432000 + notrand.Int63n(432000)
2282 return fmt.Sprintf("%d", secs)
2283}
2284
2285func lookatme(ava string) string {
2286 if strings.Contains(ava, serverName+"/"+userSep) {
2287 idx := strings.LastIndexByte(ava, '/')
2288 if idx < len(ava) {
2289 name := ava[idx+1:]
2290 user, _ := butwhatabout(name)
2291 if user != nil && user.URL == ava {
2292 return user.Options.Avatar
2293 }
2294 }
2295 }
2296 return ""
2297}
2298
2299func avatate(w http.ResponseWriter, r *http.Request) {
2300 if develMode {
2301 loadAvatarColors()
2302 }
2303 n := r.FormValue("a")
2304 if redir := lookatme(n); redir != "" {
2305 http.Redirect(w, r, redir, http.StatusSeeOther)
2306 return
2307 }
2308 a := genAvatar(n)
2309 if !develMode {
2310 w.Header().Set("Cache-Control", "max-age="+somedays())
2311 }
2312 w.Write(a)
2313}
2314
2315func serveviewasset(w http.ResponseWriter, r *http.Request) {
2316 serveasset(w, r, viewDir)
2317}
2318func servedataasset(w http.ResponseWriter, r *http.Request) {
2319 if r.URL.Path == "/favicon.ico" {
2320 r.URL.Path = "/icon.png"
2321 }
2322 serveasset(w, r, dataDir)
2323}
2324
2325func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2326 if !develMode {
2327 w.Header().Set("Cache-Control", "max-age=7776000")
2328 }
2329 http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2330}
2331func servehelp(w http.ResponseWriter, r *http.Request) {
2332 name := mux.Vars(r)["name"]
2333 if !develMode {
2334 w.Header().Set("Cache-Control", "max-age=3600")
2335 }
2336 http.ServeFile(w, r, viewDir+"/docs/"+name)
2337}
2338func servehtml(w http.ResponseWriter, r *http.Request) {
2339 u := login.GetUserInfo(r)
2340 templinfo := getInfo(r)
2341 templinfo["AboutMsg"] = aboutMsg
2342 templinfo["LoginMsg"] = loginMsg
2343 templinfo["HonkVersion"] = softwareVersion
2344 if r.URL.Path == "/about" {
2345 templinfo["Sensors"] = getSensors()
2346 }
2347 if u == nil && !develMode {
2348 w.Header().Set("Cache-Control", "max-age=60")
2349 }
2350 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2351 if err != nil {
2352 elog.Print(err)
2353 }
2354}
2355func serveemu(w http.ResponseWriter, r *http.Request) {
2356 emu := mux.Vars(r)["emu"]
2357
2358 w.Header().Set("Cache-Control", "max-age="+somedays())
2359 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2360}
2361func servememe(w http.ResponseWriter, r *http.Request) {
2362 meme := mux.Vars(r)["meme"]
2363
2364 w.Header().Set("Cache-Control", "max-age="+somedays())
2365 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2366}
2367
2368func servefile(w http.ResponseWriter, r *http.Request) {
2369 xid := mux.Vars(r)["xid"]
2370 var media string
2371 var data []byte
2372 row := stmtGetFileData.QueryRow(xid)
2373 err := row.Scan(&media, &data)
2374 if err != nil {
2375 elog.Printf("error loading file: %s", err)
2376 http.NotFound(w, r)
2377 return
2378 }
2379 w.Header().Set("Content-Type", media)
2380 w.Header().Set("X-Content-Type-Options", "nosniff")
2381 w.Header().Set("Cache-Control", "max-age="+somedays())
2382 w.Write(data)
2383}
2384
2385func nomoroboto(w http.ResponseWriter, r *http.Request) {
2386 io.WriteString(w, "User-agent: *\n")
2387 io.WriteString(w, "Disallow: /a\n")
2388 io.WriteString(w, "Disallow: /d/\n")
2389 io.WriteString(w, "Disallow: /meme/\n")
2390 io.WriteString(w, "Disallow: /o\n")
2391 io.WriteString(w, "Disallow: /o/\n")
2392 io.WriteString(w, "Disallow: /help/\n")
2393 for _, u := range allusers() {
2394 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2395 }
2396}
2397
2398type Hydration struct {
2399 Tophid int64
2400 Srvmsg template.HTML
2401 Honks string
2402 MeCount int64
2403 ChatCount int64
2404}
2405
2406func webhydra(w http.ResponseWriter, r *http.Request) {
2407 u := login.GetUserInfo(r)
2408 userid := u.UserID
2409 templinfo := getInfo(r)
2410 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2411 page := r.FormValue("page")
2412
2413 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2414
2415 var hydra Hydration
2416
2417 var honks []*Honk
2418 switch page {
2419 case "atme":
2420 honks = gethonksforme(userid, wanted)
2421 honks = osmosis(honks, userid, false)
2422 menewnone(userid)
2423 hydra.Srvmsg = "at me!"
2424 case "longago":
2425 honks = gethonksfromlongago(userid, wanted)
2426 honks = osmosis(honks, userid, false)
2427 hydra.Srvmsg = "from long ago"
2428 case "home":
2429 honks = gethonksforuser(userid, wanted)
2430 honks = osmosis(honks, userid, true)
2431 hydra.Srvmsg = serverMsg
2432 case "first":
2433 honks = gethonksforuserfirstclass(userid, wanted)
2434 honks = osmosis(honks, userid, true)
2435 hydra.Srvmsg = "first class only"
2436 case "saved":
2437 honks = getsavedhonks(userid, wanted)
2438 templinfo["PageName"] = "saved"
2439 hydra.Srvmsg = "saved honks"
2440 case "combo":
2441 c := r.FormValue("c")
2442 honks = gethonksbycombo(userid, c, wanted)
2443 honks = osmosis(honks, userid, false)
2444 hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2445 case "convoy":
2446 c := r.FormValue("c")
2447 honks = gethonksbyconvoy(userid, c, wanted)
2448 honks = osmosis(honks, userid, false)
2449 honks = threadsort(honks)
2450 reversehonks(honks)
2451 hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2452 case "honker":
2453 xid := r.FormValue("xid")
2454 honks = gethonksbyxonker(userid, xid, wanted)
2455 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2456 <input type="hidden" name="CSRF" value="%s">
2457 <input type="hidden" name="url" value="%s">
2458 <button tabindex=1 name="add honker" value="add honker">add honker</button>
2459 </form>`, login.GetCSRF("submithonker", r), xid)
2460 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2461 hydra.Srvmsg = msg
2462 case "user":
2463 uname := r.FormValue("uname")
2464 honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2465 hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2466 default:
2467 http.NotFound(w, r)
2468 }
2469
2470 if len(honks) > 0 {
2471 hydra.Tophid = honks[0].ID
2472 } else {
2473 hydra.Tophid = wanted
2474 }
2475 reverbolate(userid, honks)
2476
2477 user, _ := butwhatabout(u.Username)
2478
2479 var buf strings.Builder
2480 templinfo["Honks"] = honks
2481 templinfo["MapLink"] = getmaplink(u)
2482 templinfo["User"], _ = butwhatabout(u.Username)
2483 err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2484 if err != nil {
2485 elog.Printf("frag error: %s", err)
2486 return
2487 }
2488 hydra.Honks = buf.String()
2489 hydra.MeCount = user.Options.MeCount
2490 hydra.ChatCount = user.Options.ChatCount
2491 w.Header().Set("Content-Type", "application/json")
2492 j, _ := jsonify(&hydra)
2493 io.WriteString(w, j)
2494}
2495
2496var honkline = make(chan bool)
2497
2498func honkhonkline() {
2499 for {
2500 select {
2501 case honkline <- true:
2502 default:
2503 return
2504 }
2505 }
2506}
2507
2508func apihandler(w http.ResponseWriter, r *http.Request) {
2509 u := login.GetUserInfo(r)
2510 userid := u.UserID
2511 action := r.FormValue("action")
2512 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2513 dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2514 switch action {
2515 case "honk":
2516 h := submithonk(w, r)
2517 if h == nil {
2518 return
2519 }
2520 fmt.Fprintf(w, "%s", h.XID)
2521 case "donk":
2522 donks, err := submitdonk(w, r)
2523 if err != nil {
2524 http.Error(w, err.Error(), http.StatusBadRequest)
2525 return
2526 }
2527 if len(donks) == 0 {
2528 http.Error(w, "missing donk", http.StatusBadRequest)
2529 return
2530 }
2531 d := donks[0]
2532 donkxid := fmt.Sprintf("%s:%d", d.XID, d.FileID)
2533 w.Write([]byte(donkxid))
2534 case "zonkit":
2535 zonkit(w, r)
2536 case "gethonks":
2537 var honks []*Honk
2538 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2539 page := r.FormValue("page")
2540 var waitchan <-chan time.Time
2541 requery:
2542 switch page {
2543 case "atme":
2544 honks = gethonksforme(userid, wanted)
2545 honks = osmosis(honks, userid, false)
2546 menewnone(userid)
2547 case "longago":
2548 honks = gethonksfromlongago(userid, wanted)
2549 honks = osmosis(honks, userid, false)
2550 case "home":
2551 honks = gethonksforuser(userid, wanted)
2552 honks = osmosis(honks, userid, true)
2553 case "myhonks":
2554 honks = gethonksbyuser(u.Username, true, wanted)
2555 honks = osmosis(honks, userid, true)
2556 default:
2557 http.Error(w, "unknown page", http.StatusNotFound)
2558 return
2559 }
2560 if len(honks) == 0 && wait > 0 {
2561 if waitchan == nil {
2562 waitchan = time.After(time.Duration(wait) * time.Second)
2563 }
2564 select {
2565 case <-honkline:
2566 goto requery
2567 case <-waitchan:
2568 }
2569 }
2570 reverbolate(userid, honks)
2571 j := junk.New()
2572 j["honks"] = honks
2573 j.Write(w)
2574 case "sendactivity":
2575 user, _ := butwhatabout(u.Username)
2576 public := r.FormValue("public") == "1"
2577 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2578 msg := []byte(r.FormValue("msg"))
2579 for rcpt := range rcpts {
2580 go deliverate(userid, rcpt, msg)
2581 }
2582 case "gethonkers":
2583 j := junk.New()
2584 j["honkers"] = gethonkers(u.UserID)
2585 j.Write(w)
2586 case "savehonker":
2587 h := submithonker(w, r)
2588 if h == nil {
2589 return
2590 }
2591 fmt.Fprintf(w, "%d", h.ID)
2592 default:
2593 http.Error(w, "unknown action", http.StatusNotFound)
2594 return
2595 }
2596}
2597
2598func fiveoh(w http.ResponseWriter, r *http.Request) {
2599 if !develMode {
2600 return
2601 }
2602 fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2603 if err != nil {
2604 elog.Printf("error opening violations! %s", err)
2605 return
2606 }
2607 defer fd.Close()
2608 io.Copy(fd, r.Body)
2609 fd.WriteString("\n")
2610}
2611
2612var endoftheworld = make(chan bool)
2613var readyalready = make(chan bool)
2614var workinprogress = 0
2615
2616func enditall() {
2617 sig := make(chan os.Signal, 1)
2618 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2619 <-sig
2620 ilog.Printf("stopping...")
2621 for i := 0; i < workinprogress; i++ {
2622 endoftheworld <- true
2623 }
2624 ilog.Printf("waiting...")
2625 for i := 0; i < workinprogress; i++ {
2626 <-readyalready
2627 }
2628 ilog.Printf("apocalypse")
2629 os.Exit(0)
2630}
2631
2632var preservehooks []func()
2633
2634func bgmonitor() {
2635 for {
2636 when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2637 _, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2638 if err != nil {
2639 elog.Printf("error deleting old xonkers: %s", err)
2640 }
2641 zaggies.Flush()
2642 time.Sleep(50 * time.Minute)
2643 }
2644}
2645
2646func addcspheaders(next http.Handler) http.Handler {
2647 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2648 policy := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'"
2649 if develMode {
2650 policy += "; report-uri /csp-violation"
2651 }
2652 w.Header().Set("Content-Security-Policy", policy)
2653 next.ServeHTTP(w, r)
2654 })
2655}
2656
2657func emuinit() {
2658 var emunames []string
2659 dir, err := os.Open(dataDir + "/emus")
2660 if err == nil {
2661 emunames, _ = dir.Readdirnames(0)
2662 dir.Close()
2663 }
2664 for _, e := range emunames {
2665 if len(e) <= 4 {
2666 continue
2667 }
2668 ext := e[len(e)-4:]
2669 emu := Emu{
2670 ID: fmt.Sprintf("/emu/%s", e),
2671 Name: e[:len(e)-4],
2672 Type: "image/" + ext[1:],
2673 }
2674 allemus = append(allemus, emu)
2675 }
2676 sort.Slice(allemus, func(i, j int) bool {
2677 return allemus[i].Name < allemus[j].Name
2678 })
2679}
2680
2681func serve() {
2682 db := opendatabase()
2683 login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2684
2685 listener, err := openListener()
2686 if err != nil {
2687 elog.Fatal(err)
2688 }
2689 runBackendServer()
2690 go enditall()
2691 go redeliverator()
2692 go tracker()
2693 go bgmonitor()
2694 go qotd()
2695 loadLingo()
2696 emuinit()
2697
2698 readviews = templates.Load(develMode,
2699 viewDir+"/views/honkpage.html",
2700 viewDir+"/views/honkfrags.html",
2701 viewDir+"/views/honkers.html",
2702 viewDir+"/views/chatter.html",
2703 viewDir+"/views/hfcs.html",
2704 viewDir+"/views/combos.html",
2705 viewDir+"/views/honkform.html",
2706 viewDir+"/views/honk.html",
2707 viewDir+"/views/account.html",
2708 viewDir+"/views/about.html",
2709 viewDir+"/views/funzone.html",
2710 viewDir+"/views/login.html",
2711 viewDir+"/views/xzone.html",
2712 viewDir+"/views/msg.html",
2713 viewDir+"/views/header.html",
2714 viewDir+"/views/onts.html",
2715 viewDir+"/views/emus.html",
2716 viewDir+"/views/honkpage.js",
2717 )
2718 if !develMode {
2719 assets := []string{
2720 viewDir + "/views/style.css",
2721 dataDir + "/views/local.css",
2722 viewDir + "/views/honkpage.js",
2723 viewDir + "/views/misc.js",
2724 dataDir + "/views/local.js",
2725 }
2726 for _, s := range assets {
2727 savedassetparams[s] = getassetparam(s)
2728 }
2729 loadAvatarColors()
2730 }
2731
2732 for _, h := range preservehooks {
2733 h()
2734 }
2735
2736 mux := mux.NewRouter()
2737 mux.Use(addcspheaders)
2738 mux.Use(login.Checker)
2739
2740 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2741
2742 posters := mux.Methods("POST").Subrouter()
2743 getters := mux.Methods("GET").Subrouter()
2744
2745 getters.HandleFunc("/", homepage)
2746 getters.HandleFunc("/home", homepage)
2747 getters.HandleFunc("/front", homepage)
2748 getters.HandleFunc("/events", homepage)
2749 getters.HandleFunc("/robots.txt", nomoroboto)
2750 getters.HandleFunc("/rss", showrss)
2751 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2752 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2753 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2754 posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2755 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2756 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2757 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2758 getters.HandleFunc("/a", avatate)
2759 getters.HandleFunc("/o", thelistingoftheontologies)
2760 getters.HandleFunc("/o/{name:.+}", showontology)
2761 getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2762 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2763 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2764 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2765
2766 getters.HandleFunc("/flag/{code:.+}", showflag)
2767
2768 getters.HandleFunc("/server", serveractor)
2769 posters.HandleFunc("/server/inbox", serverinbox)
2770 posters.HandleFunc("/inbox", serverinbox)
2771
2772 posters.HandleFunc("/csp-violation", fiveoh)
2773
2774 getters.HandleFunc("/style.css", serveviewasset)
2775 getters.HandleFunc("/honkpage.js", serveviewasset)
2776 getters.HandleFunc("/misc.js", serveviewasset)
2777 getters.HandleFunc("/local.css", servedataasset)
2778 getters.HandleFunc("/local.js", servedataasset)
2779 getters.HandleFunc("/icon.png", servedataasset)
2780 getters.HandleFunc("/favicon.ico", servedataasset)
2781
2782 getters.HandleFunc("/about", servehtml)
2783 getters.HandleFunc("/login", servehtml)
2784 posters.HandleFunc("/dologin", login.LoginFunc)
2785 getters.HandleFunc("/logout", login.LogoutFunc)
2786 getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2787
2788 loggedin := mux.NewRoute().Subrouter()
2789 loggedin.Use(login.Required)
2790 loggedin.HandleFunc("/first", homepage)
2791 loggedin.HandleFunc("/chatter", showchatter)
2792 loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2793 loggedin.HandleFunc("/saved", homepage)
2794 loggedin.HandleFunc("/account", accountpage)
2795 loggedin.HandleFunc("/funzone", showfunzone)
2796 loggedin.HandleFunc("/chpass", dochpass)
2797 loggedin.HandleFunc("/atme", homepage)
2798 loggedin.HandleFunc("/longago", homepage)
2799 loggedin.HandleFunc("/hfcs", hfcspage)
2800 loggedin.HandleFunc("/xzone", xzone)
2801 loggedin.HandleFunc("/newhonk", newhonkpage)
2802 loggedin.HandleFunc("/edit", edithonkpage)
2803 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2804 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2805 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2806 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2807 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2808 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2809 loggedin.HandleFunc("/honkers", showhonkers)
2810 loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2811 loggedin.HandleFunc("/h", showhonker)
2812 loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2813 loggedin.HandleFunc("/c", showcombos)
2814 loggedin.HandleFunc("/t", showconvoy)
2815 loggedin.HandleFunc("/q", showsearch)
2816 loggedin.HandleFunc("/hydra", webhydra)
2817 loggedin.HandleFunc("/emus", showemus)
2818 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2819
2820 err = http.Serve(listener, mux)
2821 if err != nil {
2822 elog.Fatal(err)
2823 }
2824}