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