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: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
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 user, _ := butwhatabout(u.Username)
1823 name := strings.TrimSpace(r.FormValue("name"))
1824 url := strings.TrimSpace(r.FormValue("url"))
1825 peep := r.FormValue("peep")
1826 combos := strings.TrimSpace(r.FormValue("combos"))
1827 combos = " " + combos + " "
1828 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1829
1830 var meta HonkerMeta
1831 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
1832 mj, _ := jsonify(&meta)
1833
1834 defer honkerinvalidator.Clear(u.UserID)
1835
1836 if honkerid > 0 {
1837 goodbye := r.FormValue("goodbye")
1838 if goodbye == "F" {
1839 unfollowyou(user, honkerid)
1840 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1841 return
1842 }
1843 if goodbye == "X" {
1844 followyou(user, honkerid)
1845 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1846 return
1847 }
1848 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
1849 if err != nil {
1850 log.Printf("update honker err: %s", err)
1851 return
1852 }
1853 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1854 return
1855 }
1856
1857 if url == "" {
1858 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1859 return
1860 }
1861
1862 flavor := "presub"
1863 if peep == "peep" {
1864 flavor = "peep"
1865 }
1866
1867 if url[0] == '#' {
1868 flavor = "peep"
1869 if name == "" {
1870 name = url
1871 }
1872 _, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url, mj)
1873 if err != nil {
1874 log.Print(err)
1875 return
1876 }
1877 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1878 return
1879 }
1880
1881 info, err := investigate(url)
1882 if err != nil {
1883 http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1884 log.Printf("failed to investigate honker: %s", err)
1885 return
1886 }
1887 url = info.XID
1888
1889 if name == "" {
1890 name = info.Name
1891 }
1892
1893 var x string
1894 db := opendatabase()
1895 row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1896 err = row.Scan(&x)
1897 if err != sql.ErrNoRows {
1898 http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1899 if err != nil {
1900 log.Printf("honker scan err: %s", err)
1901 }
1902 return
1903 }
1904
1905 res, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner, mj)
1906 if err != nil {
1907 log.Print(err)
1908 return
1909 }
1910 honkerid, _ = res.LastInsertId()
1911 if flavor == "presub" {
1912 followyou(user, honkerid)
1913 }
1914 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1915}
1916
1917func hfcspage(w http.ResponseWriter, r *http.Request) {
1918 userinfo := login.GetUserInfo(r)
1919
1920 filters := getfilters(userinfo.UserID, filtAny)
1921
1922 templinfo := getInfo(r)
1923 templinfo["Filters"] = filters
1924 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1925 err := readviews.Execute(w, "hfcs.html", templinfo)
1926 if err != nil {
1927 log.Print(err)
1928 }
1929}
1930
1931func savehfcs(w http.ResponseWriter, r *http.Request) {
1932 userinfo := login.GetUserInfo(r)
1933 itsok := r.FormValue("itsok")
1934 if itsok == "iforgiveyou" {
1935 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1936 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1937 if err != nil {
1938 log.Printf("error deleting filter: %s", err)
1939 }
1940 filtInvalidator.Clear(userinfo.UserID)
1941 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1942 return
1943 }
1944
1945 filt := new(Filter)
1946 filt.Name = strings.TrimSpace(r.FormValue("name"))
1947 filt.Date = time.Now().UTC()
1948 filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1949 filt.IncludeAudience = r.FormValue("incaud") == "yes"
1950 filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1951 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1952 filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1953 filt.Reject = r.FormValue("doreject") == "yes"
1954 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1955 filt.Hide = r.FormValue("dohide") == "yes"
1956 filt.Collapse = r.FormValue("docollapse") == "yes"
1957 filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1958 filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1959 if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
1960 filt.Expiration = time.Now().UTC().Add(dur)
1961 }
1962 filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
1963
1964 if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
1965 log.Printf("blank filter")
1966 http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
1967 return
1968 }
1969
1970 j, err := jsonify(filt)
1971 if err == nil {
1972 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1973 }
1974 if err != nil {
1975 log.Printf("error saving filter: %s", err)
1976 }
1977
1978 filtInvalidator.Clear(userinfo.UserID)
1979 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1980}
1981
1982func accountpage(w http.ResponseWriter, r *http.Request) {
1983 u := login.GetUserInfo(r)
1984 user, _ := butwhatabout(u.Username)
1985 templinfo := getInfo(r)
1986 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1987 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1988 templinfo["User"] = user
1989 about := user.About
1990 if ava := user.Options.Avatar; ava != "" {
1991 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
1992 }
1993 templinfo["WhatAbout"] = about
1994 err := readviews.Execute(w, "account.html", templinfo)
1995 if err != nil {
1996 log.Print(err)
1997 }
1998}
1999
2000func dochpass(w http.ResponseWriter, r *http.Request) {
2001 err := login.ChangePassword(w, r)
2002 if err != nil {
2003 log.Printf("error changing password: %s", err)
2004 }
2005 http.Redirect(w, r, "/account", http.StatusSeeOther)
2006}
2007
2008func fingerlicker(w http.ResponseWriter, r *http.Request) {
2009 orig := r.FormValue("resource")
2010
2011 log.Printf("finger lick: %s", orig)
2012
2013 if strings.HasPrefix(orig, "acct:") {
2014 orig = orig[5:]
2015 }
2016
2017 name := orig
2018 idx := strings.LastIndexByte(name, '/')
2019 if idx != -1 {
2020 name = name[idx+1:]
2021 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2022 log.Printf("foreign request rejected")
2023 name = ""
2024 }
2025 } else {
2026 idx = strings.IndexByte(name, '@')
2027 if idx != -1 {
2028 name = name[:idx]
2029 if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2030 log.Printf("foreign request rejected")
2031 name = ""
2032 }
2033 }
2034 }
2035 user, err := butwhatabout(name)
2036 if err != nil {
2037 http.NotFound(w, r)
2038 return
2039 }
2040 if stealthmode(user.ID, r) {
2041 http.NotFound(w, r)
2042 return
2043 }
2044
2045 j := junk.New()
2046 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2047 j["aliases"] = []string{user.URL}
2048 l := junk.New()
2049 l["rel"] = "self"
2050 l["type"] = `application/activity+json`
2051 l["href"] = user.URL
2052 j["links"] = []junk.Junk{l}
2053
2054 w.Header().Set("Content-Type", "application/jrd+json")
2055 j.Write(w)
2056}
2057
2058func somedays() string {
2059 secs := 432000 + notrand.Int63n(432000)
2060 return fmt.Sprintf("%d", secs)
2061}
2062
2063func avatate(w http.ResponseWriter, r *http.Request) {
2064 if debugMode {
2065 loadAvatarColors()
2066 }
2067 n := r.FormValue("a")
2068 a := genAvatar(n)
2069 w.Header().Set("Cache-Control", "max-age="+somedays())
2070 w.Write(a)
2071}
2072
2073func serveasset(w http.ResponseWriter, r *http.Request) {
2074 if !debugMode {
2075 w.Header().Set("Cache-Control", "max-age=7776000")
2076 }
2077 dir := viewDir
2078 if r.URL.Path == "/local.css" {
2079 dir = dataDir
2080 }
2081 http.ServeFile(w, r, dir+"/views"+r.URL.Path)
2082}
2083func servehelp(w http.ResponseWriter, r *http.Request) {
2084 name := mux.Vars(r)["name"]
2085 if !debugMode {
2086 w.Header().Set("Cache-Control", "max-age=3600")
2087 }
2088 http.ServeFile(w, r, viewDir+"/docs/"+name)
2089}
2090func servehtml(w http.ResponseWriter, r *http.Request) {
2091 u := login.GetUserInfo(r)
2092 templinfo := getInfo(r)
2093 templinfo["AboutMsg"] = aboutMsg
2094 templinfo["LoginMsg"] = loginMsg
2095 templinfo["HonkVersion"] = softwareVersion
2096 if r.URL.Path == "/about" {
2097 templinfo["Sensors"] = getSensors()
2098 }
2099 if u == nil && !debugMode {
2100 w.Header().Set("Cache-Control", "max-age=60")
2101 }
2102 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2103 if err != nil {
2104 log.Print(err)
2105 }
2106}
2107func serveemu(w http.ResponseWriter, r *http.Request) {
2108 emu := mux.Vars(r)["emu"]
2109
2110 w.Header().Set("Cache-Control", "max-age="+somedays())
2111 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2112}
2113func servememe(w http.ResponseWriter, r *http.Request) {
2114 meme := mux.Vars(r)["meme"]
2115
2116 w.Header().Set("Cache-Control", "max-age="+somedays())
2117 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2118}
2119
2120func servefile(w http.ResponseWriter, r *http.Request) {
2121 xid := mux.Vars(r)["xid"]
2122 var media string
2123 var data []byte
2124 row := stmtGetFileData.QueryRow(xid)
2125 err := row.Scan(&media, &data)
2126 if err != nil {
2127 log.Printf("error loading file: %s", err)
2128 http.NotFound(w, r)
2129 return
2130 }
2131 w.Header().Set("Content-Type", media)
2132 w.Header().Set("X-Content-Type-Options", "nosniff")
2133 w.Header().Set("Cache-Control", "max-age="+somedays())
2134 w.Write(data)
2135}
2136
2137func nomoroboto(w http.ResponseWriter, r *http.Request) {
2138 io.WriteString(w, "User-agent: *\n")
2139 io.WriteString(w, "Disallow: /a\n")
2140 io.WriteString(w, "Disallow: /d/\n")
2141 io.WriteString(w, "Disallow: /meme/\n")
2142 io.WriteString(w, "Disallow: /o\n")
2143 io.WriteString(w, "Disallow: /o/\n")
2144 for _, u := range allusers() {
2145 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2146 }
2147}
2148
2149func webhydra(w http.ResponseWriter, r *http.Request) {
2150 u := login.GetUserInfo(r)
2151 userid := u.UserID
2152 templinfo := getInfo(r)
2153 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2154 page := r.FormValue("page")
2155
2156 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2157
2158 var honks []*Honk
2159 switch page {
2160 case "atme":
2161 honks = gethonksforme(userid, wanted)
2162 honks = osmosis(honks, userid, false)
2163 templinfo["ServerMessage"] = "at me!"
2164 case "longago":
2165 honks = gethonksfromlongago(userid, wanted)
2166 honks = osmosis(honks, userid, false)
2167 templinfo["ServerMessage"] = "from long ago"
2168 case "home":
2169 honks = gethonksforuser(userid, wanted)
2170 honks = osmosis(honks, userid, true)
2171 templinfo["ServerMessage"] = serverMsg
2172 case "first":
2173 honks = gethonksforuserfirstclass(userid, wanted)
2174 honks = osmosis(honks, userid, true)
2175 templinfo["ServerMessage"] = "first class only"
2176 case "saved":
2177 honks = getsavedhonks(userid, wanted)
2178 templinfo["PageName"] = "saved"
2179 templinfo["ServerMessage"] = "saved honks"
2180 case "combo":
2181 c := r.FormValue("c")
2182 honks = gethonksbycombo(userid, c, wanted)
2183 honks = osmosis(honks, userid, false)
2184 templinfo["ServerMessage"] = "honks by combo: " + c
2185 case "convoy":
2186 c := r.FormValue("c")
2187 honks = gethonksbyconvoy(userid, c, wanted)
2188 honks = osmosis(honks, userid, false)
2189 templinfo["ServerMessage"] = "honks in convoy: " + c
2190 case "honker":
2191 xid := r.FormValue("xid")
2192 honks = gethonksbyxonker(userid, xid, wanted)
2193 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
2194 templinfo["ServerMessage"] = msg
2195 default:
2196 http.NotFound(w, r)
2197 }
2198 if len(honks) > 0 {
2199 templinfo["TopHID"] = honks[0].ID
2200 } else {
2201 templinfo["TopHID"] = wanted
2202 }
2203 reverbolate(userid, honks)
2204 templinfo["Honks"] = honks
2205 templinfo["MapLink"] = getmaplink(u)
2206 templinfo["User"], _ = butwhatabout(u.Username)
2207 w.Header().Set("Content-Type", "text/html; charset=utf-8")
2208 err := readviews.Execute(w, "honkfrags.html", templinfo)
2209 if err != nil {
2210 log.Printf("frag error: %s", err)
2211 }
2212}
2213
2214var honkline = make(chan bool)
2215
2216func honkhonkline() {
2217 for {
2218 select {
2219 case honkline <- true:
2220 default:
2221 return
2222 }
2223 }
2224}
2225
2226func apihandler(w http.ResponseWriter, r *http.Request) {
2227 u := login.GetUserInfo(r)
2228 userid := u.UserID
2229 user, _ := butwhatabout(u.Username)
2230 action := r.FormValue("action")
2231 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2232 log.Printf("api request '%s' on behalf of %s", action, u.Username)
2233 switch action {
2234 case "honk":
2235 h := submithonk(w, r)
2236 if h == nil {
2237 return
2238 }
2239 w.Write([]byte(h.XID))
2240 case "donk":
2241 d, err := submitdonk(w, r)
2242 if err != nil {
2243 if err == http.ErrMissingFile {
2244 http.Error(w, "missing donk", http.StatusBadRequest)
2245 }
2246 return
2247 }
2248 w.Write([]byte(d.XID))
2249 case "zonkit":
2250 zonkit(w, r)
2251 case "gethonks":
2252 var honks []*Honk
2253 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2254 page := r.FormValue("page")
2255 var waitchan <-chan time.Time
2256 requery:
2257 switch page {
2258 case "atme":
2259 honks = gethonksforme(userid, wanted)
2260 honks = osmosis(honks, userid, false)
2261 case "longago":
2262 honks = gethonksfromlongago(userid, wanted)
2263 honks = osmosis(honks, userid, false)
2264 case "home":
2265 honks = gethonksforuser(userid, wanted)
2266 honks = osmosis(honks, userid, true)
2267 default:
2268 http.Error(w, "unknown page", http.StatusNotFound)
2269 return
2270 }
2271 if len(honks) == 0 && wait > 0 {
2272 if waitchan == nil {
2273 waitchan = time.After(time.Duration(wait) * time.Second)
2274 }
2275 select {
2276 case <-honkline:
2277 goto requery
2278 case <-waitchan:
2279 }
2280 }
2281 reverbolate(userid, honks)
2282 j := junk.New()
2283 j["honks"] = honks
2284 j.Write(w)
2285 case "sendactivity":
2286 public := r.FormValue("public") == "1"
2287 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2288 msg := []byte(r.FormValue("msg"))
2289 for rcpt := range rcpts {
2290 go deliverate(0, userid, rcpt, msg)
2291 }
2292 default:
2293 http.Error(w, "unknown action", http.StatusNotFound)
2294 return
2295 }
2296}
2297
2298var endoftheworld = make(chan bool)
2299var readyalready = make(chan bool)
2300var workinprogress = 0
2301
2302func enditall() {
2303 sig := make(chan os.Signal)
2304 signal.Notify(sig, os.Interrupt)
2305 signal.Notify(sig, syscall.SIGTERM)
2306 <-sig
2307 log.Printf("stopping...")
2308 for i := 0; i < workinprogress; i++ {
2309 endoftheworld <- true
2310 }
2311 log.Printf("waiting...")
2312 for i := 0; i < workinprogress; i++ {
2313 <-readyalready
2314 }
2315 log.Printf("apocalypse")
2316 os.Exit(0)
2317}
2318
2319var preservehooks []func()
2320
2321func wait100ms() chan struct{} {
2322 c := make(chan struct{})
2323 go func() {
2324 time.Sleep(100 * time.Millisecond)
2325 close(c)
2326 }()
2327 return c
2328}
2329
2330func bgmonitor() {
2331 for {
2332 time.Sleep(50 * time.Minute)
2333 }
2334}
2335
2336func serve() {
2337 db := opendatabase()
2338 login.Init(db)
2339
2340 listener, err := openListener()
2341 if err != nil {
2342 log.Fatal(err)
2343 }
2344 go runBackendServer()
2345 go enditall()
2346 go redeliverator()
2347 go tracker()
2348 go bgmonitor()
2349 w100 := wait100ms()
2350
2351 readviews = templates.Load(debugMode,
2352 viewDir+"/views/honkpage.html",
2353 viewDir+"/views/honkfrags.html",
2354 viewDir+"/views/honkers.html",
2355 viewDir+"/views/chatter.html",
2356 viewDir+"/views/hfcs.html",
2357 viewDir+"/views/combos.html",
2358 viewDir+"/views/honkform.html",
2359 viewDir+"/views/honk.html",
2360 viewDir+"/views/account.html",
2361 viewDir+"/views/about.html",
2362 viewDir+"/views/funzone.html",
2363 viewDir+"/views/login.html",
2364 viewDir+"/views/xzone.html",
2365 viewDir+"/views/msg.html",
2366 viewDir+"/views/header.html",
2367 viewDir+"/views/onts.html",
2368 viewDir+"/views/honkpage.js",
2369 )
2370 if !debugMode {
2371 assets := []string{viewDir + "/views/style.css", dataDir + "/views/local.css", viewDir + "/views/honkpage.js"}
2372 for _, s := range assets {
2373 savedassetparams[s] = getassetparam(s)
2374 }
2375 loadAvatarColors()
2376 }
2377 <-w100
2378
2379 for _, h := range preservehooks {
2380 h()
2381 }
2382
2383 mux := mux.NewRouter()
2384 mux.Use(login.Checker)
2385
2386 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2387
2388 posters := mux.Methods("POST").Subrouter()
2389 getters := mux.Methods("GET").Subrouter()
2390
2391 getters.HandleFunc("/", homepage)
2392 getters.HandleFunc("/home", homepage)
2393 getters.HandleFunc("/front", homepage)
2394 getters.HandleFunc("/events", homepage)
2395 getters.HandleFunc("/robots.txt", nomoroboto)
2396 getters.HandleFunc("/rss", showrss)
2397 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
2398 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showonehonk)
2399 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
2400 posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
2401 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
2402 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
2403 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
2404 getters.HandleFunc("/a", avatate)
2405 getters.HandleFunc("/o", thelistingoftheontologies)
2406 getters.HandleFunc("/o/{name:.+}", showontology)
2407 getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
2408 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2409 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2410 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2411
2412 getters.HandleFunc("/flag/{code:.+}", showflag)
2413
2414 getters.HandleFunc("/server", serveractor)
2415 posters.HandleFunc("/server/inbox", serverinbox)
2416 posters.HandleFunc("/inbox", serverinbox)
2417
2418 getters.HandleFunc("/style.css", serveasset)
2419 getters.HandleFunc("/local.css", serveasset)
2420 getters.HandleFunc("/honkpage.js", serveasset)
2421 getters.HandleFunc("/about", servehtml)
2422 getters.HandleFunc("/login", servehtml)
2423 posters.HandleFunc("/dologin", login.LoginFunc)
2424 getters.HandleFunc("/logout", login.LogoutFunc)
2425 getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
2426
2427 loggedin := mux.NewRoute().Subrouter()
2428 loggedin.Use(login.Required)
2429 loggedin.HandleFunc("/first", homepage)
2430 loggedin.HandleFunc("/chatter", showchatter)
2431 loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2432 loggedin.HandleFunc("/saved", homepage)
2433 loggedin.HandleFunc("/account", accountpage)
2434 loggedin.HandleFunc("/funzone", showfunzone)
2435 loggedin.HandleFunc("/chpass", dochpass)
2436 loggedin.HandleFunc("/atme", homepage)
2437 loggedin.HandleFunc("/longago", homepage)
2438 loggedin.HandleFunc("/hfcs", hfcspage)
2439 loggedin.HandleFunc("/xzone", xzone)
2440 loggedin.HandleFunc("/newhonk", newhonkpage)
2441 loggedin.HandleFunc("/edit", edithonkpage)
2442 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitwebhonk)))
2443 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2444 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2445 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2446 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2447 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2448 loggedin.HandleFunc("/honkers", showhonkers)
2449 loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
2450 loggedin.HandleFunc("/h", showhonker)
2451 loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
2452 loggedin.HandleFunc("/c", showcombos)
2453 loggedin.HandleFunc("/t", showconvoy)
2454 loggedin.HandleFunc("/q", showsearch)
2455 loggedin.HandleFunc("/hydra", webhydra)
2456 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
2457
2458 err = http.Serve(listener, mux)
2459 if err != nil {
2460 log.Fatal(err)
2461 }
2462}