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