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