web.go (view raw)
1//
2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
3//
4// Permission to use, copy, modify, and distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
16package main
17
18import (
19 "bytes"
20 "database/sql"
21 "fmt"
22 "html/template"
23 "io"
24 "log"
25 notrand "math/rand"
26 "net/http"
27 "net/url"
28 "os"
29 "regexp"
30 "sort"
31 "strconv"
32 "strings"
33 "time"
34
35 "github.com/gorilla/mux"
36 "humungus.tedunangst.com/r/webs/cache"
37 "humungus.tedunangst.com/r/webs/css"
38 "humungus.tedunangst.com/r/webs/httpsig"
39 "humungus.tedunangst.com/r/webs/image"
40 "humungus.tedunangst.com/r/webs/junk"
41 "humungus.tedunangst.com/r/webs/login"
42 "humungus.tedunangst.com/r/webs/rss"
43 "humungus.tedunangst.com/r/webs/templates"
44)
45
46var readviews *templates.Template
47
48var userSep = "u"
49var honkSep = "h"
50
51func getuserstyle(u *login.UserInfo) template.CSS {
52 if u == nil {
53 return ""
54 }
55 user, _ := butwhatabout(u.Username)
56 if user.SkinnyCSS {
57 return "main { max-width: 700px; }"
58 }
59 return ""
60}
61
62func getInfo(r *http.Request) map[string]interface{} {
63 u := login.GetUserInfo(r)
64 templinfo := make(map[string]interface{})
65 templinfo["StyleParam"] = getassetparam("views/style.css")
66 templinfo["LocalStyleParam"] = getassetparam("views/local.css")
67 templinfo["JSParam"] = getassetparam("views/honkpage.js")
68 templinfo["UserStyle"] = getuserstyle(u)
69 templinfo["ServerName"] = serverName
70 templinfo["IconName"] = iconName
71 templinfo["UserInfo"] = u
72 templinfo["UserSep"] = userSep
73 if u != nil {
74 var combos []string
75 combocache.Get(u.UserID, &combos)
76 templinfo["Combos"] = combos
77 }
78 return templinfo
79}
80
81func homepage(w http.ResponseWriter, r *http.Request) {
82 templinfo := getInfo(r)
83 u := login.GetUserInfo(r)
84 var honks []*Honk
85 var userid int64 = -1
86
87 templinfo["ServerMessage"] = serverMsg
88 if u == nil || r.URL.Path == "/front" {
89 switch r.URL.Path {
90 case "/events":
91 honks = geteventhonks(userid)
92 templinfo["ServerMessage"] = "some recent and upcoming events"
93 default:
94 templinfo["ShowRSS"] = true
95 honks = getpublichonks()
96 }
97 } else {
98 userid = u.UserID
99 switch r.URL.Path {
100 case "/atme":
101 templinfo["ServerMessage"] = "at me!"
102 templinfo["PageName"] = "atme"
103 honks = gethonksforme(userid, 0)
104 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 options := ""
933 if r.FormValue("skinny") == "skinny" {
934 options += " skinny "
935 }
936 _, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
937 if err != nil {
938 log.Printf("error bouting what: %s", err)
939 }
940 somenamedusers.Clear(u.Username)
941 somenumberedusers.Clear(u.UserID)
942
943 http.Redirect(w, r, "/account", http.StatusSeeOther)
944}
945
946func submitbonk(w http.ResponseWriter, r *http.Request) {
947 xid := r.FormValue("xid")
948 userinfo := login.GetUserInfo(r)
949 user, _ := butwhatabout(userinfo.Username)
950
951 log.Printf("bonking %s", xid)
952
953 xonk := getxonk(userinfo.UserID, xid)
954 if xonk == nil {
955 return
956 }
957 if !xonk.Public {
958 return
959 }
960 donksforhonks([]*Honk{xonk})
961
962 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
963 if err != nil {
964 log.Printf("error acking bonk: %s", err)
965 }
966
967 oonker := xonk.Oonker
968 if oonker == "" {
969 oonker = xonk.Honker
970 }
971 dt := time.Now().UTC()
972 bonk := &Honk{
973 UserID: userinfo.UserID,
974 Username: userinfo.Username,
975 What: "bonk",
976 Honker: user.URL,
977 Oonker: oonker,
978 XID: xonk.XID,
979 RID: xonk.RID,
980 Noise: xonk.Noise,
981 Precis: xonk.Precis,
982 URL: xonk.URL,
983 Date: dt,
984 Donks: xonk.Donks,
985 Whofore: 2,
986 Convoy: xonk.Convoy,
987 Audience: []string{thewholeworld, oonker},
988 Public: true,
989 Format: "html",
990 Place: xonk.Place,
991 Onts: xonk.Onts,
992 Time: xonk.Time,
993 }
994
995 err = savehonk(bonk)
996 if err != nil {
997 log.Printf("uh oh")
998 return
999 }
1000
1001 go honkworldwide(user, bonk)
1002
1003 if r.FormValue("js") != "1" {
1004 templinfo := getInfo(r)
1005 templinfo["ServerMessage"] = "Bonked!"
1006 err = readviews.Execute(w, "msg.html", templinfo)
1007 if err != nil {
1008 log.Print(err)
1009 }
1010 }
1011}
1012
1013func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
1014 zonk := &Honk{
1015 What: what,
1016 XID: xonk.XID,
1017 Date: time.Now().UTC(),
1018 Audience: oneofakind(xonk.Audience),
1019 }
1020 zonk.Public = !keepitquiet(zonk.Audience)
1021
1022 log.Printf("announcing %sed honk: %s", what, xonk.XID)
1023 go honkworldwide(user, zonk)
1024}
1025
1026func zonkit(w http.ResponseWriter, r *http.Request) {
1027 wherefore := r.FormValue("wherefore")
1028 what := r.FormValue("what")
1029 userinfo := login.GetUserInfo(r)
1030 user, _ := butwhatabout(userinfo.Username)
1031
1032 if wherefore == "save" {
1033 xonk := getxonk(userinfo.UserID, what)
1034 if xonk != nil {
1035 _, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1036 if err != nil {
1037 log.Printf("error saving: %s", err)
1038 }
1039 }
1040 return
1041 }
1042
1043 if wherefore == "unsave" {
1044 xonk := getxonk(userinfo.UserID, what)
1045 if xonk != nil {
1046 _, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1047 if err != nil {
1048 log.Printf("error unsaving: %s", err)
1049 }
1050 }
1051 return
1052 }
1053
1054 // my hammer is too big, oh well
1055 defer oldjonks.Flush()
1056
1057 if wherefore == "ack" {
1058 xonk := getxonk(userinfo.UserID, what)
1059 if xonk != nil {
1060 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1061 if err != nil {
1062 log.Printf("error acking: %s", err)
1063 }
1064 sendzonkofsorts(xonk, user, "ack")
1065 }
1066 return
1067 }
1068
1069 if wherefore == "deack" {
1070 xonk := getxonk(userinfo.UserID, what)
1071 if xonk != nil {
1072 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1073 if err != nil {
1074 log.Printf("error deacking: %s", err)
1075 }
1076 sendzonkofsorts(xonk, user, "deack")
1077 }
1078 return
1079 }
1080
1081 if wherefore == "unbonk" {
1082 xonk := getbonk(userinfo.UserID, what)
1083 if xonk != nil {
1084 deletehonk(xonk.ID)
1085 xonk = getxonk(userinfo.UserID, what)
1086 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1087 if err != nil {
1088 log.Printf("error unbonking: %s", err)
1089 }
1090 sendzonkofsorts(xonk, user, "unbonk")
1091 }
1092 return
1093 }
1094
1095 log.Printf("zonking %s %s", wherefore, what)
1096 if wherefore == "zonk" {
1097 xonk := getxonk(userinfo.UserID, what)
1098 if xonk != nil {
1099 deletehonk(xonk.ID)
1100 if xonk.Whofore == 2 || xonk.Whofore == 3 {
1101 sendzonkofsorts(xonk, user, "zonk")
1102 }
1103 }
1104 }
1105 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1106 if err != nil {
1107 log.Printf("error saving zonker: %s", err)
1108 return
1109 }
1110}
1111
1112func edithonkpage(w http.ResponseWriter, r *http.Request) {
1113 u := login.GetUserInfo(r)
1114 user, _ := butwhatabout(u.Username)
1115 xid := r.FormValue("xid")
1116 honk := getxonk(u.UserID, xid)
1117 if !canedithonk(user, honk) {
1118 http.Error(w, "no editing that please", http.StatusInternalServerError)
1119 return
1120 }
1121
1122 noise := honk.Noise
1123 if honk.Precis != "" {
1124 noise = honk.Precis + "\n\n" + noise
1125 }
1126
1127 honks := []*Honk{honk}
1128 donksforhonks(honks)
1129 reverbolate(u.UserID, honks)
1130 templinfo := getInfo(r)
1131 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1132 templinfo["Honks"] = honks
1133 templinfo["Noise"] = noise
1134 templinfo["SavedPlace"] = honk.Place
1135 templinfo["ServerMessage"] = "honk edit"
1136 templinfo["IsPreview"] = true
1137 templinfo["UpdateXID"] = honk.XID
1138 if len(honk.Donks) > 0 {
1139 templinfo["SavedFile"] = honk.Donks[0].XID
1140 }
1141 err := readviews.Execute(w, "honkpage.html", templinfo)
1142 if err != nil {
1143 log.Print(err)
1144 }
1145}
1146
1147func newhonkpage(w http.ResponseWriter, r *http.Request) {
1148 u := login.GetUserInfo(r)
1149 rid := r.FormValue("rid")
1150 noise := ""
1151
1152 xonk := getxonk(u.UserID, rid)
1153 if xonk != nil {
1154 _, replto := handles(xonk.Honker)
1155 if replto != "" {
1156 noise = "@" + replto + " "
1157 }
1158 }
1159
1160 templinfo := getInfo(r)
1161 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1162 templinfo["InReplyTo"] = rid
1163 templinfo["Noise"] = noise
1164 templinfo["ServerMessage"] = "compose honk"
1165 templinfo["IsPreview"] = true
1166 err := readviews.Execute(w, "honkpage.html", templinfo)
1167 if err != nil {
1168 log.Print(err)
1169 }
1170}
1171
1172func canedithonk(user *WhatAbout, honk *Honk) bool {
1173 if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1174 return false
1175 }
1176 return true
1177}
1178
1179// what a hot mess this function is
1180func submithonk(w http.ResponseWriter, r *http.Request) {
1181 rid := r.FormValue("rid")
1182 noise := r.FormValue("noise")
1183
1184 userinfo := login.GetUserInfo(r)
1185 user, _ := butwhatabout(userinfo.Username)
1186
1187 dt := time.Now().UTC()
1188 updatexid := r.FormValue("updatexid")
1189 var honk *Honk
1190 if updatexid != "" {
1191 honk = getxonk(userinfo.UserID, updatexid)
1192 if !canedithonk(user, honk) {
1193 http.Error(w, "no editing that please", http.StatusInternalServerError)
1194 return
1195 }
1196 honk.Date = dt
1197 honk.What = "update"
1198 honk.Format = "markdown"
1199 } else {
1200 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1201 what := "honk"
1202 if rid != "" {
1203 what = "tonk"
1204 }
1205 honk = &Honk{
1206 UserID: userinfo.UserID,
1207 Username: userinfo.Username,
1208 What: what,
1209 Honker: user.URL,
1210 XID: xid,
1211 Date: dt,
1212 Format: "markdown",
1213 }
1214 }
1215
1216 noise = hooterize(noise)
1217 honk.Noise = noise
1218 translate(honk, false)
1219
1220 var convoy string
1221 if rid != "" {
1222 xonk := getxonk(userinfo.UserID, rid)
1223 if xonk != nil {
1224 if xonk.Public {
1225 honk.Audience = append(honk.Audience, xonk.Audience...)
1226 }
1227 convoy = xonk.Convoy
1228 } else {
1229 xonkaud, c := whosthere(rid)
1230 honk.Audience = append(honk.Audience, xonkaud...)
1231 convoy = c
1232 }
1233 for i, a := range honk.Audience {
1234 if a == thewholeworld {
1235 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1236 break
1237 }
1238 }
1239 honk.RID = rid
1240 } else {
1241 honk.Audience = []string{thewholeworld}
1242 }
1243 if honk.Noise != "" && honk.Noise[0] == '@' {
1244 honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
1245 } else {
1246 honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
1247 }
1248
1249 if convoy == "" {
1250 convoy = "data:,electrichonkytonk-" + xfiltrate()
1251 }
1252 butnottooloud(honk.Audience)
1253 honk.Audience = oneofakind(honk.Audience)
1254 if len(honk.Audience) == 0 {
1255 log.Printf("honk to nowhere")
1256 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1257 return
1258 }
1259 honk.Public = !keepitquiet(honk.Audience)
1260 honk.Convoy = convoy
1261
1262 donkxid := r.FormValue("donkxid")
1263 if donkxid == "" {
1264 file, filehdr, err := r.FormFile("donk")
1265 if err == nil {
1266 var buf bytes.Buffer
1267 io.Copy(&buf, file)
1268 file.Close()
1269 data := buf.Bytes()
1270 xid := xfiltrate()
1271 var media, name string
1272 img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
1273 if err == nil {
1274 data = img.Data
1275 format := img.Format
1276 media = "image/" + format
1277 if format == "jpeg" {
1278 format = "jpg"
1279 }
1280 name = xid + "." + format
1281 xid = name
1282 } else {
1283 maxsize := 100000
1284 if len(data) > maxsize {
1285 log.Printf("bad image: %s too much text: %d", err, len(data))
1286 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1287 return
1288 }
1289 for i := 0; i < len(data); i++ {
1290 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1291 log.Printf("bad image: %s not text: %d", err, data[i])
1292 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1293 return
1294 }
1295 }
1296 media = "text/plain"
1297 name = filehdr.Filename
1298 if name == "" {
1299 name = xid + ".txt"
1300 }
1301 xid += ".txt"
1302 }
1303 desc := strings.TrimSpace(r.FormValue("donkdesc"))
1304 if desc == "" {
1305 desc = name
1306 }
1307 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1308 fileid, err := savefile(xid, name, desc, url, media, true, data)
1309 if err != nil {
1310 log.Printf("unable to save image: %s", err)
1311 return
1312 }
1313 d := &Donk{
1314 FileID: fileid,
1315 XID: xid,
1316 Desc: desc,
1317 URL: url,
1318 Local: true,
1319 }
1320 honk.Donks = append(honk.Donks, d)
1321 donkxid = xid
1322 }
1323 } else {
1324 xid := donkxid
1325 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1326 donk := finddonk(url)
1327 if donk != nil {
1328 honk.Donks = append(honk.Donks, donk)
1329 } else {
1330 log.Printf("can't find file: %s", xid)
1331 }
1332 }
1333 herd := herdofemus(honk.Noise)
1334 for _, e := range herd {
1335 donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1336 if donk != nil {
1337 donk.Name = e.Name
1338 honk.Donks = append(honk.Donks, donk)
1339 }
1340 }
1341 memetize(honk)
1342 imaginate(honk)
1343
1344 placename := strings.TrimSpace(r.FormValue("placename"))
1345 placelat := strings.TrimSpace(r.FormValue("placelat"))
1346 placelong := strings.TrimSpace(r.FormValue("placelong"))
1347 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1348 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1349 p := new(Place)
1350 p.Name = placename
1351 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1352 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1353 p.Url = placeurl
1354 honk.Place = p
1355 }
1356 timestart := strings.TrimSpace(r.FormValue("timestart"))
1357 if timestart != "" {
1358 t := new(Time)
1359 now := time.Now().Local()
1360 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1361 start, err := time.ParseInLocation(layout, timestart, now.Location())
1362 if err == nil {
1363 if start.Year() == 0 {
1364 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1365 }
1366 t.StartTime = start
1367 break
1368 }
1369 }
1370 timeend := r.FormValue("timeend")
1371 dur := parseDuration(timeend)
1372 if dur != 0 {
1373 t.Duration = Duration(dur)
1374 }
1375 if !t.StartTime.IsZero() {
1376 honk.What = "event"
1377 honk.Time = t
1378 }
1379 }
1380
1381 if honk.Public {
1382 honk.Whofore = 2
1383 } else {
1384 honk.Whofore = 3
1385 }
1386
1387 // back to markdown
1388 honk.Noise = noise
1389
1390 if r.FormValue("preview") == "preview" {
1391 honks := []*Honk{honk}
1392 reverbolate(userinfo.UserID, honks)
1393 templinfo := getInfo(r)
1394 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1395 templinfo["Honks"] = honks
1396 templinfo["InReplyTo"] = r.FormValue("rid")
1397 templinfo["Noise"] = r.FormValue("noise")
1398 templinfo["SavedFile"] = donkxid
1399 templinfo["IsPreview"] = true
1400 templinfo["ServerMessage"] = "honk preview"
1401 err := readviews.Execute(w, "honkpage.html", templinfo)
1402 if err != nil {
1403 log.Print(err)
1404 }
1405 return
1406 }
1407
1408 if updatexid != "" {
1409 updatehonk(honk)
1410 oldjonks.Clear(honk.XID)
1411 } else {
1412 err := savehonk(honk)
1413 if err != nil {
1414 log.Printf("uh oh")
1415 return
1416 }
1417 }
1418
1419 // reload for consistency
1420 honk.Donks = nil
1421 donksforhonks([]*Honk{honk})
1422
1423 go honkworldwide(user, honk)
1424
1425 http.Redirect(w, r, honk.XID[len(serverName)+8:], http.StatusSeeOther)
1426}
1427
1428func showhonkers(w http.ResponseWriter, r *http.Request) {
1429 userinfo := login.GetUserInfo(r)
1430 templinfo := getInfo(r)
1431 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1432 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1433 err := readviews.Execute(w, "honkers.html", templinfo)
1434 if err != nil {
1435 log.Print(err)
1436 }
1437}
1438
1439var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1440 honkers := gethonkers(userid)
1441 var combos []string
1442 for _, h := range honkers {
1443 combos = append(combos, h.Combos...)
1444 }
1445 for i, c := range combos {
1446 if c == "-" {
1447 combos[i] = ""
1448 }
1449 }
1450 combos = oneofakind(combos)
1451 sort.Strings(combos)
1452 return combos, true
1453}, Invalidator: &honkerinvalidator})
1454
1455func showcombos(w http.ResponseWriter, r *http.Request) {
1456 userinfo := login.GetUserInfo(r)
1457 var combos []string
1458 combocache.Get(userinfo.UserID, &combos)
1459 templinfo := getInfo(r)
1460 err := readviews.Execute(w, "combos.html", templinfo)
1461 if err != nil {
1462 log.Print(err)
1463 }
1464}
1465
1466func submithonker(w http.ResponseWriter, r *http.Request) {
1467 u := login.GetUserInfo(r)
1468 name := strings.TrimSpace(r.FormValue("name"))
1469 url := strings.TrimSpace(r.FormValue("url"))
1470 peep := r.FormValue("peep")
1471 combos := strings.TrimSpace(r.FormValue("combos"))
1472 combos = " " + combos + " "
1473 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1474
1475 defer honkerinvalidator.Clear(u.UserID)
1476
1477 if honkerid > 0 {
1478 goodbye := r.FormValue("goodbye")
1479 if goodbye == "F" {
1480 db := opendatabase()
1481 row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1482 honkerid, u.UserID)
1483 err := row.Scan(&url)
1484 if err != nil {
1485 log.Printf("can't get honker xid: %s", err)
1486 return
1487 }
1488 log.Printf("unsubscribing from %s", url)
1489 user, _ := butwhatabout(u.Username)
1490 _, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, name, "sub")
1491 if err != nil {
1492 log.Printf("error updating honker: %s", err)
1493 return
1494 }
1495 go itakeitallback(user, url)
1496
1497 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1498 return
1499 }
1500 if goodbye == "X" {
1501 var owner string
1502 db := opendatabase()
1503 row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1504 honkerid, u.UserID)
1505 err := row.Scan(&url, &owner)
1506 if err != nil {
1507 log.Printf("can't get honker xid: %s", err)
1508 return
1509 }
1510 log.Printf("resubscribing to %s", url)
1511 user, _ := butwhatabout(u.Username)
1512 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "unsub")
1513 if err == nil {
1514 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "peep")
1515 }
1516 if err != nil {
1517 log.Printf("error updating honker: %s", err)
1518 return
1519 }
1520 go subsub(user, url, owner)
1521
1522 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1523 return
1524 }
1525 _, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1526 if err != nil {
1527 log.Printf("update honker err: %s", err)
1528 return
1529 }
1530 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1531 return
1532 }
1533
1534 if url == "" {
1535 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1536 return
1537 }
1538
1539 flavor := "presub"
1540 if peep == "peep" {
1541 flavor = "peep"
1542 }
1543
1544 if url[0] == '#' {
1545 flavor = "peep"
1546 if name == "" {
1547 name = url
1548 }
1549 _, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url)
1550 if err != nil {
1551 log.Print(err)
1552 return
1553 }
1554 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1555 return
1556 }
1557
1558 info, err := investigate(url)
1559 if err != nil {
1560 http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1561 log.Printf("failed to investigate honker: %s", err)
1562 return
1563 }
1564 url = info.XID
1565
1566 db := opendatabase()
1567 row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1568 var x string
1569 err = row.Scan(&x)
1570 if err != sql.ErrNoRows {
1571 http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1572 if err != nil {
1573 log.Printf("honker scan err: %s", err)
1574 }
1575 return
1576 }
1577
1578 if name == "" {
1579 name = info.Name
1580 }
1581 _, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner)
1582 if err != nil {
1583 log.Print(err)
1584 return
1585 }
1586 if flavor == "presub" {
1587 user, _ := butwhatabout(u.Username)
1588 go subsub(user, url, info.Owner)
1589 }
1590 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1591}
1592
1593func hfcspage(w http.ResponseWriter, r *http.Request) {
1594 userinfo := login.GetUserInfo(r)
1595
1596 filters := getfilters(userinfo.UserID, filtAny)
1597
1598 templinfo := getInfo(r)
1599 templinfo["Filters"] = filters
1600 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1601 err := readviews.Execute(w, "hfcs.html", templinfo)
1602 if err != nil {
1603 log.Print(err)
1604 }
1605}
1606
1607func savehfcs(w http.ResponseWriter, r *http.Request) {
1608 userinfo := login.GetUserInfo(r)
1609 itsok := r.FormValue("itsok")
1610 if itsok == "iforgiveyou" {
1611 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1612 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1613 if err != nil {
1614 log.Printf("error deleting filter: %s", err)
1615 }
1616 filtcache.Clear(userinfo.UserID)
1617 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1618 return
1619 }
1620
1621 filt := new(Filter)
1622 filt.Name = strings.TrimSpace(r.FormValue("name"))
1623 filt.Date = time.Now().UTC()
1624 filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1625 filt.IncludeAudience = r.FormValue("incaud") == "yes"
1626 filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1627 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1628 filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1629 filt.Reject = r.FormValue("doreject") == "yes"
1630 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1631 filt.Hide = r.FormValue("dohide") == "yes"
1632 filt.Collapse = r.FormValue("docollapse") == "yes"
1633 filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1634 filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1635 if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
1636 filt.Expiration = time.Now().UTC().Add(dur)
1637 }
1638
1639 if filt.Actor == "" && filt.Text == "" {
1640 log.Printf("blank filter")
1641 return
1642 }
1643
1644 j, err := jsonify(filt)
1645 if err == nil {
1646 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1647 }
1648 if err != nil {
1649 log.Printf("error saving filter: %s", err)
1650 }
1651
1652 filtcache.Clear(userinfo.UserID)
1653 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1654}
1655
1656func accountpage(w http.ResponseWriter, r *http.Request) {
1657 u := login.GetUserInfo(r)
1658 user, _ := butwhatabout(u.Username)
1659 templinfo := getInfo(r)
1660 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1661 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1662 templinfo["User"] = user
1663 err := readviews.Execute(w, "account.html", templinfo)
1664 if err != nil {
1665 log.Print(err)
1666 }
1667}
1668
1669func dochpass(w http.ResponseWriter, r *http.Request) {
1670 err := login.ChangePassword(w, r)
1671 if err != nil {
1672 log.Printf("error changing password: %s", err)
1673 }
1674 http.Redirect(w, r, "/account", http.StatusSeeOther)
1675}
1676
1677func fingerlicker(w http.ResponseWriter, r *http.Request) {
1678 orig := r.FormValue("resource")
1679
1680 log.Printf("finger lick: %s", orig)
1681
1682 if strings.HasPrefix(orig, "acct:") {
1683 orig = orig[5:]
1684 }
1685
1686 name := orig
1687 idx := strings.LastIndexByte(name, '/')
1688 if idx != -1 {
1689 name = name[idx+1:]
1690 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1691 log.Printf("foreign request rejected")
1692 name = ""
1693 }
1694 } else {
1695 idx = strings.IndexByte(name, '@')
1696 if idx != -1 {
1697 name = name[:idx]
1698 if name+"@"+serverName != orig {
1699 log.Printf("foreign request rejected")
1700 name = ""
1701 }
1702 }
1703 }
1704 user, err := butwhatabout(name)
1705 if err != nil {
1706 http.NotFound(w, r)
1707 return
1708 }
1709 if stealthmode(user.ID, r) {
1710 http.NotFound(w, r)
1711 return
1712 }
1713
1714 j := junk.New()
1715 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1716 j["aliases"] = []string{user.URL}
1717 l := junk.New()
1718 l["rel"] = "self"
1719 l["type"] = `application/activity+json`
1720 l["href"] = user.URL
1721 j["links"] = []junk.Junk{l}
1722
1723 w.Header().Set("Content-Type", "application/jrd+json")
1724 j.Write(w)
1725}
1726
1727func somedays() string {
1728 secs := 432000 + notrand.Int63n(432000)
1729 return fmt.Sprintf("%d", secs)
1730}
1731
1732func avatate(w http.ResponseWriter, r *http.Request) {
1733 n := r.FormValue("a")
1734 a := avatar(n)
1735 w.Header().Set("Cache-Control", "max-age="+somedays())
1736 w.Write(a)
1737}
1738
1739func servecss(w http.ResponseWriter, r *http.Request) {
1740 fd, err := os.Open("views" + r.URL.Path)
1741 if err != nil {
1742 http.NotFound(w, r)
1743 return
1744 }
1745 defer fd.Close()
1746 w.Header().Set("Cache-Control", "max-age=7776000")
1747 w.Header().Set("Content-Type", "text/css; charset=utf-8")
1748 err = css.Filter(fd, w)
1749 if err != nil {
1750 log.Printf("error filtering css: %s", err)
1751 }
1752}
1753func serveasset(w http.ResponseWriter, r *http.Request) {
1754 w.Header().Set("Cache-Control", "max-age=7776000")
1755 http.ServeFile(w, r, "views"+r.URL.Path)
1756}
1757func servehelp(w http.ResponseWriter, r *http.Request) {
1758 name := mux.Vars(r)["name"]
1759 w.Header().Set("Cache-Control", "max-age=3600")
1760 http.ServeFile(w, r, "docs/"+name)
1761}
1762func servehtml(w http.ResponseWriter, r *http.Request) {
1763 u := login.GetUserInfo(r)
1764 templinfo := getInfo(r)
1765 templinfo["AboutMsg"] = aboutMsg
1766 templinfo["LoginMsg"] = loginMsg
1767 if u == nil {
1768 w.Header().Set("Cache-Control", "max-age=60")
1769 }
1770 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1771 if err != nil {
1772 log.Print(err)
1773 }
1774}
1775func serveemu(w http.ResponseWriter, r *http.Request) {
1776 xid := mux.Vars(r)["xid"]
1777 w.Header().Set("Cache-Control", "max-age="+somedays())
1778 http.ServeFile(w, r, "emus/"+xid)
1779}
1780func servememe(w http.ResponseWriter, r *http.Request) {
1781 xid := mux.Vars(r)["xid"]
1782 w.Header().Set("Cache-Control", "max-age="+somedays())
1783 http.ServeFile(w, r, "memes/"+xid)
1784}
1785
1786func servefile(w http.ResponseWriter, r *http.Request) {
1787 xid := mux.Vars(r)["xid"]
1788 row := stmtGetFileData.QueryRow(xid)
1789 var media string
1790 var data []byte
1791 err := row.Scan(&media, &data)
1792 if err != nil {
1793 log.Printf("error loading file: %s", err)
1794 http.NotFound(w, r)
1795 return
1796 }
1797 w.Header().Set("Content-Type", media)
1798 w.Header().Set("X-Content-Type-Options", "nosniff")
1799 w.Header().Set("Cache-Control", "max-age="+somedays())
1800 w.Write(data)
1801}
1802
1803func nomoroboto(w http.ResponseWriter, r *http.Request) {
1804 io.WriteString(w, "User-agent: *\n")
1805 io.WriteString(w, "Disallow: /a\n")
1806 io.WriteString(w, "Disallow: /d\n")
1807 io.WriteString(w, "Disallow: /meme\n")
1808 io.WriteString(w, "Disallow: /o\n")
1809 for _, u := range allusers() {
1810 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1811 }
1812}
1813
1814func webhydra(w http.ResponseWriter, r *http.Request) {
1815 u := login.GetUserInfo(r)
1816 userid := u.UserID
1817 templinfo := getInfo(r)
1818 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1819 page := r.FormValue("page")
1820
1821 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
1822
1823 var honks []*Honk
1824 switch page {
1825 case "atme":
1826 honks = gethonksforme(userid, wanted)
1827 honks = osmosis(honks, userid, false)
1828 templinfo["ServerMessage"] = "at me!"
1829 case "home":
1830 honks = gethonksforuser(userid, wanted)
1831 honks = osmosis(honks, userid, true)
1832 templinfo["ServerMessage"] = serverMsg
1833 case "first":
1834 honks = gethonksforuserfirstclass(userid, wanted)
1835 honks = osmosis(honks, userid, true)
1836 templinfo["ServerMessage"] = "first class only"
1837 case "saved":
1838 honks = getsavedhonks(userid, wanted)
1839 templinfo["PageName"] = "saved"
1840 templinfo["ServerMessage"] = "saved honks"
1841 case "combo":
1842 c := r.FormValue("c")
1843 honks = gethonksbycombo(userid, c, wanted)
1844 honks = osmosis(honks, userid, false)
1845 templinfo["ServerMessage"] = "honks by combo: " + c
1846 case "convoy":
1847 c := r.FormValue("c")
1848 honks = gethonksbyconvoy(userid, c, wanted)
1849 honks = osmosis(honks, userid, false)
1850 templinfo["ServerMessage"] = "honks in convoy: " + c
1851 case "honker":
1852 xid := r.FormValue("xid")
1853 if strings.IndexByte(xid, '@') != -1 {
1854 xid = gofish(xid)
1855 }
1856 honks = gethonksbyxonker(userid, xid, wanted)
1857 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
1858 templinfo["ServerMessage"] = msg
1859 default:
1860 http.NotFound(w, r)
1861 }
1862 if len(honks) > 0 {
1863 templinfo["TopHID"] = honks[0].ID
1864 } else {
1865 templinfo["TopHID"] = wanted
1866 }
1867 reverbolate(userid, honks)
1868 templinfo["Honks"] = honks
1869 w.Header().Set("Content-Type", "text/html; charset=utf-8")
1870 err := readviews.Execute(w, "honkfrags.html", templinfo)
1871 if err != nil {
1872 log.Printf("frag error: %s", err)
1873 }
1874}
1875
1876func serve() {
1877 db := opendatabase()
1878 login.Init(db)
1879
1880 listener, err := openListener()
1881 if err != nil {
1882 log.Fatal(err)
1883 }
1884 go redeliverator()
1885
1886 debug := false
1887 getconfig("debug", &debug)
1888 readviews = templates.Load(debug,
1889 "views/honkpage.html",
1890 "views/honkfrags.html",
1891 "views/honkers.html",
1892 "views/hfcs.html",
1893 "views/combos.html",
1894 "views/honkform.html",
1895 "views/honk.html",
1896 "views/account.html",
1897 "views/about.html",
1898 "views/funzone.html",
1899 "views/login.html",
1900 "views/xzone.html",
1901 "views/msg.html",
1902 "views/header.html",
1903 "views/onts.html",
1904 "views/honkpage.js",
1905 )
1906 if !debug {
1907 assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1908 for _, s := range assets {
1909 savedassetparams[s] = getassetparam(s)
1910 }
1911 }
1912
1913 mux := mux.NewRouter()
1914 mux.Use(login.Checker)
1915
1916 posters := mux.Methods("POST").Subrouter()
1917 getters := mux.Methods("GET").Subrouter()
1918
1919 getters.HandleFunc("/", homepage)
1920 getters.HandleFunc("/home", homepage)
1921 getters.HandleFunc("/front", homepage)
1922 getters.HandleFunc("/events", homepage)
1923 getters.HandleFunc("/robots.txt", nomoroboto)
1924 getters.HandleFunc("/rss", showrss)
1925 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1926 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1927 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1928 posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1929 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1930 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1931 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1932 getters.HandleFunc("/a", avatate)
1933 getters.HandleFunc("/o", thelistingoftheontologies)
1934 getters.HandleFunc("/o/{name:.+}", showontology)
1935 getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1936 getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1937 getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1938 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1939
1940 getters.HandleFunc("/server", serveractor)
1941 posters.HandleFunc("/server/inbox", serverinbox)
1942
1943 getters.HandleFunc("/style.css", servecss)
1944 getters.HandleFunc("/local.css", servecss)
1945 getters.HandleFunc("/honkpage.js", serveasset)
1946 getters.HandleFunc("/about", servehtml)
1947 getters.HandleFunc("/login", servehtml)
1948 posters.HandleFunc("/dologin", login.LoginFunc)
1949 getters.HandleFunc("/logout", login.LogoutFunc)
1950 getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
1951
1952 loggedin := mux.NewRoute().Subrouter()
1953 loggedin.Use(login.Required)
1954 loggedin.HandleFunc("/first", homepage)
1955 loggedin.HandleFunc("/saved", homepage)
1956 loggedin.HandleFunc("/account", accountpage)
1957 loggedin.HandleFunc("/funzone", showfunzone)
1958 loggedin.HandleFunc("/chpass", dochpass)
1959 loggedin.HandleFunc("/atme", homepage)
1960 loggedin.HandleFunc("/hfcs", hfcspage)
1961 loggedin.HandleFunc("/xzone", xzone)
1962 loggedin.HandleFunc("/newhonk", newhonkpage)
1963 loggedin.HandleFunc("/edit", edithonkpage)
1964 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1965 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1966 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1967 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
1968 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1969 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1970 loggedin.HandleFunc("/honkers", showhonkers)
1971 loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1972 loggedin.HandleFunc("/h", showhonker)
1973 loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1974 loggedin.HandleFunc("/c", showcombos)
1975 loggedin.HandleFunc("/t", showconvoy)
1976 loggedin.HandleFunc("/q", showsearch)
1977 loggedin.HandleFunc("/hydra", webhydra)
1978 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1979
1980 err = http.Serve(listener, mux)
1981 if err != nil {
1982 log.Fatal(err)
1983 }
1984}