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