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