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
458func outbox(w http.ResponseWriter, r *http.Request) {
459 name := mux.Vars(r)["name"]
460 user, err := butwhatabout(name)
461 if err != nil {
462 http.NotFound(w, r)
463 return
464 }
465 if stealthmode(user.ID, r) {
466 http.NotFound(w, r)
467 return
468 }
469
470 honks := gethonksbyuser(name, false)
471 if len(honks) > 20 {
472 honks = honks[0:20]
473 }
474
475 var jonks []junk.Junk
476 for _, h := range honks {
477 j, _ := jonkjonk(user, h)
478 jonks = append(jonks, j)
479 }
480
481 j := junk.New()
482 j["@context"] = itiswhatitis
483 j["id"] = user.URL + "/outbox"
484 j["type"] = "OrderedCollection"
485 j["totalItems"] = len(jonks)
486 j["orderedItems"] = jonks
487
488 w.Header().Set("Content-Type", theonetruename)
489 j.Write(w)
490}
491
492func emptiness(w http.ResponseWriter, r *http.Request) {
493 name := mux.Vars(r)["name"]
494 user, err := butwhatabout(name)
495 if err != nil {
496 http.NotFound(w, r)
497 return
498 }
499 if stealthmode(user.ID, r) {
500 http.NotFound(w, r)
501 return
502 }
503 colname := "/followers"
504 if strings.HasSuffix(r.URL.Path, "/following") {
505 colname = "/following"
506 }
507 j := junk.New()
508 j["@context"] = itiswhatitis
509 j["id"] = user.URL + colname
510 j["type"] = "OrderedCollection"
511 j["totalItems"] = 0
512 j["orderedItems"] = []junk.Junk{}
513
514 w.Header().Set("Content-Type", theonetruename)
515 j.Write(w)
516}
517
518func showuser(w http.ResponseWriter, r *http.Request) {
519 name := mux.Vars(r)["name"]
520 user, err := butwhatabout(name)
521 if err != nil {
522 log.Printf("user not found %s: %s", name, err)
523 http.NotFound(w, r)
524 return
525 }
526 if stealthmode(user.ID, r) {
527 http.NotFound(w, r)
528 return
529 }
530 if friendorfoe(r.Header.Get("Accept")) {
531 j, ok := asjonker(name)
532 if ok {
533 w.Header().Set("Content-Type", theonetruename)
534 w.Write(j)
535 } else {
536 http.NotFound(w, r)
537 }
538 return
539 }
540 u := login.GetUserInfo(r)
541 honks := gethonksbyuser(name, u != nil && u.Username == name)
542 templinfo := getInfo(r)
543 filt := htfilter.New()
544 templinfo["Name"] = user.Name
545 whatabout := user.About
546 whatabout = markitzero(user.About)
547 templinfo["WhatAbout"], _ = filt.String(whatabout)
548 templinfo["ServerMessage"] = ""
549 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
550 honkpage(w, u, honks, templinfo)
551}
552
553func showhonker(w http.ResponseWriter, r *http.Request) {
554 u := login.GetUserInfo(r)
555 name := mux.Vars(r)["name"]
556 var honks []*Honk
557 if name == "" {
558 name = r.FormValue("xid")
559 honks = gethonksbyxonker(u.UserID, name)
560 } else {
561 honks = gethonksbyhonker(u.UserID, name)
562 }
563 name = html.EscapeString(name)
564 msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, name, name)
565 templinfo := getInfo(r)
566 templinfo["PageName"] = "honker"
567 templinfo["ServerMessage"] = template.HTML(msg)
568 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
569 honkpage(w, u, honks, templinfo)
570}
571
572func showcombo(w http.ResponseWriter, r *http.Request) {
573 name := mux.Vars(r)["name"]
574 u := login.GetUserInfo(r)
575 honks := gethonksbycombo(u.UserID, name)
576 honks = osmosis(honks, u.UserID)
577 templinfo := getInfo(r)
578 templinfo["PageName"] = "combo"
579 templinfo["PageArg"] = "name"
580 templinfo["ServerMessage"] = "honks by combo: " + name
581 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
582 honkpage(w, u, honks, templinfo)
583}
584func showconvoy(w http.ResponseWriter, r *http.Request) {
585 c := r.FormValue("c")
586 u := login.GetUserInfo(r)
587 honks := gethonksbyconvoy(u.UserID, c)
588 templinfo := getInfo(r)
589 templinfo["ServerMessage"] = "honks in convoy: " + c
590 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
591 honkpage(w, u, honks, templinfo)
592}
593func showsearch(w http.ResponseWriter, r *http.Request) {
594 q := r.FormValue("q")
595 u := login.GetUserInfo(r)
596 honks := gethonksbysearch(u.UserID, q)
597 templinfo := getInfo(r)
598 templinfo["ServerMessage"] = "honks for search: " + q
599 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
600 honkpage(w, u, honks, templinfo)
601}
602func showontology(w http.ResponseWriter, r *http.Request) {
603 name := mux.Vars(r)["name"]
604 u := login.GetUserInfo(r)
605 var userid int64 = -1
606 if u != nil {
607 userid = u.UserID
608 }
609 honks := gethonksbyontology(userid, "#"+name)
610 templinfo := getInfo(r)
611 templinfo["ServerMessage"] = "honks by ontology: " + name
612 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
613 honkpage(w, u, honks, templinfo)
614}
615
616func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
617 u := login.GetUserInfo(r)
618 var userid int64 = -1
619 if u != nil {
620 userid = u.UserID
621 }
622 rows, err := stmtSelectOnts.Query(userid)
623 if err != nil {
624 log.Printf("selection error: %s", err)
625 return
626 }
627 defer rows.Close()
628 var onts [][]string
629 for rows.Next() {
630 var o string
631 err := rows.Scan(&o)
632 if err != nil {
633 log.Printf("error scanning ont: %s", err)
634 continue
635 }
636 onts = append(onts, []string{o, o[1:]})
637 }
638 if u == nil {
639 w.Header().Set("Cache-Control", "max-age=300")
640 }
641 templinfo := getInfo(r)
642 templinfo["Onts"] = onts
643 err = readviews.Execute(w, "onts.html", templinfo)
644 if err != nil {
645 log.Print(err)
646 }
647}
648
649func showhonk(w http.ResponseWriter, r *http.Request) {
650 name := mux.Vars(r)["name"]
651 user, err := butwhatabout(name)
652 if err != nil {
653 http.NotFound(w, r)
654 return
655 }
656 if stealthmode(user.ID, r) {
657 http.NotFound(w, r)
658 return
659 }
660 xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
661
662 if friendorfoe(r.Header.Get("Accept")) {
663 j, ok := gimmejonk(xid)
664 if ok {
665 w.Header().Set("Content-Type", theonetruename)
666 w.Write(j)
667 } else {
668 http.NotFound(w, r)
669 }
670 return
671 }
672 honk := getxonk(user.ID, xid)
673 if honk == nil {
674 http.NotFound(w, r)
675 return
676 }
677 u := login.GetUserInfo(r)
678 if u != nil && u.UserID != user.ID {
679 u = nil
680 }
681 if !honk.Public {
682 if u == nil {
683 http.NotFound(w, r)
684 return
685
686 }
687 templinfo := getInfo(r)
688 templinfo["ServerMessage"] = "one honk maybe more"
689 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
690 honkpage(w, u, []*Honk{honk}, templinfo)
691 return
692 }
693 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
694 var honks []*Honk
695 for _, h := range rawhonks {
696 if h.Public && (h.Whofore == 2 || h.IsAcked()) {
697 honks = append(honks, h)
698 }
699 }
700
701 templinfo := getInfo(r)
702 templinfo["ServerMessage"] = "one honk maybe more"
703 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
704 honkpage(w, u, honks, templinfo)
705}
706
707func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
708 var userid int64 = -1
709 if u != nil {
710 userid = u.UserID
711 }
712 if u == nil {
713 w.Header().Set("Cache-Control", "max-age=60")
714 }
715 reverbolate(userid, honks)
716 templinfo["Honks"] = honks
717 if len(honks) > 0 {
718 templinfo["TopXID"] = honks[0].XID
719 }
720 err := readviews.Execute(w, "honkpage.html", templinfo)
721 if err != nil {
722 log.Print(err)
723 }
724}
725
726func saveuser(w http.ResponseWriter, r *http.Request) {
727 whatabout := r.FormValue("whatabout")
728 u := login.GetUserInfo(r)
729 db := opendatabase()
730 options := ""
731 if r.FormValue("skinny") == "skinny" {
732 options += " skinny "
733 }
734 _, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
735 if err != nil {
736 log.Printf("error bouting what: %s", err)
737 }
738 someusers.Clear(u.Username)
739
740 http.Redirect(w, r, "/account", http.StatusSeeOther)
741}
742
743func submitbonk(w http.ResponseWriter, r *http.Request) {
744 xid := r.FormValue("xid")
745 userinfo := login.GetUserInfo(r)
746 user, _ := butwhatabout(userinfo.Username)
747
748 log.Printf("bonking %s", xid)
749
750 xonk := getxonk(userinfo.UserID, xid)
751 if xonk == nil {
752 return
753 }
754 if !xonk.Public {
755 return
756 }
757 donksforhonks([]*Honk{xonk})
758
759 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
760 if err != nil {
761 log.Printf("error acking bonk: %s", err)
762 }
763
764 oonker := xonk.Oonker
765 if oonker == "" {
766 oonker = xonk.Honker
767 }
768 dt := time.Now().UTC()
769 bonk := Honk{
770 UserID: userinfo.UserID,
771 Username: userinfo.Username,
772 What: "bonk",
773 Honker: user.URL,
774 Oonker: oonker,
775 XID: xonk.XID,
776 RID: xonk.RID,
777 Noise: xonk.Noise,
778 Precis: xonk.Precis,
779 URL: xonk.URL,
780 Date: dt,
781 Donks: xonk.Donks,
782 Whofore: 2,
783 Convoy: xonk.Convoy,
784 Audience: []string{thewholeworld, oonker},
785 Public: true,
786 }
787
788 bonk.Format = "html"
789
790 err = savehonk(&bonk)
791 if err != nil {
792 log.Printf("uh oh")
793 return
794 }
795
796 go honkworldwide(user, &bonk)
797}
798
799func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
800 zonk := Honk{
801 What: what,
802 XID: xonk.XID,
803 Date: time.Now().UTC(),
804 Audience: oneofakind(xonk.Audience),
805 }
806 zonk.Public = !keepitquiet(zonk.Audience)
807
808 log.Printf("announcing %sed honk: %s", what, xonk.XID)
809 go honkworldwide(user, &zonk)
810}
811
812func zonkit(w http.ResponseWriter, r *http.Request) {
813 wherefore := r.FormValue("wherefore")
814 what := r.FormValue("what")
815 userinfo := login.GetUserInfo(r)
816 user, _ := butwhatabout(userinfo.Username)
817
818 // my hammer is too big, oh well
819 defer oldjonks.Flush()
820
821 if wherefore == "ack" {
822 xonk := getxonk(userinfo.UserID, what)
823 if xonk != nil {
824 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
825 if err != nil {
826 log.Printf("error acking: %s", err)
827 }
828 sendzonkofsorts(xonk, user, "ack")
829 }
830 return
831 }
832
833 if wherefore == "deack" {
834 xonk := getxonk(userinfo.UserID, what)
835 if xonk != nil {
836 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
837 if err != nil {
838 log.Printf("error deacking: %s", err)
839 }
840 sendzonkofsorts(xonk, user, "deack")
841 }
842 return
843 }
844
845 if wherefore == "unbonk" {
846 xonk := getbonk(userinfo.UserID, what)
847 if xonk != nil {
848 deletehonk(xonk.ID)
849 xonk = getxonk(userinfo.UserID, what)
850 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
851 if err != nil {
852 log.Printf("error unbonking: %s", err)
853 }
854 sendzonkofsorts(xonk, user, "unbonk")
855 }
856 return
857 }
858
859 log.Printf("zonking %s %s", wherefore, what)
860 if wherefore == "zonk" {
861 xonk := getxonk(userinfo.UserID, what)
862 if xonk != nil {
863 deletehonk(xonk.ID)
864 if xonk.Whofore == 2 || xonk.Whofore == 3 {
865 sendzonkofsorts(xonk, user, "zonk")
866 }
867 }
868 }
869 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
870 if err != nil {
871 log.Printf("error saving zonker: %s", err)
872 return
873 }
874}
875
876func edithonkpage(w http.ResponseWriter, r *http.Request) {
877 u := login.GetUserInfo(r)
878 user, _ := butwhatabout(u.Username)
879 xid := r.FormValue("xid")
880 honk := getxonk(u.UserID, xid)
881 if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
882 log.Printf("no edit")
883 return
884 }
885
886 noise := honk.Noise
887 if honk.Precis != "" {
888 noise = honk.Precis + "\n\n" + noise
889 }
890
891 honks := []*Honk{honk}
892 donksforhonks(honks)
893 reverbolate(u.UserID, honks)
894 templinfo := getInfo(r)
895 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
896 templinfo["Honks"] = honks
897 templinfo["Noise"] = noise
898 templinfo["ServerMessage"] = "honk edit"
899 templinfo["UpdateXID"] = honk.XID
900 if len(honk.Donks) > 0 {
901 templinfo["SavedFile"] = honk.Donks[0].XID
902 }
903 err := readviews.Execute(w, "honkpage.html", templinfo)
904 if err != nil {
905 log.Print(err)
906 }
907}
908
909// what a hot mess this function is
910func submithonk(w http.ResponseWriter, r *http.Request) {
911 rid := r.FormValue("rid")
912 noise := r.FormValue("noise")
913
914 userinfo := login.GetUserInfo(r)
915 user, _ := butwhatabout(userinfo.Username)
916
917 dt := time.Now().UTC()
918 updatexid := r.FormValue("updatexid")
919 var honk *Honk
920 if updatexid != "" {
921 honk = getxonk(userinfo.UserID, updatexid)
922 if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
923 log.Printf("not saving edit")
924 return
925 }
926 honk.Date = dt
927 honk.What = "update"
928 honk.Format = "markdown"
929 } else {
930 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
931 what := "honk"
932 if rid != "" {
933 what = "tonk"
934 }
935 honk = &Honk{
936 UserID: userinfo.UserID,
937 Username: userinfo.Username,
938 What: what,
939 Honker: user.URL,
940 XID: xid,
941 Date: dt,
942 Format: "markdown",
943 }
944 }
945
946 noise = hooterize(noise)
947 honk.Noise = noise
948 translate(honk)
949
950 var convoy string
951 if rid != "" {
952 xonk := getxonk(userinfo.UserID, rid)
953 if xonk != nil {
954 if xonk.Public {
955 honk.Audience = append(honk.Audience, xonk.Audience...)
956 }
957 convoy = xonk.Convoy
958 } else {
959 xonkaud, c := whosthere(rid)
960 honk.Audience = append(honk.Audience, xonkaud...)
961 convoy = c
962 }
963 for i, a := range honk.Audience {
964 if a == thewholeworld {
965 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
966 break
967 }
968 }
969 honk.RID = rid
970 } else {
971 honk.Audience = []string{thewholeworld}
972 }
973 if honk.Noise != "" && honk.Noise[0] == '@' {
974 honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
975 } else {
976 honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
977 }
978
979 if convoy == "" {
980 convoy = "data:,electrichonkytonk-" + xfiltrate()
981 }
982 butnottooloud(honk.Audience)
983 honk.Audience = oneofakind(honk.Audience)
984 if len(honk.Audience) == 0 {
985 log.Printf("honk to nowhere")
986 http.Error(w, "honk to nowhere...", http.StatusNotFound)
987 return
988 }
989 honk.Public = !keepitquiet(honk.Audience)
990 honk.Convoy = convoy
991
992 donkxid := r.FormValue("donkxid")
993 if donkxid == "" {
994 file, filehdr, err := r.FormFile("donk")
995 if err == nil {
996 var buf bytes.Buffer
997 io.Copy(&buf, file)
998 file.Close()
999 data := buf.Bytes()
1000 xid := xfiltrate()
1001 var media, name string
1002 img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
1003 if err == nil {
1004 data = img.Data
1005 format := img.Format
1006 media = "image/" + format
1007 if format == "jpeg" {
1008 format = "jpg"
1009 }
1010 name = xid + "." + format
1011 xid = name
1012 } else {
1013 maxsize := 100000
1014 if len(data) > maxsize {
1015 log.Printf("bad image: %s too much text: %d", err, len(data))
1016 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1017 return
1018 }
1019 for i := 0; i < len(data); i++ {
1020 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1021 log.Printf("bad image: %s not text: %d", err, data[i])
1022 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1023 return
1024 }
1025 }
1026 media = "text/plain"
1027 name = filehdr.Filename
1028 if name == "" {
1029 name = xid + ".txt"
1030 }
1031 xid += ".txt"
1032 }
1033 desc := r.FormValue("donkdesc")
1034 if desc == "" {
1035 desc = name
1036 }
1037 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1038 fileid, err := savefile(xid, name, desc, url, media, true, data)
1039 if err != nil {
1040 log.Printf("unable to save image: %s", err)
1041 return
1042 }
1043 var d Donk
1044 d.FileID = fileid
1045 honk.Donks = append(honk.Donks, &d)
1046 donkxid = d.XID
1047 }
1048 } else {
1049 xid := donkxid
1050 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1051 donk := finddonk(url)
1052 if donk != nil {
1053 honk.Donks = append(honk.Donks, donk)
1054 } else {
1055 log.Printf("can't find file: %s", xid)
1056 }
1057 }
1058 herd := herdofemus(honk.Noise)
1059 for _, e := range herd {
1060 donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1061 if donk != nil {
1062 donk.Name = e.Name
1063 honk.Donks = append(honk.Donks, donk)
1064 }
1065 }
1066 memetize(honk)
1067
1068 placename := r.FormValue("placename")
1069 placelat := r.FormValue("placelat")
1070 placelong := r.FormValue("placelong")
1071 if placename != "" || placelat != "" || placelong != "" {
1072 p := new(Place)
1073 p.Name = placename
1074 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1075 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1076 p.Url = r.FormValue("placeurl")
1077 honk.Place = p
1078 }
1079 timestart := r.FormValue("timestart")
1080 if timestart != "" {
1081 t := new(Time)
1082 now := time.Now().Local()
1083 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1084 start, err := time.ParseInLocation(layout, timestart, now.Location())
1085 if err == nil {
1086 if start.Year() == 0 {
1087 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1088 }
1089 t.StartTime = start
1090 break
1091 }
1092 }
1093 timeend := r.FormValue("timeend")
1094 dur, err := time.ParseDuration(timeend)
1095 if err == nil {
1096 t.Duration = Duration(dur)
1097 }
1098 if !t.StartTime.IsZero() {
1099 honk.What = "event"
1100 honk.Time = t
1101 }
1102 }
1103
1104 if honk.Public {
1105 honk.Whofore = 2
1106 } else {
1107 honk.Whofore = 3
1108 }
1109
1110 // back to markdown
1111 honk.Noise = noise
1112
1113 if r.FormValue("preview") == "preview" {
1114 honks := []*Honk{honk}
1115 reverbolate(userinfo.UserID, honks)
1116 templinfo := getInfo(r)
1117 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1118 templinfo["Honks"] = honks
1119 templinfo["InReplyTo"] = r.FormValue("rid")
1120 templinfo["Noise"] = r.FormValue("noise")
1121 templinfo["SavedFile"] = donkxid
1122 templinfo["ServerMessage"] = "honk preview"
1123 err := readviews.Execute(w, "honkpage.html", templinfo)
1124 if err != nil {
1125 log.Print(err)
1126 }
1127 return
1128 }
1129
1130 if updatexid != "" {
1131 updatehonk(honk)
1132 oldjonks.Clear(honk.XID)
1133 } else {
1134 err := savehonk(honk)
1135 if err != nil {
1136 log.Printf("uh oh")
1137 return
1138 }
1139 }
1140
1141 // reload for consistency
1142 honk.Donks = nil
1143 donksforhonks([]*Honk{honk})
1144
1145 go honkworldwide(user, honk)
1146
1147 http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1148}
1149
1150func showhonkers(w http.ResponseWriter, r *http.Request) {
1151 userinfo := login.GetUserInfo(r)
1152 templinfo := getInfo(r)
1153 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1154 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1155 err := readviews.Execute(w, "honkers.html", templinfo)
1156 if err != nil {
1157 log.Print(err)
1158 }
1159}
1160
1161var combocache = cacheNew(cacheOptions{Filler: func(userid int64) ([]string, bool) {
1162 honkers := gethonkers(userid)
1163 var combos []string
1164 for _, h := range honkers {
1165 combos = append(combos, h.Combos...)
1166 }
1167 for i, c := range combos {
1168 if c == "-" {
1169 combos[i] = ""
1170 }
1171 }
1172 combos = oneofakind(combos)
1173 sort.Strings(combos)
1174 return combos, true
1175}})
1176
1177func showcombos(w http.ResponseWriter, r *http.Request) {
1178 userinfo := login.GetUserInfo(r)
1179 var combos []string
1180 combocache.Get(userinfo.UserID, &combos)
1181 templinfo := getInfo(r)
1182 err := readviews.Execute(w, "combos.html", templinfo)
1183 if err != nil {
1184 log.Print(err)
1185 }
1186}
1187
1188func submithonker(w http.ResponseWriter, r *http.Request) {
1189 u := login.GetUserInfo(r)
1190 name := r.FormValue("name")
1191 url := r.FormValue("url")
1192 peep := r.FormValue("peep")
1193 combos := r.FormValue("combos")
1194 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1195
1196 defer combocache.Clear(u.UserID)
1197
1198 if honkerid > 0 {
1199 goodbye := r.FormValue("goodbye")
1200 if goodbye == "F" {
1201 db := opendatabase()
1202 row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1203 honkerid, u.UserID)
1204 err := row.Scan(&url)
1205 if err != nil {
1206 log.Printf("can't get honker xid: %s", err)
1207 return
1208 }
1209 log.Printf("unsubscribing from %s", url)
1210 user, _ := butwhatabout(u.Username)
1211 _, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, "sub")
1212 if err != nil {
1213 log.Printf("error updating honker: %s", err)
1214 return
1215 }
1216 go itakeitallback(user, url)
1217
1218 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1219 return
1220 }
1221 if goodbye == "X" {
1222 db := opendatabase()
1223 row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1224 honkerid, u.UserID)
1225 err := row.Scan(&url)
1226 if err != nil {
1227 log.Printf("can't get honker xid: %s", err)
1228 return
1229 }
1230 log.Printf("resubscribing to %s", url)
1231 user, _ := butwhatabout(u.Username)
1232 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "unsub")
1233 if err == nil {
1234 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "peep")
1235 }
1236 if err != nil {
1237 log.Printf("error updating honker: %s", err)
1238 return
1239 }
1240 go subsub(user, url)
1241
1242 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1243 return
1244 }
1245 combos = " " + strings.TrimSpace(combos) + " "
1246 _, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1247 if err != nil {
1248 log.Printf("update honker err: %s", err)
1249 return
1250 }
1251 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1252 return
1253 }
1254
1255 flavor := "presub"
1256 if peep == "peep" {
1257 flavor = "peep"
1258 }
1259 p, err := investigate(url)
1260 if err != nil {
1261 http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1262 log.Printf("failed to investigate honker: %s", err)
1263 return
1264 }
1265 url = p.XID
1266
1267 db := opendatabase()
1268 row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1269 var x string
1270 err = row.Scan(&x)
1271 if err != sql.ErrNoRows {
1272 http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1273 if err != nil {
1274 log.Printf("honker scan err: %s", err)
1275 }
1276 return
1277 }
1278
1279 if name == "" {
1280 name = p.Handle
1281 }
1282 _, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1283 if err != nil {
1284 log.Print(err)
1285 return
1286 }
1287 if flavor == "presub" {
1288 user, _ := butwhatabout(u.Username)
1289 go subsub(user, url)
1290 }
1291 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1292}
1293
1294func hfcspage(w http.ResponseWriter, r *http.Request) {
1295 userinfo := login.GetUserInfo(r)
1296
1297 filters := getfilters(userinfo.UserID, filtAny)
1298
1299 templinfo := getInfo(r)
1300 templinfo["Filters"] = filters
1301 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1302 err := readviews.Execute(w, "hfcs.html", templinfo)
1303 if err != nil {
1304 log.Print(err)
1305 }
1306}
1307
1308func savehfcs(w http.ResponseWriter, r *http.Request) {
1309 userinfo := login.GetUserInfo(r)
1310 itsok := r.FormValue("itsok")
1311 if itsok == "iforgiveyou" {
1312 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1313 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1314 if err != nil {
1315 log.Printf("error deleting filter: %s", err)
1316 }
1317 filtcache.Clear(userinfo.UserID)
1318 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1319 return
1320 }
1321
1322 filt := new(Filter)
1323 filt.Name = r.FormValue("name")
1324 filt.Date = time.Now().UTC()
1325 filt.Actor = r.FormValue("actor")
1326 filt.IncludeAudience = r.FormValue("incaud") == "yes"
1327 filt.Text = r.FormValue("filttext")
1328 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1329 filt.AnnounceOf = r.FormValue("announceof")
1330 filt.Reject = r.FormValue("doreject") == "yes"
1331 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1332 filt.Hide = r.FormValue("dohide") == "yes"
1333 filt.Collapse = r.FormValue("docollapse") == "yes"
1334 filt.Rewrite = r.FormValue("filtrewrite")
1335 filt.Replace = r.FormValue("filtreplace")
1336
1337 if filt.Actor == "" && filt.Text == "" {
1338 log.Printf("blank filter")
1339 return
1340 }
1341
1342 j, err := jsonify(filt)
1343 if err == nil {
1344 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1345 }
1346 if err != nil {
1347 log.Printf("error saving filter: %s", err)
1348 }
1349
1350 filtcache.Clear(userinfo.UserID)
1351 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1352}
1353
1354func accountpage(w http.ResponseWriter, r *http.Request) {
1355 u := login.GetUserInfo(r)
1356 user, _ := butwhatabout(u.Username)
1357 templinfo := getInfo(r)
1358 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1359 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1360 templinfo["User"] = user
1361 err := readviews.Execute(w, "account.html", templinfo)
1362 if err != nil {
1363 log.Print(err)
1364 }
1365}
1366
1367func dochpass(w http.ResponseWriter, r *http.Request) {
1368 err := login.ChangePassword(w, r)
1369 if err != nil {
1370 log.Printf("error changing password: %s", err)
1371 }
1372 http.Redirect(w, r, "/account", http.StatusSeeOther)
1373}
1374
1375func fingerlicker(w http.ResponseWriter, r *http.Request) {
1376 orig := r.FormValue("resource")
1377
1378 log.Printf("finger lick: %s", orig)
1379
1380 if strings.HasPrefix(orig, "acct:") {
1381 orig = orig[5:]
1382 }
1383
1384 name := orig
1385 idx := strings.LastIndexByte(name, '/')
1386 if idx != -1 {
1387 name = name[idx+1:]
1388 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1389 log.Printf("foreign request rejected")
1390 name = ""
1391 }
1392 } else {
1393 idx = strings.IndexByte(name, '@')
1394 if idx != -1 {
1395 name = name[:idx]
1396 if name+"@"+serverName != orig {
1397 log.Printf("foreign request rejected")
1398 name = ""
1399 }
1400 }
1401 }
1402 user, err := butwhatabout(name)
1403 if err != nil {
1404 http.NotFound(w, r)
1405 return
1406 }
1407 if stealthmode(user.ID, r) {
1408 http.NotFound(w, r)
1409 return
1410 }
1411
1412 j := junk.New()
1413 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1414 j["aliases"] = []string{user.URL}
1415 var links []junk.Junk
1416 l := junk.New()
1417 l["rel"] = "self"
1418 l["type"] = `application/activity+json`
1419 l["href"] = user.URL
1420 links = append(links, l)
1421 j["links"] = links
1422
1423 w.Header().Set("Cache-Control", "max-age=3600")
1424 w.Header().Set("Content-Type", "application/jrd+json")
1425 j.Write(w)
1426}
1427
1428func somedays() string {
1429 secs := 432000 + notrand.Int63n(432000)
1430 return fmt.Sprintf("%d", secs)
1431}
1432
1433func avatate(w http.ResponseWriter, r *http.Request) {
1434 n := r.FormValue("a")
1435 a := avatar(n)
1436 w.Header().Set("Cache-Control", "max-age="+somedays())
1437 w.Write(a)
1438}
1439
1440func servecss(w http.ResponseWriter, r *http.Request) {
1441 fd, err := os.Open("views" + r.URL.Path)
1442 if err != nil {
1443 http.NotFound(w, r)
1444 return
1445 }
1446 w.Header().Set("Cache-Control", "max-age=0")
1447 w.Header().Set("Content-Type", "text/css; charset=utf-8")
1448 err = css.Filter(fd, w)
1449 if err != nil {
1450 log.Printf("error filtering css: %s", err)
1451 }
1452}
1453func serveasset(w http.ResponseWriter, r *http.Request) {
1454 w.Header().Set("Cache-Control", "max-age=7776000")
1455 http.ServeFile(w, r, "views"+r.URL.Path)
1456}
1457func servehelp(w http.ResponseWriter, r *http.Request) {
1458 name := mux.Vars(r)["name"]
1459 w.Header().Set("Cache-Control", "max-age=600")
1460 http.ServeFile(w, r, "docs/"+name)
1461}
1462func servehtml(w http.ResponseWriter, r *http.Request) {
1463 templinfo := getInfo(r)
1464 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1465 if err != nil {
1466 log.Print(err)
1467 }
1468}
1469func serveemu(w http.ResponseWriter, r *http.Request) {
1470 xid := mux.Vars(r)["xid"]
1471 w.Header().Set("Cache-Control", "max-age="+somedays())
1472 http.ServeFile(w, r, "emus/"+xid)
1473}
1474func servememe(w http.ResponseWriter, r *http.Request) {
1475 xid := mux.Vars(r)["xid"]
1476 w.Header().Set("Cache-Control", "max-age="+somedays())
1477 http.ServeFile(w, r, "memes/"+xid)
1478}
1479
1480func servefile(w http.ResponseWriter, r *http.Request) {
1481 xid := mux.Vars(r)["xid"]
1482 row := stmtGetFileData.QueryRow(xid)
1483 var media string
1484 var data []byte
1485 err := row.Scan(&media, &data)
1486 if err != nil {
1487 log.Printf("error loading file: %s", err)
1488 http.NotFound(w, r)
1489 return
1490 }
1491 w.Header().Set("Content-Type", media)
1492 w.Header().Set("X-Content-Type-Options", "nosniff")
1493 w.Header().Set("Cache-Control", "max-age="+somedays())
1494 w.Write(data)
1495}
1496
1497func nomoroboto(w http.ResponseWriter, r *http.Request) {
1498 io.WriteString(w, "User-agent: *\n")
1499 io.WriteString(w, "Disallow: /a\n")
1500 io.WriteString(w, "Disallow: /d\n")
1501 io.WriteString(w, "Disallow: /meme\n")
1502 for _, u := range allusers() {
1503 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1504 }
1505}
1506
1507func webhydra(w http.ResponseWriter, r *http.Request) {
1508 u := login.GetUserInfo(r)
1509 userid := u.UserID
1510 templinfo := getInfo(r)
1511 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1512 page := r.FormValue("page")
1513 var honks []*Honk
1514 switch page {
1515 case "atme":
1516 honks = gethonksforme(userid)
1517 templinfo["ServerMessage"] = "at me!"
1518 case "home":
1519 honks = gethonksforuser(userid)
1520 honks = osmosis(honks, userid)
1521 templinfo["ServerMessage"] = serverMsg
1522 case "first":
1523 honks = gethonksforuserfirstclass(userid)
1524 honks = osmosis(honks, userid)
1525 templinfo["ServerMessage"] = "first class only"
1526 case "combo":
1527 c := r.FormValue("c")
1528 honks = gethonksbycombo(userid, c)
1529 templinfo["ServerMessage"] = "honks by combo: " + c
1530 case "convoy":
1531 c := r.FormValue("c")
1532 honks = gethonksbyconvoy(userid, c)
1533 templinfo["ServerMessage"] = "honks in convoy: " + c
1534 case "honker":
1535 xid := r.FormValue("xid")
1536 if strings.IndexByte(xid, '@') != -1 {
1537 xid = gofish(xid)
1538 }
1539 honks = gethonksbyxonker(userid, xid)
1540 xid = html.EscapeString(xid)
1541 msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
1542 templinfo["ServerMessage"] = template.HTML(msg)
1543 default:
1544 http.NotFound(w, r)
1545 }
1546 if len(honks) > 0 {
1547 templinfo["TopXID"] = honks[0].XID
1548 }
1549 if topxid := r.FormValue("topxid"); topxid != "" {
1550 for i, h := range honks {
1551 if h.XID == topxid {
1552 honks = honks[0:i]
1553 break
1554 }
1555 }
1556 log.Printf("topxid %d frags", len(honks))
1557 }
1558 reverbolate(userid, honks)
1559 templinfo["Honks"] = honks
1560 w.Header().Set("Content-Type", "text/html; charset=utf-8")
1561 err := readviews.Execute(w, "honkfrags.html", templinfo)
1562 if err != nil {
1563 log.Printf("frag error: %s", err)
1564 }
1565}
1566
1567func serve() {
1568 db := opendatabase()
1569 login.Init(db)
1570
1571 listener, err := openListener()
1572 if err != nil {
1573 log.Fatal(err)
1574 }
1575 go redeliverator()
1576
1577 debug := false
1578 getconfig("debug", &debug)
1579 readviews = templates.Load(debug,
1580 "views/honkpage.html",
1581 "views/honkfrags.html",
1582 "views/honkers.html",
1583 "views/hfcs.html",
1584 "views/combos.html",
1585 "views/honkform.html",
1586 "views/honk.html",
1587 "views/account.html",
1588 "views/about.html",
1589 "views/funzone.html",
1590 "views/login.html",
1591 "views/xzone.html",
1592 "views/header.html",
1593 "views/onts.html",
1594 "views/honkpage.js",
1595 )
1596 if !debug {
1597 assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1598 for _, s := range assets {
1599 savedassetparams[s] = getassetparam(s)
1600 }
1601 }
1602
1603 mux := mux.NewRouter()
1604 mux.Use(login.Checker)
1605
1606 posters := mux.Methods("POST").Subrouter()
1607 getters := mux.Methods("GET").Subrouter()
1608
1609 getters.HandleFunc("/", homepage)
1610 getters.HandleFunc("/home", homepage)
1611 getters.HandleFunc("/front", homepage)
1612 getters.HandleFunc("/robots.txt", nomoroboto)
1613 getters.HandleFunc("/rss", showrss)
1614 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1615 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1616 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1617 posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1618 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1619 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1620 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1621 getters.HandleFunc("/a", avatate)
1622 getters.HandleFunc("/o", thelistingoftheontologies)
1623 getters.HandleFunc("/o/{name:.+}", showontology)
1624 getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1625 getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1626 getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1627 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1628
1629 getters.HandleFunc("/style.css", servecss)
1630 getters.HandleFunc("/local.css", servecss)
1631 getters.HandleFunc("/honkpage.js", serveasset)
1632 getters.HandleFunc("/about", servehtml)
1633 getters.HandleFunc("/login", servehtml)
1634 posters.HandleFunc("/dologin", login.LoginFunc)
1635 getters.HandleFunc("/logout", login.LogoutFunc)
1636 getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
1637
1638 loggedin := mux.NewRoute().Subrouter()
1639 loggedin.Use(login.Required)
1640 loggedin.HandleFunc("/account", accountpage)
1641 loggedin.HandleFunc("/funzone", showfunzone)
1642 loggedin.HandleFunc("/chpass", dochpass)
1643 loggedin.HandleFunc("/atme", homepage)
1644 loggedin.HandleFunc("/hfcs", hfcspage)
1645 loggedin.HandleFunc("/xzone", xzone)
1646 loggedin.HandleFunc("/edit", edithonkpage)
1647 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1648 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1649 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1650 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
1651 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1652 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1653 loggedin.HandleFunc("/honkers", showhonkers)
1654 loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1655 loggedin.HandleFunc("/h", showhonker)
1656 loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1657 loggedin.HandleFunc("/c", showcombos)
1658 loggedin.HandleFunc("/t", showconvoy)
1659 loggedin.HandleFunc("/q", showsearch)
1660 loggedin.HandleFunc("/hydra", webhydra)
1661 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1662
1663 err = http.Serve(listener, mux)
1664 if err != nil {
1665 log.Fatal(err)
1666 }
1667}