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