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