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