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