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