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