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