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