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