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