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