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 if false {
1082 sort.SliceStable(childs, func(i, j int) bool {
1083 return sameperson(childs[i], p) && !sameperson(childs[j], p)
1084 })
1085 }
1086 if true {
1087 sort.SliceStable(childs, func(i, j int) bool {
1088 return !sameperson(childs[i], p) && sameperson(childs[j], p)
1089 })
1090 }
1091 for _, h := range childs {
1092 if !done[h] {
1093 done[h] = true
1094 thread = append(thread, h)
1095 nextlevel(h)
1096 }
1097 }
1098 if levelup {
1099 level--
1100 }
1101 }
1102 for _, h := range honks {
1103 if !done[h] && h.RID == "" {
1104 done[h] = true
1105 thread = append(thread, h)
1106 nextlevel(h)
1107 }
1108 }
1109 for _, h := range honks {
1110 if !done[h] {
1111 done[h] = true
1112 thread = append(thread, h)
1113 nextlevel(h)
1114 }
1115 }
1116 return thread
1117}
1118
1119func honkology(honk *Honk) template.HTML {
1120 var user *WhatAbout
1121 ok := somenumberedusers.Get(honk.UserID, &user)
1122 if !ok {
1123 return ""
1124 }
1125 title := fmt.Sprintf("%s: %s", user.Display, honk.Precis)
1126 imgurl := avatarURL(user)
1127 for _, d := range honk.Donks {
1128 if d.Local && strings.HasPrefix(d.Media, "image") {
1129 imgurl = d.URL
1130 break
1131 }
1132 }
1133 short := honk.Noise
1134 if len(short) > 160 {
1135 short = short[0:160] + "..."
1136 }
1137 return templates.Sprintf(
1138 `<meta property="og:title" content="%s" />
1139<meta property="og:type" content="article" />
1140<meta property="article:author" content="%s" />
1141<meta property="og:url" content="%s" />
1142<meta property="og:image" content="%s" />
1143<meta property="og:description" content="%s" />`,
1144 title, user.URL, honk.XID, imgurl, short)
1145}
1146
1147func showonehonk(w http.ResponseWriter, r *http.Request) {
1148 name := mux.Vars(r)["name"]
1149 user, err := butwhatabout(name)
1150 if err != nil {
1151 http.NotFound(w, r)
1152 return
1153 }
1154 if stealthmode(user.ID, r) {
1155 http.NotFound(w, r)
1156 return
1157 }
1158 xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1159
1160 if friendorfoe(r.Header.Get("Accept")) {
1161 j, ok := gimmejonk(xid)
1162 if ok {
1163 trackback(xid, r)
1164 w.Header().Set("Content-Type", theonetruename)
1165 w.Write(j)
1166 } else {
1167 http.NotFound(w, r)
1168 }
1169 return
1170 }
1171 honk := getxonk(user.ID, xid)
1172 if honk == nil {
1173 http.NotFound(w, r)
1174 return
1175 }
1176 u := login.GetUserInfo(r)
1177 if u != nil && u.UserID != user.ID {
1178 u = nil
1179 }
1180 if !honk.Public {
1181 if u == nil {
1182 http.NotFound(w, r)
1183 return
1184
1185 }
1186 honks := []*Honk{honk}
1187 donksforhonks(honks)
1188 templinfo := getInfo(r)
1189 templinfo["ServerMessage"] = "one honk maybe more"
1190 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1191 honkpage(w, u, honks, templinfo)
1192 return
1193 }
1194
1195 templinfo := getInfo(r)
1196 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1197 //reversehonks(rawhonks)
1198 rawhonks = threadsort(rawhonks)
1199 var honks []*Honk
1200 for _, h := range rawhonks {
1201 if h.XID == xid {
1202 templinfo["Honkology"] = honkology(h)
1203 if len(honks) != 0 {
1204 h.Style += " glow"
1205 }
1206 }
1207 if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1208 honks = append(honks, h)
1209 }
1210 }
1211
1212 templinfo["ServerMessage"] = "one honk maybe more"
1213 if u != nil {
1214 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1215 }
1216 templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1217 honkpage(w, u, honks, templinfo)
1218}
1219
1220func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1221 var userid int64 = -1
1222 if u != nil {
1223 userid = u.UserID
1224 templinfo["User"], _ = butwhatabout(u.Username)
1225 }
1226 reverbolate(userid, honks)
1227 templinfo["Honks"] = honks
1228 templinfo["MapLink"] = getmaplink(u)
1229 if templinfo["TopHID"] == nil {
1230 if len(honks) > 0 {
1231 templinfo["TopHID"] = honks[0].ID
1232 } else {
1233 templinfo["TopHID"] = 0
1234 }
1235 }
1236 if u == nil && !develMode {
1237 w.Header().Set("Cache-Control", "max-age=60")
1238 }
1239 err := readviews.Execute(w, "honkpage.html", templinfo)
1240 if err != nil {
1241 elog.Print(err)
1242 }
1243}
1244
1245func saveuser(w http.ResponseWriter, r *http.Request) {
1246 whatabout := r.FormValue("whatabout")
1247 whatabout = strings.Replace(whatabout, "\r", "", -1)
1248 u := login.GetUserInfo(r)
1249 user, _ := butwhatabout(u.Username)
1250 db := opendatabase()
1251
1252 options := user.Options
1253 if r.FormValue("skinny") == "skinny" {
1254 options.SkinnyCSS = true
1255 } else {
1256 options.SkinnyCSS = false
1257 }
1258 if r.FormValue("omitimages") == "omitimages" {
1259 options.OmitImages = true
1260 } else {
1261 options.OmitImages = false
1262 }
1263 if r.FormValue("mentionall") == "mentionall" {
1264 options.MentionAll = true
1265 } else {
1266 options.MentionAll = false
1267 }
1268 if r.FormValue("inlineqts") == "inlineqts" {
1269 options.InlineQuotes = true
1270 } else {
1271 options.InlineQuotes = false
1272 }
1273 if r.FormValue("maps") == "apple" {
1274 options.MapLink = "apple"
1275 } else {
1276 options.MapLink = ""
1277 }
1278 options.Reaction = r.FormValue("reaction")
1279
1280 sendupdate := false
1281 ava := re_avatar.FindString(whatabout)
1282 if ava != "" {
1283 whatabout = re_avatar.ReplaceAllString(whatabout, "")
1284 ava = ava[7:]
1285 if ava[0] == ' ' {
1286 ava = ava[1:]
1287 }
1288 ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1289 }
1290 if ava != options.Avatar {
1291 options.Avatar = ava
1292 sendupdate = true
1293 }
1294 ban := re_banner.FindString(whatabout)
1295 if ban != "" {
1296 whatabout = re_banner.ReplaceAllString(whatabout, "")
1297 ban = ban[7:]
1298 if ban[0] == ' ' {
1299 ban = ban[1:]
1300 }
1301 ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1302 }
1303 if ban != options.Banner {
1304 options.Banner = ban
1305 sendupdate = true
1306 }
1307 whatabout = strings.TrimSpace(whatabout)
1308 if whatabout != user.About {
1309 sendupdate = true
1310 }
1311 j, err := jsonify(options)
1312 if err == nil {
1313 _, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1314 }
1315 if err != nil {
1316 elog.Printf("error bouting what: %s", err)
1317 }
1318 somenamedusers.Clear(u.Username)
1319 somenumberedusers.Clear(u.UserID)
1320 oldjonkers.Clear(u.Username)
1321
1322 if sendupdate {
1323 updateMe(u.Username)
1324 }
1325
1326 http.Redirect(w, r, "/account", http.StatusSeeOther)
1327}
1328
1329func bonkit(xid string, user *WhatAbout) {
1330 dlog.Printf("bonking %s", xid)
1331
1332 xonk := getxonk(user.ID, xid)
1333 if xonk == nil {
1334 return
1335 }
1336 if !xonk.Public {
1337 return
1338 }
1339 if xonk.IsBonked() {
1340 return
1341 }
1342 donksforhonks([]*Honk{xonk})
1343
1344 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1345 if err != nil {
1346 elog.Printf("error acking bonk: %s", err)
1347 }
1348
1349 oonker := xonk.Oonker
1350 if oonker == "" {
1351 oonker = xonk.Honker
1352 }
1353 dt := time.Now().UTC()
1354 bonk := &Honk{
1355 UserID: user.ID,
1356 Username: user.Name,
1357 What: "bonk",
1358 Honker: user.URL,
1359 Oonker: oonker,
1360 XID: xonk.XID,
1361 RID: xonk.RID,
1362 Noise: xonk.Noise,
1363 Precis: xonk.Precis,
1364 URL: xonk.URL,
1365 Date: dt,
1366 Donks: xonk.Donks,
1367 Whofore: 2,
1368 Convoy: xonk.Convoy,
1369 Audience: []string{thewholeworld, oonker},
1370 Public: true,
1371 Format: xonk.Format,
1372 Place: xonk.Place,
1373 Onts: xonk.Onts,
1374 Time: xonk.Time,
1375 }
1376
1377 err = savehonk(bonk)
1378 if err != nil {
1379 elog.Printf("uh oh")
1380 return
1381 }
1382
1383 go honkworldwide(user, bonk)
1384}
1385
1386func submitbonk(w http.ResponseWriter, r *http.Request) {
1387 xid := r.FormValue("xid")
1388 userinfo := login.GetUserInfo(r)
1389 user, _ := butwhatabout(userinfo.Username)
1390
1391 bonkit(xid, user)
1392
1393 if r.FormValue("js") != "1" {
1394 templinfo := getInfo(r)
1395 templinfo["ServerMessage"] = "Bonked!"
1396 err := readviews.Execute(w, "msg.html", templinfo)
1397 if err != nil {
1398 elog.Print(err)
1399 }
1400 }
1401}
1402
1403func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1404 zonk := &Honk{
1405 What: what,
1406 XID: xonk.XID,
1407 Date: time.Now().UTC(),
1408 Audience: oneofakind(xonk.Audience),
1409 Noise: aux,
1410 }
1411 zonk.Public = loudandproud(zonk.Audience)
1412
1413 dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1414 go honkworldwide(user, zonk)
1415}
1416
1417func zonkit(w http.ResponseWriter, r *http.Request) {
1418 wherefore := r.FormValue("wherefore")
1419 what := r.FormValue("what")
1420 userinfo := login.GetUserInfo(r)
1421 user, _ := butwhatabout(userinfo.Username)
1422
1423 if wherefore == "save" {
1424 xonk := getxonk(userinfo.UserID, what)
1425 if xonk != nil {
1426 _, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1427 if err != nil {
1428 elog.Printf("error saving: %s", err)
1429 }
1430 }
1431 return
1432 }
1433
1434 if wherefore == "unsave" {
1435 xonk := getxonk(userinfo.UserID, what)
1436 if xonk != nil {
1437 _, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1438 if err != nil {
1439 elog.Printf("error unsaving: %s", err)
1440 }
1441 }
1442 return
1443 }
1444
1445 if wherefore == "react" {
1446 reaction := user.Options.Reaction
1447 if r2 := r.FormValue("reaction"); r2 != "" {
1448 reaction = r2
1449 }
1450 if reaction == "none" {
1451 return
1452 }
1453 xonk := getxonk(userinfo.UserID, what)
1454 if xonk != nil {
1455 _, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1456 if err != nil {
1457 elog.Printf("error saving: %s", err)
1458 }
1459 sendzonkofsorts(xonk, user, "react", reaction)
1460 }
1461 return
1462 }
1463
1464 // my hammer is too big, oh well
1465 defer oldjonks.Flush()
1466
1467 if wherefore == "ack" {
1468 xonk := getxonk(userinfo.UserID, what)
1469 if xonk != nil && !xonk.IsAcked() {
1470 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1471 if err != nil {
1472 elog.Printf("error acking: %s", err)
1473 }
1474 sendzonkofsorts(xonk, user, "ack", "")
1475 }
1476 return
1477 }
1478
1479 if wherefore == "deack" {
1480 xonk := getxonk(userinfo.UserID, what)
1481 if xonk != nil && xonk.IsAcked() {
1482 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1483 if err != nil {
1484 elog.Printf("error deacking: %s", err)
1485 }
1486 sendzonkofsorts(xonk, user, "deack", "")
1487 }
1488 return
1489 }
1490
1491 if wherefore == "bonk" {
1492 user, _ := butwhatabout(userinfo.Username)
1493 bonkit(what, user)
1494 return
1495 }
1496
1497 if wherefore == "unbonk" {
1498 xonk := getbonk(userinfo.UserID, what)
1499 if xonk != nil {
1500 deletehonk(xonk.ID)
1501 xonk = getxonk(userinfo.UserID, what)
1502 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1503 if err != nil {
1504 elog.Printf("error unbonking: %s", err)
1505 }
1506 sendzonkofsorts(xonk, user, "unbonk", "")
1507 }
1508 return
1509 }
1510
1511 if wherefore == "untag" {
1512 xonk := getxonk(userinfo.UserID, what)
1513 if xonk != nil {
1514 _, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1515 if err != nil {
1516 elog.Printf("error untagging: %s", err)
1517 }
1518 }
1519 var badparents map[string]bool
1520 untagged.GetAndLock(userinfo.UserID, &badparents)
1521 badparents[what] = true
1522 untagged.Unlock()
1523 return
1524 }
1525
1526 ilog.Printf("zonking %s %s", wherefore, what)
1527 if wherefore == "zonk" {
1528 xonk := getxonk(userinfo.UserID, what)
1529 if xonk != nil {
1530 deletehonk(xonk.ID)
1531 if xonk.Whofore == 2 || xonk.Whofore == 3 {
1532 sendzonkofsorts(xonk, user, "zonk", "")
1533 }
1534 }
1535 }
1536 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1537 if err != nil {
1538 elog.Printf("error saving zonker: %s", err)
1539 return
1540 }
1541}
1542
1543func edithonkpage(w http.ResponseWriter, r *http.Request) {
1544 u := login.GetUserInfo(r)
1545 user, _ := butwhatabout(u.Username)
1546 xid := r.FormValue("xid")
1547 honk := getxonk(u.UserID, xid)
1548 if !canedithonk(user, honk) {
1549 http.Error(w, "no editing that please", http.StatusInternalServerError)
1550 return
1551 }
1552
1553 noise := honk.Noise
1554
1555 honks := []*Honk{honk}
1556 donksforhonks(honks)
1557 reverbolate(u.UserID, honks)
1558 templinfo := getInfo(r)
1559 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1560 templinfo["Honks"] = honks
1561 templinfo["MapLink"] = getmaplink(u)
1562 templinfo["Noise"] = noise
1563 templinfo["SavedPlace"] = honk.Place
1564 if tm := honk.Time; tm != nil {
1565 templinfo["ShowTime"] = " "
1566 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1567 if tm.Duration != 0 {
1568 templinfo["Duration"] = tm.Duration
1569 }
1570 }
1571 templinfo["ServerMessage"] = "honk edit 2"
1572 templinfo["IsPreview"] = true
1573 templinfo["UpdateXID"] = honk.XID
1574 if len(honk.Donks) > 0 {
1575 templinfo["SavedFile"] = honk.Donks[0].XID
1576 }
1577 err := readviews.Execute(w, "honkpage.html", templinfo)
1578 if err != nil {
1579 elog.Print(err)
1580 }
1581}
1582
1583func newhonkpage(w http.ResponseWriter, r *http.Request) {
1584 u := login.GetUserInfo(r)
1585 rid := r.FormValue("rid")
1586 noise := ""
1587
1588 xonk := getxonk(u.UserID, rid)
1589 if xonk != nil {
1590 _, replto := handles(xonk.Honker)
1591 if replto != "" {
1592 noise = "@" + replto + " "
1593 }
1594 }
1595
1596 templinfo := getInfo(r)
1597 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1598 templinfo["InReplyTo"] = rid
1599 templinfo["Noise"] = noise
1600 templinfo["ServerMessage"] = "compose honk"
1601 templinfo["IsPreview"] = true
1602 err := readviews.Execute(w, "honkpage.html", templinfo)
1603 if err != nil {
1604 elog.Print(err)
1605 }
1606}
1607
1608func canedithonk(user *WhatAbout, honk *Honk) bool {
1609 if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1610 return false
1611 }
1612 return true
1613}
1614
1615func submitdonk(w http.ResponseWriter, r *http.Request) (*Donk, error) {
1616 if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1617 return nil, nil
1618 }
1619 file, filehdr, err := r.FormFile("donk")
1620 if err != nil {
1621 if err == http.ErrMissingFile {
1622 return nil, nil
1623 }
1624 elog.Printf("error reading donk: %s", err)
1625 http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1626 return nil, err
1627 }
1628 var buf bytes.Buffer
1629 io.Copy(&buf, file)
1630 file.Close()
1631 data := buf.Bytes()
1632 var media, name string
1633 img, err := shrinkit(data)
1634 if err == nil {
1635 data = img.Data
1636 format := img.Format
1637 media = "image/" + format
1638 if format == "jpeg" {
1639 format = "jpg"
1640 }
1641 if format == "svg+xml" {
1642 format = "svg"
1643 }
1644 name = xfiltrate() + "." + format
1645 } else {
1646 ct := http.DetectContentType(data)
1647 switch ct {
1648 case "application/pdf":
1649 maxsize := 10000000
1650 if len(data) > maxsize {
1651 ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1652 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1653 return nil, err
1654 }
1655 media = ct
1656 name = filehdr.Filename
1657 if name == "" {
1658 name = xfiltrate() + ".pdf"
1659 }
1660 default:
1661 maxsize := 100000
1662 if len(data) > maxsize {
1663 ilog.Printf("bad image: %s too much text: %d", err, len(data))
1664 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1665 return nil, err
1666 }
1667 for i := 0; i < len(data); i++ {
1668 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1669 ilog.Printf("bad image: %s not text: %d", err, data[i])
1670 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1671 return nil, err
1672 }
1673 }
1674 media = "text/plain"
1675 name = filehdr.Filename
1676 if name == "" {
1677 name = xfiltrate() + ".txt"
1678 }
1679 }
1680 }
1681 desc := strings.TrimSpace(r.FormValue("donkdesc"))
1682 if desc == "" {
1683 desc = name
1684 }
1685 fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1686 if err != nil {
1687 elog.Printf("unable to save image: %s", err)
1688 http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1689 return nil, err
1690 }
1691 d := &Donk{
1692 FileID: fileid,
1693 XID: xid,
1694 Desc: desc,
1695 Local: true,
1696 }
1697 return d, nil
1698}
1699
1700func websubmithonk(w http.ResponseWriter, r *http.Request) {
1701 h := submithonk(w, r)
1702 if h == nil {
1703 return
1704 }
1705 http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1706}
1707
1708// what a hot mess this function is
1709func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1710 rid := r.FormValue("rid")
1711 noise := r.FormValue("noise")
1712 format := r.FormValue("format")
1713 if format == "" {
1714 format = "markdown"
1715 }
1716 if !(format == "markdown" || format == "html") {
1717 http.Error(w, "unknown format", 500)
1718 return nil
1719 }
1720
1721 userinfo := login.GetUserInfo(r)
1722 user, _ := butwhatabout(userinfo.Username)
1723
1724 dt := time.Now().UTC()
1725 updatexid := r.FormValue("updatexid")
1726 var honk *Honk
1727 if updatexid != "" {
1728 honk = getxonk(userinfo.UserID, updatexid)
1729 if !canedithonk(user, honk) {
1730 http.Error(w, "no editing that please", http.StatusInternalServerError)
1731 return nil
1732 }
1733 honk.Date = dt
1734 honk.What = "update"
1735 honk.Format = format
1736 } else {
1737 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1738 what := "honk"
1739 honk = &Honk{
1740 UserID: userinfo.UserID,
1741 Username: userinfo.Username,
1742 What: what,
1743 Honker: user.URL,
1744 XID: xid,
1745 Date: dt,
1746 Format: format,
1747 }
1748 }
1749
1750 var convoy string
1751 noise = strings.Replace(noise, "\r", "", -1)
1752 if updatexid == "" && rid == "" {
1753 noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1754 convoy = m[7:]
1755 convoy = strings.TrimSpace(convoy)
1756 if !re_convalidate.MatchString(convoy) {
1757 convoy = ""
1758 }
1759 return ""
1760 })
1761 }
1762 noise = quickrename(noise, userinfo.UserID)
1763 noise = hooterize(noise)
1764 honk.Noise = noise
1765 precipitate(honk)
1766 noise = honk.Noise
1767 recategorize(honk)
1768 translate(honk)
1769
1770 if rid != "" {
1771 xonk := getxonk(userinfo.UserID, rid)
1772 if xonk == nil {
1773 http.Error(w, "replyto disappeared", http.StatusNotFound)
1774 return nil
1775 }
1776 if xonk.Public {
1777 honk.Audience = append(honk.Audience, xonk.Audience...)
1778 }
1779 convoy = xonk.Convoy
1780 for i, a := range honk.Audience {
1781 if a == thewholeworld {
1782 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1783 break
1784 }
1785 }
1786 honk.RID = rid
1787 if xonk.Precis != "" && honk.Precis == "" {
1788 honk.Precis = xonk.Precis
1789 if !re_dangerous.MatchString(honk.Precis) {
1790 honk.Precis = "re: " + honk.Precis
1791 }
1792 }
1793 } else if updatexid == "" {
1794 honk.Audience = []string{thewholeworld}
1795 }
1796 if honk.Noise != "" && honk.Noise[0] == '@' {
1797 honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1798 } else {
1799 honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1800 }
1801
1802 if convoy == "" {
1803 convoy = "data:,electrichonkytonk-" + xfiltrate()
1804 }
1805 butnottooloud(honk.Audience)
1806 honk.Audience = oneofakind(honk.Audience)
1807 if len(honk.Audience) == 0 {
1808 ilog.Printf("honk to nowhere")
1809 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1810 return nil
1811 }
1812 honk.Public = loudandproud(honk.Audience)
1813 honk.Convoy = convoy
1814
1815 donkxid := r.FormValue("donkxid")
1816 if donkxid == "" {
1817 d, err := submitdonk(w, r)
1818 if err != nil && err != http.ErrMissingFile {
1819 return nil
1820 }
1821 if d != nil {
1822 honk.Donks = append(honk.Donks, d)
1823 donkxid = fmt.Sprintf("%s:%d", d.XID, d.FileID)
1824 }
1825 } else {
1826 for _, xid := range r.Form["donkxid"] {
1827 p := strings.Split(xid, ":")
1828 xid = p[0]
1829 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1830 var donk *Donk
1831 if len(p) > 1 {
1832 fileid, _ := strconv.ParseInt(p[1], 10, 0)
1833 donk = finddonkid(fileid, url)
1834 } else {
1835 donk = finddonk(url)
1836 }
1837 if donk != nil {
1838 honk.Donks = append(honk.Donks, donk)
1839 } else {
1840 ilog.Printf("can't find file: %s", xid)
1841 }
1842 }
1843 }
1844 memetize(honk)
1845 imaginate(honk)
1846
1847 placename := strings.TrimSpace(r.FormValue("placename"))
1848 placelat := strings.TrimSpace(r.FormValue("placelat"))
1849 placelong := strings.TrimSpace(r.FormValue("placelong"))
1850 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1851 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1852 p := new(Place)
1853 p.Name = placename
1854 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1855 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1856 p.Url = placeurl
1857 honk.Place = p
1858 }
1859 timestart := strings.TrimSpace(r.FormValue("timestart"))
1860 if timestart != "" {
1861 t := new(Time)
1862 now := time.Now().Local()
1863 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1864 start, err := time.ParseInLocation(layout, timestart, now.Location())
1865 if err == nil {
1866 if start.Year() == 0 {
1867 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1868 }
1869 t.StartTime = start
1870 break
1871 }
1872 }
1873 timeend := r.FormValue("timeend")
1874 dur := parseDuration(timeend)
1875 if dur != 0 {
1876 t.Duration = Duration(dur)
1877 }
1878 if !t.StartTime.IsZero() {
1879 honk.What = "event"
1880 honk.Time = t
1881 }
1882 }
1883
1884 if honk.Public {
1885 honk.Whofore = 2
1886 } else {
1887 honk.Whofore = 3
1888 }
1889
1890 // back to markdown
1891 honk.Noise = noise
1892
1893 if r.FormValue("preview") == "preview" {
1894 honks := []*Honk{honk}
1895 reverbolate(userinfo.UserID, honks)
1896 templinfo := getInfo(r)
1897 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1898 templinfo["Honks"] = honks
1899 templinfo["MapLink"] = getmaplink(userinfo)
1900 templinfo["InReplyTo"] = r.FormValue("rid")
1901 templinfo["Noise"] = r.FormValue("noise")
1902 templinfo["SavedFile"] = donkxid
1903 if tm := honk.Time; tm != nil {
1904 templinfo["ShowTime"] = " "
1905 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1906 if tm.Duration != 0 {
1907 templinfo["Duration"] = tm.Duration
1908 }
1909 }
1910 templinfo["IsPreview"] = true
1911 templinfo["UpdateXID"] = updatexid
1912 templinfo["ServerMessage"] = "honk preview"
1913 err := readviews.Execute(w, "honkpage.html", templinfo)
1914 if err != nil {
1915 elog.Print(err)
1916 }
1917 return nil
1918 }
1919
1920 if updatexid != "" {
1921 updatehonk(honk)
1922 oldjonks.Clear(honk.XID)
1923 } else {
1924 err := savehonk(honk)
1925 if err != nil {
1926 elog.Printf("uh oh")
1927 return nil
1928 }
1929 }
1930
1931 // reload for consistency
1932 honk.Donks = nil
1933 donksforhonks([]*Honk{honk})
1934
1935 go honkworldwide(user, honk)
1936
1937 return honk
1938}
1939
1940func showhonkers(w http.ResponseWriter, r *http.Request) {
1941 userinfo := login.GetUserInfo(r)
1942 templinfo := getInfo(r)
1943 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1944 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1945 err := readviews.Execute(w, "honkers.html", templinfo)
1946 if err != nil {
1947 elog.Print(err)
1948 }
1949}
1950
1951func showchatter(w http.ResponseWriter, r *http.Request) {
1952 u := login.GetUserInfo(r)
1953 chatnewnone(u.UserID)
1954 chatter := loadchatter(u.UserID)
1955 for _, chat := range chatter {
1956 for _, ch := range chat.Chonks {
1957 filterchonk(ch)
1958 }
1959 }
1960
1961 templinfo := getInfo(r)
1962 templinfo["Chatter"] = chatter
1963 templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1964 err := readviews.Execute(w, "chatter.html", templinfo)
1965 if err != nil {
1966 elog.Print(err)
1967 }
1968}
1969
1970func submitchonk(w http.ResponseWriter, r *http.Request) {
1971 u := login.GetUserInfo(r)
1972 user, _ := butwhatabout(u.Username)
1973 noise := r.FormValue("noise")
1974 target := r.FormValue("target")
1975 format := "markdown"
1976 dt := time.Now().UTC()
1977 xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1978
1979 if !strings.HasPrefix(target, "https://") {
1980 target = fullname(target, u.UserID)
1981 }
1982 if target == "" {
1983 http.Error(w, "who is that?", http.StatusInternalServerError)
1984 return
1985 }
1986 ch := Chonk{
1987 UserID: u.UserID,
1988 XID: xid,
1989 Who: user.URL,
1990 Target: target,
1991 Date: dt,
1992 Noise: noise,
1993 Format: format,
1994 }
1995 d, err := submitdonk(w, r)
1996 if err != nil && err != http.ErrMissingFile {
1997 return
1998 }
1999 if d != nil {
2000 ch.Donks = append(ch.Donks, d)
2001 }
2002
2003 translatechonk(&ch)
2004 savechonk(&ch)
2005 // reload for consistency
2006 ch.Donks = nil
2007 donksforchonks([]*Chonk{&ch})
2008 go sendchonk(user, &ch)
2009
2010 http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2011}
2012
2013var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
2014 honkers := gethonkers(userid)
2015 var combos []string
2016 for _, h := range honkers {
2017 combos = append(combos, h.Combos...)
2018 }
2019 for i, c := range combos {
2020 if c == "-" {
2021 combos[i] = ""
2022 }
2023 }
2024 combos = oneofakind(combos)
2025 sort.Strings(combos)
2026 return combos, true
2027}, Invalidator: &honkerinvalidator})
2028
2029func showcombos(w http.ResponseWriter, r *http.Request) {
2030 userinfo := login.GetUserInfo(r)
2031 var combos []string
2032 combocache.Get(userinfo.UserID, &combos)
2033 templinfo := getInfo(r)
2034 err := readviews.Execute(w, "combos.html", templinfo)
2035 if err != nil {
2036 elog.Print(err)
2037 }
2038}
2039
2040func websubmithonker(w http.ResponseWriter, r *http.Request) {
2041 h := submithonker(w, r)
2042 if h == nil {
2043 return
2044 }
2045 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2046}
2047
2048func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2049 u := login.GetUserInfo(r)
2050 user, _ := butwhatabout(u.Username)
2051 name := strings.TrimSpace(r.FormValue("name"))
2052 url := strings.TrimSpace(r.FormValue("url"))
2053 peep := r.FormValue("peep")
2054 combos := strings.TrimSpace(r.FormValue("combos"))
2055 combos = " " + combos + " "
2056 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2057
2058 re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2059 if name != "" && !re_namecheck.MatchString(name) {
2060 http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2061 return nil
2062 }
2063
2064 var meta HonkerMeta
2065 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2066 mj, _ := jsonify(&meta)
2067
2068 defer honkerinvalidator.Clear(u.UserID)
2069
2070 // mostly dummy, fill in later...
2071 h := &Honker{
2072 ID: honkerid,
2073 }
2074
2075 if honkerid > 0 {
2076 if r.FormValue("delete") == "delete" {
2077 unfollowyou(user, honkerid, false)
2078 stmtDeleteHonker.Exec(honkerid)
2079 return h
2080 }
2081 if r.FormValue("unsub") == "unsub" {
2082 unfollowyou(user, honkerid, false)
2083 }
2084 if r.FormValue("sub") == "sub" {
2085 followyou(user, honkerid, false)
2086 }
2087 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2088 if err != nil {
2089 elog.Printf("update honker err: %s", err)
2090 return nil
2091 }
2092 return h
2093 }
2094
2095 if url == "" {
2096 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2097 return nil
2098 }
2099
2100 flavor := "presub"
2101 if peep == "peep" {
2102 flavor = "peep"
2103 }
2104
2105 var err error
2106 honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2107 if err != nil {
2108 http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2109 return nil
2110 }
2111 if flavor == "presub" {
2112 followyou(user, honkerid, false)
2113 }
2114 h.ID = honkerid
2115 return h
2116}
2117
2118func hfcspage(w http.ResponseWriter, r *http.Request) {
2119 userinfo := login.GetUserInfo(r)
2120
2121 filters := getfilters(userinfo.UserID, filtAny)
2122
2123 templinfo := getInfo(r)
2124 templinfo["Filters"] = filters
2125 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2126 err := readviews.Execute(w, "hfcs.html", templinfo)
2127 if err != nil {
2128 elog.Print(err)
2129 }
2130}
2131
2132func savehfcs(w http.ResponseWriter, r *http.Request) {
2133 userinfo := login.GetUserInfo(r)
2134 itsok := r.FormValue("itsok")
2135 if itsok == "iforgiveyou" {
2136 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2137 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2138 if err != nil {
2139 elog.Printf("error deleting filter: %s", err)
2140 }
2141 filtInvalidator.Clear(userinfo.UserID)
2142 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2143 return
2144 }
2145
2146 filt := new(Filter)
2147 filt.Name = strings.TrimSpace(r.FormValue("name"))
2148 filt.Date = time.Now().UTC()
2149 filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2150 filt.IncludeAudience = r.FormValue("incaud") == "yes"
2151 filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2152 filt.IsReply = r.FormValue("isreply") == "yes"
2153 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2154 filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2155 filt.Reject = r.FormValue("doreject") == "yes"
2156 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2157 filt.Hide = r.FormValue("dohide") == "yes"
2158 filt.Collapse = r.FormValue("docollapse") == "yes"
2159 filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2160 filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2161 if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2162 filt.Expiration = time.Now().UTC().Add(dur)
2163 }
2164 filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2165
2166 if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2167 ilog.Printf("blank filter")
2168 http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2169 return
2170 }
2171
2172 j, err := jsonify(filt)
2173 if err == nil {
2174 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2175 }
2176 if err != nil {
2177 elog.Printf("error saving filter: %s", err)
2178 }
2179
2180 filtInvalidator.Clear(userinfo.UserID)
2181 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2182}
2183
2184func accountpage(w http.ResponseWriter, r *http.Request) {
2185 u := login.GetUserInfo(r)
2186 user, _ := butwhatabout(u.Username)
2187 templinfo := getInfo(r)
2188 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2189 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2190 templinfo["User"] = user
2191 about := user.About
2192 if ava := user.Options.Avatar; ava != "" {
2193 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2194 }
2195 if ban := user.Options.Banner; ban != "" {
2196 about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2197 }
2198 templinfo["WhatAbout"] = about
2199 err := readviews.Execute(w, "account.html", templinfo)
2200 if err != nil {
2201 elog.Print(err)
2202 }
2203}
2204
2205func dochpass(w http.ResponseWriter, r *http.Request) {
2206 err := login.ChangePassword(w, r)
2207 if err != nil {
2208 elog.Printf("error changing password: %s", err)
2209 }
2210 http.Redirect(w, r, "/account", http.StatusSeeOther)
2211}
2212
2213var oldfingers = cache.New(cache.Options{Filler: func(orig string) ([]byte, bool) {
2214 if strings.HasPrefix(orig, "acct:") {
2215 orig = orig[5:]
2216 }
2217 name := orig
2218 idx := strings.LastIndexByte(name, '/')
2219 if idx != -1 {
2220 name = name[idx+1:]
2221 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2222 ilog.Printf("foreign request rejected")
2223 name = ""
2224 }
2225 } else {
2226 idx = strings.IndexByte(name, '@')
2227 if idx != -1 {
2228 name = name[:idx]
2229 if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2230 ilog.Printf("foreign request rejected")
2231 name = ""
2232 }
2233 }
2234 }
2235 user, err := butwhatabout(name)
2236 if err != nil {
2237 return nil, false
2238 }
2239
2240 j := junk.New()
2241 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2242 j["aliases"] = []string{user.URL}
2243 l := junk.New()
2244 l["rel"] = "self"
2245 l["type"] = `application/activity+json`
2246 l["href"] = user.URL
2247 j["links"] = []junk.Junk{l}
2248 return j.ToBytes(), true
2249}})
2250
2251func fingerlicker(w http.ResponseWriter, r *http.Request) {
2252 orig := r.FormValue("resource")
2253
2254 dlog.Printf("finger lick: %s", orig)
2255
2256 var j []byte
2257 ok := oldfingers.Get(orig, &j)
2258 if ok {
2259 w.Header().Set("Content-Type", "application/jrd+json")
2260 w.Write(j)
2261 } else {
2262 http.NotFound(w, r)
2263 }
2264}
2265
2266func somedays() string {
2267 secs := 432000 + notrand.Int63n(432000)
2268 return fmt.Sprintf("%d", secs)
2269}
2270
2271func lookatme(ava string) string {
2272 if strings.Contains(ava, serverName+"/"+userSep) {
2273 idx := strings.LastIndexByte(ava, '/')
2274 if idx < len(ava) {
2275 name := ava[idx+1:]
2276 user, _ := butwhatabout(name)
2277 if user != nil && user.URL == ava {
2278 return user.Options.Avatar
2279 }
2280 }
2281 }
2282 return ""
2283}
2284
2285func avatate(w http.ResponseWriter, r *http.Request) {
2286 if develMode {
2287 loadAvatarColors()
2288 }
2289 n := r.FormValue("a")
2290 if redir := lookatme(n); redir != "" {
2291 http.Redirect(w, r, redir, http.StatusSeeOther)
2292 return
2293 }
2294 a := genAvatar(n)
2295 if !develMode {
2296 w.Header().Set("Cache-Control", "max-age="+somedays())
2297 }
2298 w.Write(a)
2299}
2300
2301func serveviewasset(w http.ResponseWriter, r *http.Request) {
2302 serveasset(w, r, viewDir)
2303}
2304func servedataasset(w http.ResponseWriter, r *http.Request) {
2305 if r.URL.Path == "/favicon.ico" {
2306 r.URL.Path = "/icon.png"
2307 }
2308 serveasset(w, r, dataDir)
2309}
2310
2311func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2312 if !develMode {
2313 w.Header().Set("Cache-Control", "max-age=7776000")
2314 }
2315 http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2316}
2317func servehelp(w http.ResponseWriter, r *http.Request) {
2318 name := mux.Vars(r)["name"]
2319 if !develMode {
2320 w.Header().Set("Cache-Control", "max-age=3600")
2321 }
2322 http.ServeFile(w, r, viewDir+"/docs/"+name)
2323}
2324func servehtml(w http.ResponseWriter, r *http.Request) {
2325 u := login.GetUserInfo(r)
2326 templinfo := getInfo(r)
2327 templinfo["AboutMsg"] = aboutMsg
2328 templinfo["LoginMsg"] = loginMsg
2329 templinfo["HonkVersion"] = softwareVersion
2330 if r.URL.Path == "/about" {
2331 templinfo["Sensors"] = getSensors()
2332 }
2333 if u == nil && !develMode {
2334 w.Header().Set("Cache-Control", "max-age=60")
2335 }
2336 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2337 if err != nil {
2338 elog.Print(err)
2339 }
2340}
2341func serveemu(w http.ResponseWriter, r *http.Request) {
2342 emu := mux.Vars(r)["emu"]
2343
2344 w.Header().Set("Cache-Control", "max-age="+somedays())
2345 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2346}
2347func servememe(w http.ResponseWriter, r *http.Request) {
2348 meme := mux.Vars(r)["meme"]
2349
2350 w.Header().Set("Cache-Control", "max-age="+somedays())
2351 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2352}
2353
2354func servefile(w http.ResponseWriter, r *http.Request) {
2355 xid := mux.Vars(r)["xid"]
2356 var media string
2357 var data []byte
2358 row := stmtGetFileData.QueryRow(xid)
2359 err := row.Scan(&media, &data)
2360 if err != nil {
2361 elog.Printf("error loading file: %s", err)
2362 http.NotFound(w, r)
2363 return
2364 }
2365 w.Header().Set("Content-Type", media)
2366 w.Header().Set("X-Content-Type-Options", "nosniff")
2367 w.Header().Set("Cache-Control", "max-age="+somedays())
2368 w.Write(data)
2369}
2370
2371func nomoroboto(w http.ResponseWriter, r *http.Request) {
2372 io.WriteString(w, "User-agent: *\n")
2373 io.WriteString(w, "Disallow: /a\n")
2374 io.WriteString(w, "Disallow: /d/\n")
2375 io.WriteString(w, "Disallow: /meme/\n")
2376 io.WriteString(w, "Disallow: /o\n")
2377 io.WriteString(w, "Disallow: /o/\n")
2378 io.WriteString(w, "Disallow: /help/\n")
2379 for _, u := range allusers() {
2380 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2381 }
2382}
2383
2384type Hydration struct {
2385 Tophid int64
2386 Srvmsg template.HTML
2387 Honks string
2388 MeCount int64
2389 ChatCount int64
2390}
2391
2392func webhydra(w http.ResponseWriter, r *http.Request) {
2393 u := login.GetUserInfo(r)
2394 userid := u.UserID
2395 templinfo := getInfo(r)
2396 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2397 page := r.FormValue("page")
2398
2399 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2400
2401 var hydra Hydration
2402
2403 var honks []*Honk
2404 switch page {
2405 case "atme":
2406 honks = gethonksforme(userid, wanted)
2407 honks = osmosis(honks, userid, false)
2408 menewnone(userid)
2409 hydra.Srvmsg = "at me!"
2410 case "longago":
2411 honks = gethonksfromlongago(userid, wanted)
2412 honks = osmosis(honks, userid, false)
2413 hydra.Srvmsg = "from long ago"
2414 case "home":
2415 honks = gethonksforuser(userid, wanted)
2416 honks = osmosis(honks, userid, true)
2417 hydra.Srvmsg = serverMsg
2418 case "first":
2419 honks = gethonksforuserfirstclass(userid, wanted)
2420 honks = osmosis(honks, userid, true)
2421 hydra.Srvmsg = "first class only"
2422 case "saved":
2423 honks = getsavedhonks(userid, wanted)
2424 templinfo["PageName"] = "saved"
2425 hydra.Srvmsg = "saved honks"
2426 case "combo":
2427 c := r.FormValue("c")
2428 honks = gethonksbycombo(userid, c, wanted)
2429 honks = osmosis(honks, userid, false)
2430 hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2431 case "convoy":
2432 c := r.FormValue("c")
2433 honks = gethonksbyconvoy(userid, c, wanted)
2434 honks = osmosis(honks, userid, false)
2435 honks = threadsort(honks)
2436 reversehonks(honks)
2437 hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2438 case "honker":
2439 xid := r.FormValue("xid")
2440 honks = gethonksbyxonker(userid, xid, wanted)
2441 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2442 <input type="hidden" name="CSRF" value="%s">
2443 <input type="hidden" name="url" value="%s">
2444 <button tabindex=1 name="add honker" value="add honker">add honker</button>
2445 </form>`, login.GetCSRF("submithonker", r), xid)
2446 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2447 hydra.Srvmsg = msg
2448 case "user":
2449 uname := r.FormValue("uname")
2450 honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2451 hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2452 default:
2453 http.NotFound(w, r)
2454 }
2455
2456 if len(honks) > 0 {
2457 hydra.Tophid = honks[0].ID
2458 } else {
2459 hydra.Tophid = wanted
2460 }
2461 reverbolate(userid, honks)
2462
2463 user, _ := butwhatabout(u.Username)
2464
2465 var buf strings.Builder
2466 templinfo["Honks"] = honks
2467 templinfo["MapLink"] = getmaplink(u)
2468 templinfo["User"], _ = butwhatabout(u.Username)
2469 err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2470 if err != nil {
2471 elog.Printf("frag error: %s", err)
2472 return
2473 }
2474 hydra.Honks = buf.String()
2475 hydra.MeCount = user.Options.MeCount
2476 hydra.ChatCount = user.Options.ChatCount
2477 w.Header().Set("Content-Type", "application/json")
2478 j, _ := jsonify(&hydra)
2479 io.WriteString(w, j)
2480}
2481
2482var honkline = make(chan bool)
2483
2484func honkhonkline() {
2485 for {
2486 select {
2487 case honkline <- true:
2488 default:
2489 return
2490 }
2491 }
2492}
2493
2494func apihandler(w http.ResponseWriter, r *http.Request) {
2495 u := login.GetUserInfo(r)
2496 userid := u.UserID
2497 action := r.FormValue("action")
2498 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2499 dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2500 switch action {
2501 case "honk":
2502 h := submithonk(w, r)
2503 if h == nil {
2504 return
2505 }
2506 fmt.Fprintf(w, "%s", h.XID)
2507 case "donk":
2508 d, err := submitdonk(w, r)
2509 if err != nil {
2510 http.Error(w, err.Error(), http.StatusBadRequest)
2511 return
2512 }
2513 if d == nil {
2514 http.Error(w, "missing donk", http.StatusBadRequest)
2515 return
2516 }
2517 donkxid := fmt.Sprintf("%s:%d", d.XID, d.FileID)
2518 w.Write([]byte(donkxid))
2519 case "zonkit":
2520 zonkit(w, r)
2521 case "gethonks":
2522 var honks []*Honk
2523 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2524 page := r.FormValue("page")
2525 var waitchan <-chan time.Time
2526 requery:
2527 switch page {
2528 case "atme":
2529 honks = gethonksforme(userid, wanted)
2530 honks = osmosis(honks, userid, false)
2531 menewnone(userid)
2532 case "longago":
2533 honks = gethonksfromlongago(userid, wanted)
2534 honks = osmosis(honks, userid, false)
2535 case "home":
2536 honks = gethonksforuser(userid, wanted)
2537 honks = osmosis(honks, userid, true)
2538 case "myhonks":
2539 honks = gethonksbyuser(u.Username, true, wanted)
2540 honks = osmosis(honks, userid, true)
2541 default:
2542 http.Error(w, "unknown page", http.StatusNotFound)
2543 return
2544 }
2545 if len(honks) == 0 && wait > 0 {
2546 if waitchan == nil {
2547 waitchan = time.After(time.Duration(wait) * time.Second)
2548 }
2549 select {
2550 case <-honkline:
2551 goto requery
2552 case <-waitchan:
2553 }
2554 }
2555 reverbolate(userid, honks)
2556 j := junk.New()
2557 j["honks"] = honks
2558 j.Write(w)
2559 case "sendactivity":
2560 user, _ := butwhatabout(u.Username)
2561 public := r.FormValue("public") == "1"
2562 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2563 msg := []byte(r.FormValue("msg"))
2564 for rcpt := range rcpts {
2565 go deliverate(userid, rcpt, msg)
2566 }
2567 case "gethonkers":
2568 j := junk.New()
2569 j["honkers"] = gethonkers(u.UserID)
2570 j.Write(w)
2571 case "savehonker":
2572 h := submithonker(w, r)
2573 if h == nil {
2574 return
2575 }
2576 fmt.Fprintf(w, "%d", h.ID)
2577 default:
2578 http.Error(w, "unknown action", http.StatusNotFound)
2579 return
2580 }
2581}
2582
2583func fiveoh(w http.ResponseWriter, r *http.Request) {
2584 if !develMode {
2585 return
2586 }
2587 fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2588 if err != nil {
2589 elog.Printf("error opening violations! %s", err)
2590 return
2591 }
2592 defer fd.Close()
2593 io.Copy(fd, r.Body)
2594 fd.WriteString("\n")
2595}
2596
2597var endoftheworld = make(chan bool)
2598var readyalready = make(chan bool)
2599var workinprogress = 0
2600
2601func enditall() {
2602 sig := make(chan os.Signal, 1)
2603 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2604 <-sig
2605 ilog.Printf("stopping...")
2606 for i := 0; i < workinprogress; i++ {
2607 endoftheworld <- true
2608 }
2609 ilog.Printf("waiting...")
2610 for i := 0; i < workinprogress; i++ {
2611 <-readyalready
2612 }
2613 ilog.Printf("apocalypse")
2614 os.Exit(0)
2615}
2616
2617var preservehooks []func()
2618
2619func bgmonitor() {
2620 for {
2621 when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2622 _, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2623 if err != nil {
2624 elog.Printf("error deleting old xonkers: %s", err)
2625 }
2626 zaggies.Flush()
2627 time.Sleep(50 * time.Minute)
2628 }
2629}
2630
2631func addcspheaders(next http.Handler) http.Handler {
2632 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2633 policy := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'"
2634 if develMode {
2635 policy += "; report-uri /csp-violation"
2636 }
2637 w.Header().Set("Content-Security-Policy", policy)
2638 next.ServeHTTP(w, r)
2639 })
2640}
2641
2642func emuinit() {
2643 var emunames []string
2644 dir, err := os.Open(dataDir + "/emus")
2645 if err == nil {
2646 emunames, _ = dir.Readdirnames(0)
2647 dir.Close()
2648 }
2649 for _, e := range emunames {
2650 if len(e) <= 4 {
2651 continue
2652 }
2653 ext := e[len(e)-4:]
2654 emu := Emu{
2655 ID: fmt.Sprintf("/emu/%s", e),
2656 Name: e[:len(e)-4],
2657 Type: "image/" + ext[1:],
2658 }
2659 allemus = append(allemus, emu)
2660 }
2661 sort.Slice(allemus, func(i, j int) bool {
2662 return allemus[i].Name < allemus[j].Name
2663 })
2664}
2665
2666func serve() {
2667 db := opendatabase()
2668 login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2669
2670 listener, err := openListener()
2671 if err != nil {
2672 elog.Fatal(err)
2673 }
2674 runBackendServer()
2675 go enditall()
2676 go redeliverator()
2677 go tracker()
2678 go bgmonitor()
2679 go qotd()
2680 loadLingo()
2681 emuinit()
2682
2683 readviews = templates.Load(develMode,
2684 viewDir+"/views/honkpage.html",
2685 viewDir+"/views/honkfrags.html",
2686 viewDir+"/views/honkers.html",
2687 viewDir+"/views/chatter.html",
2688 viewDir+"/views/hfcs.html",
2689 viewDir+"/views/combos.html",
2690 viewDir+"/views/honkform.html",
2691 viewDir+"/views/honk.html",
2692 viewDir+"/views/account.html",
2693 viewDir+"/views/about.html",
2694 viewDir+"/views/funzone.html",
2695 viewDir+"/views/login.html",
2696 viewDir+"/views/xzone.html",
2697 viewDir+"/views/msg.html",
2698 viewDir+"/views/header.html",
2699 viewDir+"/views/onts.html",
2700 viewDir+"/views/emus.html",
2701 viewDir+"/views/honkpage.js",
2702 )
2703 if !develMode {
2704 assets := []string{
2705 viewDir + "/views/style.css",
2706 dataDir + "/views/local.css",
2707 viewDir + "/views/honkpage.js",
2708 viewDir + "/views/misc.js",
2709 dataDir + "/views/local.js",
2710 }
2711 for _, s := range assets {
2712 savedassetparams[s] = getassetparam(s)
2713 }
2714 loadAvatarColors()
2715 }
2716
2717 for _, h := range preservehooks {
2718 h()
2719 }
2720
2721 mux := mux.NewRouter()
2722 mux.Use(addcspheaders)
2723 mux.Use(login.Checker)
2724
2725 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2726
2727 posters := mux.Methods("POST").Subrouter()
2728 getters := mux.Methods("GET").Subrouter()
2729
2730 getters.HandleFunc("/", homepage)
2731 getters.HandleFunc("/home", homepage)
2732 getters.HandleFunc("/front", homepage)
2733 getters.HandleFunc("/events", homepage)
2734 getters.HandleFunc("/robots.txt", nomoroboto)
2735 getters.HandleFunc("/rss", showrss)
2736 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2737 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2738 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2739 posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2740 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2741 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2742 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2743 getters.HandleFunc("/a", avatate)
2744 getters.HandleFunc("/o", thelistingoftheontologies)
2745 getters.HandleFunc("/o/{name:.+}", showontology)
2746 getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2747 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2748 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2749 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2750
2751 getters.HandleFunc("/flag/{code:.+}", showflag)
2752
2753 getters.HandleFunc("/server", serveractor)
2754 posters.HandleFunc("/server/inbox", serverinbox)
2755 posters.HandleFunc("/inbox", serverinbox)
2756
2757 posters.HandleFunc("/csp-violation", fiveoh)
2758
2759 getters.HandleFunc("/style.css", serveviewasset)
2760 getters.HandleFunc("/honkpage.js", serveviewasset)
2761 getters.HandleFunc("/misc.js", serveviewasset)
2762 getters.HandleFunc("/local.css", servedataasset)
2763 getters.HandleFunc("/local.js", servedataasset)
2764 getters.HandleFunc("/icon.png", servedataasset)
2765 getters.HandleFunc("/favicon.ico", servedataasset)
2766
2767 getters.HandleFunc("/about", servehtml)
2768 getters.HandleFunc("/login", servehtml)
2769 posters.HandleFunc("/dologin", login.LoginFunc)
2770 getters.HandleFunc("/logout", login.LogoutFunc)
2771 getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2772
2773 loggedin := mux.NewRoute().Subrouter()
2774 loggedin.Use(login.Required)
2775 loggedin.HandleFunc("/first", homepage)
2776 loggedin.HandleFunc("/chatter", showchatter)
2777 loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2778 loggedin.HandleFunc("/saved", homepage)
2779 loggedin.HandleFunc("/account", accountpage)
2780 loggedin.HandleFunc("/funzone", showfunzone)
2781 loggedin.HandleFunc("/chpass", dochpass)
2782 loggedin.HandleFunc("/atme", homepage)
2783 loggedin.HandleFunc("/longago", homepage)
2784 loggedin.HandleFunc("/hfcs", hfcspage)
2785 loggedin.HandleFunc("/xzone", xzone)
2786 loggedin.HandleFunc("/newhonk", newhonkpage)
2787 loggedin.HandleFunc("/edit", edithonkpage)
2788 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2789 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2790 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2791 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2792 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2793 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2794 loggedin.HandleFunc("/honkers", showhonkers)
2795 loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2796 loggedin.HandleFunc("/h", showhonker)
2797 loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2798 loggedin.HandleFunc("/c", showcombos)
2799 loggedin.HandleFunc("/t", showconvoy)
2800 loggedin.HandleFunc("/q", showsearch)
2801 loggedin.HandleFunc("/hydra", webhydra)
2802 loggedin.HandleFunc("/emus", showemus)
2803 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2804
2805 err = http.Serve(listener, mux)
2806 if err != nil {
2807 elog.Fatal(err)
2808 }
2809}