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