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