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