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"
23 "html/template"
24 "io"
25 "log"
26 notrand "math/rand"
27 "net/http"
28 "net/url"
29 "os"
30 "sort"
31 "strconv"
32 "strings"
33 "time"
34
35 "github.com/gorilla/mux"
36 "humungus.tedunangst.com/r/webs/css"
37 "humungus.tedunangst.com/r/webs/htfilter"
38 "humungus.tedunangst.com/r/webs/httpsig"
39 "humungus.tedunangst.com/r/webs/image"
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
51func getuserstyle(u *login.UserInfo) template.CSS {
52 if u == nil {
53 return ""
54 }
55 user, _ := butwhatabout(u.Username)
56 if user.SkinnyCSS {
57 return "main { max-width: 700px; }"
58 }
59 return ""
60}
61
62func getInfo(r *http.Request) map[string]interface{} {
63 u := login.GetUserInfo(r)
64 templinfo := make(map[string]interface{})
65 templinfo["StyleParam"] = getassetparam("views/style.css")
66 templinfo["LocalStyleParam"] = getassetparam("views/local.css")
67 templinfo["JSParam"] = getassetparam("views/honkpage.js")
68 templinfo["UserStyle"] = getuserstyle(u)
69 templinfo["ServerName"] = serverName
70 templinfo["IconName"] = iconName
71 templinfo["UserInfo"] = u
72 templinfo["UserSep"] = userSep
73 if u != nil {
74 var combos []string
75 combocache.Get(u.UserID, &combos)
76 templinfo["Combos"] = combos
77 }
78 return templinfo
79}
80
81func homepage(w http.ResponseWriter, r *http.Request) {
82 templinfo := getInfo(r)
83 u := login.GetUserInfo(r)
84 var honks []*Honk
85 var userid int64 = -1
86 if r.URL.Path == "/front" || u == nil {
87 honks = getpublichonks()
88 } else {
89 userid = u.UserID
90 if r.URL.Path == "/atme" {
91 templinfo["PageName"] = "atme"
92 honks = gethonksforme(userid)
93 } else if r.URL.Path == "/first" {
94 templinfo["PageName"] = "first"
95 honks = gethonksforuser(userid)
96 honks = osmosis(honks, userid)
97 } else {
98 templinfo["PageName"] = "home"
99 honks = gethonksforuser(userid)
100 honks = osmosis(honks, userid)
101 }
102 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
103 }
104
105 templinfo["ShowRSS"] = true
106 templinfo["ServerMessage"] = serverMsg
107 honkpage(w, u, honks, templinfo)
108}
109
110func showfunzone(w http.ResponseWriter, r *http.Request) {
111 var emunames, memenames []string
112 dir, err := os.Open("emus")
113 if err == nil {
114 emunames, _ = dir.Readdirnames(0)
115 dir.Close()
116 }
117 for i, e := range emunames {
118 if len(e) > 4 {
119 emunames[i] = e[:len(e)-4]
120 }
121 }
122 dir, err = os.Open("memes")
123 if err == nil {
124 memenames, _ = dir.Readdirnames(0)
125 dir.Close()
126 }
127 templinfo := getInfo(r)
128 templinfo["Emus"] = emunames
129 templinfo["Memes"] = memenames
130 err = readviews.Execute(w, "funzone.html", templinfo)
131 if err != nil {
132 log.Print(err)
133 }
134}
135
136func showrss(w http.ResponseWriter, r *http.Request) {
137 name := mux.Vars(r)["name"]
138
139 var honks []*Honk
140 if name != "" {
141 honks = gethonksbyuser(name, false)
142 } else {
143 honks = getpublichonks()
144 }
145 if len(honks) > 20 {
146 honks = honks[0:20]
147 }
148 reverbolate(-1, honks)
149
150 home := fmt.Sprintf("https://%s/", serverName)
151 base := home
152 if name != "" {
153 home += "u/" + name
154 name += " "
155 }
156 feed := rss.Feed{
157 Title: name + "honk",
158 Link: home,
159 Description: name + "honk rss",
160 Image: &rss.Image{
161 URL: base + "icon.png",
162 Title: name + "honk rss",
163 Link: home,
164 },
165 }
166 var modtime time.Time
167 for _, honk := range honks {
168 if !firstclass(honk) {
169 continue
170 }
171 desc := string(honk.HTML)
172 if t := honk.Time; t != nil {
173 desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM EDT Mon Jan 02"))
174 if t.Duration != 0 {
175 desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
176 }
177 }
178 if p := honk.Place; p != nil {
179 desc += fmt.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
180 html.EscapeString(p.Url), html.EscapeString(p.Name), p.Latitude, p.Longitude)
181 }
182 for _, d := range honk.Donks {
183 desc += fmt.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
184 d.URL, html.EscapeString(d.Name))
185 }
186
187 feed.Items = append(feed.Items, &rss.Item{
188 Title: fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
189 Description: rss.CData{Data: desc},
190 Link: honk.URL,
191 PubDate: honk.Date.Format(time.RFC1123),
192 Guid: &rss.Guid{IsPermaLink: true, Value: honk.URL},
193 })
194 if honk.Date.After(modtime) {
195 modtime = honk.Date
196 }
197 }
198 w.Header().Set("Cache-Control", "max-age=300")
199 w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
200
201 err := feed.Write(w)
202 if err != nil {
203 log.Printf("error writing rss: %s", err)
204 }
205}
206
207func crappola(j junk.Junk) bool {
208 t, _ := j.GetString("type")
209 a, _ := j.GetString("actor")
210 o, _ := j.GetString("object")
211 if t == "Delete" && a == o {
212 log.Printf("crappola from %s", a)
213 return true
214 }
215 return false
216}
217
218func ping(user *WhatAbout, who string) {
219 var box *Box
220 ok := boxofboxes.Get(who, &box)
221 if !ok {
222 log.Printf("no inbox to ping %s", who)
223 return
224 }
225 j := junk.New()
226 j["@context"] = itiswhatitis
227 j["type"] = "Ping"
228 j["id"] = user.URL + "/ping/" + xfiltrate()
229 j["actor"] = user.URL
230 j["to"] = who
231 keyname, key := ziggy(user.Name)
232 err := PostJunk(keyname, key, box.In, j)
233 if err != nil {
234 log.Printf("can't send ping: %s", err)
235 return
236 }
237 log.Printf("sent ping to %s: %s", who, j["id"])
238}
239
240func pong(user *WhatAbout, who string, obj string) {
241 var box *Box
242 ok := boxofboxes.Get(who, &box)
243 if !ok {
244 log.Printf("no inbox to pong %s", who)
245 return
246 }
247 j := junk.New()
248 j["@context"] = itiswhatitis
249 j["type"] = "Pong"
250 j["id"] = user.URL + "/pong/" + xfiltrate()
251 j["actor"] = user.URL
252 j["to"] = who
253 j["object"] = obj
254 keyname, key := ziggy(user.Name)
255 err := PostJunk(keyname, key, box.In, j)
256 if err != nil {
257 log.Printf("can't send pong: %s", err)
258 return
259 }
260}
261
262func inbox(w http.ResponseWriter, r *http.Request) {
263 name := mux.Vars(r)["name"]
264 user, err := butwhatabout(name)
265 if err != nil {
266 http.NotFound(w, r)
267 return
268 }
269 if stealthmode(user.ID, r) {
270 http.NotFound(w, r)
271 return
272 }
273 var buf bytes.Buffer
274 io.Copy(&buf, r.Body)
275 payload := buf.Bytes()
276 j, err := junk.Read(bytes.NewReader(payload))
277 if err != nil {
278 log.Printf("bad payload: %s", err)
279 io.WriteString(os.Stdout, "bad payload\n")
280 os.Stdout.Write(payload)
281 io.WriteString(os.Stdout, "\n")
282 return
283 }
284 if crappola(j) {
285 return
286 }
287 keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
288 if err != nil {
289 log.Printf("inbox message failed signature: %s", err)
290 if keyname != "" {
291 keyname, err = makeitworksomehowwithoutregardforkeycontinuity(keyname, r, payload)
292 if err != nil {
293 log.Printf("still failed: %s", err)
294 }
295 }
296 if err != nil {
297 return
298 }
299 }
300 what, _ := j.GetString("type")
301 if what == "Like" {
302 return
303 }
304 who, _ := j.GetString("actor")
305 origin := keymatch(keyname, who)
306 if origin == "" {
307 log.Printf("keyname actor mismatch: %s <> %s", keyname, who)
308 return
309 }
310 if rejectactor(user.ID, who) {
311 return
312 }
313 switch what {
314 case "Ping":
315 obj, _ := j.GetString("id")
316 log.Printf("ping from %s: %s", who, obj)
317 pong(user, who, obj)
318 case "Pong":
319 obj, _ := j.GetString("object")
320 log.Printf("pong from %s: %s", who, obj)
321 case "Follow":
322 obj, _ := j.GetString("object")
323 if obj == user.URL {
324 log.Printf("updating honker follow: %s", who)
325
326 db := opendatabase()
327 row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('dub', 'undub')", who, user.ID)
328 var x string
329 err = row.Scan(&x)
330 if err != sql.ErrNoRows {
331 log.Printf("duplicate follow request: %s", who)
332 _, err = stmtUpdateFlavor.Exec("dub", user.ID, who, "undub")
333 if err != nil {
334 log.Printf("error updating honker: %s", err)
335 }
336 } else {
337 stmtSaveDub.Exec(user.ID, who, who, "dub")
338 }
339 go rubadubdub(user, j)
340 } else {
341 log.Printf("can't follow %s", obj)
342 }
343 case "Accept":
344 log.Printf("updating honker accept: %s", who)
345 _, err = stmtUpdateFlavor.Exec("sub", user.ID, who, "presub")
346 if err != nil {
347 log.Printf("error updating honker: %s", err)
348 return
349 }
350 case "Update":
351 obj, ok := j.GetMap("object")
352 if ok {
353 what, _ := obj.GetString("type")
354 switch what {
355 case "Person":
356 return
357 case "Question":
358 return
359 case "Note":
360 go xonksaver(user, j, origin)
361 return
362 }
363 }
364 log.Printf("unknown Update activity")
365 fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
366 j.Write(fd)
367 io.WriteString(fd, "\n")
368 fd.Close()
369
370 case "Undo":
371 obj, ok := j.GetMap("object")
372 if !ok {
373 log.Printf("unknown undo no object")
374 } else {
375 what, _ := obj.GetString("type")
376 switch what {
377 case "Follow":
378 log.Printf("updating honker undo: %s", who)
379 _, err = stmtUpdateFlavor.Exec("undub", user.ID, who, "dub")
380 if err != nil {
381 log.Printf("error updating honker: %s", err)
382 return
383 }
384 case "Announce":
385 xid, _ := obj.GetString("object")
386 log.Printf("undo announce: %s", xid)
387 case "Like":
388 default:
389 log.Printf("unknown undo: %s", what)
390 }
391 }
392 default:
393 go xonksaver(user, j, origin)
394 }
395}
396
397func ximport(w http.ResponseWriter, r *http.Request) {
398 u := login.GetUserInfo(r)
399 xid := r.FormValue("xid")
400 xonk := getxonk(u.UserID, xid)
401 if xonk == nil {
402 p, _ := investigate(xid)
403 if p != nil {
404 xid = p.XID
405 }
406 j, err := GetJunk(xid)
407 if err != nil {
408 http.Error(w, "error getting external object", http.StatusInternalServerError)
409 log.Printf("error getting external object: %s", err)
410 return
411 }
412 log.Printf("importing %s", xid)
413 user, _ := butwhatabout(u.Username)
414
415 what, _ := j.GetString("type")
416 if isactor(what) {
417 outbox, _ := j.GetString("outbox")
418 gimmexonks(user, outbox)
419 http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
420 return
421 }
422 xonk = xonksaver(user, j, originate(xid))
423 }
424 convoy := ""
425 if xonk != nil {
426 convoy = xonk.Convoy
427 }
428 http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
429}
430
431func xzone(w http.ResponseWriter, r *http.Request) {
432 u := login.GetUserInfo(r)
433 rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
434 if err != nil {
435 log.Printf("query err: %s", err)
436 return
437 }
438 defer rows.Close()
439 var honkers []Honker
440 for rows.Next() {
441 var xid string
442 rows.Scan(&xid)
443 honkers = append(honkers, Honker{XID: xid})
444 }
445 rows.Close()
446 for i, _ := range honkers {
447 _, honkers[i].Handle = handles(honkers[i].XID)
448 }
449 templinfo := getInfo(r)
450 templinfo["XCSRF"] = login.GetCSRF("ximport", r)
451 templinfo["Honkers"] = honkers
452 err = readviews.Execute(w, "xzone.html", templinfo)
453 if err != nil {
454 log.Print(err)
455 }
456}
457
458var oldoutbox = cacheNew(cacheOptions{Filler: func(name string) ([]byte, bool) {
459 user, err := butwhatabout(name)
460 if err != nil {
461 return nil, false
462 }
463 honks := gethonksbyuser(name, false)
464 if len(honks) > 20 {
465 honks = honks[0:20]
466 }
467
468 var jonks []junk.Junk
469 for _, h := range honks {
470 j, _ := jonkjonk(user, h)
471 jonks = append(jonks, j)
472 }
473
474 j := junk.New()
475 j["@context"] = itiswhatitis
476 j["id"] = user.URL + "/outbox"
477 j["type"] = "OrderedCollection"
478 j["totalItems"] = len(jonks)
479 j["orderedItems"] = jonks
480
481 var buf bytes.Buffer
482 j.Write(&buf)
483 return buf.Bytes(), true
484}, Duration: 1 * time.Minute})
485
486func outbox(w http.ResponseWriter, r *http.Request) {
487 name := mux.Vars(r)["name"]
488 user, err := butwhatabout(name)
489 if err != nil {
490 http.NotFound(w, r)
491 return
492 }
493 if stealthmode(user.ID, r) {
494 http.NotFound(w, r)
495 return
496 }
497 var j []byte
498 ok := oldoutbox.Get(name, &j)
499 if ok {
500 w.Header().Set("Content-Type", theonetruename)
501 w.Write(j)
502 } else {
503 http.NotFound(w, r)
504 }
505}
506
507func emptiness(w http.ResponseWriter, r *http.Request) {
508 name := mux.Vars(r)["name"]
509 user, err := butwhatabout(name)
510 if err != nil {
511 http.NotFound(w, r)
512 return
513 }
514 if stealthmode(user.ID, r) {
515 http.NotFound(w, r)
516 return
517 }
518 colname := "/followers"
519 if strings.HasSuffix(r.URL.Path, "/following") {
520 colname = "/following"
521 }
522 j := junk.New()
523 j["@context"] = itiswhatitis
524 j["id"] = user.URL + colname
525 j["type"] = "OrderedCollection"
526 j["totalItems"] = 0
527 j["orderedItems"] = []junk.Junk{}
528
529 w.Header().Set("Content-Type", theonetruename)
530 j.Write(w)
531}
532
533func showuser(w http.ResponseWriter, r *http.Request) {
534 name := mux.Vars(r)["name"]
535 user, err := butwhatabout(name)
536 if err != nil {
537 log.Printf("user not found %s: %s", name, err)
538 http.NotFound(w, r)
539 return
540 }
541 if stealthmode(user.ID, r) {
542 http.NotFound(w, r)
543 return
544 }
545 if friendorfoe(r.Header.Get("Accept")) {
546 j, ok := asjonker(name)
547 if ok {
548 w.Header().Set("Content-Type", theonetruename)
549 w.Write(j)
550 } else {
551 http.NotFound(w, r)
552 }
553 return
554 }
555 u := login.GetUserInfo(r)
556 honks := gethonksbyuser(name, u != nil && u.Username == name)
557 templinfo := getInfo(r)
558 filt := htfilter.New()
559 templinfo["Name"] = user.Name
560 whatabout := user.About
561 whatabout = markitzero(user.About)
562 templinfo["WhatAbout"], _ = filt.String(whatabout)
563 templinfo["ServerMessage"] = ""
564 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
565 honkpage(w, u, honks, templinfo)
566}
567
568func showhonker(w http.ResponseWriter, r *http.Request) {
569 u := login.GetUserInfo(r)
570 name := mux.Vars(r)["name"]
571 var honks []*Honk
572 if name == "" {
573 name = r.FormValue("xid")
574 honks = gethonksbyxonker(u.UserID, name)
575 } else {
576 honks = gethonksbyhonker(u.UserID, name)
577 }
578 name = html.EscapeString(name)
579 msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, name, name)
580 templinfo := getInfo(r)
581 templinfo["PageName"] = "honker"
582 templinfo["PageArg"] = name
583 templinfo["ServerMessage"] = template.HTML(msg)
584 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
585 honkpage(w, u, honks, templinfo)
586}
587
588func showcombo(w http.ResponseWriter, r *http.Request) {
589 name := mux.Vars(r)["name"]
590 u := login.GetUserInfo(r)
591 honks := gethonksbycombo(u.UserID, name)
592 honks = osmosis(honks, u.UserID)
593 templinfo := getInfo(r)
594 templinfo["PageName"] = "combo"
595 templinfo["PageArg"] = name
596 templinfo["ServerMessage"] = "honks by combo: " + name
597 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
598 honkpage(w, u, honks, templinfo)
599}
600func showconvoy(w http.ResponseWriter, r *http.Request) {
601 c := r.FormValue("c")
602 u := login.GetUserInfo(r)
603 honks := gethonksbyconvoy(u.UserID, c)
604 templinfo := getInfo(r)
605 if len(honks) > 0 {
606 templinfo["TopXID"] = honks[0].XID
607 }
608 reversehonks(honks)
609 templinfo["PageName"] = "convoy"
610 templinfo["PageArg"] = c
611 templinfo["ServerMessage"] = "honks in convoy: " + c
612 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
613 honkpage(w, u, honks, templinfo)
614}
615func showsearch(w http.ResponseWriter, r *http.Request) {
616 q := r.FormValue("q")
617 u := login.GetUserInfo(r)
618 honks := gethonksbysearch(u.UserID, q)
619 templinfo := getInfo(r)
620 templinfo["PageName"] = "search"
621 templinfo["PageArg"] = q
622 templinfo["ServerMessage"] = "honks for search: " + q
623 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
624 honkpage(w, u, honks, templinfo)
625}
626func showontology(w http.ResponseWriter, r *http.Request) {
627 name := mux.Vars(r)["name"]
628 u := login.GetUserInfo(r)
629 var userid int64 = -1
630 if u != nil {
631 userid = u.UserID
632 }
633 honks := gethonksbyontology(userid, "#"+name)
634 templinfo := getInfo(r)
635 templinfo["ServerMessage"] = "honks by ontology: " + name
636 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
637 honkpage(w, u, honks, templinfo)
638}
639
640func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
641 u := login.GetUserInfo(r)
642 var userid int64 = -1
643 if u != nil {
644 userid = u.UserID
645 }
646 rows, err := stmtSelectOnts.Query(userid)
647 if err != nil {
648 log.Printf("selection error: %s", err)
649 return
650 }
651 defer rows.Close()
652 var onts [][]string
653 for rows.Next() {
654 var o string
655 err := rows.Scan(&o)
656 if err != nil {
657 log.Printf("error scanning ont: %s", err)
658 continue
659 }
660 onts = append(onts, []string{o, o[1:]})
661 }
662 if u == nil {
663 w.Header().Set("Cache-Control", "max-age=300")
664 }
665 templinfo := getInfo(r)
666 templinfo["Onts"] = onts
667 err = readviews.Execute(w, "onts.html", templinfo)
668 if err != nil {
669 log.Print(err)
670 }
671}
672
673func showhonk(w http.ResponseWriter, r *http.Request) {
674 name := mux.Vars(r)["name"]
675 user, err := butwhatabout(name)
676 if err != nil {
677 http.NotFound(w, r)
678 return
679 }
680 if stealthmode(user.ID, r) {
681 http.NotFound(w, r)
682 return
683 }
684 xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
685
686 if friendorfoe(r.Header.Get("Accept")) {
687 j, ok := gimmejonk(xid)
688 if ok {
689 w.Header().Set("Content-Type", theonetruename)
690 w.Write(j)
691 } else {
692 http.NotFound(w, r)
693 }
694 return
695 }
696 honk := getxonk(user.ID, xid)
697 if honk == nil {
698 http.NotFound(w, r)
699 return
700 }
701 u := login.GetUserInfo(r)
702 if u != nil && u.UserID != user.ID {
703 u = nil
704 }
705 if !honk.Public {
706 if u == nil {
707 http.NotFound(w, r)
708 return
709
710 }
711 templinfo := getInfo(r)
712 templinfo["ServerMessage"] = "one honk maybe more"
713 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
714 honkpage(w, u, []*Honk{honk}, templinfo)
715 return
716 }
717 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
718 reversehonks(rawhonks)
719 var honks []*Honk
720 for _, h := range rawhonks {
721 if h.Public && (h.Whofore == 2 || h.IsAcked()) {
722 honks = append(honks, h)
723 }
724 }
725
726 templinfo := getInfo(r)
727 templinfo["ServerMessage"] = "one honk maybe more"
728 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
729 honkpage(w, u, honks, templinfo)
730}
731
732func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
733 var userid int64 = -1
734 if u != nil {
735 userid = u.UserID
736 }
737 if u == nil {
738 w.Header().Set("Cache-Control", "max-age=60")
739 }
740 reverbolate(userid, honks)
741 templinfo["Honks"] = honks
742 if templinfo["TopXID"] == nil && len(honks) > 0 {
743 templinfo["TopXID"] = honks[0].XID
744 }
745 err := readviews.Execute(w, "honkpage.html", templinfo)
746 if err != nil {
747 log.Print(err)
748 }
749}
750
751func saveuser(w http.ResponseWriter, r *http.Request) {
752 whatabout := r.FormValue("whatabout")
753 u := login.GetUserInfo(r)
754 db := opendatabase()
755 options := ""
756 if r.FormValue("skinny") == "skinny" {
757 options += " skinny "
758 }
759 _, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
760 if err != nil {
761 log.Printf("error bouting what: %s", err)
762 }
763 someusers.Clear(u.Username)
764
765 http.Redirect(w, r, "/account", http.StatusSeeOther)
766}
767
768func submitbonk(w http.ResponseWriter, r *http.Request) {
769 xid := r.FormValue("xid")
770 userinfo := login.GetUserInfo(r)
771 user, _ := butwhatabout(userinfo.Username)
772
773 log.Printf("bonking %s", xid)
774
775 xonk := getxonk(userinfo.UserID, xid)
776 if xonk == nil {
777 return
778 }
779 if !xonk.Public {
780 return
781 }
782 donksforhonks([]*Honk{xonk})
783
784 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
785 if err != nil {
786 log.Printf("error acking bonk: %s", err)
787 }
788
789 oonker := xonk.Oonker
790 if oonker == "" {
791 oonker = xonk.Honker
792 }
793 dt := time.Now().UTC()
794 bonk := Honk{
795 UserID: userinfo.UserID,
796 Username: userinfo.Username,
797 What: "bonk",
798 Honker: user.URL,
799 Oonker: oonker,
800 XID: xonk.XID,
801 RID: xonk.RID,
802 Noise: xonk.Noise,
803 Precis: xonk.Precis,
804 URL: xonk.URL,
805 Date: dt,
806 Donks: xonk.Donks,
807 Whofore: 2,
808 Convoy: xonk.Convoy,
809 Audience: []string{thewholeworld, oonker},
810 Public: true,
811 }
812
813 bonk.Format = "html"
814
815 err = savehonk(&bonk)
816 if err != nil {
817 log.Printf("uh oh")
818 return
819 }
820
821 go honkworldwide(user, &bonk)
822}
823
824func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
825 zonk := Honk{
826 What: what,
827 XID: xonk.XID,
828 Date: time.Now().UTC(),
829 Audience: oneofakind(xonk.Audience),
830 }
831 zonk.Public = !keepitquiet(zonk.Audience)
832
833 log.Printf("announcing %sed honk: %s", what, xonk.XID)
834 go honkworldwide(user, &zonk)
835}
836
837func zonkit(w http.ResponseWriter, r *http.Request) {
838 wherefore := r.FormValue("wherefore")
839 what := r.FormValue("what")
840 userinfo := login.GetUserInfo(r)
841 user, _ := butwhatabout(userinfo.Username)
842
843 // my hammer is too big, oh well
844 defer oldjonks.Flush()
845
846 if wherefore == "ack" {
847 xonk := getxonk(userinfo.UserID, what)
848 if xonk != nil {
849 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
850 if err != nil {
851 log.Printf("error acking: %s", err)
852 }
853 sendzonkofsorts(xonk, user, "ack")
854 }
855 return
856 }
857
858 if wherefore == "deack" {
859 xonk := getxonk(userinfo.UserID, what)
860 if xonk != nil {
861 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
862 if err != nil {
863 log.Printf("error deacking: %s", err)
864 }
865 sendzonkofsorts(xonk, user, "deack")
866 }
867 return
868 }
869
870 if wherefore == "unbonk" {
871 xonk := getbonk(userinfo.UserID, what)
872 if xonk != nil {
873 deletehonk(xonk.ID)
874 xonk = getxonk(userinfo.UserID, what)
875 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
876 if err != nil {
877 log.Printf("error unbonking: %s", err)
878 }
879 sendzonkofsorts(xonk, user, "unbonk")
880 }
881 return
882 }
883
884 log.Printf("zonking %s %s", wherefore, what)
885 if wherefore == "zonk" {
886 xonk := getxonk(userinfo.UserID, what)
887 if xonk != nil {
888 deletehonk(xonk.ID)
889 if xonk.Whofore == 2 || xonk.Whofore == 3 {
890 sendzonkofsorts(xonk, user, "zonk")
891 }
892 }
893 }
894 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
895 if err != nil {
896 log.Printf("error saving zonker: %s", err)
897 return
898 }
899}
900
901func edithonkpage(w http.ResponseWriter, r *http.Request) {
902 u := login.GetUserInfo(r)
903 user, _ := butwhatabout(u.Username)
904 xid := r.FormValue("xid")
905 honk := getxonk(u.UserID, xid)
906 if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
907 log.Printf("no edit")
908 return
909 }
910
911 noise := honk.Noise
912 if honk.Precis != "" {
913 noise = honk.Precis + "\n\n" + noise
914 }
915
916 honks := []*Honk{honk}
917 donksforhonks(honks)
918 reverbolate(u.UserID, honks)
919 templinfo := getInfo(r)
920 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
921 templinfo["Honks"] = honks
922 templinfo["Noise"] = noise
923 templinfo["ServerMessage"] = "honk edit"
924 templinfo["UpdateXID"] = honk.XID
925 if len(honk.Donks) > 0 {
926 templinfo["SavedFile"] = honk.Donks[0].XID
927 }
928 err := readviews.Execute(w, "honkpage.html", templinfo)
929 if err != nil {
930 log.Print(err)
931 }
932}
933
934// what a hot mess this function is
935func submithonk(w http.ResponseWriter, r *http.Request) {
936 rid := r.FormValue("rid")
937 noise := r.FormValue("noise")
938
939 userinfo := login.GetUserInfo(r)
940 user, _ := butwhatabout(userinfo.Username)
941
942 dt := time.Now().UTC()
943 updatexid := r.FormValue("updatexid")
944 var honk *Honk
945 if updatexid != "" {
946 honk = getxonk(userinfo.UserID, updatexid)
947 if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
948 log.Printf("not saving edit")
949 return
950 }
951 honk.Date = dt
952 honk.What = "update"
953 honk.Format = "markdown"
954 } else {
955 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
956 what := "honk"
957 if rid != "" {
958 what = "tonk"
959 }
960 honk = &Honk{
961 UserID: userinfo.UserID,
962 Username: userinfo.Username,
963 What: what,
964 Honker: user.URL,
965 XID: xid,
966 Date: dt,
967 Format: "markdown",
968 }
969 }
970
971 noise = hooterize(noise)
972 honk.Noise = noise
973 translate(honk)
974
975 var convoy string
976 if rid != "" {
977 xonk := getxonk(userinfo.UserID, rid)
978 if xonk != nil {
979 if xonk.Public {
980 honk.Audience = append(honk.Audience, xonk.Audience...)
981 }
982 convoy = xonk.Convoy
983 } else {
984 xonkaud, c := whosthere(rid)
985 honk.Audience = append(honk.Audience, xonkaud...)
986 convoy = c
987 }
988 for i, a := range honk.Audience {
989 if a == thewholeworld {
990 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
991 break
992 }
993 }
994 honk.RID = rid
995 } else {
996 honk.Audience = []string{thewholeworld}
997 }
998 if honk.Noise != "" && honk.Noise[0] == '@' {
999 honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
1000 } else {
1001 honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
1002 }
1003
1004 if convoy == "" {
1005 convoy = "data:,electrichonkytonk-" + xfiltrate()
1006 }
1007 butnottooloud(honk.Audience)
1008 honk.Audience = oneofakind(honk.Audience)
1009 if len(honk.Audience) == 0 {
1010 log.Printf("honk to nowhere")
1011 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1012 return
1013 }
1014 honk.Public = !keepitquiet(honk.Audience)
1015 honk.Convoy = convoy
1016
1017 donkxid := r.FormValue("donkxid")
1018 if donkxid == "" {
1019 file, filehdr, err := r.FormFile("donk")
1020 if err == nil {
1021 var buf bytes.Buffer
1022 io.Copy(&buf, file)
1023 file.Close()
1024 data := buf.Bytes()
1025 xid := xfiltrate()
1026 var media, name string
1027 img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
1028 if err == nil {
1029 data = img.Data
1030 format := img.Format
1031 media = "image/" + format
1032 if format == "jpeg" {
1033 format = "jpg"
1034 }
1035 name = xid + "." + format
1036 xid = name
1037 } else {
1038 maxsize := 100000
1039 if len(data) > maxsize {
1040 log.Printf("bad image: %s too much text: %d", err, len(data))
1041 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1042 return
1043 }
1044 for i := 0; i < len(data); i++ {
1045 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1046 log.Printf("bad image: %s not text: %d", err, data[i])
1047 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1048 return
1049 }
1050 }
1051 media = "text/plain"
1052 name = filehdr.Filename
1053 if name == "" {
1054 name = xid + ".txt"
1055 }
1056 xid += ".txt"
1057 }
1058 desc := r.FormValue("donkdesc")
1059 if desc == "" {
1060 desc = name
1061 }
1062 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1063 fileid, err := savefile(xid, name, desc, url, media, true, data)
1064 if err != nil {
1065 log.Printf("unable to save image: %s", err)
1066 return
1067 }
1068 var d Donk
1069 d.FileID = fileid
1070 honk.Donks = append(honk.Donks, &d)
1071 donkxid = d.XID
1072 }
1073 } else {
1074 xid := donkxid
1075 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1076 donk := finddonk(url)
1077 if donk != nil {
1078 honk.Donks = append(honk.Donks, donk)
1079 } else {
1080 log.Printf("can't find file: %s", xid)
1081 }
1082 }
1083 herd := herdofemus(honk.Noise)
1084 for _, e := range herd {
1085 donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1086 if donk != nil {
1087 donk.Name = e.Name
1088 honk.Donks = append(honk.Donks, donk)
1089 }
1090 }
1091 memetize(honk)
1092
1093 placename := r.FormValue("placename")
1094 placelat := r.FormValue("placelat")
1095 placelong := r.FormValue("placelong")
1096 if placename != "" || placelat != "" || placelong != "" {
1097 p := new(Place)
1098 p.Name = placename
1099 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1100 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1101 p.Url = r.FormValue("placeurl")
1102 honk.Place = p
1103 }
1104 timestart := r.FormValue("timestart")
1105 if timestart != "" {
1106 t := new(Time)
1107 now := time.Now().Local()
1108 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1109 start, err := time.ParseInLocation(layout, timestart, now.Location())
1110 if err == nil {
1111 if start.Year() == 0 {
1112 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1113 }
1114 t.StartTime = start
1115 break
1116 }
1117 }
1118 timeend := r.FormValue("timeend")
1119 dur, err := time.ParseDuration(timeend)
1120 if err == nil {
1121 t.Duration = Duration(dur)
1122 }
1123 if !t.StartTime.IsZero() {
1124 honk.What = "event"
1125 honk.Time = t
1126 }
1127 }
1128
1129 if honk.Public {
1130 honk.Whofore = 2
1131 } else {
1132 honk.Whofore = 3
1133 }
1134
1135 // back to markdown
1136 honk.Noise = noise
1137
1138 if r.FormValue("preview") == "preview" {
1139 honks := []*Honk{honk}
1140 reverbolate(userinfo.UserID, honks)
1141 templinfo := getInfo(r)
1142 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1143 templinfo["Honks"] = honks
1144 templinfo["InReplyTo"] = r.FormValue("rid")
1145 templinfo["Noise"] = r.FormValue("noise")
1146 templinfo["SavedFile"] = donkxid
1147 templinfo["ServerMessage"] = "honk preview"
1148 err := readviews.Execute(w, "honkpage.html", templinfo)
1149 if err != nil {
1150 log.Print(err)
1151 }
1152 return
1153 }
1154
1155 if updatexid != "" {
1156 updatehonk(honk)
1157 oldjonks.Clear(honk.XID)
1158 } else {
1159 err := savehonk(honk)
1160 if err != nil {
1161 log.Printf("uh oh")
1162 return
1163 }
1164 }
1165
1166 // reload for consistency
1167 honk.Donks = nil
1168 donksforhonks([]*Honk{honk})
1169
1170 go honkworldwide(user, honk)
1171
1172 http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1173}
1174
1175func showhonkers(w http.ResponseWriter, r *http.Request) {
1176 userinfo := login.GetUserInfo(r)
1177 templinfo := getInfo(r)
1178 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1179 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1180 err := readviews.Execute(w, "honkers.html", templinfo)
1181 if err != nil {
1182 log.Print(err)
1183 }
1184}
1185
1186var combocache = cacheNew(cacheOptions{Filler: func(userid int64) ([]string, bool) {
1187 honkers := gethonkers(userid)
1188 var combos []string
1189 for _, h := range honkers {
1190 combos = append(combos, h.Combos...)
1191 }
1192 for i, c := range combos {
1193 if c == "-" {
1194 combos[i] = ""
1195 }
1196 }
1197 combos = oneofakind(combos)
1198 sort.Strings(combos)
1199 return combos, true
1200}})
1201
1202func showcombos(w http.ResponseWriter, r *http.Request) {
1203 userinfo := login.GetUserInfo(r)
1204 var combos []string
1205 combocache.Get(userinfo.UserID, &combos)
1206 templinfo := getInfo(r)
1207 err := readviews.Execute(w, "combos.html", templinfo)
1208 if err != nil {
1209 log.Print(err)
1210 }
1211}
1212
1213func submithonker(w http.ResponseWriter, r *http.Request) {
1214 u := login.GetUserInfo(r)
1215 name := r.FormValue("name")
1216 url := r.FormValue("url")
1217 peep := r.FormValue("peep")
1218 combos := r.FormValue("combos")
1219 combos = " " + strings.TrimSpace(combos) + " "
1220 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1221
1222 defer combocache.Clear(u.UserID)
1223
1224 if honkerid > 0 {
1225 goodbye := r.FormValue("goodbye")
1226 if goodbye == "F" {
1227 db := opendatabase()
1228 row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1229 honkerid, u.UserID)
1230 err := row.Scan(&url)
1231 if err != nil {
1232 log.Printf("can't get honker xid: %s", err)
1233 return
1234 }
1235 log.Printf("unsubscribing from %s", url)
1236 user, _ := butwhatabout(u.Username)
1237 _, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, "sub")
1238 if err != nil {
1239 log.Printf("error updating honker: %s", err)
1240 return
1241 }
1242 go itakeitallback(user, url)
1243
1244 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1245 return
1246 }
1247 if goodbye == "X" {
1248 db := opendatabase()
1249 row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1250 honkerid, u.UserID)
1251 err := row.Scan(&url)
1252 if err != nil {
1253 log.Printf("can't get honker xid: %s", err)
1254 return
1255 }
1256 log.Printf("resubscribing to %s", url)
1257 user, _ := butwhatabout(u.Username)
1258 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "unsub")
1259 if err == nil {
1260 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "peep")
1261 }
1262 if err != nil {
1263 log.Printf("error updating honker: %s", err)
1264 return
1265 }
1266 go subsub(user, url)
1267
1268 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1269 return
1270 }
1271 _, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1272 if err != nil {
1273 log.Printf("update honker err: %s", err)
1274 return
1275 }
1276 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1277 return
1278 }
1279
1280 flavor := "presub"
1281 if peep == "peep" {
1282 flavor = "peep"
1283 }
1284 p, err := investigate(url)
1285 if err != nil {
1286 http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1287 log.Printf("failed to investigate honker: %s", err)
1288 return
1289 }
1290 url = p.XID
1291
1292 db := opendatabase()
1293 row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1294 var x string
1295 err = row.Scan(&x)
1296 if err != sql.ErrNoRows {
1297 http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1298 if err != nil {
1299 log.Printf("honker scan err: %s", err)
1300 }
1301 return
1302 }
1303
1304 if name == "" {
1305 name = p.Handle
1306 }
1307 _, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1308 if err != nil {
1309 log.Print(err)
1310 return
1311 }
1312 if flavor == "presub" {
1313 user, _ := butwhatabout(u.Username)
1314 go subsub(user, url)
1315 }
1316 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1317}
1318
1319func hfcspage(w http.ResponseWriter, r *http.Request) {
1320 userinfo := login.GetUserInfo(r)
1321
1322 filters := getfilters(userinfo.UserID, filtAny)
1323
1324 templinfo := getInfo(r)
1325 templinfo["Filters"] = filters
1326 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1327 err := readviews.Execute(w, "hfcs.html", templinfo)
1328 if err != nil {
1329 log.Print(err)
1330 }
1331}
1332
1333func savehfcs(w http.ResponseWriter, r *http.Request) {
1334 userinfo := login.GetUserInfo(r)
1335 itsok := r.FormValue("itsok")
1336 if itsok == "iforgiveyou" {
1337 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1338 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1339 if err != nil {
1340 log.Printf("error deleting filter: %s", err)
1341 }
1342 filtcache.Clear(userinfo.UserID)
1343 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1344 return
1345 }
1346
1347 filt := new(Filter)
1348 filt.Name = r.FormValue("name")
1349 filt.Date = time.Now().UTC()
1350 filt.Actor = r.FormValue("actor")
1351 filt.IncludeAudience = r.FormValue("incaud") == "yes"
1352 filt.Text = r.FormValue("filttext")
1353 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1354 filt.AnnounceOf = r.FormValue("announceof")
1355 filt.Reject = r.FormValue("doreject") == "yes"
1356 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1357 filt.Hide = r.FormValue("dohide") == "yes"
1358 filt.Collapse = r.FormValue("docollapse") == "yes"
1359 filt.Rewrite = r.FormValue("filtrewrite")
1360 filt.Replace = r.FormValue("filtreplace")
1361
1362 if filt.Actor == "" && filt.Text == "" {
1363 log.Printf("blank filter")
1364 return
1365 }
1366
1367 j, err := jsonify(filt)
1368 if err == nil {
1369 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1370 }
1371 if err != nil {
1372 log.Printf("error saving filter: %s", err)
1373 }
1374
1375 filtcache.Clear(userinfo.UserID)
1376 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1377}
1378
1379func accountpage(w http.ResponseWriter, r *http.Request) {
1380 u := login.GetUserInfo(r)
1381 user, _ := butwhatabout(u.Username)
1382 templinfo := getInfo(r)
1383 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1384 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1385 templinfo["User"] = user
1386 err := readviews.Execute(w, "account.html", templinfo)
1387 if err != nil {
1388 log.Print(err)
1389 }
1390}
1391
1392func dochpass(w http.ResponseWriter, r *http.Request) {
1393 err := login.ChangePassword(w, r)
1394 if err != nil {
1395 log.Printf("error changing password: %s", err)
1396 }
1397 http.Redirect(w, r, "/account", http.StatusSeeOther)
1398}
1399
1400func fingerlicker(w http.ResponseWriter, r *http.Request) {
1401 orig := r.FormValue("resource")
1402
1403 log.Printf("finger lick: %s", orig)
1404
1405 if strings.HasPrefix(orig, "acct:") {
1406 orig = orig[5:]
1407 }
1408
1409 name := orig
1410 idx := strings.LastIndexByte(name, '/')
1411 if idx != -1 {
1412 name = name[idx+1:]
1413 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1414 log.Printf("foreign request rejected")
1415 name = ""
1416 }
1417 } else {
1418 idx = strings.IndexByte(name, '@')
1419 if idx != -1 {
1420 name = name[:idx]
1421 if name+"@"+serverName != orig {
1422 log.Printf("foreign request rejected")
1423 name = ""
1424 }
1425 }
1426 }
1427 user, err := butwhatabout(name)
1428 if err != nil {
1429 http.NotFound(w, r)
1430 return
1431 }
1432 if stealthmode(user.ID, r) {
1433 http.NotFound(w, r)
1434 return
1435 }
1436
1437 j := junk.New()
1438 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1439 j["aliases"] = []string{user.URL}
1440 var links []junk.Junk
1441 l := junk.New()
1442 l["rel"] = "self"
1443 l["type"] = `application/activity+json`
1444 l["href"] = user.URL
1445 links = append(links, l)
1446 j["links"] = links
1447
1448 w.Header().Set("Cache-Control", "max-age=3600")
1449 w.Header().Set("Content-Type", "application/jrd+json")
1450 j.Write(w)
1451}
1452
1453func somedays() string {
1454 secs := 432000 + notrand.Int63n(432000)
1455 return fmt.Sprintf("%d", secs)
1456}
1457
1458func avatate(w http.ResponseWriter, r *http.Request) {
1459 n := r.FormValue("a")
1460 a := avatar(n)
1461 w.Header().Set("Cache-Control", "max-age="+somedays())
1462 w.Write(a)
1463}
1464
1465func servecss(w http.ResponseWriter, r *http.Request) {
1466 fd, err := os.Open("views" + r.URL.Path)
1467 if err != nil {
1468 http.NotFound(w, r)
1469 return
1470 }
1471 w.Header().Set("Cache-Control", "max-age=0")
1472 w.Header().Set("Content-Type", "text/css; charset=utf-8")
1473 err = css.Filter(fd, w)
1474 if err != nil {
1475 log.Printf("error filtering css: %s", err)
1476 }
1477}
1478func serveasset(w http.ResponseWriter, r *http.Request) {
1479 w.Header().Set("Cache-Control", "max-age=7776000")
1480 http.ServeFile(w, r, "views"+r.URL.Path)
1481}
1482func servehelp(w http.ResponseWriter, r *http.Request) {
1483 name := mux.Vars(r)["name"]
1484 w.Header().Set("Cache-Control", "max-age=600")
1485 http.ServeFile(w, r, "docs/"+name)
1486}
1487func servehtml(w http.ResponseWriter, r *http.Request) {
1488 templinfo := getInfo(r)
1489 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1490 if err != nil {
1491 log.Print(err)
1492 }
1493}
1494func serveemu(w http.ResponseWriter, r *http.Request) {
1495 xid := mux.Vars(r)["xid"]
1496 w.Header().Set("Cache-Control", "max-age="+somedays())
1497 http.ServeFile(w, r, "emus/"+xid)
1498}
1499func servememe(w http.ResponseWriter, r *http.Request) {
1500 xid := mux.Vars(r)["xid"]
1501 w.Header().Set("Cache-Control", "max-age="+somedays())
1502 http.ServeFile(w, r, "memes/"+xid)
1503}
1504
1505func servefile(w http.ResponseWriter, r *http.Request) {
1506 xid := mux.Vars(r)["xid"]
1507 row := stmtGetFileData.QueryRow(xid)
1508 var media string
1509 var data []byte
1510 err := row.Scan(&media, &data)
1511 if err != nil {
1512 log.Printf("error loading file: %s", err)
1513 http.NotFound(w, r)
1514 return
1515 }
1516 w.Header().Set("Content-Type", media)
1517 w.Header().Set("X-Content-Type-Options", "nosniff")
1518 w.Header().Set("Cache-Control", "max-age="+somedays())
1519 w.Write(data)
1520}
1521
1522func nomoroboto(w http.ResponseWriter, r *http.Request) {
1523 io.WriteString(w, "User-agent: *\n")
1524 io.WriteString(w, "Disallow: /a\n")
1525 io.WriteString(w, "Disallow: /d\n")
1526 io.WriteString(w, "Disallow: /meme\n")
1527 for _, u := range allusers() {
1528 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1529 }
1530}
1531
1532func webhydra(w http.ResponseWriter, r *http.Request) {
1533 u := login.GetUserInfo(r)
1534 userid := u.UserID
1535 templinfo := getInfo(r)
1536 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1537 page := r.FormValue("page")
1538 var honks []*Honk
1539 switch page {
1540 case "atme":
1541 honks = gethonksforme(userid)
1542 templinfo["ServerMessage"] = "at me!"
1543 case "home":
1544 honks = gethonksforuser(userid)
1545 honks = osmosis(honks, userid)
1546 templinfo["ServerMessage"] = serverMsg
1547 case "first":
1548 honks = gethonksforuserfirstclass(userid)
1549 honks = osmosis(honks, userid)
1550 templinfo["ServerMessage"] = "first class only"
1551 case "combo":
1552 c := r.FormValue("c")
1553 honks = gethonksbycombo(userid, c)
1554 honks = osmosis(honks, userid)
1555 templinfo["ServerMessage"] = "honks by combo: " + c
1556 case "convoy":
1557 c := r.FormValue("c")
1558 honks = gethonksbyconvoy(userid, c)
1559 templinfo["ServerMessage"] = "honks in convoy: " + c
1560 case "honker":
1561 xid := r.FormValue("xid")
1562 if strings.IndexByte(xid, '@') != -1 {
1563 xid = gofish(xid)
1564 }
1565 honks = gethonksbyxonker(userid, xid)
1566 xid = html.EscapeString(xid)
1567 msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
1568 templinfo["ServerMessage"] = template.HTML(msg)
1569 default:
1570 http.NotFound(w, r)
1571 }
1572 if len(honks) > 0 {
1573 templinfo["TopXID"] = honks[0].XID
1574 }
1575 if topxid := r.FormValue("topxid"); topxid != "" {
1576 for i, h := range honks {
1577 if h.XID == topxid {
1578 honks = honks[0:i]
1579 break
1580 }
1581 }
1582 log.Printf("topxid %d frags", len(honks))
1583 }
1584 reverbolate(userid, honks)
1585 templinfo["Honks"] = honks
1586 w.Header().Set("Content-Type", "text/html; charset=utf-8")
1587 err := readviews.Execute(w, "honkfrags.html", templinfo)
1588 if err != nil {
1589 log.Printf("frag error: %s", err)
1590 }
1591}
1592
1593func serve() {
1594 db := opendatabase()
1595 login.Init(db)
1596
1597 listener, err := openListener()
1598 if err != nil {
1599 log.Fatal(err)
1600 }
1601 go redeliverator()
1602
1603 debug := false
1604 getconfig("debug", &debug)
1605 readviews = templates.Load(debug,
1606 "views/honkpage.html",
1607 "views/honkfrags.html",
1608 "views/honkers.html",
1609 "views/hfcs.html",
1610 "views/combos.html",
1611 "views/honkform.html",
1612 "views/honk.html",
1613 "views/account.html",
1614 "views/about.html",
1615 "views/funzone.html",
1616 "views/login.html",
1617 "views/xzone.html",
1618 "views/header.html",
1619 "views/onts.html",
1620 "views/honkpage.js",
1621 )
1622 if !debug {
1623 assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1624 for _, s := range assets {
1625 savedassetparams[s] = getassetparam(s)
1626 }
1627 }
1628
1629 mux := mux.NewRouter()
1630 mux.Use(login.Checker)
1631
1632 posters := mux.Methods("POST").Subrouter()
1633 getters := mux.Methods("GET").Subrouter()
1634
1635 getters.HandleFunc("/", homepage)
1636 getters.HandleFunc("/home", homepage)
1637 getters.HandleFunc("/front", homepage)
1638 getters.HandleFunc("/robots.txt", nomoroboto)
1639 getters.HandleFunc("/rss", showrss)
1640 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1641 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1642 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1643 posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1644 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1645 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1646 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1647 getters.HandleFunc("/a", avatate)
1648 getters.HandleFunc("/o", thelistingoftheontologies)
1649 getters.HandleFunc("/o/{name:.+}", showontology)
1650 getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1651 getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1652 getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1653 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1654
1655 getters.HandleFunc("/style.css", servecss)
1656 getters.HandleFunc("/local.css", servecss)
1657 getters.HandleFunc("/honkpage.js", serveasset)
1658 getters.HandleFunc("/about", servehtml)
1659 getters.HandleFunc("/login", servehtml)
1660 posters.HandleFunc("/dologin", login.LoginFunc)
1661 getters.HandleFunc("/logout", login.LogoutFunc)
1662 getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
1663
1664 loggedin := mux.NewRoute().Subrouter()
1665 loggedin.Use(login.Required)
1666 loggedin.HandleFunc("/account", accountpage)
1667 loggedin.HandleFunc("/funzone", showfunzone)
1668 loggedin.HandleFunc("/chpass", dochpass)
1669 loggedin.HandleFunc("/atme", homepage)
1670 loggedin.HandleFunc("/hfcs", hfcspage)
1671 loggedin.HandleFunc("/xzone", xzone)
1672 loggedin.HandleFunc("/edit", edithonkpage)
1673 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1674 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1675 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1676 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
1677 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1678 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1679 loggedin.HandleFunc("/honkers", showhonkers)
1680 loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1681 loggedin.HandleFunc("/h", showhonker)
1682 loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1683 loggedin.HandleFunc("/c", showcombos)
1684 loggedin.HandleFunc("/t", showconvoy)
1685 loggedin.HandleFunc("/q", showsearch)
1686 loggedin.HandleFunc("/hydra", webhydra)
1687 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1688
1689 err = http.Serve(listener, mux)
1690 if err != nil {
1691 log.Fatal(err)
1692 }
1693}