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