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