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