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