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"] = func(s string) rune { r, _ := utf8.DecodeRuneInString(s); return r }
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 showhonkers(w http.ResponseWriter, r *http.Request) {
2088 userid := UserID(login.GetUserInfo(r).UserID)
2089 templinfo := getInfo(r)
2090 templinfo["Honkers"] = gethonkers(userid)
2091 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
2092 err := readviews.Execute(w, "honkers.html", templinfo)
2093 if err != nil {
2094 elog.Print(err)
2095 }
2096}
2097
2098func showchatter(w http.ResponseWriter, r *http.Request) {
2099 u := login.GetUserInfo(r)
2100 chatnewnone(UserID(u.UserID))
2101 chatter := loadchatter(UserID(u.UserID))
2102 for _, chat := range chatter {
2103 for _, ch := range chat.Chonks {
2104 filterchonk(ch)
2105 }
2106 }
2107
2108 templinfo := getInfo(r)
2109 templinfo["Chatter"] = chatter
2110 templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
2111 err := readviews.Execute(w, "chatter.html", templinfo)
2112 if err != nil {
2113 elog.Print(err)
2114 }
2115}
2116
2117func submitchonk(w http.ResponseWriter, r *http.Request) {
2118 u := login.GetUserInfo(r)
2119 user, _ := butwhatabout(u.Username)
2120 noise := r.FormValue("noise")
2121 target := r.FormValue("target")
2122 format := "markdown"
2123 dt := time.Now().UTC()
2124 xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
2125
2126 if !strings.HasPrefix(target, "https://") {
2127 target = fullname(target, user.ID)
2128 }
2129 if target == "" {
2130 http.Error(w, "who is that?", http.StatusInternalServerError)
2131 return
2132 }
2133 ch := Chonk{
2134 UserID: user.ID,
2135 XID: xid,
2136 Who: user.URL,
2137 Target: target,
2138 Date: dt,
2139 Noise: noise,
2140 Format: format,
2141 }
2142 donks, err := submitdonk(w, r)
2143 if err != nil && err != http.ErrMissingFile {
2144 return
2145 }
2146 if len(donks) > 0 {
2147 ch.Donks = append(ch.Donks, donks...)
2148 }
2149
2150 translatechonk(&ch)
2151 savechonk(&ch)
2152 // reload for consistency
2153 ch.Donks = nil
2154 donksforchonks([]*Chonk{&ch})
2155 go sendchonk(user, &ch)
2156
2157 http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2158}
2159
2160var combocache = gencache.New(gencache.Options[UserID, []string]{Fill: func(userid UserID) ([]string, bool) {
2161 honkers := gethonkers(userid)
2162 var combos []string
2163 for _, h := range honkers {
2164 combos = append(combos, h.Combos...)
2165 }
2166 for i, c := range combos {
2167 if c == "-" {
2168 combos[i] = ""
2169 }
2170 }
2171 combos = oneofakind(combos)
2172 sort.Strings(combos)
2173 return combos, true
2174}, Invalidator: &honkerinvalidator})
2175
2176func showcombos(w http.ResponseWriter, r *http.Request) {
2177 templinfo := getInfo(r)
2178 err := readviews.Execute(w, "combos.html", templinfo)
2179 if err != nil {
2180 elog.Print(err)
2181 }
2182}
2183
2184func websubmithonker(w http.ResponseWriter, r *http.Request) {
2185 h := submithonker(w, r)
2186 if h == nil {
2187 return
2188 }
2189 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2190}
2191
2192func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2193 u := login.GetUserInfo(r)
2194 user, _ := butwhatabout(u.Username)
2195 name := strings.TrimSpace(r.FormValue("name"))
2196 url := strings.TrimSpace(r.FormValue("url"))
2197 peep := r.FormValue("peep")
2198 combos := strings.TrimSpace(r.FormValue("combos"))
2199 combos = " " + combos + " "
2200 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2201
2202 re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2203 if name != "" && !re_namecheck.MatchString(name) {
2204 http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2205 return nil
2206 }
2207
2208 var meta HonkerMeta
2209 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2210 mj, _ := jsonify(&meta)
2211
2212 defer honkerinvalidator.Clear(user.ID)
2213
2214 // mostly dummy, fill in later...
2215 h := &Honker{
2216 ID: honkerid,
2217 }
2218
2219 if honkerid > 0 {
2220 if r.FormValue("delete") == "delete" {
2221 unfollowyou(user, honkerid, false)
2222 stmtDeleteHonker.Exec(honkerid)
2223 return h
2224 }
2225 if r.FormValue("unsub") == "unsub" {
2226 unfollowyou(user, honkerid, false)
2227 }
2228 if r.FormValue("sub") == "sub" {
2229 followyou(user, honkerid, false)
2230 }
2231 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, user.ID)
2232 if err != nil {
2233 elog.Printf("update honker err: %s", err)
2234 return nil
2235 }
2236 return h
2237 }
2238
2239 if url == "" {
2240 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2241 return nil
2242 }
2243
2244 flavor := "presub"
2245 if peep == "peep" {
2246 flavor = "peep"
2247 }
2248
2249 var err error
2250 honkerid, flavor, err = savehonker(user, url, name, flavor, combos, mj)
2251 if err != nil {
2252 http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2253 return nil
2254 }
2255 if flavor == "presub" {
2256 followyou(user, honkerid, false)
2257 }
2258 h.ID = honkerid
2259 return h
2260}
2261
2262func hfcspage(w http.ResponseWriter, r *http.Request) {
2263 u := login.GetUserInfo(r)
2264
2265 filters := getfilters(UserID(u.UserID), filtAny)
2266
2267 templinfo := getInfo(r)
2268 templinfo["Filters"] = filters
2269 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2270 err := readviews.Execute(w, "hfcs.html", templinfo)
2271 if err != nil {
2272 elog.Print(err)
2273 }
2274}
2275
2276func accountpage(w http.ResponseWriter, r *http.Request) {
2277 u := login.GetUserInfo(r)
2278 user, _ := butwhatabout(u.Username)
2279 templinfo := getInfo(r)
2280 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2281 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2282 templinfo["User"] = user
2283 about := user.About
2284 if ava := user.Options.Avatar; ava != "" {
2285 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2286 }
2287 if ban := user.Options.Banner; ban != "" {
2288 about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2289 }
2290 templinfo["WhatAbout"] = about
2291 err := readviews.Execute(w, "account.html", templinfo)
2292 if err != nil {
2293 elog.Print(err)
2294 }
2295}
2296
2297func dochpass(w http.ResponseWriter, r *http.Request) {
2298 err := login.ChangePassword(w, r)
2299 if err != nil {
2300 elog.Printf("error changing password: %s", err)
2301 }
2302 http.Redirect(w, r, "/account", http.StatusSeeOther)
2303}
2304
2305var oldfingers = gencache.New(gencache.Options[string, []byte]{Fill: func(orig string) ([]byte, bool) {
2306 if strings.HasPrefix(orig, "acct:") {
2307 orig = orig[5:]
2308 }
2309 name := orig
2310 idx := strings.LastIndexByte(name, '/')
2311 if idx != -1 {
2312 name = name[idx+1:]
2313 if serverURL("/%s/%s", userSep, name) != orig {
2314 ilog.Printf("foreign request rejected")
2315 name = ""
2316 }
2317 } else {
2318 idx = strings.IndexByte(name, '@')
2319 if idx != -1 {
2320 name = name[:idx]
2321 if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2322 ilog.Printf("foreign request rejected")
2323 name = ""
2324 }
2325 }
2326 }
2327 user, err := butwhatabout(name)
2328 if err != nil {
2329 return nil, false
2330 }
2331
2332 j := junk.New()
2333 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2334 j["aliases"] = []string{user.URL}
2335 l := junk.New()
2336 l["rel"] = "self"
2337 l["type"] = `application/activity+json`
2338 l["href"] = user.URL
2339 j["links"] = []junk.Junk{l}
2340 return j.ToBytes(), true
2341}})
2342
2343func fingerlicker(w http.ResponseWriter, r *http.Request) {
2344 orig := r.FormValue("resource")
2345
2346 dlog.Printf("finger lick: %s", orig)
2347
2348 j, ok := oldfingers.Get(orig)
2349 if ok {
2350 w.Header().Set("Content-Type", "application/jrd+json")
2351 w.Write(j)
2352 } else {
2353 http.NotFound(w, r)
2354 }
2355}
2356
2357func somedays() string {
2358 secs := 432000 + notrand.Int63n(432000)
2359 return fmt.Sprintf("%d", secs)
2360}
2361
2362func lookatme(ava string) string {
2363 if strings.Contains(ava, serverName+"/"+userSep) {
2364 idx := strings.LastIndexByte(ava, '/')
2365 if idx < len(ava) {
2366 name := ava[idx+1:]
2367 user, _ := butwhatabout(name)
2368 if user != nil && user.URL == ava {
2369 return user.Options.Avatar
2370 }
2371 }
2372 }
2373 return ""
2374}
2375
2376func avatate(w http.ResponseWriter, r *http.Request) {
2377 if develMode {
2378 loadAvatarColors()
2379 }
2380 n := r.FormValue("a")
2381 if redir := lookatme(n); redir != "" {
2382 http.Redirect(w, r, redir, http.StatusSeeOther)
2383 return
2384 }
2385 a := genAvatar(n)
2386 if !develMode {
2387 w.Header().Set("Cache-Control", "max-age="+somedays())
2388 }
2389 w.Write(a)
2390}
2391
2392func serveviewasset(w http.ResponseWriter, r *http.Request) {
2393 serveasset(w, r, viewDir)
2394}
2395func servedataasset(w http.ResponseWriter, r *http.Request) {
2396 if r.URL.Path == "/favicon.ico" {
2397 r.URL.Path = "/icon.png"
2398 }
2399 serveasset(w, r, dataDir)
2400}
2401
2402func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2403 if !develMode {
2404 w.Header().Set("Cache-Control", "max-age=7776000")
2405 }
2406 http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2407}
2408func servehelp(w http.ResponseWriter, r *http.Request) {
2409 name := mux.Vars(r)["name"]
2410 if !develMode {
2411 w.Header().Set("Cache-Control", "max-age=3600")
2412 }
2413 http.ServeFile(w, r, viewDir+"/docs/"+name)
2414}
2415func servehtml(w http.ResponseWriter, r *http.Request) {
2416 u := login.GetUserInfo(r)
2417 templinfo := getInfo(r)
2418 templinfo["AboutMsg"] = aboutMsg
2419 templinfo["LoginMsg"] = loginMsg
2420 templinfo["HonkVersion"] = softwareVersion
2421 if r.URL.Path == "/about" {
2422 templinfo["Sensors"] = getSensors()
2423 }
2424 if u == nil && !develMode {
2425 w.Header().Set("Cache-Control", "max-age=60")
2426 }
2427 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2428 if err != nil {
2429 elog.Print(err)
2430 }
2431}
2432func serveemu(w http.ResponseWriter, r *http.Request) {
2433 emu := mux.Vars(r)["emu"]
2434
2435 w.Header().Set("Cache-Control", "max-age="+somedays())
2436 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2437}
2438func servememe(w http.ResponseWriter, r *http.Request) {
2439 meme := mux.Vars(r)["meme"]
2440
2441 w.Header().Set("Cache-Control", "max-age="+somedays())
2442 _, err := os.Stat(dataDir + "/memes/" + meme)
2443 if err == nil {
2444 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2445 } else {
2446 mux.Vars(r)["xid"] = meme
2447 servefile(w, r)
2448 }
2449}
2450
2451func servefile(w http.ResponseWriter, r *http.Request) {
2452 if friendorfoe(r.Header.Get("Accept")) {
2453 dlog.Printf("incompatible accept for donk")
2454 http.Error(w, "there are no activities here", http.StatusNotAcceptable)
2455 return
2456 }
2457 xid := mux.Vars(r)["xid"]
2458 preview := r.FormValue("preview") == "1"
2459 var media string
2460 var data []byte
2461 row := stmtGetFileData.QueryRow(xid)
2462 err := row.Scan(&media, &data)
2463 if err != nil {
2464 elog.Printf("error loading file: %s", err)
2465 http.NotFound(w, r)
2466 return
2467 }
2468 if preview && strings.HasPrefix(media, "image") {
2469 img, err := lilshrink(data)
2470 if err == nil {
2471 data = img.Data
2472 }
2473 }
2474 w.Header().Set("Content-Type", media)
2475 w.Header().Set("X-Content-Type-Options", "nosniff")
2476 w.Header().Set("Cache-Control", "max-age="+somedays())
2477 w.Write(data)
2478}
2479
2480func nomoroboto(w http.ResponseWriter, r *http.Request) {
2481 io.WriteString(w, "User-agent: *\n")
2482 io.WriteString(w, "Disallow: /a\n")
2483 io.WriteString(w, "Disallow: /d/\n")
2484 io.WriteString(w, "Disallow: /meme/\n")
2485 io.WriteString(w, "Disallow: /o\n")
2486 io.WriteString(w, "Disallow: /o/\n")
2487 io.WriteString(w, "Disallow: /help/\n")
2488 for _, u := range allusers() {
2489 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2490 }
2491}
2492
2493type Hydration struct {
2494 Tophid int64
2495 Srvmsg template.HTML
2496 Honks string
2497 MeCount int64
2498 ChatCount int64
2499 Poses []int
2500}
2501
2502func webhydra(w http.ResponseWriter, r *http.Request) {
2503 u := login.GetUserInfo(r)
2504 userid := UserID(u.UserID)
2505 templinfo := getInfo(r)
2506 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2507 page := r.FormValue("page")
2508
2509 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2510
2511 var hydra Hydration
2512
2513 var honks []*Honk
2514 switch page {
2515 case "atme":
2516 honks = gethonksforme(userid, wanted)
2517 honks = osmosis(honks, userid, false)
2518 menewnone(userid)
2519 hydra.Srvmsg = "at me!"
2520 case "longago":
2521 honks = gethonksfromlongago(userid, wanted)
2522 honks = osmosis(honks, userid, false)
2523 hydra.Srvmsg = "from long ago"
2524 case "home":
2525 honks = gethonksforuser(userid, wanted)
2526 honks = osmosis(honks, userid, true)
2527 hydra.Srvmsg = serverMsg
2528 case "first":
2529 honks = gethonksforuserfirstclass(userid, wanted)
2530 honks = osmosis(honks, userid, true)
2531 hydra.Srvmsg = "first class only"
2532 case "saved":
2533 honks = getsavedhonks(userid, wanted)
2534 templinfo["PageName"] = "saved"
2535 hydra.Srvmsg = "saved honks"
2536 case "combo":
2537 c := r.FormValue("c")
2538 honks = gethonksbycombo(userid, c, wanted)
2539 honks = osmosis(honks, userid, false)
2540 hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2541 case "convoy":
2542 c := r.FormValue("c")
2543 honks = gethonksbyconvoy(userid, c, 0)
2544 honks = osmosis(honks, userid, false)
2545 honks = threadsort(honks)
2546 honks, hydra.Poses = threadposes(honks, wanted)
2547 hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2548 case "honker":
2549 xid := r.FormValue("xid")
2550 honks = gethonksbyxonker(userid, xid, wanted)
2551 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2552 <input type="hidden" name="CSRF" value="%s">
2553 <input type="hidden" name="url" value="%s">
2554 <button tabindex=1 name="add honker" value="add honker">add honker</button>
2555 </form>`, login.GetCSRF("submithonker", r), xid)
2556 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2557 hydra.Srvmsg = msg
2558 case "user":
2559 uname := r.FormValue("uname")
2560 honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2561 hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2562 default:
2563 http.NotFound(w, r)
2564 }
2565
2566 if len(honks) > 0 {
2567 if page == "convoy" {
2568 hydra.Tophid = honks[len(honks)-1].ID
2569 } else {
2570 hydra.Tophid = honks[0].ID
2571 }
2572 } else {
2573 hydra.Tophid = wanted
2574 }
2575 reverbolate(userid, honks)
2576
2577 user, _ := butwhatabout(u.Username)
2578
2579 var buf strings.Builder
2580 templinfo["Honks"] = honks
2581 templinfo["MapLink"] = getmaplink(u)
2582 templinfo["User"], _ = butwhatabout(u.Username)
2583 err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2584 if err != nil {
2585 elog.Printf("frag error: %s", err)
2586 return
2587 }
2588 hydra.Honks = buf.String()
2589 hydra.MeCount = user.Options.MeCount
2590 hydra.ChatCount = user.Options.ChatCount
2591 w.Header().Set("Content-Type", "application/json")
2592 j, _ := jsonify(&hydra)
2593 io.WriteString(w, j)
2594}
2595
2596var honkline = make(chan bool)
2597
2598func honkhonkline() {
2599 for {
2600 select {
2601 case honkline <- true:
2602 default:
2603 return
2604 }
2605 }
2606}
2607
2608func apihandler(w http.ResponseWriter, r *http.Request) {
2609 u := login.GetUserInfo(r)
2610 userid := UserID(u.UserID)
2611 action := r.FormValue("action")
2612 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2613 dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2614 switch action {
2615 case "honk":
2616 h := submithonk(w, r)
2617 if h == nil {
2618 return
2619 }
2620 fmt.Fprintf(w, "%s", h.XID)
2621 case "donk":
2622 donks, err := submitdonk(w, r)
2623 if err != nil {
2624 http.Error(w, err.Error(), http.StatusBadRequest)
2625 return
2626 }
2627 if len(donks) == 0 {
2628 http.Error(w, "missing donk", http.StatusBadRequest)
2629 return
2630 }
2631 d := donks[0]
2632 donkxid := fmt.Sprintf("%s:%d", d.XID, d.FileID)
2633 w.Write([]byte(donkxid))
2634 case "zonkit":
2635 zonkit(w, r)
2636 case "gethonks":
2637 var honks []*Honk
2638 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2639 page := r.FormValue("page")
2640 var waitchan <-chan time.Time
2641 requery:
2642 switch page {
2643 case "atme":
2644 honks = gethonksforme(userid, wanted)
2645 honks = osmosis(honks, userid, false)
2646 menewnone(userid)
2647 case "longago":
2648 honks = gethonksfromlongago(userid, wanted)
2649 honks = osmosis(honks, userid, false)
2650 case "home":
2651 honks = gethonksforuser(userid, wanted)
2652 honks = osmosis(honks, userid, true)
2653 case "myhonks":
2654 honks = gethonksbyuser(u.Username, true, wanted)
2655 honks = osmosis(honks, userid, true)
2656 case "saved":
2657 honks = getsavedhonks(userid, wanted)
2658 case "combo":
2659 c := r.FormValue("c")
2660 honks = gethonksbycombo(userid, c, wanted)
2661 honks = osmosis(honks, userid, false)
2662 case "convoy":
2663 c := r.FormValue("c")
2664 honks = gethonksbyconvoy(userid, c, 0)
2665 honks = osmosis(honks, userid, false)
2666 honks = threadsort(honks)
2667 honks, _ = threadposes(honks, wanted)
2668 case "honker":
2669 xid := r.FormValue("xid")
2670 honks = gethonksbyxonker(userid, xid, wanted)
2671 case "search":
2672 q := r.FormValue("q")
2673 honks = gethonksbysearch(userid, q, wanted)
2674 default:
2675 http.Error(w, "unknown page", http.StatusNotFound)
2676 return
2677 }
2678 if len(honks) == 0 && wait > 0 {
2679 if waitchan == nil {
2680 waitchan = time.After(time.Duration(wait) * time.Second)
2681 }
2682 select {
2683 case <-honkline:
2684 goto requery
2685 case <-waitchan:
2686 }
2687 }
2688 reverbolate(userid, honks)
2689 user, _ := butwhatabout(u.Username)
2690 j := junk.New()
2691 j["honks"] = honks
2692 j["mecount"] = user.Options.MeCount
2693 j["chatcount"] = user.Options.ChatCount
2694 j.Write(w)
2695 case "sendactivity":
2696 public := r.FormValue("public") == "1"
2697 user, _ := butwhatabout(u.Username)
2698 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2699 msg := []byte(r.FormValue("msg"))
2700 for rcpt := range rcpts {
2701 go deliverate(userid, rcpt, msg)
2702 }
2703 case "gethonkers":
2704 j := junk.New()
2705 j["honkers"] = gethonkers(userid)
2706 j.Write(w)
2707 case "savehonker":
2708 h := submithonker(w, r)
2709 if h == nil {
2710 return
2711 }
2712 fmt.Fprintf(w, "%d", h.ID)
2713 default:
2714 http.Error(w, "unknown action", http.StatusNotFound)
2715 return
2716 }
2717}
2718
2719func fiveoh(w http.ResponseWriter, r *http.Request) {
2720 if !develMode {
2721 return
2722 }
2723 fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2724 if err != nil {
2725 elog.Printf("error opening violations! %s", err)
2726 return
2727 }
2728 defer fd.Close()
2729 io.Copy(fd, r.Body)
2730 fd.WriteString("\n")
2731}
2732
2733var endoftheworld = make(chan bool)
2734var readyalready = make(chan bool)
2735var workinprogress = 0
2736var requestWG sync.WaitGroup
2737var listenSocket net.Listener
2738
2739func enditall() {
2740 sig := make(chan os.Signal, 1)
2741 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2742 <-sig
2743 ilog.Printf("stopping...")
2744 listenSocket.Close()
2745 for i := 0; i < workinprogress; i++ {
2746 endoftheworld <- true
2747 }
2748 if *cpuprofile != "" {
2749 pprof.StopCPUProfile()
2750 }
2751 if *memprofile != "" {
2752 pprof.WriteHeapProfile(memprofilefd)
2753 memprofilefd.Close()
2754 }
2755 ilog.Printf("waiting...")
2756 go func() {
2757 time.Sleep(10 * time.Second)
2758 elog.Printf("timed out waiting for requests to finish")
2759 os.Exit(0)
2760 }()
2761 for i := 0; i < workinprogress; i++ {
2762 <-readyalready
2763 }
2764 requestWG.Wait()
2765 ilog.Printf("apocalypse")
2766 closedatabases()
2767 os.Exit(0)
2768}
2769
2770func bgmonitor() {
2771 for {
2772 when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2773 _, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2774 if err != nil {
2775 elog.Printf("error deleting old xonkers: %s", err)
2776 }
2777 zaggies.Flush()
2778 time.Sleep(50 * time.Minute)
2779 }
2780}
2781
2782func addcspheaders(next http.Handler) http.Handler {
2783 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2784 requestWG.Add(1)
2785 defer requestWG.Done()
2786 policy := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'"
2787 if develMode {
2788 policy += "; report-uri /csp-violation"
2789 }
2790 w.Header().Set("Content-Security-Policy", policy)
2791 next.ServeHTTP(w, r)
2792 })
2793}
2794
2795func emuinit() {
2796 var emunames []string
2797 dir, err := os.Open(dataDir + "/emus")
2798 if err == nil {
2799 emunames, _ = dir.Readdirnames(0)
2800 dir.Close()
2801 }
2802 for _, e := range emunames {
2803 if len(e) <= 4 {
2804 continue
2805 }
2806 ext := e[len(e)-4:]
2807 emu := Emu{
2808 ID: fmt.Sprintf("/emu/%s", e),
2809 Name: e[:len(e)-4],
2810 Type: "image/" + ext[1:],
2811 }
2812 allemus = append(allemus, emu)
2813 }
2814 sort.Slice(allemus, func(i, j int) bool {
2815 return allemus[i].Name < allemus[j].Name
2816 })
2817}
2818
2819var savedassetparams = make(map[string]string)
2820
2821func getassetparam(file string) string {
2822 if p, ok := savedassetparams[file]; ok {
2823 return p
2824 }
2825 data, err := os.ReadFile(file)
2826 if err != nil {
2827 return ""
2828 }
2829 hasher := sha512.New()
2830 hasher.Write(data)
2831
2832 return fmt.Sprintf("?v=%.8x", hasher.Sum(nil))
2833}
2834
2835func startWatcher() {
2836 watcher, err := gonix.NewWatcher()
2837 if err != nil {
2838 return
2839 }
2840 go func() {
2841 s := dataDir + "/views/local.css"
2842 for {
2843 err := watcher.WatchFile(s)
2844 if err != nil {
2845 break
2846 }
2847 err = watcher.WaitForChange()
2848 if err != nil {
2849 dlog.Printf("can't wait: %s", err)
2850 break
2851 }
2852 dlog.Printf("local.css changed")
2853 delete(savedassetparams, s)
2854 savedassetparams[s] = getassetparam(s)
2855 }
2856 }()
2857}
2858
2859var usefcgi bool
2860
2861func serve() {
2862 db := opendatabase()
2863 login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2864
2865 listener, err := openListener()
2866 if err != nil {
2867 elog.Fatal(err)
2868 }
2869 runBackendServer()
2870 go enditall()
2871 go redeliverator()
2872 go tracker()
2873 go syndicator()
2874 go bgmonitor()
2875 go qotd()
2876 loadLingo()
2877 emuinit()
2878
2879 var toload []string
2880 dents, _ := os.ReadDir(viewDir + "/views")
2881 for _, dent := range dents {
2882 name := dent.Name()
2883 if strings.HasSuffix(name, ".html") {
2884 toload = append(toload, viewDir+"/views/"+name)
2885 }
2886 }
2887
2888 readviews = templates.Load(develMode, toload...)
2889 if !develMode {
2890 assets := []string{
2891 viewDir + "/views/style.css",
2892 dataDir + "/views/local.css",
2893 viewDir + "/views/honkpage.js",
2894 viewDir + "/views/misc.js",
2895 dataDir + "/views/local.js",
2896 }
2897 for _, s := range assets {
2898 savedassetparams[s] = getassetparam(s)
2899 }
2900 loadAvatarColors()
2901 }
2902 startWatcher()
2903
2904 securitizeweb()
2905
2906 mux := mux.NewRouter()
2907 mux.Use(addcspheaders)
2908 mux.Use(login.Checker)
2909
2910 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2911
2912 posters := mux.Methods("POST").Subrouter()
2913 getters := mux.Methods("GET").Subrouter()
2914
2915 getters.HandleFunc("/", homepage)
2916 getters.HandleFunc("/home", homepage)
2917 getters.HandleFunc("/front", homepage)
2918 getters.HandleFunc("/events", homepage)
2919 getters.HandleFunc("/robots.txt", nomoroboto)
2920 getters.HandleFunc("/rss", showrss)
2921 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2922 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}.json", showuser)
2923 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2924 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}.json", showonehonk)
2925 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2926 posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2927 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2928 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2929 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2930 getters.HandleFunc("/a", avatate)
2931 getters.HandleFunc("/o", thelistingoftheontologies)
2932 getters.HandleFunc("/o/{name:.+}", showontology)
2933 getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2934 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2935 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2936 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2937
2938 getters.HandleFunc("/flag/{code:.+}", showflag)
2939
2940 getters.HandleFunc("/server", serveractor)
2941 posters.HandleFunc("/server/inbox", serverinbox)
2942 posters.HandleFunc("/inbox", serverinbox)
2943
2944 posters.HandleFunc("/csp-violation", fiveoh)
2945
2946 getters.HandleFunc("/style.css", serveviewasset)
2947 getters.HandleFunc("/honkpage.js", serveviewasset)
2948 getters.HandleFunc("/misc.js", serveviewasset)
2949 getters.HandleFunc("/local.css", servedataasset)
2950 getters.HandleFunc("/local.js", servedataasset)
2951 getters.HandleFunc("/icon.png", servedataasset)
2952 getters.HandleFunc("/favicon.ico", servedataasset)
2953
2954 getters.HandleFunc("/about", servehtml)
2955 getters.HandleFunc("/login", servehtml)
2956 posters.HandleFunc("/dologin", login.LoginFunc)
2957 getters.HandleFunc("/logout", login.LogoutFunc)
2958 getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2959
2960 loggedin := mux.NewRoute().Subrouter()
2961 loggedin.Use(login.Required)
2962 loggedin.HandleFunc("/first", homepage)
2963 loggedin.HandleFunc("/chatter", showchatter)
2964 loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2965 loggedin.HandleFunc("/saved", homepage)
2966 loggedin.HandleFunc("/account", accountpage)
2967 loggedin.HandleFunc("/funzone", showfunzone)
2968 loggedin.HandleFunc("/chpass", dochpass)
2969 loggedin.HandleFunc("/atme", homepage)
2970 loggedin.HandleFunc("/longago", homepage)
2971 loggedin.HandleFunc("/hfcs", hfcspage)
2972 loggedin.HandleFunc("/xzone", xzone)
2973 loggedin.HandleFunc("/newhonk", newhonkpage)
2974 loggedin.HandleFunc("/edit", edithonkpage)
2975 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2976 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2977 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2978 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2979 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2980 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2981 loggedin.HandleFunc("/honkers", showhonkers)
2982 loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2983 loggedin.HandleFunc("/h", showhonker)
2984 loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2985 loggedin.HandleFunc("/c", showcombos)
2986 loggedin.HandleFunc("/t", showconvoy)
2987 loggedin.HandleFunc("/q", showsearch)
2988 loggedin.HandleFunc("/hydra", webhydra)
2989 loggedin.HandleFunc("/emus", showemus)
2990 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2991
2992 if usefcgi {
2993 err = fcgi.Serve(listener, mux)
2994 } else {
2995 err = http.Serve(listener, mux)
2996 }
2997 if err != nil && !errors.Is(err, net.ErrClosed) {
2998 elog.Printf("serve error: %s", err)
2999 }
3000 time.Sleep(15 * time.Second)
3001 elog.Printf("fell off the bottom")
3002}