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