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