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