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