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