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