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 == "Dislike" || (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 sameperson(h1, h2 *Honk) bool {
1022 n1, n2 := h1.Honker, h2.Honker
1023 if h1.Oonker != "" {
1024 n1 = h1.Oonker
1025 }
1026 if h2.Oonker != "" {
1027 n2 = h2.Oonker
1028 }
1029 return n1 == n2
1030}
1031
1032func threadsort(honks []*Honk) []*Honk {
1033 sort.Slice(honks, func(i, j int) bool {
1034 return honks[i].Date.Before(honks[j].Date)
1035 })
1036 honkx := make(map[string]*Honk)
1037 kids := make(map[string][]*Honk)
1038 for _, h := range honks {
1039 honkx[h.XID] = h
1040 rid := h.RID
1041 kids[rid] = append(kids[rid], h)
1042 }
1043 done := make(map[*Honk]bool)
1044 var thread []*Honk
1045 var nextlevel func(p *Honk)
1046 level := 0
1047 nextlevel = func(p *Honk) {
1048 levelup := level < 4
1049 if pp := honkx[p.RID]; p.RID == "" || (pp != nil && sameperson(p, pp)) {
1050 levelup = false
1051 }
1052 if level > 0 && len(kids[p.RID]) == 1 {
1053 if pp := honkx[p.RID]; pp != nil && len(kids[pp.RID]) == 1 {
1054 levelup = false
1055 }
1056 }
1057 if levelup {
1058 level++
1059 }
1060 p.Style += fmt.Sprintf(" level%d", level)
1061 childs := kids[p.XID]
1062 sort.SliceStable(childs, func(i, j int) bool {
1063 return sameperson(childs[i], p) && !sameperson(childs[j], p)
1064 })
1065 for _, h := range childs {
1066 if !done[h] {
1067 done[h] = true
1068 thread = append(thread, h)
1069 nextlevel(h)
1070 }
1071 }
1072 if levelup {
1073 level--
1074 }
1075 }
1076 for _, h := range honks {
1077 if !done[h] && h.RID == "" {
1078 done[h] = true
1079 thread = append(thread, h)
1080 nextlevel(h)
1081 }
1082 }
1083 for _, h := range honks {
1084 if !done[h] {
1085 done[h] = true
1086 thread = append(thread, h)
1087 nextlevel(h)
1088 }
1089 }
1090 return thread
1091}
1092
1093func honkology(honk *Honk) template.HTML {
1094 var user *WhatAbout
1095 ok := somenumberedusers.Get(honk.UserID, &user)
1096 if !ok {
1097 return ""
1098 }
1099 title := fmt.Sprintf("%s: %s", user.Display, honk.Precis)
1100 imgurl := avatarURL(user)
1101 for _, d := range honk.Donks {
1102 if d.Local && strings.HasPrefix(d.Media, "image") {
1103 imgurl = d.URL
1104 break
1105 }
1106 }
1107 short := honk.Noise
1108 if len(short) > 160 {
1109 short = short[0:160] + "..."
1110 }
1111 return templates.Sprintf(
1112 `<meta property="og:title" content="%s" />
1113<meta property="og:type" content="article" />
1114<meta property="article:author" content="%s" />
1115<meta property="og:url" content="%s" />
1116<meta property="og:image" content="%s" />
1117<meta property="og:description" content="%s" />`,
1118 title, user.URL, honk.XID, imgurl, short)
1119}
1120
1121func showonehonk(w http.ResponseWriter, r *http.Request) {
1122 name := mux.Vars(r)["name"]
1123 user, err := butwhatabout(name)
1124 if err != nil {
1125 http.NotFound(w, r)
1126 return
1127 }
1128 if stealthmode(user.ID, r) {
1129 http.NotFound(w, r)
1130 return
1131 }
1132 xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1133
1134 if friendorfoe(r.Header.Get("Accept")) {
1135 j, ok := gimmejonk(xid)
1136 if ok {
1137 trackback(xid, r)
1138 w.Header().Set("Content-Type", theonetruename)
1139 w.Write(j)
1140 } else {
1141 http.NotFound(w, r)
1142 }
1143 return
1144 }
1145 honk := getxonk(user.ID, xid)
1146 if honk == nil {
1147 http.NotFound(w, r)
1148 return
1149 }
1150 u := login.GetUserInfo(r)
1151 if u != nil && u.UserID != user.ID {
1152 u = nil
1153 }
1154 if !honk.Public {
1155 if u == nil {
1156 http.NotFound(w, r)
1157 return
1158
1159 }
1160 honks := []*Honk{honk}
1161 donksforhonks(honks)
1162 templinfo := getInfo(r)
1163 templinfo["ServerMessage"] = "one honk maybe more"
1164 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1165 honkpage(w, u, honks, templinfo)
1166 return
1167 }
1168
1169 templinfo := getInfo(r)
1170 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1171 //reversehonks(rawhonks)
1172 rawhonks = threadsort(rawhonks)
1173 var honks []*Honk
1174 for _, h := range rawhonks {
1175 if h.XID == xid {
1176 templinfo["Honkology"] = honkology(h)
1177 if len(honks) != 0 {
1178 h.Style += " glow"
1179 }
1180 }
1181 if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1182 honks = append(honks, h)
1183 }
1184 }
1185
1186 templinfo["ServerMessage"] = "one honk maybe more"
1187 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1188 templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1189 honkpage(w, u, honks, templinfo)
1190}
1191
1192func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1193 var userid int64 = -1
1194 if u != nil {
1195 userid = u.UserID
1196 templinfo["User"], _ = butwhatabout(u.Username)
1197 }
1198 reverbolate(userid, honks)
1199 templinfo["Honks"] = honks
1200 templinfo["MapLink"] = getmaplink(u)
1201 if templinfo["TopHID"] == nil {
1202 if len(honks) > 0 {
1203 templinfo["TopHID"] = honks[0].ID
1204 } else {
1205 templinfo["TopHID"] = 0
1206 }
1207 }
1208 if u == nil && !develMode {
1209 w.Header().Set("Cache-Control", "max-age=60")
1210 }
1211 err := readviews.Execute(w, "honkpage.html", templinfo)
1212 if err != nil {
1213 elog.Print(err)
1214 }
1215}
1216
1217func saveuser(w http.ResponseWriter, r *http.Request) {
1218 whatabout := r.FormValue("whatabout")
1219 whatabout = strings.Replace(whatabout, "\r", "", -1)
1220 u := login.GetUserInfo(r)
1221 user, _ := butwhatabout(u.Username)
1222 db := opendatabase()
1223
1224 options := user.Options
1225 if r.FormValue("skinny") == "skinny" {
1226 options.SkinnyCSS = true
1227 } else {
1228 options.SkinnyCSS = false
1229 }
1230 if r.FormValue("omitimages") == "omitimages" {
1231 options.OmitImages = true
1232 } else {
1233 options.OmitImages = false
1234 }
1235 if r.FormValue("mentionall") == "mentionall" {
1236 options.MentionAll = true
1237 } else {
1238 options.MentionAll = false
1239 }
1240 if r.FormValue("inlineqts") == "inlineqts" {
1241 options.InlineQuotes = true
1242 } else {
1243 options.InlineQuotes = false
1244 }
1245 if r.FormValue("maps") == "apple" {
1246 options.MapLink = "apple"
1247 } else {
1248 options.MapLink = ""
1249 }
1250 options.Reaction = r.FormValue("reaction")
1251
1252 sendupdate := false
1253 ava := re_avatar.FindString(whatabout)
1254 if ava != "" {
1255 whatabout = re_avatar.ReplaceAllString(whatabout, "")
1256 ava = ava[7:]
1257 if ava[0] == ' ' {
1258 ava = ava[1:]
1259 }
1260 ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1261 }
1262 if ava != options.Avatar {
1263 options.Avatar = ava
1264 sendupdate = true
1265 }
1266 ban := re_banner.FindString(whatabout)
1267 if ban != "" {
1268 whatabout = re_banner.ReplaceAllString(whatabout, "")
1269 ban = ban[7:]
1270 if ban[0] == ' ' {
1271 ban = ban[1:]
1272 }
1273 ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1274 }
1275 if ban != options.Banner {
1276 options.Banner = ban
1277 sendupdate = true
1278 }
1279 whatabout = strings.TrimSpace(whatabout)
1280 if whatabout != user.About {
1281 sendupdate = true
1282 }
1283 j, err := jsonify(options)
1284 if err == nil {
1285 _, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1286 }
1287 if err != nil {
1288 elog.Printf("error bouting what: %s", err)
1289 }
1290 somenamedusers.Clear(u.Username)
1291 somenumberedusers.Clear(u.UserID)
1292 oldjonkers.Clear(u.Username)
1293
1294 if sendupdate {
1295 updateMe(u.Username)
1296 }
1297
1298 http.Redirect(w, r, "/account", http.StatusSeeOther)
1299}
1300
1301func bonkit(xid string, user *WhatAbout) {
1302 dlog.Printf("bonking %s", xid)
1303
1304 xonk := getxonk(user.ID, xid)
1305 if xonk == nil {
1306 return
1307 }
1308 if !xonk.Public {
1309 return
1310 }
1311 if xonk.IsBonked() {
1312 return
1313 }
1314 donksforhonks([]*Honk{xonk})
1315
1316 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1317 if err != nil {
1318 elog.Printf("error acking bonk: %s", err)
1319 }
1320
1321 oonker := xonk.Oonker
1322 if oonker == "" {
1323 oonker = xonk.Honker
1324 }
1325 dt := time.Now().UTC()
1326 bonk := &Honk{
1327 UserID: user.ID,
1328 Username: user.Name,
1329 What: "bonk",
1330 Honker: user.URL,
1331 Oonker: oonker,
1332 XID: xonk.XID,
1333 RID: xonk.RID,
1334 Noise: xonk.Noise,
1335 Precis: xonk.Precis,
1336 URL: xonk.URL,
1337 Date: dt,
1338 Donks: xonk.Donks,
1339 Whofore: 2,
1340 Convoy: xonk.Convoy,
1341 Audience: []string{thewholeworld, oonker},
1342 Public: true,
1343 Format: xonk.Format,
1344 Place: xonk.Place,
1345 Onts: xonk.Onts,
1346 Time: xonk.Time,
1347 }
1348
1349 err = savehonk(bonk)
1350 if err != nil {
1351 elog.Printf("uh oh")
1352 return
1353 }
1354
1355 go honkworldwide(user, bonk)
1356}
1357
1358func submitbonk(w http.ResponseWriter, r *http.Request) {
1359 xid := r.FormValue("xid")
1360 userinfo := login.GetUserInfo(r)
1361 user, _ := butwhatabout(userinfo.Username)
1362
1363 bonkit(xid, user)
1364
1365 if r.FormValue("js") != "1" {
1366 templinfo := getInfo(r)
1367 templinfo["ServerMessage"] = "Bonked!"
1368 err := readviews.Execute(w, "msg.html", templinfo)
1369 if err != nil {
1370 elog.Print(err)
1371 }
1372 }
1373}
1374
1375func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1376 zonk := &Honk{
1377 What: what,
1378 XID: xonk.XID,
1379 Date: time.Now().UTC(),
1380 Audience: oneofakind(xonk.Audience),
1381 Noise: aux,
1382 }
1383 zonk.Public = loudandproud(zonk.Audience)
1384
1385 dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1386 go honkworldwide(user, zonk)
1387}
1388
1389func zonkit(w http.ResponseWriter, r *http.Request) {
1390 wherefore := r.FormValue("wherefore")
1391 what := r.FormValue("what")
1392 userinfo := login.GetUserInfo(r)
1393 user, _ := butwhatabout(userinfo.Username)
1394
1395 if wherefore == "save" {
1396 xonk := getxonk(userinfo.UserID, what)
1397 if xonk != nil {
1398 _, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1399 if err != nil {
1400 elog.Printf("error saving: %s", err)
1401 }
1402 }
1403 return
1404 }
1405
1406 if wherefore == "unsave" {
1407 xonk := getxonk(userinfo.UserID, what)
1408 if xonk != nil {
1409 _, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1410 if err != nil {
1411 elog.Printf("error unsaving: %s", err)
1412 }
1413 }
1414 return
1415 }
1416
1417 if wherefore == "react" {
1418 reaction := user.Options.Reaction
1419 if r2 := r.FormValue("reaction"); r2 != "" {
1420 reaction = r2
1421 }
1422 if reaction == "none" {
1423 return
1424 }
1425 xonk := getxonk(userinfo.UserID, what)
1426 if xonk != nil {
1427 _, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1428 if err != nil {
1429 elog.Printf("error saving: %s", err)
1430 }
1431 sendzonkofsorts(xonk, user, "react", reaction)
1432 }
1433 return
1434 }
1435
1436 // my hammer is too big, oh well
1437 defer oldjonks.Flush()
1438
1439 if wherefore == "ack" {
1440 xonk := getxonk(userinfo.UserID, what)
1441 if xonk != nil && !xonk.IsAcked() {
1442 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1443 if err != nil {
1444 elog.Printf("error acking: %s", err)
1445 }
1446 sendzonkofsorts(xonk, user, "ack", "")
1447 }
1448 return
1449 }
1450
1451 if wherefore == "deack" {
1452 xonk := getxonk(userinfo.UserID, what)
1453 if xonk != nil && xonk.IsAcked() {
1454 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1455 if err != nil {
1456 elog.Printf("error deacking: %s", err)
1457 }
1458 sendzonkofsorts(xonk, user, "deack", "")
1459 }
1460 return
1461 }
1462
1463 if wherefore == "bonk" {
1464 user, _ := butwhatabout(userinfo.Username)
1465 bonkit(what, user)
1466 return
1467 }
1468
1469 if wherefore == "unbonk" {
1470 xonk := getbonk(userinfo.UserID, what)
1471 if xonk != nil {
1472 deletehonk(xonk.ID)
1473 xonk = getxonk(userinfo.UserID, what)
1474 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1475 if err != nil {
1476 elog.Printf("error unbonking: %s", err)
1477 }
1478 sendzonkofsorts(xonk, user, "unbonk", "")
1479 }
1480 return
1481 }
1482
1483 if wherefore == "untag" {
1484 xonk := getxonk(userinfo.UserID, what)
1485 if xonk != nil {
1486 _, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1487 if err != nil {
1488 elog.Printf("error untagging: %s", err)
1489 }
1490 }
1491 var badparents map[string]bool
1492 untagged.GetAndLock(userinfo.UserID, &badparents)
1493 badparents[what] = true
1494 untagged.Unlock()
1495 return
1496 }
1497
1498 ilog.Printf("zonking %s %s", wherefore, what)
1499 if wherefore == "zonk" {
1500 xonk := getxonk(userinfo.UserID, what)
1501 if xonk != nil {
1502 deletehonk(xonk.ID)
1503 if xonk.Whofore == 2 || xonk.Whofore == 3 {
1504 sendzonkofsorts(xonk, user, "zonk", "")
1505 }
1506 }
1507 }
1508 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1509 if err != nil {
1510 elog.Printf("error saving zonker: %s", err)
1511 return
1512 }
1513}
1514
1515func edithonkpage(w http.ResponseWriter, r *http.Request) {
1516 u := login.GetUserInfo(r)
1517 user, _ := butwhatabout(u.Username)
1518 xid := r.FormValue("xid")
1519 honk := getxonk(u.UserID, xid)
1520 if !canedithonk(user, honk) {
1521 http.Error(w, "no editing that please", http.StatusInternalServerError)
1522 return
1523 }
1524
1525 noise := honk.Noise
1526
1527 honks := []*Honk{honk}
1528 donksforhonks(honks)
1529 reverbolate(u.UserID, honks)
1530 templinfo := getInfo(r)
1531 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1532 templinfo["Honks"] = honks
1533 templinfo["MapLink"] = getmaplink(u)
1534 templinfo["Noise"] = noise
1535 templinfo["SavedPlace"] = honk.Place
1536 if tm := honk.Time; tm != nil {
1537 templinfo["ShowTime"] = " "
1538 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1539 if tm.Duration != 0 {
1540 templinfo["Duration"] = tm.Duration
1541 }
1542 }
1543 templinfo["ServerMessage"] = "honk edit 2"
1544 templinfo["IsPreview"] = true
1545 templinfo["UpdateXID"] = honk.XID
1546 if len(honk.Donks) > 0 {
1547 templinfo["SavedFile"] = honk.Donks[0].XID
1548 }
1549 err := readviews.Execute(w, "honkpage.html", templinfo)
1550 if err != nil {
1551 elog.Print(err)
1552 }
1553}
1554
1555func newhonkpage(w http.ResponseWriter, r *http.Request) {
1556 u := login.GetUserInfo(r)
1557 rid := r.FormValue("rid")
1558 noise := ""
1559
1560 xonk := getxonk(u.UserID, rid)
1561 if xonk != nil {
1562 _, replto := handles(xonk.Honker)
1563 if replto != "" {
1564 noise = "@" + replto + " "
1565 }
1566 }
1567
1568 templinfo := getInfo(r)
1569 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1570 templinfo["InReplyTo"] = rid
1571 templinfo["Noise"] = noise
1572 templinfo["ServerMessage"] = "compose honk"
1573 templinfo["IsPreview"] = true
1574 err := readviews.Execute(w, "honkpage.html", templinfo)
1575 if err != nil {
1576 elog.Print(err)
1577 }
1578}
1579
1580func canedithonk(user *WhatAbout, honk *Honk) bool {
1581 if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1582 return false
1583 }
1584 return true
1585}
1586
1587func submitdonk(w http.ResponseWriter, r *http.Request) (*Donk, error) {
1588 if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1589 return nil, nil
1590 }
1591 file, filehdr, err := r.FormFile("donk")
1592 if err != nil {
1593 if err == http.ErrMissingFile {
1594 return nil, nil
1595 }
1596 elog.Printf("error reading donk: %s", err)
1597 http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1598 return nil, err
1599 }
1600 var buf bytes.Buffer
1601 io.Copy(&buf, file)
1602 file.Close()
1603 data := buf.Bytes()
1604 var media, name string
1605 img, err := shrinkit(data)
1606 if err == nil {
1607 data = img.Data
1608 format := img.Format
1609 media = "image/" + format
1610 if format == "jpeg" {
1611 format = "jpg"
1612 }
1613 if format == "svg+xml" {
1614 format = "svg"
1615 }
1616 name = xfiltrate() + "." + format
1617 } else {
1618 ct := http.DetectContentType(data)
1619 switch ct {
1620 case "application/pdf":
1621 maxsize := 10000000
1622 if len(data) > maxsize {
1623 ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1624 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1625 return nil, err
1626 }
1627 media = ct
1628 name = filehdr.Filename
1629 if name == "" {
1630 name = xfiltrate() + ".pdf"
1631 }
1632 default:
1633 maxsize := 100000
1634 if len(data) > maxsize {
1635 ilog.Printf("bad image: %s too much text: %d", err, len(data))
1636 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1637 return nil, err
1638 }
1639 for i := 0; i < len(data); i++ {
1640 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1641 ilog.Printf("bad image: %s not text: %d", err, data[i])
1642 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1643 return nil, err
1644 }
1645 }
1646 media = "text/plain"
1647 name = filehdr.Filename
1648 if name == "" {
1649 name = xfiltrate() + ".txt"
1650 }
1651 }
1652 }
1653 desc := strings.TrimSpace(r.FormValue("donkdesc"))
1654 if desc == "" {
1655 desc = name
1656 }
1657 fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1658 if err != nil {
1659 elog.Printf("unable to save image: %s", err)
1660 http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1661 return nil, err
1662 }
1663 d := &Donk{
1664 FileID: fileid,
1665 XID: xid,
1666 Desc: desc,
1667 Local: true,
1668 }
1669 return d, nil
1670}
1671
1672func websubmithonk(w http.ResponseWriter, r *http.Request) {
1673 h := submithonk(w, r)
1674 if h == nil {
1675 return
1676 }
1677 http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1678}
1679
1680// what a hot mess this function is
1681func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1682 rid := r.FormValue("rid")
1683 noise := r.FormValue("noise")
1684 format := r.FormValue("format")
1685 if format == "" {
1686 format = "markdown"
1687 }
1688 if !(format == "markdown" || format == "html") {
1689 http.Error(w, "unknown format", 500)
1690 return nil
1691 }
1692
1693 userinfo := login.GetUserInfo(r)
1694 user, _ := butwhatabout(userinfo.Username)
1695
1696 dt := time.Now().UTC()
1697 updatexid := r.FormValue("updatexid")
1698 var honk *Honk
1699 if updatexid != "" {
1700 honk = getxonk(userinfo.UserID, updatexid)
1701 if !canedithonk(user, honk) {
1702 http.Error(w, "no editing that please", http.StatusInternalServerError)
1703 return nil
1704 }
1705 honk.Date = dt
1706 honk.What = "update"
1707 honk.Format = format
1708 } else {
1709 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1710 what := "honk"
1711 honk = &Honk{
1712 UserID: userinfo.UserID,
1713 Username: userinfo.Username,
1714 What: what,
1715 Honker: user.URL,
1716 XID: xid,
1717 Date: dt,
1718 Format: format,
1719 }
1720 }
1721
1722 var convoy string
1723 noise = strings.Replace(noise, "\r", "", -1)
1724 if updatexid == "" && rid == "" {
1725 noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1726 convoy = m[7:]
1727 convoy = strings.TrimSpace(convoy)
1728 if !re_convalidate.MatchString(convoy) {
1729 convoy = ""
1730 }
1731 return ""
1732 })
1733 }
1734 noise = quickrename(noise, userinfo.UserID)
1735 noise = hooterize(noise)
1736 honk.Noise = noise
1737 precipitate(honk)
1738 noise = honk.Noise
1739 translate(honk)
1740
1741 if rid != "" {
1742 xonk := getxonk(userinfo.UserID, rid)
1743 if xonk == nil {
1744 http.Error(w, "replyto disappeared", http.StatusNotFound)
1745 return nil
1746 }
1747 if xonk.Public {
1748 honk.Audience = append(honk.Audience, xonk.Audience...)
1749 }
1750 convoy = xonk.Convoy
1751 for i, a := range honk.Audience {
1752 if a == thewholeworld {
1753 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1754 break
1755 }
1756 }
1757 honk.RID = rid
1758 if xonk.Precis != "" && honk.Precis == "" {
1759 honk.Precis = xonk.Precis
1760 if !re_dangerous.MatchString(honk.Precis) {
1761 honk.Precis = "re: " + honk.Precis
1762 }
1763 }
1764 } else {
1765 honk.Audience = []string{thewholeworld}
1766 }
1767 if honk.Noise != "" && honk.Noise[0] == '@' {
1768 honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1769 } else {
1770 honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1771 }
1772
1773 if convoy == "" {
1774 convoy = "data:,electrichonkytonk-" + xfiltrate()
1775 }
1776 butnottooloud(honk.Audience)
1777 honk.Audience = oneofakind(honk.Audience)
1778 if len(honk.Audience) == 0 {
1779 ilog.Printf("honk to nowhere")
1780 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1781 return nil
1782 }
1783 honk.Public = loudandproud(honk.Audience)
1784 honk.Convoy = convoy
1785
1786 donkxid := r.FormValue("donkxid")
1787 if donkxid == "" {
1788 d, err := submitdonk(w, r)
1789 if err != nil && err != http.ErrMissingFile {
1790 return nil
1791 }
1792 if d != nil {
1793 honk.Donks = append(honk.Donks, d)
1794 donkxid = fmt.Sprintf("%s:%d", d.XID, d.FileID)
1795 }
1796 } else {
1797 p := strings.Split(donkxid, ":")
1798 xid := p[0]
1799 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1800 var donk *Donk
1801 if len(p) > 1 {
1802 fileid, _ := strconv.ParseInt(p[1], 10, 0)
1803 donk = finddonkid(fileid, url)
1804 } else {
1805 donk = finddonk(url)
1806 }
1807 if donk != nil {
1808 honk.Donks = append(honk.Donks, donk)
1809 } else {
1810 ilog.Printf("can't find file: %s", xid)
1811 }
1812 }
1813 memetize(honk)
1814 imaginate(honk)
1815
1816 placename := strings.TrimSpace(r.FormValue("placename"))
1817 placelat := strings.TrimSpace(r.FormValue("placelat"))
1818 placelong := strings.TrimSpace(r.FormValue("placelong"))
1819 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1820 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1821 p := new(Place)
1822 p.Name = placename
1823 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1824 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1825 p.Url = placeurl
1826 honk.Place = p
1827 }
1828 timestart := strings.TrimSpace(r.FormValue("timestart"))
1829 if timestart != "" {
1830 t := new(Time)
1831 now := time.Now().Local()
1832 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1833 start, err := time.ParseInLocation(layout, timestart, now.Location())
1834 if err == nil {
1835 if start.Year() == 0 {
1836 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1837 }
1838 t.StartTime = start
1839 break
1840 }
1841 }
1842 timeend := r.FormValue("timeend")
1843 dur := parseDuration(timeend)
1844 if dur != 0 {
1845 t.Duration = Duration(dur)
1846 }
1847 if !t.StartTime.IsZero() {
1848 honk.What = "event"
1849 honk.Time = t
1850 }
1851 }
1852
1853 if honk.Public {
1854 honk.Whofore = 2
1855 } else {
1856 honk.Whofore = 3
1857 }
1858
1859 // back to markdown
1860 honk.Noise = noise
1861
1862 if r.FormValue("preview") == "preview" {
1863 honks := []*Honk{honk}
1864 reverbolate(userinfo.UserID, honks)
1865 templinfo := getInfo(r)
1866 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1867 templinfo["Honks"] = honks
1868 templinfo["MapLink"] = getmaplink(userinfo)
1869 templinfo["InReplyTo"] = r.FormValue("rid")
1870 templinfo["Noise"] = r.FormValue("noise")
1871 templinfo["SavedFile"] = donkxid
1872 if tm := honk.Time; tm != nil {
1873 templinfo["ShowTime"] = " "
1874 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1875 if tm.Duration != 0 {
1876 templinfo["Duration"] = tm.Duration
1877 }
1878 }
1879 templinfo["IsPreview"] = true
1880 templinfo["UpdateXID"] = updatexid
1881 templinfo["ServerMessage"] = "honk preview"
1882 err := readviews.Execute(w, "honkpage.html", templinfo)
1883 if err != nil {
1884 elog.Print(err)
1885 }
1886 return nil
1887 }
1888
1889 if updatexid != "" {
1890 updatehonk(honk)
1891 oldjonks.Clear(honk.XID)
1892 } else {
1893 err := savehonk(honk)
1894 if err != nil {
1895 elog.Printf("uh oh")
1896 return nil
1897 }
1898 }
1899
1900 // reload for consistency
1901 honk.Donks = nil
1902 donksforhonks([]*Honk{honk})
1903
1904 go honkworldwide(user, honk)
1905
1906 return honk
1907}
1908
1909func showhonkers(w http.ResponseWriter, r *http.Request) {
1910 userinfo := login.GetUserInfo(r)
1911 templinfo := getInfo(r)
1912 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1913 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1914 err := readviews.Execute(w, "honkers.html", templinfo)
1915 if err != nil {
1916 elog.Print(err)
1917 }
1918}
1919
1920func showchatter(w http.ResponseWriter, r *http.Request) {
1921 u := login.GetUserInfo(r)
1922 chatnewnone(u.UserID)
1923 chatter := loadchatter(u.UserID)
1924 for _, chat := range chatter {
1925 for _, ch := range chat.Chonks {
1926 filterchonk(ch)
1927 }
1928 }
1929
1930 templinfo := getInfo(r)
1931 templinfo["Chatter"] = chatter
1932 templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1933 err := readviews.Execute(w, "chatter.html", templinfo)
1934 if err != nil {
1935 elog.Print(err)
1936 }
1937}
1938
1939func submitchonk(w http.ResponseWriter, r *http.Request) {
1940 u := login.GetUserInfo(r)
1941 user, _ := butwhatabout(u.Username)
1942 noise := r.FormValue("noise")
1943 target := r.FormValue("target")
1944 format := "markdown"
1945 dt := time.Now().UTC()
1946 xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1947
1948 if !strings.HasPrefix(target, "https://") {
1949 target = fullname(target, u.UserID)
1950 }
1951 if target == "" {
1952 http.Error(w, "who is that?", http.StatusInternalServerError)
1953 return
1954 }
1955 ch := Chonk{
1956 UserID: u.UserID,
1957 XID: xid,
1958 Who: user.URL,
1959 Target: target,
1960 Date: dt,
1961 Noise: noise,
1962 Format: format,
1963 }
1964 d, err := submitdonk(w, r)
1965 if err != nil && err != http.ErrMissingFile {
1966 return
1967 }
1968 if d != nil {
1969 ch.Donks = append(ch.Donks, d)
1970 }
1971
1972 translatechonk(&ch)
1973 savechonk(&ch)
1974 // reload for consistency
1975 ch.Donks = nil
1976 donksforchonks([]*Chonk{&ch})
1977 go sendchonk(user, &ch)
1978
1979 http.Redirect(w, r, "/chatter", http.StatusSeeOther)
1980}
1981
1982var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1983 honkers := gethonkers(userid)
1984 var combos []string
1985 for _, h := range honkers {
1986 combos = append(combos, h.Combos...)
1987 }
1988 for i, c := range combos {
1989 if c == "-" {
1990 combos[i] = ""
1991 }
1992 }
1993 combos = oneofakind(combos)
1994 sort.Strings(combos)
1995 return combos, true
1996}, Invalidator: &honkerinvalidator})
1997
1998func showcombos(w http.ResponseWriter, r *http.Request) {
1999 userinfo := login.GetUserInfo(r)
2000 var combos []string
2001 combocache.Get(userinfo.UserID, &combos)
2002 templinfo := getInfo(r)
2003 err := readviews.Execute(w, "combos.html", templinfo)
2004 if err != nil {
2005 elog.Print(err)
2006 }
2007}
2008
2009func websubmithonker(w http.ResponseWriter, r *http.Request) {
2010 h := submithonker(w, r)
2011 if h == nil {
2012 return
2013 }
2014 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2015}
2016
2017func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2018 u := login.GetUserInfo(r)
2019 user, _ := butwhatabout(u.Username)
2020 name := strings.TrimSpace(r.FormValue("name"))
2021 url := strings.TrimSpace(r.FormValue("url"))
2022 peep := r.FormValue("peep")
2023 combos := strings.TrimSpace(r.FormValue("combos"))
2024 combos = " " + combos + " "
2025 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2026
2027 re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2028 if name != "" && !re_namecheck.MatchString(name) {
2029 http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2030 return nil
2031 }
2032
2033 var meta HonkerMeta
2034 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2035 mj, _ := jsonify(&meta)
2036
2037 defer honkerinvalidator.Clear(u.UserID)
2038
2039 // mostly dummy, fill in later...
2040 h := &Honker{
2041 ID: honkerid,
2042 }
2043
2044 if honkerid > 0 {
2045 if r.FormValue("delete") == "delete" {
2046 unfollowyou(user, honkerid, false)
2047 stmtDeleteHonker.Exec(honkerid)
2048 return h
2049 }
2050 if r.FormValue("unsub") == "unsub" {
2051 unfollowyou(user, honkerid, false)
2052 }
2053 if r.FormValue("sub") == "sub" {
2054 followyou(user, honkerid, false)
2055 }
2056 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2057 if err != nil {
2058 elog.Printf("update honker err: %s", err)
2059 return nil
2060 }
2061 return h
2062 }
2063
2064 if url == "" {
2065 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2066 return nil
2067 }
2068
2069 flavor := "presub"
2070 if peep == "peep" {
2071 flavor = "peep"
2072 }
2073
2074 var err error
2075 honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2076 if err != nil {
2077 http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2078 return nil
2079 }
2080 if flavor == "presub" {
2081 followyou(user, honkerid, false)
2082 }
2083 h.ID = honkerid
2084 return h
2085}
2086
2087func hfcspage(w http.ResponseWriter, r *http.Request) {
2088 userinfo := login.GetUserInfo(r)
2089
2090 filters := getfilters(userinfo.UserID, filtAny)
2091
2092 templinfo := getInfo(r)
2093 templinfo["Filters"] = filters
2094 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2095 err := readviews.Execute(w, "hfcs.html", templinfo)
2096 if err != nil {
2097 elog.Print(err)
2098 }
2099}
2100
2101func savehfcs(w http.ResponseWriter, r *http.Request) {
2102 userinfo := login.GetUserInfo(r)
2103 itsok := r.FormValue("itsok")
2104 if itsok == "iforgiveyou" {
2105 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2106 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2107 if err != nil {
2108 elog.Printf("error deleting filter: %s", err)
2109 }
2110 filtInvalidator.Clear(userinfo.UserID)
2111 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2112 return
2113 }
2114
2115 filt := new(Filter)
2116 filt.Name = strings.TrimSpace(r.FormValue("name"))
2117 filt.Date = time.Now().UTC()
2118 filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2119 filt.IncludeAudience = r.FormValue("incaud") == "yes"
2120 filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2121 filt.IsReply = r.FormValue("isreply") == "yes"
2122 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2123 filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2124 filt.Reject = r.FormValue("doreject") == "yes"
2125 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2126 filt.Hide = r.FormValue("dohide") == "yes"
2127 filt.Collapse = r.FormValue("docollapse") == "yes"
2128 filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2129 filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2130 if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2131 filt.Expiration = time.Now().UTC().Add(dur)
2132 }
2133 filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2134
2135 if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2136 ilog.Printf("blank filter")
2137 http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2138 return
2139 }
2140
2141 j, err := jsonify(filt)
2142 if err == nil {
2143 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2144 }
2145 if err != nil {
2146 elog.Printf("error saving filter: %s", err)
2147 }
2148
2149 filtInvalidator.Clear(userinfo.UserID)
2150 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2151}
2152
2153func accountpage(w http.ResponseWriter, r *http.Request) {
2154 u := login.GetUserInfo(r)
2155 user, _ := butwhatabout(u.Username)
2156 templinfo := getInfo(r)
2157 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2158 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2159 templinfo["User"] = user
2160 about := user.About
2161 if ava := user.Options.Avatar; ava != "" {
2162 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2163 }
2164 if ban := user.Options.Banner; ban != "" {
2165 about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2166 }
2167 templinfo["WhatAbout"] = about
2168 err := readviews.Execute(w, "account.html", templinfo)
2169 if err != nil {
2170 elog.Print(err)
2171 }
2172}
2173
2174func dochpass(w http.ResponseWriter, r *http.Request) {
2175 err := login.ChangePassword(w, r)
2176 if err != nil {
2177 elog.Printf("error changing password: %s", err)
2178 }
2179 http.Redirect(w, r, "/account", http.StatusSeeOther)
2180}
2181
2182var oldfingers = cache.New(cache.Options{Filler: func(orig string) ([]byte, bool) {
2183 if strings.HasPrefix(orig, "acct:") {
2184 orig = orig[5:]
2185 }
2186 name := orig
2187 idx := strings.LastIndexByte(name, '/')
2188 if idx != -1 {
2189 name = name[idx+1:]
2190 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2191 ilog.Printf("foreign request rejected")
2192 name = ""
2193 }
2194 } else {
2195 idx = strings.IndexByte(name, '@')
2196 if idx != -1 {
2197 name = name[:idx]
2198 if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2199 ilog.Printf("foreign request rejected")
2200 name = ""
2201 }
2202 }
2203 }
2204 user, err := butwhatabout(name)
2205 if err != nil {
2206 return nil, false
2207 }
2208
2209 j := junk.New()
2210 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2211 j["aliases"] = []string{user.URL}
2212 l := junk.New()
2213 l["rel"] = "self"
2214 l["type"] = `application/activity+json`
2215 l["href"] = user.URL
2216 j["links"] = []junk.Junk{l}
2217 return j.ToBytes(), true
2218}})
2219
2220func fingerlicker(w http.ResponseWriter, r *http.Request) {
2221 orig := r.FormValue("resource")
2222
2223 dlog.Printf("finger lick: %s", orig)
2224
2225 var j []byte
2226 ok := oldfingers.Get(orig, &j)
2227 if ok {
2228 w.Header().Set("Content-Type", "application/jrd+json")
2229 w.Write(j)
2230 } else {
2231 http.NotFound(w, r)
2232 }
2233}
2234
2235func somedays() string {
2236 secs := 432000 + notrand.Int63n(432000)
2237 return fmt.Sprintf("%d", secs)
2238}
2239
2240func lookatme(ava string) string {
2241 if strings.Contains(ava, serverName+"/"+userSep) {
2242 idx := strings.LastIndexByte(ava, '/')
2243 if idx < len(ava) {
2244 name := ava[idx+1:]
2245 user, _ := butwhatabout(name)
2246 if user != nil && user.URL == ava {
2247 return user.Options.Avatar
2248 }
2249 }
2250 }
2251 return ""
2252}
2253
2254func avatate(w http.ResponseWriter, r *http.Request) {
2255 if develMode {
2256 loadAvatarColors()
2257 }
2258 n := r.FormValue("a")
2259 if redir := lookatme(n); redir != "" {
2260 http.Redirect(w, r, redir, http.StatusSeeOther)
2261 return
2262 }
2263 a := genAvatar(n)
2264 if !develMode {
2265 w.Header().Set("Cache-Control", "max-age="+somedays())
2266 }
2267 w.Write(a)
2268}
2269
2270func serveviewasset(w http.ResponseWriter, r *http.Request) {
2271 serveasset(w, r, viewDir)
2272}
2273func servedataasset(w http.ResponseWriter, r *http.Request) {
2274 if r.URL.Path == "/favicon.ico" {
2275 r.URL.Path = "/icon.png"
2276 }
2277 serveasset(w, r, dataDir)
2278}
2279
2280func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2281 if !develMode {
2282 w.Header().Set("Cache-Control", "max-age=7776000")
2283 }
2284 http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2285}
2286func servehelp(w http.ResponseWriter, r *http.Request) {
2287 name := mux.Vars(r)["name"]
2288 if !develMode {
2289 w.Header().Set("Cache-Control", "max-age=3600")
2290 }
2291 http.ServeFile(w, r, viewDir+"/docs/"+name)
2292}
2293func servehtml(w http.ResponseWriter, r *http.Request) {
2294 u := login.GetUserInfo(r)
2295 templinfo := getInfo(r)
2296 templinfo["AboutMsg"] = aboutMsg
2297 templinfo["LoginMsg"] = loginMsg
2298 templinfo["HonkVersion"] = softwareVersion
2299 if r.URL.Path == "/about" {
2300 templinfo["Sensors"] = getSensors()
2301 }
2302 if u == nil && !develMode {
2303 w.Header().Set("Cache-Control", "max-age=60")
2304 }
2305 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2306 if err != nil {
2307 elog.Print(err)
2308 }
2309}
2310func serveemu(w http.ResponseWriter, r *http.Request) {
2311 emu := mux.Vars(r)["emu"]
2312
2313 w.Header().Set("Cache-Control", "max-age="+somedays())
2314 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2315}
2316func servememe(w http.ResponseWriter, r *http.Request) {
2317 meme := mux.Vars(r)["meme"]
2318
2319 w.Header().Set("Cache-Control", "max-age="+somedays())
2320 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2321}
2322
2323func servefile(w http.ResponseWriter, r *http.Request) {
2324 xid := mux.Vars(r)["xid"]
2325 var media string
2326 var data []byte
2327 row := stmtGetFileData.QueryRow(xid)
2328 err := row.Scan(&media, &data)
2329 if err != nil {
2330 elog.Printf("error loading file: %s", err)
2331 http.NotFound(w, r)
2332 return
2333 }
2334 w.Header().Set("Content-Type", media)
2335 w.Header().Set("X-Content-Type-Options", "nosniff")
2336 w.Header().Set("Cache-Control", "max-age="+somedays())
2337 w.Write(data)
2338}
2339
2340func nomoroboto(w http.ResponseWriter, r *http.Request) {
2341 io.WriteString(w, "User-agent: *\n")
2342 io.WriteString(w, "Disallow: /a\n")
2343 io.WriteString(w, "Disallow: /d/\n")
2344 io.WriteString(w, "Disallow: /meme/\n")
2345 io.WriteString(w, "Disallow: /o\n")
2346 io.WriteString(w, "Disallow: /o/\n")
2347 io.WriteString(w, "Disallow: /help/\n")
2348 for _, u := range allusers() {
2349 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2350 }
2351}
2352
2353type Hydration struct {
2354 Tophid int64
2355 Srvmsg template.HTML
2356 Honks string
2357 MeCount int64
2358 ChatCount int64
2359}
2360
2361func webhydra(w http.ResponseWriter, r *http.Request) {
2362 u := login.GetUserInfo(r)
2363 userid := u.UserID
2364 templinfo := getInfo(r)
2365 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2366 page := r.FormValue("page")
2367
2368 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2369
2370 var hydra Hydration
2371
2372 var honks []*Honk
2373 switch page {
2374 case "atme":
2375 honks = gethonksforme(userid, wanted)
2376 honks = osmosis(honks, userid, false)
2377 menewnone(userid)
2378 hydra.Srvmsg = "at me!"
2379 case "longago":
2380 honks = gethonksfromlongago(userid, wanted)
2381 honks = osmosis(honks, userid, false)
2382 hydra.Srvmsg = "from long ago"
2383 case "home":
2384 honks = gethonksforuser(userid, wanted)
2385 honks = osmosis(honks, userid, true)
2386 hydra.Srvmsg = serverMsg
2387 case "first":
2388 honks = gethonksforuserfirstclass(userid, wanted)
2389 honks = osmosis(honks, userid, true)
2390 hydra.Srvmsg = "first class only"
2391 case "saved":
2392 honks = getsavedhonks(userid, wanted)
2393 templinfo["PageName"] = "saved"
2394 hydra.Srvmsg = "saved honks"
2395 case "combo":
2396 c := r.FormValue("c")
2397 honks = gethonksbycombo(userid, c, wanted)
2398 honks = osmosis(honks, userid, false)
2399 hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2400 case "convoy":
2401 c := r.FormValue("c")
2402 honks = gethonksbyconvoy(userid, c, wanted)
2403 honks = osmosis(honks, userid, false)
2404 honks = threadsort(honks)
2405 reversehonks(honks)
2406 hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2407 case "honker":
2408 xid := r.FormValue("xid")
2409 honks = gethonksbyxonker(userid, xid, wanted)
2410 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2411 <input type="hidden" name="CSRF" value="%s">
2412 <input type="hidden" name="url" value="%s">
2413 <button tabindex=1 name="add honker" value="add honker">add honker</button>
2414 </form>`, login.GetCSRF("submithonker", r), xid)
2415 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2416 hydra.Srvmsg = msg
2417 case "user":
2418 uname := r.FormValue("uname")
2419 honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2420 hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2421 default:
2422 http.NotFound(w, r)
2423 }
2424
2425 if len(honks) > 0 {
2426 hydra.Tophid = honks[0].ID
2427 } else {
2428 hydra.Tophid = wanted
2429 }
2430 reverbolate(userid, honks)
2431
2432 user, _ := butwhatabout(u.Username)
2433
2434 var buf strings.Builder
2435 templinfo["Honks"] = honks
2436 templinfo["MapLink"] = getmaplink(u)
2437 templinfo["User"], _ = butwhatabout(u.Username)
2438 err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2439 if err != nil {
2440 elog.Printf("frag error: %s", err)
2441 return
2442 }
2443 hydra.Honks = buf.String()
2444 hydra.MeCount = user.Options.MeCount
2445 hydra.ChatCount = user.Options.ChatCount
2446 w.Header().Set("Content-Type", "application/json")
2447 j, _ := jsonify(&hydra)
2448 io.WriteString(w, j)
2449}
2450
2451var honkline = make(chan bool)
2452
2453func honkhonkline() {
2454 for {
2455 select {
2456 case honkline <- true:
2457 default:
2458 return
2459 }
2460 }
2461}
2462
2463func apihandler(w http.ResponseWriter, r *http.Request) {
2464 u := login.GetUserInfo(r)
2465 userid := u.UserID
2466 action := r.FormValue("action")
2467 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2468 dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2469 switch action {
2470 case "honk":
2471 h := submithonk(w, r)
2472 if h == nil {
2473 return
2474 }
2475 fmt.Fprintf(w, "%s", h.XID)
2476 case "donk":
2477 d, err := submitdonk(w, r)
2478 if err != nil {
2479 http.Error(w, err.Error(), http.StatusBadRequest)
2480 return
2481 }
2482 if d == nil {
2483 http.Error(w, "missing donk", http.StatusBadRequest)
2484 return
2485 }
2486 w.Write([]byte(d.XID))
2487 case "zonkit":
2488 zonkit(w, r)
2489 case "gethonks":
2490 var honks []*Honk
2491 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2492 page := r.FormValue("page")
2493 var waitchan <-chan time.Time
2494 requery:
2495 switch page {
2496 case "atme":
2497 honks = gethonksforme(userid, wanted)
2498 honks = osmosis(honks, userid, false)
2499 menewnone(userid)
2500 case "longago":
2501 honks = gethonksfromlongago(userid, wanted)
2502 honks = osmosis(honks, userid, false)
2503 case "home":
2504 honks = gethonksforuser(userid, wanted)
2505 honks = osmosis(honks, userid, true)
2506 case "myhonks":
2507 honks = gethonksbyuser(u.Username, true, wanted)
2508 honks = osmosis(honks, userid, true)
2509 default:
2510 http.Error(w, "unknown page", http.StatusNotFound)
2511 return
2512 }
2513 if len(honks) == 0 && wait > 0 {
2514 if waitchan == nil {
2515 waitchan = time.After(time.Duration(wait) * time.Second)
2516 }
2517 select {
2518 case <-honkline:
2519 goto requery
2520 case <-waitchan:
2521 }
2522 }
2523 reverbolate(userid, honks)
2524 j := junk.New()
2525 j["honks"] = honks
2526 j.Write(w)
2527 case "sendactivity":
2528 user, _ := butwhatabout(u.Username)
2529 public := r.FormValue("public") == "1"
2530 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2531 msg := []byte(r.FormValue("msg"))
2532 for rcpt := range rcpts {
2533 go deliverate(userid, rcpt, msg)
2534 }
2535 case "gethonkers":
2536 j := junk.New()
2537 j["honkers"] = gethonkers(u.UserID)
2538 j.Write(w)
2539 case "savehonker":
2540 h := submithonker(w, r)
2541 if h == nil {
2542 return
2543 }
2544 fmt.Fprintf(w, "%d", h.ID)
2545 default:
2546 http.Error(w, "unknown action", http.StatusNotFound)
2547 return
2548 }
2549}
2550
2551func fiveoh(w http.ResponseWriter, r *http.Request) {
2552 fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2553 if err != nil {
2554 elog.Printf("error opening violations! %s", err)
2555 return
2556 }
2557 defer fd.Close()
2558 io.Copy(fd, r.Body)
2559 fd.WriteString("\n")
2560}
2561
2562var endoftheworld = make(chan bool)
2563var readyalready = make(chan bool)
2564var workinprogress = 0
2565
2566func enditall() {
2567 sig := make(chan os.Signal, 1)
2568 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2569 <-sig
2570 ilog.Printf("stopping...")
2571 for i := 0; i < workinprogress; i++ {
2572 endoftheworld <- true
2573 }
2574 ilog.Printf("waiting...")
2575 for i := 0; i < workinprogress; i++ {
2576 <-readyalready
2577 }
2578 ilog.Printf("apocalypse")
2579 os.Exit(0)
2580}
2581
2582var preservehooks []func()
2583
2584func bgmonitor() {
2585 for {
2586 when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2587 _, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2588 if err != nil {
2589 elog.Printf("error deleting old xonkers: %s", err)
2590 }
2591 zaggies.Flush()
2592 time.Sleep(50 * time.Minute)
2593 }
2594}
2595
2596func addcspheaders(next http.Handler) http.Handler {
2597 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2598 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")
2599 next.ServeHTTP(w, r)
2600 })
2601}
2602
2603func emuinit() {
2604 var emunames []string
2605 dir, err := os.Open(dataDir + "/emus")
2606 if err == nil {
2607 emunames, _ = dir.Readdirnames(0)
2608 dir.Close()
2609 }
2610 for _, e := range emunames {
2611 if len(e) <= 4 {
2612 continue
2613 }
2614 ext := e[len(e)-4:]
2615 emu := Emu{
2616 ID: fmt.Sprintf("/emu/%s", e),
2617 Name: e[:len(e)-4],
2618 Type: "image/" + ext[1:],
2619 }
2620 allemus = append(allemus, emu)
2621 }
2622 sort.Slice(allemus, func(i, j int) bool {
2623 return allemus[i].Name < allemus[j].Name
2624 })
2625}
2626
2627func serve() {
2628 db := opendatabase()
2629 login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2630
2631 listener, err := openListener()
2632 if err != nil {
2633 elog.Fatal(err)
2634 }
2635 runBackendServer()
2636 go enditall()
2637 go redeliverator()
2638 go tracker()
2639 go bgmonitor()
2640 loadLingo()
2641 emuinit()
2642
2643 readviews = templates.Load(develMode,
2644 viewDir+"/views/honkpage.html",
2645 viewDir+"/views/honkfrags.html",
2646 viewDir+"/views/honkers.html",
2647 viewDir+"/views/chatter.html",
2648 viewDir+"/views/hfcs.html",
2649 viewDir+"/views/combos.html",
2650 viewDir+"/views/honkform.html",
2651 viewDir+"/views/honk.html",
2652 viewDir+"/views/account.html",
2653 viewDir+"/views/about.html",
2654 viewDir+"/views/funzone.html",
2655 viewDir+"/views/login.html",
2656 viewDir+"/views/xzone.html",
2657 viewDir+"/views/msg.html",
2658 viewDir+"/views/header.html",
2659 viewDir+"/views/onts.html",
2660 viewDir+"/views/emus.html",
2661 viewDir+"/views/honkpage.js",
2662 )
2663 if !develMode {
2664 assets := []string{
2665 viewDir + "/views/style.css",
2666 dataDir + "/views/local.css",
2667 viewDir + "/views/honkpage.js",
2668 dataDir + "/views/local.js",
2669 }
2670 for _, s := range assets {
2671 savedassetparams[s] = getassetparam(s)
2672 }
2673 loadAvatarColors()
2674 }
2675
2676 for _, h := range preservehooks {
2677 h()
2678 }
2679
2680 mux := mux.NewRouter()
2681 mux.Use(addcspheaders)
2682 mux.Use(login.Checker)
2683
2684 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2685
2686 posters := mux.Methods("POST").Subrouter()
2687 getters := mux.Methods("GET").Subrouter()
2688
2689 getters.HandleFunc("/", homepage)
2690 getters.HandleFunc("/home", homepage)
2691 getters.HandleFunc("/front", homepage)
2692 getters.HandleFunc("/events", homepage)
2693 getters.HandleFunc("/robots.txt", nomoroboto)
2694 getters.HandleFunc("/rss", showrss)
2695 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2696 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2697 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2698 posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2699 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2700 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2701 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2702 getters.HandleFunc("/a", avatate)
2703 getters.HandleFunc("/o", thelistingoftheontologies)
2704 getters.HandleFunc("/o/{name:.+}", showontology)
2705 getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2706 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2707 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2708 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2709
2710 getters.HandleFunc("/flag/{code:.+}", showflag)
2711
2712 getters.HandleFunc("/server", serveractor)
2713 posters.HandleFunc("/server/inbox", serverinbox)
2714 posters.HandleFunc("/inbox", serverinbox)
2715
2716 posters.HandleFunc("/csp-violation", fiveoh)
2717
2718 getters.HandleFunc("/style.css", serveviewasset)
2719 getters.HandleFunc("/honkpage.js", serveviewasset)
2720 getters.HandleFunc("/misc.js", serveviewasset)
2721 getters.HandleFunc("/local.css", servedataasset)
2722 getters.HandleFunc("/local.js", servedataasset)
2723 getters.HandleFunc("/icon.png", servedataasset)
2724 getters.HandleFunc("/favicon.ico", servedataasset)
2725
2726 getters.HandleFunc("/about", servehtml)
2727 getters.HandleFunc("/login", servehtml)
2728 posters.HandleFunc("/dologin", login.LoginFunc)
2729 getters.HandleFunc("/logout", login.LogoutFunc)
2730 getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2731
2732 loggedin := mux.NewRoute().Subrouter()
2733 loggedin.Use(login.Required)
2734 loggedin.HandleFunc("/first", homepage)
2735 loggedin.HandleFunc("/chatter", showchatter)
2736 loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2737 loggedin.HandleFunc("/saved", homepage)
2738 loggedin.HandleFunc("/account", accountpage)
2739 loggedin.HandleFunc("/funzone", showfunzone)
2740 loggedin.HandleFunc("/chpass", dochpass)
2741 loggedin.HandleFunc("/atme", homepage)
2742 loggedin.HandleFunc("/longago", homepage)
2743 loggedin.HandleFunc("/hfcs", hfcspage)
2744 loggedin.HandleFunc("/xzone", xzone)
2745 loggedin.HandleFunc("/newhonk", newhonkpage)
2746 loggedin.HandleFunc("/edit", edithonkpage)
2747 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2748 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2749 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2750 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2751 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2752 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2753 loggedin.HandleFunc("/honkers", showhonkers)
2754 loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2755 loggedin.HandleFunc("/h", showhonker)
2756 loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2757 loggedin.HandleFunc("/c", showcombos)
2758 loggedin.HandleFunc("/t", showconvoy)
2759 loggedin.HandleFunc("/q", showsearch)
2760 loggedin.HandleFunc("/hydra", webhydra)
2761 loggedin.HandleFunc("/emus", showemus)
2762 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2763
2764 err = http.Serve(listener, mux)
2765 if err != nil {
2766 elog.Fatal(err)
2767 }
2768}