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