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