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