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