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