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