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