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