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