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