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