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