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