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 "github.com/sassoftware/relic/lib/dlog"
39 "humungus.tedunangst.com/r/webs/cache"
40 "humungus.tedunangst.com/r/webs/httpsig"
41 "humungus.tedunangst.com/r/webs/junk"
42 "humungus.tedunangst.com/r/webs/login"
43 "humungus.tedunangst.com/r/webs/rss"
44 "humungus.tedunangst.com/r/webs/templates"
45)
46
47var readviews *templates.Template
48
49var userSep = "u"
50var honkSep = "h"
51
52var develMode = false
53
54var allemus []Emu
55
56func getuserstyle(u *login.UserInfo) template.HTMLAttr {
57 if u == nil {
58 return ""
59 }
60 user, _ := butwhatabout(u.Username)
61 class := template.HTMLAttr("")
62 if user.Options.SkinnyCSS {
63 class += `class="skinny"`
64 }
65 return class
66}
67
68func getmaplink(u *login.UserInfo) string {
69 if u == nil {
70 return "osm"
71 }
72 user, _ := butwhatabout(u.Username)
73 ml := user.Options.MapLink
74 if ml == "" {
75 ml = "osm"
76 }
77 return ml
78}
79
80func getInfo(r *http.Request) map[string]interface{} {
81 templinfo := make(map[string]interface{})
82 templinfo["StyleParam"] = getassetparam(viewDir + "/views/style.css")
83 templinfo["LocalStyleParam"] = getassetparam(dataDir + "/views/local.css")
84 templinfo["JSParam"] = getassetparam(viewDir + "/views/honkpage.js")
85 templinfo["LocalJSParam"] = getassetparam(dataDir + "/views/local.js")
86 templinfo["MiscJSParam"] = getassetparam(dataDir + "/views/misc.js")
87 templinfo["ServerName"] = serverName
88 templinfo["IconName"] = iconName
89 templinfo["UserSep"] = userSep
90 if u := login.GetUserInfo(r); u != nil {
91 templinfo["UserInfo"], _ = butwhatabout(u.Username)
92 templinfo["UserStyle"] = getuserstyle(u)
93 var combos []string
94 combocache.Get(u.UserID, &combos)
95 templinfo["Combos"] = combos
96 }
97 return templinfo
98}
99
100func homepage(w http.ResponseWriter, r *http.Request) {
101 templinfo := getInfo(r)
102 u := login.GetUserInfo(r)
103 var honks []*Honk
104 var userid int64 = -1
105
106 templinfo["ServerMessage"] = serverMsg
107 if u == nil || r.URL.Path == "/front" {
108 switch r.URL.Path {
109 case "/events":
110 honks = geteventhonks(userid)
111 templinfo["ServerMessage"] = "some recent and upcoming events"
112 default:
113 templinfo["ShowRSS"] = true
114 honks = getpublichonks()
115 }
116 } else {
117 userid = u.UserID
118 switch r.URL.Path {
119 case "/atme":
120 templinfo["ServerMessage"] = "at me!"
121 templinfo["PageName"] = "atme"
122 honks = gethonksforme(userid, 0)
123 honks = osmosis(honks, userid, false)
124 menewnone(userid)
125 templinfo["UserInfo"], _ = butwhatabout(u.Username)
126 case "/longago":
127 templinfo["ServerMessage"] = "long ago and far away!"
128 templinfo["PageName"] = "longago"
129 honks = gethonksfromlongago(userid, 0)
130 honks = osmosis(honks, userid, false)
131 case "/events":
132 templinfo["ServerMessage"] = "some recent and upcoming events"
133 templinfo["PageName"] = "events"
134 honks = geteventhonks(userid)
135 honks = osmosis(honks, userid, true)
136 case "/first":
137 templinfo["PageName"] = "first"
138 honks = gethonksforuserfirstclass(userid, 0)
139 honks = osmosis(honks, userid, true)
140 case "/saved":
141 templinfo["ServerMessage"] = "saved honks"
142 templinfo["PageName"] = "saved"
143 honks = getsavedhonks(userid, 0)
144 default:
145 templinfo["PageName"] = "home"
146 honks = gethonksforuser(userid, 0)
147 honks = osmosis(honks, userid, true)
148 }
149 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
150 }
151
152 honkpage(w, u, honks, templinfo)
153}
154
155func showemus(w http.ResponseWriter, r *http.Request) {
156 templinfo := getInfo(r)
157 templinfo["Emus"] = allemus
158 err := readviews.Execute(w, "emus.html", templinfo)
159 if err != nil {
160 elog.Print(err)
161 }
162}
163
164func showfunzone(w http.ResponseWriter, r *http.Request) {
165 var emunames, memenames []string
166 emuext := make(map[string]string)
167 dir, err := os.Open(dataDir + "/emus")
168 if err == nil {
169 emunames, _ = dir.Readdirnames(0)
170 dir.Close()
171 }
172 for i, e := range emunames {
173 if len(e) > 4 {
174 emunames[i] = e[:len(e)-4]
175 emuext[emunames[i]] = e[len(e)-4:]
176 }
177 }
178 dir, err = os.Open(dataDir + "/memes")
179 if err == nil {
180 memenames, _ = dir.Readdirnames(0)
181 dir.Close()
182 }
183 sort.Strings(emunames)
184 sort.Strings(memenames)
185 templinfo := getInfo(r)
186 templinfo["Emus"] = emunames
187 templinfo["Emuext"] = emuext
188 templinfo["Memes"] = memenames
189 err = readviews.Execute(w, "funzone.html", templinfo)
190 if err != nil {
191 elog.Print(err)
192 }
193}
194
195func showrss(w http.ResponseWriter, r *http.Request) {
196 name := mux.Vars(r)["name"]
197
198 var honks []*Honk
199 if name != "" {
200 honks = gethonksbyuser(name, false, 0)
201 } else {
202 honks = getpublichonks()
203 }
204 reverbolate(-1, honks)
205
206 home := fmt.Sprintf("https://%s/", serverName)
207 base := home
208 if name != "" {
209 home += "u/" + name
210 name += " "
211 }
212 feed := rss.Feed{
213 Title: name + "honk",
214 Link: home,
215 Description: name + "honk rss",
216 Image: &rss.Image{
217 URL: base + "icon.png",
218 Title: name + "honk rss",
219 Link: home,
220 },
221 }
222 var modtime time.Time
223 for _, honk := range honks {
224 if !firstclass(honk) {
225 continue
226 }
227 desc := string(honk.HTML)
228 if t := honk.Time; t != nil {
229 desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM EDT Mon Jan 02"))
230 if t.Duration != 0 {
231 desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
232 }
233 }
234 if p := honk.Place; p != nil {
235 desc += string(templates.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
236 p.Url, p.Name, p.Latitude, p.Longitude))
237 }
238 for _, d := range honk.Donks {
239 desc += string(templates.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
240 d.URL, d.Desc))
241 if strings.HasPrefix(d.Media, "image") {
242 desc += string(templates.Sprintf(`<img src="%s">`, d.URL))
243 }
244 }
245
246 feed.Items = append(feed.Items, &rss.Item{
247 Title: fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
248 Description: rss.CData{Data: desc},
249 Link: honk.URL,
250 PubDate: honk.Date.Format(time.RFC1123),
251 Guid: &rss.Guid{IsPermaLink: true, Value: honk.URL},
252 })
253 if honk.Date.After(modtime) {
254 modtime = honk.Date
255 }
256 }
257 if !develMode {
258 w.Header().Set("Cache-Control", "max-age=300")
259 w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
260 }
261
262 err := feed.Write(w)
263 if err != nil {
264 elog.Printf("error writing rss: %s", err)
265 }
266}
267
268func crappola(j junk.Junk) bool {
269 t, _ := j.GetString("type")
270 a, _ := j.GetString("actor")
271 o, _ := j.GetString("object")
272 if t == "Delete" && a == o {
273 dlog.Printf("crappola from %s", a)
274 return true
275 }
276 return false
277}
278
279func ping(user *WhatAbout, who string) {
280 if targ := fullname(who, user.ID); targ != "" {
281 who = targ
282 }
283 if !strings.HasPrefix(who, "https:") {
284 who = gofish(who)
285 }
286 if who == "" {
287 ilog.Printf("nobody to ping!")
288 return
289 }
290 var box *Box
291 ok := boxofboxes.Get(who, &box)
292 if !ok {
293 ilog.Printf("no inbox to ping %s", who)
294 return
295 }
296 ilog.Printf("sending ping to %s", box.In)
297 j := junk.New()
298 j["@context"] = itiswhatitis
299 j["type"] = "Ping"
300 j["id"] = user.URL + "/ping/" + xfiltrate()
301 j["actor"] = user.URL
302 j["to"] = who
303 ki := ziggy(user.ID)
304 if ki == nil {
305 return
306 }
307 err := PostJunk(ki.keyname, ki.seckey, box.In, j)
308 if err != nil {
309 elog.Printf("can't send ping: %s", err)
310 return
311 }
312 ilog.Printf("sent ping to %s: %s", who, j["id"])
313}
314
315func pong(user *WhatAbout, who string, obj string) {
316 var box *Box
317 ok := boxofboxes.Get(who, &box)
318 if !ok {
319 ilog.Printf("no inbox to pong %s", who)
320 return
321 }
322 j := junk.New()
323 j["@context"] = itiswhatitis
324 j["type"] = "Pong"
325 j["id"] = user.URL + "/pong/" + xfiltrate()
326 j["actor"] = user.URL
327 j["to"] = who
328 j["object"] = obj
329 ki := ziggy(user.ID)
330 if ki == nil {
331 return
332 }
333 err := PostJunk(ki.keyname, ki.seckey, box.In, j)
334 if err != nil {
335 elog.Printf("can't send pong: %s", err)
336 return
337 }
338}
339
340func inbox(w http.ResponseWriter, r *http.Request) {
341 name := mux.Vars(r)["name"]
342 user, err := butwhatabout(name)
343 if err != nil {
344 http.NotFound(w, r)
345 return
346 }
347 if stealthmode(user.ID, r) {
348 http.NotFound(w, r)
349 return
350 }
351 var buf bytes.Buffer
352 limiter := io.LimitReader(r.Body, 1*1024*1024)
353 io.Copy(&buf, limiter)
354 payload := buf.Bytes()
355 j, err := junk.FromBytes(payload)
356 if err != nil {
357 ilog.Printf("bad payload: %s", err)
358 ilog.Writer().Write(payload)
359 ilog.Writer().Write([]byte{'\n'})
360 return
361 }
362
363 if crappola(j) {
364 return
365 }
366 what, _ := j.GetString("type")
367 obj, _ := j.GetString("object")
368 if what == "Like" || (what == "EmojiReact" && originate(obj) != serverName) {
369 return
370 }
371 who, _ := j.GetString("actor")
372 if rejectactor(user.ID, who) {
373 return
374 }
375
376 keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
377 if err != nil && keyname != "" {
378 savingthrow(keyname)
379 keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
380 }
381 if err != nil {
382 ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
383 if keyname != "" {
384 ilog.Printf("bad signature from %s", keyname)
385 }
386 http.Error(w, "what did you call me?", http.StatusTeapot)
387 return
388 }
389 origin := keymatch(keyname, who)
390 if origin == "" {
391 ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
392 return
393 }
394
395 switch what {
396 case "Ping":
397 id, _ := j.GetString("id")
398 ilog.Printf("ping from %s: %s", who, id)
399 pong(user, who, id)
400 case "Pong":
401 ilog.Printf("pong from %s: %s", who, obj)
402 case "Follow":
403 if obj != user.URL {
404 ilog.Printf("can't follow %s", obj)
405 return
406 }
407 followme(user, who, who, j)
408 case "Accept":
409 followyou2(user, j)
410 case "Reject":
411 nofollowyou2(user, j)
412 case "Update":
413 obj, ok := j.GetMap("object")
414 if ok {
415 what, _ := obj.GetString("type")
416 switch what {
417 case "Service":
418 fallthrough
419 case "Person":
420 return
421 case "Question":
422 return
423 }
424 }
425 go xonksaver(user, j, origin)
426 case "Undo":
427 obj, ok := j.GetMap("object")
428 if !ok {
429 folxid, ok := j.GetString("object")
430 if ok && originate(folxid) == origin {
431 unfollowme(user, "", "", j)
432 }
433 return
434 }
435 what, _ := obj.GetString("type")
436 switch what {
437 case "Follow":
438 unfollowme(user, who, who, j)
439 case "Announce":
440 xid, _ := obj.GetString("object")
441 dlog.Printf("undo announce: %s", xid)
442 case "Like":
443 default:
444 ilog.Printf("unknown undo: %s", what)
445 }
446 case "EmojiReact":
447 obj, ok := j.GetString("object")
448 if ok {
449 content, _ := j.GetString("content")
450 addreaction(user, obj, who, content)
451 }
452 default:
453 go xonksaver(user, j, origin)
454 }
455}
456
457func serverinbox(w http.ResponseWriter, r *http.Request) {
458 user := getserveruser()
459 if stealthmode(user.ID, r) {
460 http.NotFound(w, r)
461 return
462 }
463 var buf bytes.Buffer
464 io.Copy(&buf, r.Body)
465 payload := buf.Bytes()
466 j, err := junk.FromBytes(payload)
467 if err != nil {
468 ilog.Printf("bad payload: %s", err)
469 ilog.Writer().Write(payload)
470 ilog.Writer().Write([]byte{'\n'})
471 return
472 }
473 if crappola(j) {
474 return
475 }
476 keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
477 if err != nil && keyname != "" {
478 savingthrow(keyname)
479 keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
480 }
481 if err != nil {
482 ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
483 if keyname != "" {
484 ilog.Printf("bad signature from %s", keyname)
485 }
486 http.Error(w, "what did you call me?", http.StatusTeapot)
487 return
488 }
489 who, _ := j.GetString("actor")
490 origin := keymatch(keyname, who)
491 if origin == "" {
492 ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
493 return
494 }
495 if rejectactor(user.ID, who) {
496 return
497 }
498 re_ont := regexp.MustCompile("https://" + serverName + "/o/([\\pL[:digit:]]+)")
499 what, _ := j.GetString("type")
500 dlog.Printf("server got a %s", what)
501 switch what {
502 case "Follow":
503 obj, _ := j.GetString("object")
504 if obj == user.URL {
505 ilog.Printf("can't follow the server!")
506 return
507 }
508 m := re_ont.FindStringSubmatch(obj)
509 if len(m) != 2 {
510 ilog.Printf("not sure how to handle this")
511 return
512 }
513 ont := "#" + m[1]
514
515 followme(user, who, ont, j)
516 case "Undo":
517 obj, ok := j.GetMap("object")
518 if !ok {
519 ilog.Printf("unknown undo no object")
520 return
521 }
522 what, _ := obj.GetString("type")
523 if what != "Follow" {
524 ilog.Printf("unknown undo: %s", what)
525 return
526 }
527 targ, _ := obj.GetString("object")
528 m := re_ont.FindStringSubmatch(targ)
529 if len(m) != 2 {
530 ilog.Printf("not sure how to handle this")
531 return
532 }
533 ont := "#" + m[1]
534 unfollowme(user, who, ont, j)
535 default:
536 ilog.Printf("unhandled server activity: %s", what)
537 dumpactivity(j)
538 }
539}
540
541func serveractor(w http.ResponseWriter, r *http.Request) {
542 user := getserveruser()
543 if stealthmode(user.ID, r) {
544 http.NotFound(w, r)
545 return
546 }
547 j := junkuser(user)
548 j.Write(w)
549}
550
551func ximport(w http.ResponseWriter, r *http.Request) {
552 u := login.GetUserInfo(r)
553 xid := strings.TrimSpace(r.FormValue("q"))
554 xonk := getxonk(u.UserID, xid)
555 if xonk == nil {
556 p, _ := investigate(xid)
557 if p != nil {
558 xid = p.XID
559 }
560 j, err := GetJunk(u.UserID, xid)
561 if err != nil {
562 http.Error(w, "error getting external object", http.StatusInternalServerError)
563 ilog.Printf("error getting external object: %s", err)
564 return
565 }
566 allinjest(originate(xid), j)
567 dlog.Printf("importing %s", xid)
568 user, _ := butwhatabout(u.Username)
569
570 info, _ := somethingabout(j)
571 if info == nil {
572 xonk = xonksaver(user, j, originate(xid))
573 } else if info.What == SomeActor {
574 outbox, _ := j.GetString("outbox")
575 gimmexonks(user, outbox)
576 http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
577 return
578 } else if info.What == SomeCollection {
579 gimmexonks(user, xid)
580 http.Redirect(w, r, "/xzone", http.StatusSeeOther)
581 return
582 }
583 }
584 convoy := ""
585 if xonk != nil {
586 convoy = xonk.Convoy
587 }
588 http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
589}
590
591func xzone(w http.ResponseWriter, r *http.Request) {
592 u := login.GetUserInfo(r)
593 rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
594 if err != nil {
595 elog.Printf("query err: %s", err)
596 return
597 }
598 defer rows.Close()
599 var honkers []Honker
600 for rows.Next() {
601 var xid string
602 rows.Scan(&xid)
603 honkers = append(honkers, Honker{XID: xid})
604 }
605 rows.Close()
606 for i, _ := range honkers {
607 _, honkers[i].Handle = handles(honkers[i].XID)
608 }
609 templinfo := getInfo(r)
610 templinfo["XCSRF"] = login.GetCSRF("ximport", r)
611 templinfo["Honkers"] = honkers
612 err = readviews.Execute(w, "xzone.html", templinfo)
613 if err != nil {
614 elog.Print(err)
615 }
616}
617
618var oldoutbox = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
619 user, err := butwhatabout(name)
620 if err != nil {
621 return nil, false
622 }
623 honks := gethonksbyuser(name, false, 0)
624 if len(honks) > 20 {
625 honks = honks[0:20]
626 }
627
628 var jonks []junk.Junk
629 for _, h := range honks {
630 j, _ := jonkjonk(user, h)
631 jonks = append(jonks, j)
632 }
633
634 j := junk.New()
635 j["@context"] = itiswhatitis
636 j["id"] = user.URL + "/outbox"
637 j["attributedTo"] = user.URL
638 j["type"] = "OrderedCollection"
639 j["totalItems"] = len(jonks)
640 j["orderedItems"] = jonks
641
642 return j.ToBytes(), true
643}, Duration: 1 * time.Minute})
644
645func outbox(w http.ResponseWriter, r *http.Request) {
646 name := mux.Vars(r)["name"]
647 user, err := butwhatabout(name)
648 if err != nil {
649 http.NotFound(w, r)
650 return
651 }
652 if stealthmode(user.ID, r) {
653 http.NotFound(w, r)
654 return
655 }
656 var j []byte
657 ok := oldoutbox.Get(name, &j)
658 if ok {
659 w.Header().Set("Content-Type", theonetruename)
660 w.Write(j)
661 } else {
662 http.NotFound(w, r)
663 }
664}
665
666var oldempties = cache.New(cache.Options{Filler: func(url string) ([]byte, bool) {
667 colname := "/followers"
668 if strings.HasSuffix(url, "/following") {
669 colname = "/following"
670 }
671 user := fmt.Sprintf("https://%s%s", serverName, url[:len(url)-10])
672 j := junk.New()
673 j["@context"] = itiswhatitis
674 j["id"] = user + colname
675 j["attributedTo"] = user
676 j["type"] = "OrderedCollection"
677 j["totalItems"] = 0
678 j["orderedItems"] = []junk.Junk{}
679
680 return j.ToBytes(), true
681}})
682
683func emptiness(w http.ResponseWriter, r *http.Request) {
684 name := mux.Vars(r)["name"]
685 user, err := butwhatabout(name)
686 if err != nil {
687 http.NotFound(w, r)
688 return
689 }
690 if stealthmode(user.ID, r) {
691 http.NotFound(w, r)
692 return
693 }
694 var j []byte
695 ok := oldempties.Get(r.URL.Path, &j)
696 if ok {
697 w.Header().Set("Content-Type", theonetruename)
698 w.Write(j)
699 } else {
700 http.NotFound(w, r)
701 }
702}
703
704func showuser(w http.ResponseWriter, r *http.Request) {
705 name := mux.Vars(r)["name"]
706 user, err := butwhatabout(name)
707 if err != nil {
708 ilog.Printf("user not found %s: %s", name, err)
709 http.NotFound(w, r)
710 return
711 }
712 if stealthmode(user.ID, r) {
713 http.NotFound(w, r)
714 return
715 }
716 if friendorfoe(r.Header.Get("Accept")) {
717 j, ok := asjonker(name)
718 if ok {
719 w.Header().Set("Content-Type", theonetruename)
720 w.Write(j)
721 } else {
722 http.NotFound(w, r)
723 }
724 return
725 }
726 u := login.GetUserInfo(r)
727 honks := gethonksbyuser(name, u != nil && u.Username == name, 0)
728 templinfo := getInfo(r)
729 templinfo["PageName"] = "user"
730 templinfo["PageArg"] = name
731 templinfo["Name"] = user.Name
732 templinfo["WhatAbout"] = user.HTAbout
733 templinfo["ServerMessage"] = ""
734 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
735 honkpage(w, u, honks, templinfo)
736}
737
738func showhonker(w http.ResponseWriter, r *http.Request) {
739 u := login.GetUserInfo(r)
740 name := mux.Vars(r)["name"]
741 var honks []*Honk
742 if name == "" {
743 name = r.FormValue("xid")
744 honks = gethonksbyxonker(u.UserID, name, 0)
745 } else {
746 honks = gethonksbyhonker(u.UserID, name, 0)
747 }
748 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
749<input type="hidden" name="CSRF" value="%s">
750<input type="hidden" name="url" value="%s">
751<button tabindex=1 name="add honker" value="add honker">add honker</button>
752</form>`, login.GetCSRF("submithonker", r), name)
753 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, name, name, miniform)
754 templinfo := getInfo(r)
755 templinfo["PageName"] = "honker"
756 templinfo["PageArg"] = name
757 templinfo["ServerMessage"] = msg
758 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
759 honkpage(w, u, honks, templinfo)
760}
761
762func showcombo(w http.ResponseWriter, r *http.Request) {
763 name := mux.Vars(r)["name"]
764 u := login.GetUserInfo(r)
765 honks := gethonksbycombo(u.UserID, name, 0)
766 honks = osmosis(honks, u.UserID, true)
767 templinfo := getInfo(r)
768 templinfo["PageName"] = "combo"
769 templinfo["PageArg"] = name
770 templinfo["ServerMessage"] = "honks by combo: " + name
771 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
772 honkpage(w, u, honks, templinfo)
773}
774func showconvoy(w http.ResponseWriter, r *http.Request) {
775 c := r.FormValue("c")
776 u := login.GetUserInfo(r)
777 honks := gethonksbyconvoy(u.UserID, c, 0)
778 templinfo := getInfo(r)
779 if len(honks) > 0 {
780 templinfo["TopHID"] = honks[0].ID
781 }
782 honks = osmosis(honks, u.UserID, false)
783 //reversehonks(honks)
784 honks = threadsort(honks)
785 templinfo["PageName"] = "convoy"
786 templinfo["PageArg"] = c
787 templinfo["ServerMessage"] = "honks in convoy: " + c
788 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
789 honkpage(w, u, honks, templinfo)
790}
791func showsearch(w http.ResponseWriter, r *http.Request) {
792 q := r.FormValue("q")
793 if strings.HasPrefix(q, "https://") {
794 ximport(w, r)
795 return
796 }
797 u := login.GetUserInfo(r)
798 honks := gethonksbysearch(u.UserID, q, 0)
799 templinfo := getInfo(r)
800 templinfo["PageName"] = "search"
801 templinfo["PageArg"] = q
802 templinfo["ServerMessage"] = "honks for search: " + q
803 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
804 honkpage(w, u, honks, templinfo)
805}
806func showontology(w http.ResponseWriter, r *http.Request) {
807 name := mux.Vars(r)["name"]
808 u := login.GetUserInfo(r)
809 var userid int64 = -1
810 if u != nil {
811 userid = u.UserID
812 }
813 honks := gethonksbyontology(userid, "#"+name, 0)
814 if friendorfoe(r.Header.Get("Accept")) {
815 if len(honks) > 40 {
816 honks = honks[0:40]
817 }
818
819 var xids []string
820 for _, h := range honks {
821 xids = append(xids, h.XID)
822 }
823
824 user := getserveruser()
825
826 j := junk.New()
827 j["@context"] = itiswhatitis
828 j["id"] = fmt.Sprintf("https://%s/o/%s", serverName, name)
829 j["name"] = "#" + name
830 j["attributedTo"] = user.URL
831 j["type"] = "OrderedCollection"
832 j["totalItems"] = len(xids)
833 j["orderedItems"] = xids
834
835 j.Write(w)
836 return
837 }
838
839 templinfo := getInfo(r)
840 templinfo["ServerMessage"] = "honks by ontology: " + name
841 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
842 honkpage(w, u, honks, templinfo)
843}
844
845type Ont struct {
846 Name string
847 Count int64
848}
849
850func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
851 u := login.GetUserInfo(r)
852 var userid int64 = -1
853 if u != nil {
854 userid = u.UserID
855 }
856 rows, err := stmtAllOnts.Query(userid)
857 if err != nil {
858 elog.Printf("selection error: %s", err)
859 return
860 }
861 defer rows.Close()
862 var onts []Ont
863 for rows.Next() {
864 var o Ont
865 err := rows.Scan(&o.Name, &o.Count)
866 if err != nil {
867 elog.Printf("error scanning ont: %s", err)
868 continue
869 }
870 if utf8.RuneCountInString(o.Name) > 24 {
871 continue
872 }
873 o.Name = o.Name[1:]
874 onts = append(onts, o)
875 }
876 sort.Slice(onts, func(i, j int) bool {
877 return onts[i].Name < onts[j].Name
878 })
879 if u == nil && !develMode {
880 w.Header().Set("Cache-Control", "max-age=300")
881 }
882 templinfo := getInfo(r)
883 templinfo["Onts"] = onts
884 templinfo["FirstRune"] = func(s string) rune { r, _ := utf8.DecodeRuneInString(s); return r }
885 err = readviews.Execute(w, "onts.html", templinfo)
886 if err != nil {
887 elog.Print(err)
888 }
889}
890
891type Track struct {
892 xid string
893 who string
894}
895
896func getbacktracks(xid string) []string {
897 c := make(chan bool)
898 dumptracks <- c
899 <-c
900 row := stmtGetTracks.QueryRow(xid)
901 var rawtracks string
902 err := row.Scan(&rawtracks)
903 if err != nil {
904 if err != sql.ErrNoRows {
905 elog.Printf("error scanning tracks: %s", err)
906 }
907 return nil
908 }
909 var rcpts []string
910 for _, f := range strings.Split(rawtracks, " ") {
911 idx := strings.LastIndexByte(f, '#')
912 if idx != -1 {
913 f = f[:idx]
914 }
915 if !strings.HasPrefix(f, "https://") {
916 f = fmt.Sprintf("%%https://%s/inbox", f)
917 }
918 rcpts = append(rcpts, f)
919 }
920 return rcpts
921}
922
923func savetracks(tracks map[string][]string) {
924 db := opendatabase()
925 tx, err := db.Begin()
926 if err != nil {
927 elog.Printf("savetracks begin error: %s", err)
928 return
929 }
930 defer func() {
931 err := tx.Commit()
932 if err != nil {
933 elog.Printf("savetracks commit error: %s", err)
934 }
935
936 }()
937 stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
938 if err != nil {
939 elog.Printf("savetracks error: %s", err)
940 return
941 }
942 stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
943 if err != nil {
944 elog.Printf("savetracks error: %s", err)
945 return
946 }
947 stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
948 if err != nil {
949 elog.Printf("savetracks error: %s", err)
950 return
951 }
952 count := 0
953 for xid, f := range tracks {
954 count += len(f)
955 var prev string
956 row := stmtGetTracks.QueryRow(xid)
957 err := row.Scan(&prev)
958 if err == sql.ErrNoRows {
959 f = oneofakind(f)
960 stmtNewTracks.Exec(xid, strings.Join(f, " "))
961 } else if err == nil {
962 all := append(strings.Split(prev, " "), f...)
963 all = oneofakind(all)
964 stmtUpdateTracks.Exec(strings.Join(all, " "))
965 } else {
966 elog.Printf("savetracks error: %s", err)
967 }
968 }
969 dlog.Printf("saved %d new fetches", count)
970}
971
972var trackchan = make(chan Track)
973var dumptracks = make(chan chan bool)
974
975func tracker() {
976 timeout := 4 * time.Minute
977 sleeper := time.NewTimer(timeout)
978 tracks := make(map[string][]string)
979 workinprogress++
980 for {
981 select {
982 case track := <-trackchan:
983 tracks[track.xid] = append(tracks[track.xid], track.who)
984 case <-sleeper.C:
985 if len(tracks) > 0 {
986 go savetracks(tracks)
987 tracks = make(map[string][]string)
988 }
989 sleeper.Reset(timeout)
990 case c := <-dumptracks:
991 if len(tracks) > 0 {
992 savetracks(tracks)
993 }
994 c <- true
995 case <-endoftheworld:
996 if len(tracks) > 0 {
997 savetracks(tracks)
998 }
999 readyalready <- true
1000 return
1001 }
1002 }
1003}
1004
1005var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
1006
1007func trackback(xid string, r *http.Request) {
1008 agent := r.UserAgent()
1009 who := originate(agent)
1010 sig := r.Header.Get("Signature")
1011 if sig != "" {
1012 m := re_keyholder.FindStringSubmatch(sig)
1013 if len(m) == 2 {
1014 who = m[1]
1015 }
1016 }
1017 if who != "" {
1018 trackchan <- Track{xid: xid, who: who}
1019 }
1020}
1021
1022func threadsort(honks []*Honk) []*Honk {
1023 sort.Slice(honks, func(i, j int) bool {
1024 return honks[i].Date.Before(honks[j].Date)
1025 })
1026 honkx := make(map[string]*Honk)
1027 kids := make(map[string][]*Honk)
1028 for _, h := range honks {
1029 honkx[h.XID] = h
1030 rid := h.RID
1031 kids[rid] = append(kids[rid], h)
1032 }
1033 done := make(map[*Honk]bool)
1034 var thread []*Honk
1035 var nextlevel func(p *Honk)
1036 level := 0
1037 nextlevel = func(p *Honk) {
1038 levelup := level < 4
1039 if pp := honkx[p.RID]; p.RID == "" || (pp != nil && p.Honker == pp.Honker) {
1040 levelup = false
1041 }
1042 if level > 0 && len(kids[p.RID]) == 1 {
1043 if pp := honkx[p.RID]; pp != nil && len(kids[pp.RID]) == 1 {
1044 levelup = false
1045 }
1046 }
1047 if levelup {
1048 level++
1049 }
1050 p.Style += fmt.Sprintf(" level%d", level)
1051 childs := kids[p.XID]
1052 sort.SliceStable(childs, func(i, j int) bool {
1053 return childs[i].Honker == p.Honker && childs[j].Honker != p.Honker
1054 })
1055 for _, h := range childs {
1056 if !done[h] {
1057 done[h] = true
1058 thread = append(thread, h)
1059 nextlevel(h)
1060 }
1061 }
1062 if levelup {
1063 level--
1064 }
1065 }
1066 for _, h := range honks {
1067 if !done[h] && h.RID == "" {
1068 done[h] = true
1069 thread = append(thread, h)
1070 nextlevel(h)
1071 }
1072 }
1073 for _, h := range honks {
1074 if !done[h] {
1075 done[h] = true
1076 thread = append(thread, h)
1077 nextlevel(h)
1078 }
1079 }
1080 return thread
1081}
1082
1083func honkology(honk *Honk) template.HTML {
1084 var user *WhatAbout
1085 ok := somenumberedusers.Get(honk.UserID, &user)
1086 if !ok {
1087 return ""
1088 }
1089 title := fmt.Sprintf("%s: %s", user.Display, honk.Precis)
1090 imgurl := avatarURL(user)
1091 for _, d := range honk.Donks {
1092 if d.Local && strings.HasPrefix(d.Media, "image") {
1093 imgurl = d.URL
1094 break
1095 }
1096 }
1097 short := honk.Noise
1098 if len(short) > 160 {
1099 short = short[0:160] + "..."
1100 }
1101 return templates.Sprintf(
1102 `<meta property="og:title" content="%s" />
1103<meta property="og:type" content="article" />
1104<meta property="article:author" content="%s" />
1105<meta property="og:url" content="%s" />
1106<meta property="og:image" content="%s" />
1107<meta property="og:description" content="%s" />`,
1108 title, user.URL, honk.XID, imgurl, short)
1109}
1110
1111func showonehonk(w http.ResponseWriter, r *http.Request) {
1112 name := mux.Vars(r)["name"]
1113 user, err := butwhatabout(name)
1114 if err != nil {
1115 http.NotFound(w, r)
1116 return
1117 }
1118 if stealthmode(user.ID, r) {
1119 http.NotFound(w, r)
1120 return
1121 }
1122 xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1123
1124 if friendorfoe(r.Header.Get("Accept")) {
1125 j, ok := gimmejonk(xid)
1126 if ok {
1127 trackback(xid, r)
1128 w.Header().Set("Content-Type", theonetruename)
1129 w.Write(j)
1130 } else {
1131 http.NotFound(w, r)
1132 }
1133 return
1134 }
1135 honk := getxonk(user.ID, xid)
1136 if honk == nil {
1137 http.NotFound(w, r)
1138 return
1139 }
1140 u := login.GetUserInfo(r)
1141 if u != nil && u.UserID != user.ID {
1142 u = nil
1143 }
1144 if !honk.Public {
1145 if u == nil {
1146 http.NotFound(w, r)
1147 return
1148
1149 }
1150 honks := []*Honk{honk}
1151 donksforhonks(honks)
1152 templinfo := getInfo(r)
1153 templinfo["ServerMessage"] = "one honk maybe more"
1154 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1155 honkpage(w, u, honks, templinfo)
1156 return
1157 }
1158
1159 templinfo := getInfo(r)
1160 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1161 //reversehonks(rawhonks)
1162 rawhonks = threadsort(rawhonks)
1163 var honks []*Honk
1164 for _, h := range rawhonks {
1165 if h.XID == xid {
1166 templinfo["Honkology"] = honkology(h)
1167 if len(honks) != 0 {
1168 h.Style += " glow"
1169 }
1170 }
1171 if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1172 honks = append(honks, h)
1173 }
1174 }
1175
1176 templinfo["ServerMessage"] = "one honk maybe more"
1177 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1178 templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1179 honkpage(w, u, honks, templinfo)
1180}
1181
1182func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1183 var userid int64 = -1
1184 if u != nil {
1185 userid = u.UserID
1186 templinfo["User"], _ = butwhatabout(u.Username)
1187 }
1188 reverbolate(userid, honks)
1189 templinfo["Honks"] = honks
1190 templinfo["MapLink"] = getmaplink(u)
1191 if templinfo["TopHID"] == nil {
1192 if len(honks) > 0 {
1193 templinfo["TopHID"] = honks[0].ID
1194 } else {
1195 templinfo["TopHID"] = 0
1196 }
1197 }
1198 if u == nil && !develMode {
1199 w.Header().Set("Cache-Control", "max-age=60")
1200 }
1201 err := readviews.Execute(w, "honkpage.html", templinfo)
1202 if err != nil {
1203 elog.Print(err)
1204 }
1205}
1206
1207func saveuser(w http.ResponseWriter, r *http.Request) {
1208 whatabout := r.FormValue("whatabout")
1209 whatabout = strings.Replace(whatabout, "\r", "", -1)
1210 u := login.GetUserInfo(r)
1211 user, _ := butwhatabout(u.Username)
1212 db := opendatabase()
1213
1214 options := user.Options
1215 if r.FormValue("skinny") == "skinny" {
1216 options.SkinnyCSS = true
1217 } else {
1218 options.SkinnyCSS = false
1219 }
1220 if r.FormValue("omitimages") == "omitimages" {
1221 options.OmitImages = true
1222 } else {
1223 options.OmitImages = false
1224 }
1225 if r.FormValue("mentionall") == "mentionall" {
1226 options.MentionAll = true
1227 } else {
1228 options.MentionAll = false
1229 }
1230 if r.FormValue("inlineqts") == "inlineqts" {
1231 options.InlineQuotes = true
1232 } else {
1233 options.InlineQuotes = false
1234 }
1235 if r.FormValue("maps") == "apple" {
1236 options.MapLink = "apple"
1237 } else {
1238 options.MapLink = ""
1239 }
1240 if r.FormValue("displayname") != "" {
1241 options.DisplayName = r.FormValue("displayname")
1242 } else {
1243 options.DisplayName = ""
1244 }
1245 options.Reaction = r.FormValue("reaction")
1246
1247 sendupdate := false
1248 ava := re_avatar.FindString(whatabout)
1249 if ava != "" {
1250 whatabout = re_avatar.ReplaceAllString(whatabout, "")
1251 ava = ava[7:]
1252 if ava[0] == ' ' {
1253 ava = ava[1:]
1254 }
1255 ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1256 }
1257 if ava != options.Avatar {
1258 options.Avatar = ava
1259 sendupdate = true
1260 }
1261 ban := re_banner.FindString(whatabout)
1262 if ban != "" {
1263 whatabout = re_banner.ReplaceAllString(whatabout, "")
1264 ban = ban[7:]
1265 if ban[0] == ' ' {
1266 ban = ban[1:]
1267 }
1268 ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1269 }
1270 if ban != options.Banner {
1271 options.Banner = ban
1272 sendupdate = true
1273 }
1274 whatabout = strings.TrimSpace(whatabout)
1275 if whatabout != user.About {
1276 sendupdate = true
1277 }
1278 j, err := jsonify(options)
1279 if err == nil {
1280 _, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1281 }
1282 if err != nil {
1283 elog.Printf("error bouting what: %s", err)
1284 }
1285 somenamedusers.Clear(u.Username)
1286 somenumberedusers.Clear(u.UserID)
1287 oldjonkers.Clear(u.Username)
1288
1289 if sendupdate {
1290 updateMe(u.Username)
1291 }
1292
1293 http.Redirect(w, r, "/account", http.StatusSeeOther)
1294}
1295
1296func bonkit(xid string, user *WhatAbout) {
1297 dlog.Printf("bonking %s", xid)
1298
1299 xonk := getxonk(user.ID, xid)
1300 if xonk == nil {
1301 return
1302 }
1303 if !xonk.Public {
1304 return
1305 }
1306 if xonk.IsBonked() {
1307 return
1308 }
1309 donksforhonks([]*Honk{xonk})
1310
1311 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1312 if err != nil {
1313 elog.Printf("error acking bonk: %s", err)
1314 }
1315
1316 oonker := xonk.Oonker
1317 if oonker == "" {
1318 oonker = xonk.Honker
1319 }
1320 dt := time.Now().UTC()
1321 bonk := &Honk{
1322 UserID: user.ID,
1323 Username: user.Name,
1324 What: "bonk",
1325 Honker: user.URL,
1326 Oonker: oonker,
1327 XID: xonk.XID,
1328 RID: xonk.RID,
1329 Noise: xonk.Noise,
1330 Precis: xonk.Precis,
1331 URL: xonk.URL,
1332 Date: dt,
1333 Donks: xonk.Donks,
1334 Whofore: 2,
1335 Convoy: xonk.Convoy,
1336 Audience: []string{thewholeworld, oonker},
1337 Public: true,
1338 Format: xonk.Format,
1339 Place: xonk.Place,
1340 Onts: xonk.Onts,
1341 Time: xonk.Time,
1342 }
1343
1344 err = savehonk(bonk)
1345 if err != nil {
1346 elog.Printf("uh oh")
1347 return
1348 }
1349
1350 go honkworldwide(user, bonk)
1351}
1352
1353func submitbonk(w http.ResponseWriter, r *http.Request) {
1354 xid := r.FormValue("xid")
1355 userinfo := login.GetUserInfo(r)
1356 user, _ := butwhatabout(userinfo.Username)
1357
1358 bonkit(xid, user)
1359
1360 if r.FormValue("js") != "1" {
1361 templinfo := getInfo(r)
1362 templinfo["ServerMessage"] = "Bonked!"
1363 err := readviews.Execute(w, "msg.html", templinfo)
1364 if err != nil {
1365 elog.Print(err)
1366 }
1367 }
1368}
1369
1370func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1371 zonk := &Honk{
1372 What: what,
1373 XID: xonk.XID,
1374 Date: time.Now().UTC(),
1375 Audience: oneofakind(xonk.Audience),
1376 Noise: aux,
1377 }
1378 zonk.Public = loudandproud(zonk.Audience)
1379
1380 dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1381 go honkworldwide(user, zonk)
1382}
1383
1384func zonkit(w http.ResponseWriter, r *http.Request) {
1385 wherefore := r.FormValue("wherefore")
1386 what := r.FormValue("what")
1387 userinfo := login.GetUserInfo(r)
1388 user, _ := butwhatabout(userinfo.Username)
1389
1390 if wherefore == "save" {
1391 xonk := getxonk(userinfo.UserID, what)
1392 if xonk != nil {
1393 _, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1394 if err != nil {
1395 elog.Printf("error saving: %s", err)
1396 }
1397 }
1398 return
1399 }
1400
1401 if wherefore == "unsave" {
1402 xonk := getxonk(userinfo.UserID, what)
1403 if xonk != nil {
1404 _, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1405 if err != nil {
1406 elog.Printf("error unsaving: %s", err)
1407 }
1408 }
1409 return
1410 }
1411
1412 if wherefore == "react" {
1413 reaction := user.Options.Reaction
1414 if r2 := r.FormValue("reaction"); r2 != "" {
1415 reaction = r2
1416 }
1417 if reaction == "none" {
1418 return
1419 }
1420 xonk := getxonk(userinfo.UserID, what)
1421 if xonk != nil {
1422 _, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1423 if err != nil {
1424 elog.Printf("error saving: %s", err)
1425 }
1426 sendzonkofsorts(xonk, user, "react", reaction)
1427 }
1428 return
1429 }
1430
1431 // my hammer is too big, oh well
1432 defer oldjonks.Flush()
1433
1434 if wherefore == "ack" {
1435 xonk := getxonk(userinfo.UserID, what)
1436 if xonk != nil && !xonk.IsAcked() {
1437 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1438 if err != nil {
1439 elog.Printf("error acking: %s", err)
1440 }
1441 sendzonkofsorts(xonk, user, "ack", "")
1442 }
1443 return
1444 }
1445
1446 if wherefore == "deack" {
1447 xonk := getxonk(userinfo.UserID, what)
1448 if xonk != nil && xonk.IsAcked() {
1449 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1450 if err != nil {
1451 elog.Printf("error deacking: %s", err)
1452 }
1453 sendzonkofsorts(xonk, user, "deack", "")
1454 }
1455 return
1456 }
1457
1458 if wherefore == "bonk" {
1459 user, _ := butwhatabout(userinfo.Username)
1460 bonkit(what, user)
1461 return
1462 }
1463
1464 if wherefore == "unbonk" {
1465 xonk := getbonk(userinfo.UserID, what)
1466 if xonk != nil {
1467 deletehonk(xonk.ID)
1468 xonk = getxonk(userinfo.UserID, what)
1469 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1470 if err != nil {
1471 elog.Printf("error unbonking: %s", err)
1472 }
1473 sendzonkofsorts(xonk, user, "unbonk", "")
1474 }
1475 return
1476 }
1477
1478 if wherefore == "untag" {
1479 xonk := getxonk(userinfo.UserID, what)
1480 if xonk != nil {
1481 _, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1482 if err != nil {
1483 elog.Printf("error untagging: %s", err)
1484 }
1485 }
1486 var badparents map[string]bool
1487 untagged.GetAndLock(userinfo.UserID, &badparents)
1488 badparents[what] = true
1489 untagged.Unlock()
1490 return
1491 }
1492
1493 ilog.Printf("zonking %s %s", wherefore, what)
1494 if wherefore == "zonk" {
1495 xonk := getxonk(userinfo.UserID, what)
1496 if xonk != nil {
1497 deletehonk(xonk.ID)
1498 if xonk.Whofore == 2 || xonk.Whofore == 3 {
1499 sendzonkofsorts(xonk, user, "zonk", "")
1500 }
1501 }
1502 }
1503 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1504 if err != nil {
1505 elog.Printf("error saving zonker: %s", err)
1506 return
1507 }
1508}
1509
1510func edithonkpage(w http.ResponseWriter, r *http.Request) {
1511 u := login.GetUserInfo(r)
1512 user, _ := butwhatabout(u.Username)
1513 xid := r.FormValue("xid")
1514 honk := getxonk(u.UserID, xid)
1515 if !canedithonk(user, honk) {
1516 http.Error(w, "no editing that please", http.StatusInternalServerError)
1517 return
1518 }
1519
1520 noise := honk.Noise
1521
1522 honks := []*Honk{honk}
1523 donksforhonks(honks)
1524 reverbolate(u.UserID, honks)
1525 templinfo := getInfo(r)
1526 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1527 templinfo["Honks"] = honks
1528 templinfo["MapLink"] = getmaplink(u)
1529 templinfo["Noise"] = noise
1530 templinfo["SavedPlace"] = honk.Place
1531 if tm := honk.Time; tm != nil {
1532 templinfo["ShowTime"] = " "
1533 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1534 if tm.Duration != 0 {
1535 templinfo["Duration"] = tm.Duration
1536 }
1537 }
1538 templinfo["ServerMessage"] = "honk edit 2"
1539 templinfo["IsPreview"] = true
1540 templinfo["UpdateXID"] = honk.XID
1541 if len(honk.Donks) > 0 {
1542 templinfo["SavedFile"] = honk.Donks[0].XID
1543 }
1544 err := readviews.Execute(w, "honkpage.html", templinfo)
1545 if err != nil {
1546 elog.Print(err)
1547 }
1548}
1549
1550func newhonkpage(w http.ResponseWriter, r *http.Request) {
1551 u := login.GetUserInfo(r)
1552 rid := r.FormValue("rid")
1553 noise := ""
1554
1555 xonk := getxonk(u.UserID, rid)
1556 if xonk != nil {
1557 _, replto := handles(xonk.Honker)
1558 if replto != "" {
1559 noise = "@" + replto + " "
1560 }
1561 }
1562
1563 templinfo := getInfo(r)
1564 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1565 templinfo["InReplyTo"] = rid
1566 templinfo["Noise"] = noise
1567 templinfo["ServerMessage"] = "compose honk"
1568 templinfo["IsPreview"] = true
1569 err := readviews.Execute(w, "honkpage.html", templinfo)
1570 if err != nil {
1571 elog.Print(err)
1572 }
1573}
1574
1575func canedithonk(user *WhatAbout, honk *Honk) bool {
1576 if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1577 return false
1578 }
1579 return true
1580}
1581
1582func submitdonk(w http.ResponseWriter, r *http.Request) (*Donk, error) {
1583 if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1584 return nil, nil
1585 }
1586 file, filehdr, err := r.FormFile("donk")
1587 if err != nil {
1588 if err == http.ErrMissingFile {
1589 return nil, nil
1590 }
1591 elog.Printf("error reading donk: %s", err)
1592 http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1593 return nil, err
1594 }
1595 var buf bytes.Buffer
1596 io.Copy(&buf, file)
1597 file.Close()
1598 data := buf.Bytes()
1599 var media, name string
1600 img, err := shrinkit(data)
1601 if err == nil {
1602 data = img.Data
1603 format := img.Format
1604 media = "image/" + format
1605 if format == "jpeg" {
1606 format = "jpg"
1607 }
1608 if format == "svg+xml" {
1609 format = "svg"
1610 }
1611 name = xfiltrate() + "." + format
1612 } else {
1613 ct := http.DetectContentType(data)
1614 switch ct {
1615 case "application/pdf":
1616 maxsize := 10000000
1617 if len(data) > maxsize {
1618 ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1619 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1620 return nil, err
1621 }
1622 media = ct
1623 name = filehdr.Filename
1624 if name == "" {
1625 name = xfiltrate() + ".pdf"
1626 }
1627 default:
1628 maxsize := 100000
1629 if len(data) > maxsize {
1630 ilog.Printf("bad image: %s too much text: %d", err, len(data))
1631 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1632 return nil, err
1633 }
1634 for i := 0; i < len(data); i++ {
1635 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1636 ilog.Printf("bad image: %s not text: %d", err, data[i])
1637 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1638 return nil, err
1639 }
1640 }
1641 media = "text/plain"
1642 name = filehdr.Filename
1643 if name == "" {
1644 name = xfiltrate() + ".txt"
1645 }
1646 }
1647 }
1648 desc := strings.TrimSpace(r.FormValue("donkdesc"))
1649 if desc == "" {
1650 desc = name
1651 }
1652 fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1653 if err != nil {
1654 elog.Printf("unable to save image: %s", err)
1655 http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1656 return nil, err
1657 }
1658 d := &Donk{
1659 FileID: fileid,
1660 XID: xid,
1661 Desc: desc,
1662 Local: true,
1663 }
1664 return d, nil
1665}
1666
1667func websubmithonk(w http.ResponseWriter, r *http.Request) {
1668 h := submithonk(w, r)
1669 if h == nil {
1670 return
1671 }
1672 http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1673}
1674
1675// what a hot mess this function is
1676func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1677 rid := r.FormValue("rid")
1678 noise := r.FormValue("noise")
1679 format := r.FormValue("format")
1680 if format == "" {
1681 format = "markdown"
1682 }
1683 if !(format == "markdown" || format == "html") {
1684 http.Error(w, "unknown format", 500)
1685 return nil
1686 }
1687
1688 userinfo := login.GetUserInfo(r)
1689 user, _ := butwhatabout(userinfo.Username)
1690
1691 dt := time.Now().UTC()
1692 updatexid := r.FormValue("updatexid")
1693 var honk *Honk
1694 if updatexid != "" {
1695 honk = getxonk(userinfo.UserID, updatexid)
1696 if !canedithonk(user, honk) {
1697 http.Error(w, "no editing that please", http.StatusInternalServerError)
1698 return nil
1699 }
1700 honk.Date = dt
1701 honk.What = "update"
1702 honk.Format = format
1703 } else {
1704 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1705 what := "honk"
1706 if rid != "" {
1707 what = "tonk"
1708 }
1709 honk = &Honk{
1710 UserID: userinfo.UserID,
1711 Username: userinfo.Username,
1712 What: what,
1713 Honker: user.URL,
1714 XID: xid,
1715 Date: dt,
1716 Format: format,
1717 }
1718 }
1719
1720 var convoy string
1721 noise = strings.Replace(noise, "\r", "", -1)
1722 if updatexid == "" && rid == "" {
1723 noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1724 convoy = m[7:]
1725 convoy = strings.TrimSpace(convoy)
1726 if !re_convalidate.MatchString(convoy) {
1727 convoy = ""
1728 }
1729 return ""
1730 })
1731 }
1732 noise = quickrename(noise, userinfo.UserID)
1733 noise = hooterize(noise)
1734 honk.Noise = noise
1735 precipitate(honk)
1736 noise = honk.Noise
1737 translate(honk)
1738
1739 if rid != "" {
1740 xonk := getxonk(userinfo.UserID, rid)
1741 if xonk == nil {
1742 http.Error(w, "replyto disappeared", http.StatusNotFound)
1743 return nil
1744 }
1745 if xonk.Public {
1746 honk.Audience = append(honk.Audience, xonk.Audience...)
1747 }
1748 convoy = xonk.Convoy
1749 for i, a := range honk.Audience {
1750 if a == thewholeworld {
1751 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1752 break
1753 }
1754 }
1755 honk.RID = rid
1756 if xonk.Precis != "" && honk.Precis == "" {
1757 honk.Precis = xonk.Precis
1758 if !re_dangerous.MatchString(honk.Precis) {
1759 honk.Precis = "re: " + honk.Precis
1760 }
1761 }
1762 } else {
1763 honk.Audience = []string{thewholeworld}
1764 }
1765 if honk.Noise != "" && honk.Noise[0] == '@' {
1766 honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1767 } else {
1768 honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1769 }
1770
1771 if convoy == "" {
1772 convoy = fmt.Sprintf("data:,%s-", masqName) + xfiltrate()
1773 }
1774 butnottooloud(honk.Audience)
1775 honk.Audience = oneofakind(honk.Audience)
1776 if len(honk.Audience) == 0 {
1777 ilog.Printf("honk to nowhere")
1778 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1779 return nil
1780 }
1781 honk.Public = loudandproud(honk.Audience)
1782 honk.Convoy = convoy
1783
1784 donkxid := r.FormValue("donkxid")
1785 if donkxid == "" {
1786 d, err := submitdonk(w, r)
1787 if err != nil && err != http.ErrMissingFile {
1788 return nil
1789 }
1790 if d != nil {
1791 honk.Donks = append(honk.Donks, d)
1792 donkxid = fmt.Sprintf("%s:%d", d.XID, d.FileID)
1793 }
1794 } else {
1795 p := strings.Split(donkxid, ":")
1796 xid := p[0]
1797 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1798 var donk *Donk
1799 if len(p) > 1 {
1800 fileid, _ := strconv.ParseInt(p[1], 10, 0)
1801 donk = finddonkid(fileid, url)
1802 } else {
1803 donk = finddonk(url)
1804 }
1805 if donk != nil {
1806 honk.Donks = append(honk.Donks, donk)
1807 } else {
1808 ilog.Printf("can't find file: %s", xid)
1809 }
1810 }
1811 memetize(honk)
1812 imaginate(honk)
1813
1814 placename := strings.TrimSpace(r.FormValue("placename"))
1815 placelat := strings.TrimSpace(r.FormValue("placelat"))
1816 placelong := strings.TrimSpace(r.FormValue("placelong"))
1817 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1818 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1819 p := new(Place)
1820 p.Name = placename
1821 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1822 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1823 p.Url = placeurl
1824 honk.Place = p
1825 }
1826 timestart := strings.TrimSpace(r.FormValue("timestart"))
1827 if timestart != "" {
1828 t := new(Time)
1829 now := time.Now().Local()
1830 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1831 start, err := time.ParseInLocation(layout, timestart, now.Location())
1832 if err == nil {
1833 if start.Year() == 0 {
1834 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1835 }
1836 t.StartTime = start
1837 break
1838 }
1839 }
1840 timeend := r.FormValue("timeend")
1841 dur := parseDuration(timeend)
1842 if dur != 0 {
1843 t.Duration = Duration(dur)
1844 }
1845 if !t.StartTime.IsZero() {
1846 honk.What = "event"
1847 honk.Time = t
1848 }
1849 }
1850
1851 if honk.Public {
1852 honk.Whofore = 2
1853 } else {
1854 honk.Whofore = 3
1855 }
1856
1857 // back to markdown
1858 honk.Noise = noise
1859
1860 if r.FormValue("preview") == "preview" {
1861 honks := []*Honk{honk}
1862 reverbolate(userinfo.UserID, honks)
1863 templinfo := getInfo(r)
1864 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1865 templinfo["Honks"] = honks
1866 templinfo["MapLink"] = getmaplink(userinfo)
1867 templinfo["InReplyTo"] = r.FormValue("rid")
1868 templinfo["Noise"] = r.FormValue("noise")
1869 templinfo["SavedFile"] = donkxid
1870 if tm := honk.Time; tm != nil {
1871 templinfo["ShowTime"] = " "
1872 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1873 if tm.Duration != 0 {
1874 templinfo["Duration"] = tm.Duration
1875 }
1876 }
1877 templinfo["IsPreview"] = true
1878 templinfo["UpdateXID"] = updatexid
1879 templinfo["ServerMessage"] = "honk preview"
1880 err := readviews.Execute(w, "honkpage.html", templinfo)
1881 if err != nil {
1882 elog.Print(err)
1883 }
1884 return nil
1885 }
1886
1887 if updatexid != "" {
1888 updatehonk(honk)
1889 oldjonks.Clear(honk.XID)
1890 } else {
1891 err := savehonk(honk)
1892 if err != nil {
1893 elog.Printf("uh oh")
1894 return nil
1895 }
1896 }
1897
1898 // reload for consistency
1899 honk.Donks = nil
1900 donksforhonks([]*Honk{honk})
1901
1902 go honkworldwide(user, honk)
1903
1904 return honk
1905}
1906
1907func showhonkers(w http.ResponseWriter, r *http.Request) {
1908 userinfo := login.GetUserInfo(r)
1909 templinfo := getInfo(r)
1910 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1911 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1912 err := readviews.Execute(w, "honkers.html", templinfo)
1913 if err != nil {
1914 elog.Print(err)
1915 }
1916}
1917
1918func showchatter(w http.ResponseWriter, r *http.Request) {
1919 u := login.GetUserInfo(r)
1920 chatnewnone(u.UserID)
1921 chatter := loadchatter(u.UserID)
1922 for _, chat := range chatter {
1923 for _, ch := range chat.Chonks {
1924 filterchonk(ch)
1925 }
1926 }
1927
1928 templinfo := getInfo(r)
1929 templinfo["Chatter"] = chatter
1930 templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1931 err := readviews.Execute(w, "chatter.html", templinfo)
1932 if err != nil {
1933 elog.Print(err)
1934 }
1935}
1936
1937func submitchonk(w http.ResponseWriter, r *http.Request) {
1938 u := login.GetUserInfo(r)
1939 user, _ := butwhatabout(u.Username)
1940 noise := r.FormValue("noise")
1941 target := r.FormValue("target")
1942 format := "markdown"
1943 dt := time.Now().UTC()
1944 xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1945
1946 if !strings.HasPrefix(target, "https://") {
1947 target = fullname(target, u.UserID)
1948 }
1949 if target == "" {
1950 http.Error(w, "who is that?", http.StatusInternalServerError)
1951 return
1952 }
1953 ch := Chonk{
1954 UserID: u.UserID,
1955 XID: xid,
1956 Who: user.URL,
1957 Target: target,
1958 Date: dt,
1959 Noise: noise,
1960 Format: format,
1961 }
1962 d, err := submitdonk(w, r)
1963 if err != nil && err != http.ErrMissingFile {
1964 return
1965 }
1966 if d != nil {
1967 ch.Donks = append(ch.Donks, d)
1968 }
1969
1970 translatechonk(&ch)
1971 savechonk(&ch)
1972 // reload for consistency
1973 ch.Donks = nil
1974 donksforchonks([]*Chonk{&ch})
1975 go sendchonk(user, &ch)
1976
1977 http.Redirect(w, r, "/chatter", http.StatusSeeOther)
1978}
1979
1980var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1981 honkers := gethonkers(userid)
1982 var combos []string
1983 for _, h := range honkers {
1984 combos = append(combos, h.Combos...)
1985 }
1986 for i, c := range combos {
1987 if c == "-" {
1988 combos[i] = ""
1989 }
1990 }
1991 combos = oneofakind(combos)
1992 sort.Strings(combos)
1993 return combos, true
1994}, Invalidator: &honkerinvalidator})
1995
1996func showcombos(w http.ResponseWriter, r *http.Request) {
1997 userinfo := login.GetUserInfo(r)
1998 var combos []string
1999 combocache.Get(userinfo.UserID, &combos)
2000 templinfo := getInfo(r)
2001 err := readviews.Execute(w, "combos.html", templinfo)
2002 if err != nil {
2003 elog.Print(err)
2004 }
2005}
2006
2007func websubmithonker(w http.ResponseWriter, r *http.Request) {
2008 h := submithonker(w, r)
2009 if h == nil {
2010 return
2011 }
2012 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2013}
2014
2015func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2016 u := login.GetUserInfo(r)
2017 user, _ := butwhatabout(u.Username)
2018 name := strings.TrimSpace(r.FormValue("name"))
2019 url := strings.TrimSpace(r.FormValue("url"))
2020 peep := r.FormValue("peep")
2021 combos := strings.TrimSpace(r.FormValue("combos"))
2022 combos = " " + combos + " "
2023 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2024
2025 re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2026 if name != "" && !re_namecheck.MatchString(name) {
2027 http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2028 return nil
2029 }
2030
2031 var meta HonkerMeta
2032 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2033 mj, _ := jsonify(&meta)
2034
2035 defer honkerinvalidator.Clear(u.UserID)
2036
2037 // mostly dummy, fill in later...
2038 h := &Honker{
2039 ID: honkerid,
2040 }
2041
2042 if honkerid > 0 {
2043 if r.FormValue("delete") == "delete" {
2044 unfollowyou(user, honkerid, false)
2045 stmtDeleteHonker.Exec(honkerid)
2046 return h
2047 }
2048 if r.FormValue("unsub") == "unsub" {
2049 unfollowyou(user, honkerid, false)
2050 }
2051 if r.FormValue("sub") == "sub" {
2052 followyou(user, honkerid, false)
2053 }
2054 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2055 if err != nil {
2056 elog.Printf("update honker err: %s", err)
2057 return nil
2058 }
2059 return h
2060 }
2061
2062 if url == "" {
2063 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2064 return nil
2065 }
2066
2067 flavor := "presub"
2068 if peep == "peep" {
2069 flavor = "peep"
2070 }
2071
2072 var err error
2073 honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2074 if err != nil {
2075 http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2076 return nil
2077 }
2078 if flavor == "presub" {
2079 followyou(user, honkerid, false)
2080 }
2081 h.ID = honkerid
2082 return h
2083}
2084
2085func hfcspage(w http.ResponseWriter, r *http.Request) {
2086 userinfo := login.GetUserInfo(r)
2087
2088 filters := getfilters(userinfo.UserID, filtAny)
2089
2090 templinfo := getInfo(r)
2091 templinfo["Filters"] = filters
2092 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2093 err := readviews.Execute(w, "hfcs.html", templinfo)
2094 if err != nil {
2095 elog.Print(err)
2096 }
2097}
2098
2099func savehfcs(w http.ResponseWriter, r *http.Request) {
2100 userinfo := login.GetUserInfo(r)
2101 itsok := r.FormValue("itsok")
2102 if itsok == "iforgiveyou" {
2103 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2104 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2105 if err != nil {
2106 elog.Printf("error deleting filter: %s", err)
2107 }
2108 filtInvalidator.Clear(userinfo.UserID)
2109 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2110 return
2111 }
2112
2113 filt := new(Filter)
2114 filt.Name = strings.TrimSpace(r.FormValue("name"))
2115 filt.Date = time.Now().UTC()
2116 filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2117 filt.IncludeAudience = r.FormValue("incaud") == "yes"
2118 filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2119 filt.IsReply = r.FormValue("isreply") == "yes"
2120 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2121 filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2122 filt.Reject = r.FormValue("doreject") == "yes"
2123 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2124 filt.Hide = r.FormValue("dohide") == "yes"
2125 filt.Collapse = r.FormValue("docollapse") == "yes"
2126 filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2127 filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2128 if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2129 filt.Expiration = time.Now().UTC().Add(dur)
2130 }
2131 filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2132
2133 if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2134 ilog.Printf("blank filter")
2135 http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2136 return
2137 }
2138
2139 j, err := jsonify(filt)
2140 if err == nil {
2141 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2142 }
2143 if err != nil {
2144 elog.Printf("error saving filter: %s", err)
2145 }
2146
2147 filtInvalidator.Clear(userinfo.UserID)
2148 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2149}
2150
2151func accountpage(w http.ResponseWriter, r *http.Request) {
2152 u := login.GetUserInfo(r)
2153 user, _ := butwhatabout(u.Username)
2154 templinfo := getInfo(r)
2155 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2156 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2157 templinfo["User"] = user
2158 about := user.About
2159 if ava := user.Options.Avatar; ava != "" {
2160 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2161 }
2162 if ban := user.Options.Banner; ban != "" {
2163 about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2164 }
2165 templinfo["WhatAbout"] = about
2166 err := readviews.Execute(w, "account.html", templinfo)
2167 if err != nil {
2168 elog.Print(err)
2169 }
2170}
2171
2172func dochpass(w http.ResponseWriter, r *http.Request) {
2173 err := login.ChangePassword(w, r)
2174 if err != nil {
2175 elog.Printf("error changing password: %s", err)
2176 }
2177 http.Redirect(w, r, "/account", http.StatusSeeOther)
2178}
2179
2180var oldfingers = cache.New(cache.Options{Filler: func(orig string) ([]byte, bool) {
2181 if strings.HasPrefix(orig, "acct:") {
2182 orig = orig[5:]
2183 }
2184 name := orig
2185 idx := strings.LastIndexByte(name, '/')
2186 if idx != -1 {
2187 name = name[idx+1:]
2188 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2189 ilog.Printf("foreign request rejected")
2190 name = ""
2191 }
2192 } else {
2193 idx = strings.IndexByte(name, '@')
2194 if idx != -1 {
2195 name = name[:idx]
2196 if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2197 ilog.Printf("foreign request rejected")
2198 name = ""
2199 }
2200 }
2201 }
2202 user, err := butwhatabout(name)
2203 if err != nil {
2204 return nil, false
2205 }
2206
2207 j := junk.New()
2208 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2209 j["aliases"] = []string{user.URL}
2210 l := junk.New()
2211 l["rel"] = "self"
2212 l["type"] = `application/activity+json`
2213 l["href"] = user.URL
2214 j["links"] = []junk.Junk{l}
2215 return j.ToBytes(), true
2216}})
2217
2218func fingerlicker(w http.ResponseWriter, r *http.Request) {
2219 orig := r.FormValue("resource")
2220
2221 dlog.Printf("finger lick: %s", orig)
2222
2223 var j []byte
2224 ok := oldfingers.Get(orig, &j)
2225 if ok {
2226 w.Header().Set("Content-Type", "application/jrd+json")
2227 w.Write(j)
2228 } else {
2229 http.NotFound(w, r)
2230 }
2231}
2232
2233func somedays() string {
2234 secs := 432000 + notrand.Int63n(432000)
2235 return fmt.Sprintf("%d", secs)
2236}
2237
2238func lookatme(ava string) string {
2239 if strings.Contains(ava, serverName+"/"+userSep) {
2240 idx := strings.LastIndexByte(ava, '/')
2241 if idx < len(ava) {
2242 name := ava[idx+1:]
2243 user, _ := butwhatabout(name)
2244 if user != nil && user.URL == ava {
2245 return user.Options.Avatar
2246 }
2247 }
2248 }
2249 return ""
2250}
2251
2252func avatate(w http.ResponseWriter, r *http.Request) {
2253 if develMode {
2254 loadAvatarColors()
2255 }
2256 var a []byte
2257 n := r.FormValue("a")
2258 if redir := lookatme(n); redir != "" {
2259 http.Redirect(w, r, redir, http.StatusSeeOther)
2260 return
2261 }
2262 a := genAvatar(n)
2263 if !develMode {
2264 w.Header().Set("Cache-Control", "max-age="+somedays())
2265 }
2266
2267 w.Write(a)
2268}
2269
2270func serveviewasset(w http.ResponseWriter, r *http.Request) {
2271 serveasset(w, r, viewDir)
2272}
2273func servedataasset(w http.ResponseWriter, r *http.Request) {
2274 if r.URL.Path == "/favicon.ico" {
2275 r.URL.Path = "/icon.png"
2276 }
2277 serveasset(w, r, dataDir)
2278}
2279
2280func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2281 if !develMode {
2282 w.Header().Set("Cache-Control", "max-age=7776000")
2283 }
2284 http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2285}
2286func servehelp(w http.ResponseWriter, r *http.Request) {
2287 name := mux.Vars(r)["name"]
2288 if !develMode {
2289 w.Header().Set("Cache-Control", "max-age=3600")
2290 }
2291 http.ServeFile(w, r, viewDir+"/docs/"+name)
2292}
2293func servehtml(w http.ResponseWriter, r *http.Request) {
2294 u := login.GetUserInfo(r)
2295 templinfo := getInfo(r)
2296 templinfo["AboutMsg"] = aboutMsg
2297 templinfo["LoginMsg"] = loginMsg
2298 templinfo["HonkVersion"] = softwareVersion
2299 if r.URL.Path == "/about" {
2300 templinfo["Sensors"] = getSensors()
2301 }
2302 if u == nil && !develMode {
2303 w.Header().Set("Cache-Control", "max-age=60")
2304 }
2305 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2306 if err != nil {
2307 elog.Print(err)
2308 }
2309}
2310func serveemu(w http.ResponseWriter, r *http.Request) {
2311 emu := mux.Vars(r)["emu"]
2312
2313 w.Header().Set("Cache-Control", "max-age="+somedays())
2314 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2315}
2316func servememe(w http.ResponseWriter, r *http.Request) {
2317 meme := mux.Vars(r)["meme"]
2318
2319 w.Header().Set("Cache-Control", "max-age="+somedays())
2320 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2321}
2322
2323func servefile(w http.ResponseWriter, r *http.Request) {
2324 xid := mux.Vars(r)["xid"]
2325 var media string
2326 var data []byte
2327 row := stmtGetFileData.QueryRow(xid)
2328 err := row.Scan(&media, &data)
2329 if err != nil {
2330 elog.Printf("error loading file: %s", err)
2331 http.NotFound(w, r)
2332 return
2333 }
2334 w.Header().Set("Content-Type", media)
2335 w.Header().Set("X-Content-Type-Options", "nosniff")
2336 w.Header().Set("Cache-Control", "max-age="+somedays())
2337 w.Write(data)
2338}
2339
2340func nomoroboto(w http.ResponseWriter, r *http.Request) {
2341 io.WriteString(w, "User-agent: *\n")
2342 io.WriteString(w, "Disallow: /a\n")
2343 io.WriteString(w, "Disallow: /d/\n")
2344 io.WriteString(w, "Disallow: /meme/\n")
2345 io.WriteString(w, "Disallow: /o\n")
2346 io.WriteString(w, "Disallow: /o/\n")
2347 io.WriteString(w, "Disallow: /help/\n")
2348 for _, u := range allusers() {
2349 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2350 }
2351}
2352
2353type Hydration struct {
2354 Tophid int64
2355 Srvmsg template.HTML
2356 Honks string
2357 MeCount int64
2358 ChatCount int64
2359}
2360
2361func webhydra(w http.ResponseWriter, r *http.Request) {
2362 u := login.GetUserInfo(r)
2363 userid := u.UserID
2364 templinfo := getInfo(r)
2365 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2366 page := r.FormValue("page")
2367
2368 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2369
2370 var hydra Hydration
2371
2372 var honks []*Honk
2373 switch page {
2374 case "atme":
2375 honks = gethonksforme(userid, wanted)
2376 honks = osmosis(honks, userid, false)
2377 menewnone(userid)
2378 hydra.Srvmsg = "at me!"
2379 case "longago":
2380 honks = gethonksfromlongago(userid, wanted)
2381 honks = osmosis(honks, userid, false)
2382 hydra.Srvmsg = "from long ago"
2383 case "home":
2384 honks = gethonksforuser(userid, wanted)
2385 honks = osmosis(honks, userid, true)
2386 hydra.Srvmsg = serverMsg
2387 case "first":
2388 honks = gethonksforuserfirstclass(userid, wanted)
2389 honks = osmosis(honks, userid, true)
2390 hydra.Srvmsg = "first class only"
2391 case "saved":
2392 honks = getsavedhonks(userid, wanted)
2393 templinfo["PageName"] = "saved"
2394 hydra.Srvmsg = "saved honks"
2395 case "combo":
2396 c := r.FormValue("c")
2397 honks = gethonksbycombo(userid, c, wanted)
2398 honks = osmosis(honks, userid, false)
2399 hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2400 case "convoy":
2401 c := r.FormValue("c")
2402 honks = gethonksbyconvoy(userid, c, wanted)
2403 honks = osmosis(honks, userid, false)
2404 honks = threadsort(honks)
2405 reversehonks(honks)
2406 hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2407 case "honker":
2408 xid := r.FormValue("xid")
2409 honks = gethonksbyxonker(userid, xid, wanted)
2410 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2411 <input type="hidden" name="CSRF" value="%s">
2412 <input type="hidden" name="url" value="%s">
2413 <button tabindex=1 name="add honker" value="add honker">add honker</button>
2414 </form>`, login.GetCSRF("submithonker", r), xid)
2415 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2416 hydra.Srvmsg = msg
2417 case "user":
2418 uname := r.FormValue("uname")
2419 honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2420 hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2421 default:
2422 http.NotFound(w, r)
2423 }
2424
2425 if len(honks) > 0 {
2426 hydra.Tophid = honks[0].ID
2427 } else {
2428 hydra.Tophid = wanted
2429 }
2430 reverbolate(userid, honks)
2431
2432 user, _ := butwhatabout(u.Username)
2433
2434 var buf strings.Builder
2435 templinfo["Honks"] = honks
2436 templinfo["MapLink"] = getmaplink(u)
2437 templinfo["User"], _ = butwhatabout(u.Username)
2438 err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2439 if err != nil {
2440 elog.Printf("frag error: %s", err)
2441 return
2442 }
2443 hydra.Honks = buf.String()
2444 hydra.MeCount = user.Options.MeCount
2445 hydra.ChatCount = user.Options.ChatCount
2446 w.Header().Set("Content-Type", "application/json")
2447 j, _ := jsonify(&hydra)
2448 io.WriteString(w, j)
2449}
2450
2451var honkline = make(chan bool)
2452
2453func honkhonkline() {
2454 for {
2455 select {
2456 case honkline <- true:
2457 default:
2458 return
2459 }
2460 }
2461}
2462
2463func apihandler(w http.ResponseWriter, r *http.Request) {
2464 u := login.GetUserInfo(r)
2465 userid := u.UserID
2466 action := r.FormValue("action")
2467 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2468 dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2469 switch action {
2470 case "honk":
2471 h := submithonk(w, r)
2472 if h == nil {
2473 return
2474 }
2475
2476 fmt.Fprintf(w, "%s", h.XID)
2477 case "donk":
2478 d, err := submitdonk(w, r)
2479 if err != nil {
2480 http.Error(w, err.Error(), http.StatusBadRequest)
2481 return
2482 }
2483 if d == nil {
2484 http.Error(w, "missing donk", http.StatusBadRequest)
2485 return
2486 }
2487 w.Write([]byte(d.XID))
2488 case "zonkit":
2489 zonkit(w, r)
2490 case "gethonks":
2491 var honks []*Honk
2492 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2493 page := r.FormValue("page")
2494 var waitchan <-chan time.Time
2495 requery:
2496 switch page {
2497 case "atme":
2498 honks = gethonksforme(userid, wanted)
2499 honks = osmosis(honks, userid, false)
2500 menewnone(userid)
2501 case "longago":
2502 honks = gethonksfromlongago(userid, wanted)
2503 honks = osmosis(honks, userid, false)
2504 case "home":
2505 honks = gethonksforuser(userid, wanted)
2506 honks = osmosis(honks, userid, true)
2507 case "myhonks":
2508 honks = gethonksbyuser(u.Username, true, wanted)
2509 honks = osmosis(honks, userid, true)
2510 default:
2511 http.Error(w, "unknown page", http.StatusNotFound)
2512 return
2513 }
2514 if len(honks) == 0 && wait > 0 {
2515 if waitchan == nil {
2516 waitchan = time.After(time.Duration(wait) * time.Second)
2517 }
2518 select {
2519 case <-honkline:
2520 goto requery
2521 case <-waitchan:
2522 }
2523 }
2524 reverbolate(userid, honks)
2525 j := junk.New()
2526 j["honks"] = honks
2527 j.Write(w)
2528 case "sendactivity":
2529 user, _ := butwhatabout(u.Username)
2530 public := r.FormValue("public") == "1"
2531 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2532 msg := []byte(r.FormValue("msg"))
2533 for rcpt := range rcpts {
2534 go deliverate(userid, rcpt, msg)
2535 }
2536 case "gethonkers":
2537 j := junk.New()
2538 j["honkers"] = gethonkers(u.UserID)
2539 j.Write(w)
2540 case "savehonker":
2541 h := submithonker(w, r)
2542 if h == nil {
2543 return
2544 }
2545 fmt.Fprintf(w, "%d", h.ID)
2546 default:
2547 http.Error(w, "unknown action", http.StatusNotFound)
2548 return
2549 }
2550}
2551
2552func fiveoh(w http.ResponseWriter, r *http.Request) {
2553 fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2554 if err != nil {
2555 elog.Printf("error opening violations! %s", err)
2556 return
2557 }
2558 defer fd.Close()
2559 io.Copy(fd, r.Body)
2560}
2561
2562var endoftheworld = make(chan bool)
2563var readyalready = make(chan bool)
2564var workinprogress = 0
2565
2566func enditall() {
2567 sig := make(chan os.Signal)
2568 signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
2569 <-sig
2570 ilog.Printf("stopping...")
2571 for i := 0; i < workinprogress; i++ {
2572 endoftheworld <- true
2573 }
2574 ilog.Printf("waiting...")
2575 for i := 0; i < workinprogress; i++ {
2576 <-readyalready
2577 }
2578 ilog.Printf("apocalypse")
2579 os.Exit(0)
2580}
2581
2582var preservehooks []func()
2583
2584func bgmonitor() {
2585 for {
2586 when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2587 _, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2588 if err != nil {
2589 elog.Printf("error deleting old xonkers: %s", err)
2590 }
2591 zaggies.Flush()
2592 time.Sleep(50 * time.Minute)
2593 }
2594}
2595
2596func addcspheaders(next http.Handler) http.Handler {
2597 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2598 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")
2599 next.ServeHTTP(w, r)
2600 })
2601}
2602
2603func emuinit() {
2604 var emunames []string
2605 dir, err := os.Open(dataDir + "/emus")
2606 if err == nil {
2607 emunames, _ = dir.Readdirnames(0)
2608 dir.Close()
2609 }
2610 for _, e := range emunames {
2611 if len(e) <= 4 {
2612 continue
2613 }
2614 ext := e[len(e)-4:]
2615 emu := Emu{
2616 ID: fmt.Sprintf("/emu/%s", e),
2617 Name: e[:len(e)-4],
2618 Type: "image/" + ext[1:],
2619 }
2620 allemus = append(allemus, emu)
2621 }
2622 sort.Slice(allemus, func(i, j int) bool {
2623 return allemus[i].Name < allemus[j].Name
2624 })
2625}
2626
2627func serve() {
2628 db := opendatabase()
2629 login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2630
2631 listener, err := openListener()
2632 if err != nil {
2633 elog.Fatal(err)
2634 }
2635 runBackendServer()
2636 go enditall()
2637 go redeliverator()
2638 go tracker()
2639 go bgmonitor()
2640 loadLingo()
2641 emuinit()
2642
2643 readviews = templates.Load(develMode,
2644 viewDir+"/views/honkpage.html",
2645 viewDir+"/views/honkfrags.html",
2646 viewDir+"/views/honkers.html",
2647 viewDir+"/views/chatter.html",
2648 viewDir+"/views/hfcs.html",
2649 viewDir+"/views/combos.html",
2650 viewDir+"/views/honkform.html",
2651 viewDir+"/views/honk.html",
2652 viewDir+"/views/account.html",
2653 viewDir+"/views/about.html",
2654 viewDir+"/views/funzone.html",
2655 viewDir+"/views/login.html",
2656 viewDir+"/views/xzone.html",
2657 viewDir+"/views/msg.html",
2658 viewDir+"/views/header.html",
2659 viewDir+"/views/onts.html",
2660 viewDir+"/views/emus.html",
2661 viewDir+"/views/honkpage.js",
2662 )
2663 if !develMode {
2664 assets := []string{
2665 viewDir + "/views/style.css",
2666 dataDir + "/views/local.css",
2667 viewDir + "/views/honkpage.js",
2668 dataDir + "/views/local.js",
2669 }
2670 for _, s := range assets {
2671 savedassetparams[s] = getassetparam(s)
2672 }
2673 loadAvatarColors()
2674 }
2675
2676 for _, h := range preservehooks {
2677 h()
2678 }
2679
2680 mux := mux.NewRouter()
2681 mux.Use(addcspheaders)
2682 mux.Use(login.Checker)
2683
2684 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2685
2686 posters := mux.Methods("POST").Subrouter()
2687 getters := mux.Methods("GET").Subrouter()
2688
2689 getters.HandleFunc("/", homepage)
2690 getters.HandleFunc("/home", homepage)
2691 getters.HandleFunc("/front", homepage)
2692 getters.HandleFunc("/events", homepage)
2693 getters.HandleFunc("/robots.txt", nomoroboto)
2694 getters.HandleFunc("/rss", showrss)
2695 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", showuser)
2696 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2697 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2698 posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2699 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2700 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2701 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2702 getters.HandleFunc("/a", avatate)
2703 getters.HandleFunc("/o", thelistingoftheontologies)
2704 getters.HandleFunc("/o/{name:.+}", showontology)
2705 getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2706 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2707 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2708 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2709
2710 getters.HandleFunc("/flag/{code:.+}", showflag)
2711
2712 getters.HandleFunc("/server", serveractor)
2713 posters.HandleFunc("/server/inbox", serverinbox)
2714 posters.HandleFunc("/inbox", serverinbox)
2715
2716 posters.HandleFunc("/csp-violation", fiveoh)
2717
2718 getters.HandleFunc("/style.css", serveviewasset)
2719 getters.HandleFunc("/honkpage.js", serveviewasset)
2720 getters.HandleFunc("/misc.js", serveviewasset)
2721 getters.HandleFunc("/local.css", servedataasset)
2722 getters.HandleFunc("/local.js", servedataasset)
2723 getters.HandleFunc("/icon.png", servedataasset)
2724 getters.HandleFunc("/favicon.ico", servedataasset)
2725
2726 getters.HandleFunc("/about", servehtml)
2727 getters.HandleFunc("/login", servehtml)
2728 posters.HandleFunc("/dologin", login.LoginFunc)
2729 getters.HandleFunc("/logout", login.LogoutFunc)
2730 getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2731
2732 loggedin := mux.NewRoute().Subrouter()
2733 loggedin.Use(login.Required)
2734 loggedin.HandleFunc("/first", homepage)
2735 loggedin.HandleFunc("/chatter", showchatter)
2736 loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2737 loggedin.HandleFunc("/saved", homepage)
2738 loggedin.HandleFunc("/account", accountpage)
2739 loggedin.HandleFunc("/funzone", showfunzone)
2740 loggedin.HandleFunc("/chpass", dochpass)
2741 loggedin.HandleFunc("/atme", homepage)
2742 loggedin.HandleFunc("/longago", homepage)
2743 loggedin.HandleFunc("/hfcs", hfcspage)
2744 loggedin.HandleFunc("/xzone", xzone)
2745 loggedin.HandleFunc("/newhonk", newhonkpage)
2746 loggedin.HandleFunc("/edit", edithonkpage)
2747 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2748 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2749 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2750 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2751 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2752 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2753 loggedin.HandleFunc("/honkers", showhonkers)
2754 loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2755 loggedin.HandleFunc("/h", showhonker)
2756 loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2757 loggedin.HandleFunc("/c", showcombos)
2758 loggedin.HandleFunc("/t", showconvoy)
2759 loggedin.HandleFunc("/q", showsearch)
2760 loggedin.HandleFunc("/hydra", webhydra)
2761 loggedin.HandleFunc("/emus", showemus)
2762 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2763
2764 err = http.Serve(listener, mux)
2765 if err != nil {
2766 elog.Fatal(err)
2767 }
2768}