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