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