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 options.Reaction = r.FormValue("reaction")
1136 if ava := re_avatar.FindString(whatabout); ava != "" {
1137 whatabout = re_avatar.ReplaceAllString(whatabout, "")
1138 ava = ava[7:]
1139 if ava[0] == ' ' {
1140 ava = ava[1:]
1141 }
1142 options.Avatar = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1143 } else {
1144 options.Avatar = ""
1145 }
1146 whatabout = strings.TrimSpace(whatabout)
1147 j, err := jsonify(options)
1148 if err == nil {
1149 _, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1150 }
1151 if err != nil {
1152 log.Printf("error bouting what: %s", err)
1153 }
1154 somenamedusers.Clear(u.Username)
1155 somenumberedusers.Clear(u.UserID)
1156
1157 http.Redirect(w, r, "/account", http.StatusSeeOther)
1158}
1159
1160func submitbonk(w http.ResponseWriter, r *http.Request) {
1161 xid := r.FormValue("xid")
1162 userinfo := login.GetUserInfo(r)
1163 user, _ := butwhatabout(userinfo.Username)
1164
1165 log.Printf("bonking %s", xid)
1166
1167 xonk := getxonk(userinfo.UserID, xid)
1168 if xonk == nil {
1169 return
1170 }
1171 if !xonk.Public {
1172 return
1173 }
1174 if xonk.IsBonked() {
1175 return
1176 }
1177 donksforhonks([]*Honk{xonk})
1178
1179 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1180 if err != nil {
1181 log.Printf("error acking bonk: %s", err)
1182 }
1183
1184 oonker := xonk.Oonker
1185 if oonker == "" {
1186 oonker = xonk.Honker
1187 }
1188 dt := time.Now().UTC()
1189 bonk := &Honk{
1190 UserID: userinfo.UserID,
1191 Username: userinfo.Username,
1192 What: "bonk",
1193 Honker: user.URL,
1194 Oonker: oonker,
1195 XID: xonk.XID,
1196 RID: xonk.RID,
1197 Noise: xonk.Noise,
1198 Precis: xonk.Precis,
1199 URL: xonk.URL,
1200 Date: dt,
1201 Donks: xonk.Donks,
1202 Whofore: 2,
1203 Convoy: xonk.Convoy,
1204 Audience: []string{thewholeworld, oonker},
1205 Public: true,
1206 Format: "html",
1207 Place: xonk.Place,
1208 Onts: xonk.Onts,
1209 Time: xonk.Time,
1210 }
1211
1212 err = savehonk(bonk)
1213 if err != nil {
1214 log.Printf("uh oh")
1215 return
1216 }
1217
1218 go honkworldwide(user, bonk)
1219
1220 if r.FormValue("js") != "1" {
1221 templinfo := getInfo(r)
1222 templinfo["ServerMessage"] = "Bonked!"
1223 err = readviews.Execute(w, "msg.html", templinfo)
1224 if err != nil {
1225 log.Print(err)
1226 }
1227 }
1228}
1229
1230func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
1231 zonk := &Honk{
1232 What: what,
1233 XID: xonk.XID,
1234 Date: time.Now().UTC(),
1235 Audience: oneofakind(xonk.Audience),
1236 }
1237 zonk.Public = loudandproud(zonk.Audience)
1238
1239 log.Printf("announcing %sed honk: %s", what, xonk.XID)
1240 go honkworldwide(user, zonk)
1241}
1242
1243func zonkit(w http.ResponseWriter, r *http.Request) {
1244 wherefore := r.FormValue("wherefore")
1245 what := r.FormValue("what")
1246 userinfo := login.GetUserInfo(r)
1247 user, _ := butwhatabout(userinfo.Username)
1248
1249 if wherefore == "save" {
1250 xonk := getxonk(userinfo.UserID, what)
1251 if xonk != nil {
1252 _, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1253 if err != nil {
1254 log.Printf("error saving: %s", err)
1255 }
1256 }
1257 return
1258 }
1259
1260 if wherefore == "unsave" {
1261 xonk := getxonk(userinfo.UserID, what)
1262 if xonk != nil {
1263 _, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1264 if err != nil {
1265 log.Printf("error unsaving: %s", err)
1266 }
1267 }
1268 return
1269 }
1270
1271 if wherefore == "react" {
1272 xonk := getxonk(userinfo.UserID, what)
1273 if xonk != nil {
1274 _, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1275 if err != nil {
1276 log.Printf("error saving: %s", err)
1277 }
1278 sendzonkofsorts(xonk, user, "react")
1279 }
1280 return
1281 }
1282
1283 // my hammer is too big, oh well
1284 defer oldjonks.Flush()
1285
1286 if wherefore == "ack" {
1287 xonk := getxonk(userinfo.UserID, what)
1288 if xonk != nil && !xonk.IsAcked() {
1289 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1290 if err != nil {
1291 log.Printf("error acking: %s", err)
1292 }
1293 sendzonkofsorts(xonk, user, "ack")
1294 }
1295 return
1296 }
1297
1298 if wherefore == "deack" {
1299 xonk := getxonk(userinfo.UserID, what)
1300 if xonk != nil && xonk.IsAcked() {
1301 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1302 if err != nil {
1303 log.Printf("error deacking: %s", err)
1304 }
1305 sendzonkofsorts(xonk, user, "deack")
1306 }
1307 return
1308 }
1309
1310 if wherefore == "unbonk" {
1311 xonk := getbonk(userinfo.UserID, what)
1312 if xonk != nil {
1313 deletehonk(xonk.ID)
1314 xonk = getxonk(userinfo.UserID, what)
1315 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1316 if err != nil {
1317 log.Printf("error unbonking: %s", err)
1318 }
1319 sendzonkofsorts(xonk, user, "unbonk")
1320 }
1321 return
1322 }
1323
1324 if wherefore == "untag" {
1325 xonk := getxonk(userinfo.UserID, what)
1326 if xonk != nil {
1327 _, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1328 if err != nil {
1329 log.Printf("error untagging: %s", err)
1330 }
1331 }
1332 var badparents map[string]bool
1333 untagged.GetAndLock(userinfo.UserID, &badparents)
1334 badparents[what] = true
1335 untagged.Unlock()
1336 return
1337 }
1338
1339 log.Printf("zonking %s %s", wherefore, what)
1340 if wherefore == "zonk" {
1341 xonk := getxonk(userinfo.UserID, what)
1342 if xonk != nil {
1343 deletehonk(xonk.ID)
1344 if xonk.Whofore == 2 || xonk.Whofore == 3 {
1345 sendzonkofsorts(xonk, user, "zonk")
1346 }
1347 }
1348 }
1349 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1350 if err != nil {
1351 log.Printf("error saving zonker: %s", err)
1352 return
1353 }
1354}
1355
1356func edithonkpage(w http.ResponseWriter, r *http.Request) {
1357 u := login.GetUserInfo(r)
1358 user, _ := butwhatabout(u.Username)
1359 xid := r.FormValue("xid")
1360 honk := getxonk(u.UserID, xid)
1361 if !canedithonk(user, honk) {
1362 http.Error(w, "no editing that please", http.StatusInternalServerError)
1363 return
1364 }
1365
1366 noise := honk.Noise
1367
1368 honks := []*Honk{honk}
1369 donksforhonks(honks)
1370 reverbolate(u.UserID, honks)
1371 templinfo := getInfo(r)
1372 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1373 templinfo["Honks"] = honks
1374 templinfo["MapLink"] = getmaplink(u)
1375 templinfo["Noise"] = noise
1376 templinfo["SavedPlace"] = honk.Place
1377 if tm := honk.Time; tm != nil {
1378 templinfo["ShowTime"] = ";"
1379 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 03:04")
1380 templinfo["Duration"] = tm.Duration
1381 }
1382 templinfo["ServerMessage"] = "honk edit 2"
1383 templinfo["IsPreview"] = true
1384 templinfo["UpdateXID"] = honk.XID
1385 if len(honk.Donks) > 0 {
1386 templinfo["SavedFile"] = honk.Donks[0].XID
1387 }
1388 err := readviews.Execute(w, "honkpage.html", templinfo)
1389 if err != nil {
1390 log.Print(err)
1391 }
1392}
1393
1394func newhonkpage(w http.ResponseWriter, r *http.Request) {
1395 u := login.GetUserInfo(r)
1396 rid := r.FormValue("rid")
1397 noise := ""
1398
1399 xonk := getxonk(u.UserID, rid)
1400 if xonk != nil {
1401 _, replto := handles(xonk.Honker)
1402 if replto != "" {
1403 noise = "@" + replto + " "
1404 }
1405 }
1406
1407 templinfo := getInfo(r)
1408 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1409 templinfo["InReplyTo"] = rid
1410 templinfo["Noise"] = noise
1411 templinfo["ServerMessage"] = "compose honk"
1412 templinfo["IsPreview"] = true
1413 err := readviews.Execute(w, "honkpage.html", templinfo)
1414 if err != nil {
1415 log.Print(err)
1416 }
1417}
1418
1419func canedithonk(user *WhatAbout, honk *Honk) bool {
1420 if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1421 return false
1422 }
1423 return true
1424}
1425
1426func submitwebhonk(w http.ResponseWriter, r *http.Request) {
1427 submithonk(w, r, false)
1428}
1429
1430// what a hot mess this function is
1431func submithonk(w http.ResponseWriter, r *http.Request, isAPI bool) {
1432 rid := r.FormValue("rid")
1433 noise := r.FormValue("noise")
1434
1435 userinfo := login.GetUserInfo(r)
1436 user, _ := butwhatabout(userinfo.Username)
1437
1438 dt := time.Now().UTC()
1439 updatexid := r.FormValue("updatexid")
1440 var honk *Honk
1441 if updatexid != "" {
1442 honk = getxonk(userinfo.UserID, updatexid)
1443 if !canedithonk(user, honk) {
1444 http.Error(w, "no editing that please", http.StatusInternalServerError)
1445 return
1446 }
1447 honk.Date = dt
1448 honk.What = "update"
1449 honk.Format = "markdown"
1450 } else {
1451 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1452 what := "honk"
1453 if rid != "" {
1454 what = "tonk"
1455 }
1456 honk = &Honk{
1457 UserID: userinfo.UserID,
1458 Username: userinfo.Username,
1459 What: what,
1460 Honker: user.URL,
1461 XID: xid,
1462 Date: dt,
1463 Format: "markdown",
1464 }
1465 }
1466
1467 noise = strings.Replace(noise, "\r", "", -1)
1468 noise = quickrename(noise, userinfo.UserID)
1469 noise = hooterize(noise)
1470 honk.Mentions = bunchofgrapes(noise)
1471 honk.Noise = noise
1472 translate(honk)
1473
1474 var convoy string
1475 if rid != "" {
1476 xonk := getxonk(userinfo.UserID, rid)
1477 if xonk != nil {
1478 if xonk.Public {
1479 honk.Audience = append(honk.Audience, xonk.Audience...)
1480 }
1481 convoy = xonk.Convoy
1482 } else {
1483 xonkaud, c := whosthere(rid)
1484 honk.Audience = append(honk.Audience, xonkaud...)
1485 convoy = c
1486 }
1487 for i, a := range honk.Audience {
1488 if a == thewholeworld {
1489 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1490 break
1491 }
1492 }
1493 honk.RID = rid
1494 if xonk.Precis != "" && honk.Precis == "" {
1495 honk.Precis = xonk.Precis
1496 if !(strings.HasPrefix(honk.Precis, "DZ:") || strings.HasPrefix(honk.Precis, "re: re: re: ")) {
1497 honk.Precis = "re: " + honk.Precis
1498 }
1499 }
1500 } else {
1501 honk.Audience = []string{thewholeworld}
1502 }
1503 if honk.Noise != "" && honk.Noise[0] == '@' {
1504 honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
1505 } else {
1506 honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
1507 }
1508
1509 if convoy == "" {
1510 convoy = "data:,electrichonkytonk-" + xfiltrate()
1511 }
1512 butnottooloud(honk.Audience)
1513 honk.Audience = oneofakind(honk.Audience)
1514 if len(honk.Audience) == 0 {
1515 log.Printf("honk to nowhere")
1516 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1517 return
1518 }
1519 honk.Public = loudandproud(honk.Audience)
1520 honk.Convoy = convoy
1521
1522 donkxid := r.FormValue("donkxid")
1523 if donkxid == "" {
1524 file, filehdr, err := r.FormFile("donk")
1525 if err == nil {
1526 var buf bytes.Buffer
1527 io.Copy(&buf, file)
1528 file.Close()
1529 data := buf.Bytes()
1530 xid := xfiltrate()
1531 var media, name string
1532 img, err := shrinkit(data)
1533 if err == nil {
1534 data = img.Data
1535 format := img.Format
1536 media = "image/" + format
1537 if format == "jpeg" {
1538 format = "jpg"
1539 }
1540 name = xid + "." + format
1541 xid = name
1542 } else {
1543 ct := http.DetectContentType(data)
1544 switch ct {
1545 case "application/pdf":
1546 maxsize := 1000000
1547 if len(data) > maxsize {
1548 log.Printf("bad image: %s too much pdf: %d", err, len(data))
1549 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1550 return
1551 }
1552 media = ct
1553 xid += ".pdf"
1554 name = filehdr.Filename
1555 if name == "" {
1556 name = xid
1557 }
1558 default:
1559 maxsize := 100000
1560 if len(data) > maxsize {
1561 log.Printf("bad image: %s too much text: %d", err, len(data))
1562 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1563 return
1564 }
1565 for i := 0; i < len(data); i++ {
1566 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1567 log.Printf("bad image: %s not text: %d", err, data[i])
1568 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1569 return
1570 }
1571 }
1572 media = "text/plain"
1573 xid += ".txt"
1574 name = filehdr.Filename
1575 if name == "" {
1576 name = xid
1577 }
1578 }
1579 }
1580 desc := strings.TrimSpace(r.FormValue("donkdesc"))
1581 if desc == "" {
1582 desc = name
1583 }
1584 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1585 fileid, err := savefile(xid, name, desc, url, media, true, data)
1586 if err != nil {
1587 log.Printf("unable to save image: %s", err)
1588 return
1589 }
1590 d := &Donk{
1591 FileID: fileid,
1592 XID: xid,
1593 Desc: desc,
1594 URL: url,
1595 Local: true,
1596 }
1597 honk.Donks = append(honk.Donks, d)
1598 donkxid = xid
1599 }
1600 } else {
1601 xid := donkxid
1602 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1603 donk := finddonk(url)
1604 if donk != nil {
1605 honk.Donks = append(honk.Donks, donk)
1606 } else {
1607 log.Printf("can't find file: %s", xid)
1608 }
1609 }
1610 memetize(honk)
1611 imaginate(honk)
1612
1613 placename := strings.TrimSpace(r.FormValue("placename"))
1614 placelat := strings.TrimSpace(r.FormValue("placelat"))
1615 placelong := strings.TrimSpace(r.FormValue("placelong"))
1616 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1617 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1618 p := new(Place)
1619 p.Name = placename
1620 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1621 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1622 p.Url = placeurl
1623 honk.Place = p
1624 }
1625 timestart := strings.TrimSpace(r.FormValue("timestart"))
1626 if timestart != "" {
1627 t := new(Time)
1628 now := time.Now().Local()
1629 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1630 start, err := time.ParseInLocation(layout, timestart, now.Location())
1631 if err == nil {
1632 if start.Year() == 0 {
1633 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1634 }
1635 t.StartTime = start
1636 break
1637 }
1638 }
1639 timeend := r.FormValue("timeend")
1640 dur := parseDuration(timeend)
1641 if dur != 0 {
1642 t.Duration = Duration(dur)
1643 }
1644 if !t.StartTime.IsZero() {
1645 honk.What = "event"
1646 honk.Time = t
1647 }
1648 }
1649
1650 if honk.Public {
1651 honk.Whofore = 2
1652 } else {
1653 honk.Whofore = 3
1654 }
1655
1656 // back to markdown
1657 honk.Noise = noise
1658
1659 if r.FormValue("preview") == "preview" {
1660 honks := []*Honk{honk}
1661 reverbolate(userinfo.UserID, honks)
1662 templinfo := getInfo(r)
1663 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1664 templinfo["Honks"] = honks
1665 templinfo["MapLink"] = getmaplink(userinfo)
1666 templinfo["InReplyTo"] = r.FormValue("rid")
1667 templinfo["Noise"] = r.FormValue("noise")
1668 templinfo["SavedFile"] = donkxid
1669 if tm := honk.Time; tm != nil {
1670 templinfo["ShowTime"] = ";"
1671 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 03:04")
1672 templinfo["Duration"] = tm.Duration
1673 }
1674 templinfo["IsPreview"] = true
1675 templinfo["UpdateXID"] = updatexid
1676 templinfo["ServerMessage"] = "honk preview"
1677 err := readviews.Execute(w, "honkpage.html", templinfo)
1678 if err != nil {
1679 log.Print(err)
1680 }
1681 return
1682 }
1683
1684 if updatexid != "" {
1685 updatehonk(honk)
1686 oldjonks.Clear(honk.XID)
1687 } else {
1688 err := savehonk(honk)
1689 if err != nil {
1690 log.Printf("uh oh")
1691 return
1692 }
1693 }
1694
1695 // reload for consistency
1696 honk.Donks = nil
1697 donksforhonks([]*Honk{honk})
1698
1699 go honkworldwide(user, honk)
1700
1701 if isAPI {
1702 w.Write([]byte(honk.XID))
1703 } else {
1704 http.Redirect(w, r, honk.XID[len(serverName)+8:], http.StatusSeeOther)
1705 }
1706}
1707
1708func showhonkers(w http.ResponseWriter, r *http.Request) {
1709 userinfo := login.GetUserInfo(r)
1710 templinfo := getInfo(r)
1711 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1712 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1713 err := readviews.Execute(w, "honkers.html", templinfo)
1714 if err != nil {
1715 log.Print(err)
1716 }
1717}
1718
1719var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1720 honkers := gethonkers(userid)
1721 var combos []string
1722 for _, h := range honkers {
1723 combos = append(combos, h.Combos...)
1724 }
1725 for i, c := range combos {
1726 if c == "-" {
1727 combos[i] = ""
1728 }
1729 }
1730 combos = oneofakind(combos)
1731 sort.Strings(combos)
1732 return combos, true
1733}, Invalidator: &honkerinvalidator})
1734
1735func showcombos(w http.ResponseWriter, r *http.Request) {
1736 userinfo := login.GetUserInfo(r)
1737 var combos []string
1738 combocache.Get(userinfo.UserID, &combos)
1739 templinfo := getInfo(r)
1740 err := readviews.Execute(w, "combos.html", templinfo)
1741 if err != nil {
1742 log.Print(err)
1743 }
1744}
1745
1746func submithonker(w http.ResponseWriter, r *http.Request) {
1747 u := login.GetUserInfo(r)
1748 name := strings.TrimSpace(r.FormValue("name"))
1749 url := strings.TrimSpace(r.FormValue("url"))
1750 peep := r.FormValue("peep")
1751 combos := strings.TrimSpace(r.FormValue("combos"))
1752 combos = " " + combos + " "
1753 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1754
1755 var meta HonkerMeta
1756 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
1757 mj, _ := jsonify(&meta)
1758
1759 defer honkerinvalidator.Clear(u.UserID)
1760
1761 if honkerid > 0 {
1762 goodbye := r.FormValue("goodbye")
1763 if goodbye == "F" {
1764 db := opendatabase()
1765 row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1766 honkerid, u.UserID)
1767 err := row.Scan(&url)
1768 if err != nil {
1769 log.Printf("can't get honker xid: %s", err)
1770 return
1771 }
1772 log.Printf("unsubscribing from %s", url)
1773 user, _ := butwhatabout(u.Username)
1774 _, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, name, "sub")
1775 if err != nil {
1776 log.Printf("error updating honker: %s", err)
1777 return
1778 }
1779 go itakeitallback(user, url)
1780
1781 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1782 return
1783 }
1784 if goodbye == "X" {
1785 var owner string
1786 db := opendatabase()
1787 row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub')",
1788 honkerid, u.UserID)
1789 err := row.Scan(&url, &owner)
1790 if err != nil {
1791 log.Printf("can't get honker xid: %s", err)
1792 return
1793 }
1794 log.Printf("resubscribing to %s", url)
1795 user, _ := butwhatabout(u.Username)
1796 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "unsub")
1797 if err == nil {
1798 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "peep")
1799 }
1800 if err != nil {
1801 log.Printf("error updating honker: %s", err)
1802 return
1803 }
1804 go subsub(user, url, owner)
1805
1806 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1807 return
1808 }
1809 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
1810 if err != nil {
1811 log.Printf("update honker err: %s", err)
1812 return
1813 }
1814 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1815 return
1816 }
1817
1818 if url == "" {
1819 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1820 return
1821 }
1822
1823 flavor := "presub"
1824 if peep == "peep" {
1825 flavor = "peep"
1826 }
1827
1828 if url[0] == '#' {
1829 flavor = "peep"
1830 if name == "" {
1831 name = url
1832 }
1833 _, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url, mj)
1834 if err != nil {
1835 log.Print(err)
1836 return
1837 }
1838 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1839 return
1840 }
1841
1842 info, err := investigate(url)
1843 if err != nil {
1844 http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1845 log.Printf("failed to investigate honker: %s", err)
1846 return
1847 }
1848 url = info.XID
1849
1850 var x string
1851 db := opendatabase()
1852 row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1853 err = row.Scan(&x)
1854 if err != sql.ErrNoRows {
1855 http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1856 if err != nil {
1857 log.Printf("honker scan err: %s", err)
1858 }
1859 return
1860 }
1861
1862 if name == "" {
1863 name = info.Name
1864 }
1865 _, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner, mj)
1866 if err != nil {
1867 log.Print(err)
1868 return
1869 }
1870 if flavor == "presub" {
1871 user, _ := butwhatabout(u.Username)
1872 go subsub(user, url, info.Owner)
1873 }
1874 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1875}
1876
1877func hfcspage(w http.ResponseWriter, r *http.Request) {
1878 userinfo := login.GetUserInfo(r)
1879
1880 filters := getfilters(userinfo.UserID, filtAny)
1881
1882 templinfo := getInfo(r)
1883 templinfo["Filters"] = filters
1884 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1885 err := readviews.Execute(w, "hfcs.html", templinfo)
1886 if err != nil {
1887 log.Print(err)
1888 }
1889}
1890
1891func savehfcs(w http.ResponseWriter, r *http.Request) {
1892 userinfo := login.GetUserInfo(r)
1893 itsok := r.FormValue("itsok")
1894 if itsok == "iforgiveyou" {
1895 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1896 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1897 if err != nil {
1898 log.Printf("error deleting filter: %s", err)
1899 }
1900 filtInvalidator.Clear(userinfo.UserID)
1901 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1902 return
1903 }
1904
1905 filt := new(Filter)
1906 filt.Name = strings.TrimSpace(r.FormValue("name"))
1907 filt.Date = time.Now().UTC()
1908 filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1909 filt.IncludeAudience = r.FormValue("incaud") == "yes"
1910 filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1911 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1912 filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1913 filt.Reject = r.FormValue("doreject") == "yes"
1914 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1915 filt.Hide = r.FormValue("dohide") == "yes"
1916 filt.Collapse = r.FormValue("docollapse") == "yes"
1917 filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1918 filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1919 if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
1920 filt.Expiration = time.Now().UTC().Add(dur)
1921 }
1922 filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
1923
1924 if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
1925 log.Printf("blank filter")
1926 http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
1927 return
1928 }
1929
1930 j, err := jsonify(filt)
1931 if err == nil {
1932 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1933 }
1934 if err != nil {
1935 log.Printf("error saving filter: %s", err)
1936 }
1937
1938 filtInvalidator.Clear(userinfo.UserID)
1939 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1940}
1941
1942func accountpage(w http.ResponseWriter, r *http.Request) {
1943 u := login.GetUserInfo(r)
1944 user, _ := butwhatabout(u.Username)
1945 templinfo := getInfo(r)
1946 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1947 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1948 templinfo["User"] = user
1949 about := user.About
1950 if ava := user.Options.Avatar; ava != "" {
1951 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
1952 }
1953 templinfo["WhatAbout"] = about
1954 err := readviews.Execute(w, "account.html", templinfo)
1955 if err != nil {
1956 log.Print(err)
1957 }
1958}
1959
1960func dochpass(w http.ResponseWriter, r *http.Request) {
1961 err := login.ChangePassword(w, r)
1962 if err != nil {
1963 log.Printf("error changing password: %s", err)
1964 }
1965 http.Redirect(w, r, "/account", http.StatusSeeOther)
1966}
1967
1968func fingerlicker(w http.ResponseWriter, r *http.Request) {
1969 orig := r.FormValue("resource")
1970
1971 log.Printf("finger lick: %s", orig)
1972
1973 if strings.HasPrefix(orig, "acct:") {
1974 orig = orig[5:]
1975 }
1976
1977 name := orig
1978 idx := strings.LastIndexByte(name, '/')
1979 if idx != -1 {
1980 name = name[idx+1:]
1981 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1982 log.Printf("foreign request rejected")
1983 name = ""
1984 }
1985 } else {
1986 idx = strings.IndexByte(name, '@')
1987 if idx != -1 {
1988 name = name[:idx]
1989 if name+"@"+serverName != orig {
1990 log.Printf("foreign request rejected")
1991 name = ""
1992 }
1993 }
1994 }
1995 user, err := butwhatabout(name)
1996 if err != nil {
1997 http.NotFound(w, r)
1998 return
1999 }
2000 if stealthmode(user.ID, r) {
2001 http.NotFound(w, r)
2002 return
2003 }
2004
2005 j := junk.New()
2006 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
2007 j["aliases"] = []string{user.URL}
2008 l := junk.New()
2009 l["rel"] = "self"
2010 l["type"] = `application/activity+json`
2011 l["href"] = user.URL
2012 j["links"] = []junk.Junk{l}
2013
2014 w.Header().Set("Content-Type", "application/jrd+json")
2015 j.Write(w)
2016}
2017
2018func somedays() string {
2019 secs := 432000 + notrand.Int63n(432000)
2020 return fmt.Sprintf("%d", secs)
2021}
2022
2023func avatate(w http.ResponseWriter, r *http.Request) {
2024 if debugMode {
2025 loadAvatarColors()
2026 }
2027 n := r.FormValue("a")
2028 a := genAvatar(n)
2029 w.Header().Set("Cache-Control", "max-age="+somedays())
2030 w.Write(a)
2031}
2032
2033func serveasset(w http.ResponseWriter, r *http.Request) {
2034 if !debugMode {
2035 w.Header().Set("Cache-Control", "max-age=7776000")
2036 }
2037 dir := viewDir
2038 if r.URL.Path == "/local.css" {
2039 dir = dataDir
2040 }
2041 http.ServeFile(w, r, dir+"/views"+r.URL.Path)
2042}
2043func servehelp(w http.ResponseWriter, r *http.Request) {
2044 name := mux.Vars(r)["name"]
2045 if !debugMode {
2046 w.Header().Set("Cache-Control", "max-age=3600")
2047 }
2048 http.ServeFile(w, r, viewDir+"/docs/"+name)
2049}
2050func servehtml(w http.ResponseWriter, r *http.Request) {
2051 u := login.GetUserInfo(r)
2052 templinfo := getInfo(r)
2053 templinfo["AboutMsg"] = aboutMsg
2054 templinfo["LoginMsg"] = loginMsg
2055 templinfo["HonkVersion"] = softwareVersion
2056 if r.URL.Path == "/about" {
2057 templinfo["Sensors"] = getSensors()
2058 }
2059 if u == nil && !debugMode {
2060 w.Header().Set("Cache-Control", "max-age=60")
2061 }
2062 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2063 if err != nil {
2064 log.Print(err)
2065 }
2066}
2067func serveemu(w http.ResponseWriter, r *http.Request) {
2068 emu := mux.Vars(r)["emu"]
2069
2070 w.Header().Set("Cache-Control", "max-age="+somedays())
2071 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2072}
2073func servememe(w http.ResponseWriter, r *http.Request) {
2074 meme := mux.Vars(r)["meme"]
2075
2076 w.Header().Set("Cache-Control", "max-age="+somedays())
2077 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2078}
2079
2080func servefile(w http.ResponseWriter, r *http.Request) {
2081 xid := mux.Vars(r)["xid"]
2082 var media string
2083 var data []byte
2084 row := stmtGetFileData.QueryRow(xid)
2085 err := row.Scan(&media, &data)
2086 if err != nil {
2087 log.Printf("error loading file: %s", err)
2088 http.NotFound(w, r)
2089 return
2090 }
2091 w.Header().Set("Content-Type", media)
2092 w.Header().Set("X-Content-Type-Options", "nosniff")
2093 w.Header().Set("Cache-Control", "max-age="+somedays())
2094 w.Write(data)
2095}
2096
2097func nomoroboto(w http.ResponseWriter, r *http.Request) {
2098 io.WriteString(w, "User-agent: *\n")
2099 io.WriteString(w, "Disallow: /a\n")
2100 io.WriteString(w, "Disallow: /d/\n")
2101 io.WriteString(w, "Disallow: /meme/\n")
2102 io.WriteString(w, "Disallow: /o\n")
2103 io.WriteString(w, "Disallow: /o/\n")
2104 for _, u := range allusers() {
2105 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2106 }
2107}
2108
2109func webhydra(w http.ResponseWriter, r *http.Request) {
2110 u := login.GetUserInfo(r)
2111 userid := u.UserID
2112 templinfo := getInfo(r)
2113 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2114 page := r.FormValue("page")
2115
2116 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2117
2118 var honks []*Honk
2119 switch page {
2120 case "atme":
2121 honks = gethonksforme(userid, wanted)
2122 honks = osmosis(honks, userid, false)
2123 templinfo["ServerMessage"] = "at me!"
2124 case "home":
2125 honks = gethonksforuser(userid, wanted)
2126 honks = osmosis(honks, userid, true)
2127 templinfo["ServerMessage"] = serverMsg
2128 case "first":
2129 honks = gethonksforuserfirstclass(userid, wanted)
2130 honks = osmosis(honks, userid, true)
2131 templinfo["ServerMessage"] = "first class only"
2132 case "saved":
2133 honks = getsavedhonks(userid, wanted)
2134 templinfo["PageName"] = "saved"
2135 templinfo["ServerMessage"] = "saved honks"
2136 case "combo":
2137 c := r.FormValue("c")
2138 honks = gethonksbycombo(userid, c, wanted)
2139 honks = osmosis(honks, userid, false)
2140 templinfo["ServerMessage"] = "honks by combo: " + c
2141 case "convoy":
2142 c := r.FormValue("c")
2143 honks = gethonksbyconvoy(userid, c, wanted)
2144 honks = osmosis(honks, userid, false)
2145 templinfo["ServerMessage"] = "honks in convoy: " + c
2146 case "honker":
2147 xid := r.FormValue("xid")
2148 honks = gethonksbyxonker(userid, xid, wanted)
2149 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
2150 templinfo["ServerMessage"] = msg
2151 default:
2152 http.NotFound(w, r)
2153 }
2154 if len(honks) > 0 {
2155 templinfo["TopHID"] = honks[0].ID
2156 } else {
2157 templinfo["TopHID"] = wanted
2158 }
2159 reverbolate(userid, honks)
2160 templinfo["Honks"] = honks
2161 templinfo["MapLink"] = getmaplink(u)
2162 w.Header().Set("Content-Type", "text/html; charset=utf-8")
2163 err := readviews.Execute(w, "honkfrags.html", templinfo)
2164 if err != nil {
2165 log.Printf("frag error: %s", err)
2166 }
2167}
2168
2169var honkline = make(chan bool)
2170
2171func honkhonkline() {
2172 for {
2173 select {
2174 case honkline <- true:
2175 default:
2176 return
2177 }
2178 }
2179}
2180
2181func apihandler(w http.ResponseWriter, r *http.Request) {
2182 u := login.GetUserInfo(r)
2183 userid := u.UserID
2184 user, _ := butwhatabout(u.Username)
2185 action := r.FormValue("action")
2186 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2187 log.Printf("api request '%s' on behalf of %s", action, u.Username)
2188 switch action {
2189 case "honk":
2190 submithonk(w, r, true)
2191 case "gethonks":
2192 var honks []*Honk
2193 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2194 page := r.FormValue("page")
2195 var waitchan <-chan time.Time
2196 requery:
2197 switch page {
2198 case "atme":
2199 honks = gethonksforme(userid, wanted)
2200 honks = osmosis(honks, userid, false)
2201 case "home":
2202 honks = gethonksforuser(userid, wanted)
2203 honks = osmosis(honks, userid, true)
2204 default:
2205 http.Error(w, "unknown page", http.StatusNotFound)
2206 return
2207 }
2208 if len(honks) == 0 && wait > 0 {
2209 if waitchan == nil {
2210 waitchan = time.After(time.Duration(wait) * time.Second)
2211 }
2212 select {
2213 case <-honkline:
2214 goto requery
2215 case <-waitchan:
2216 }
2217 }
2218 reverbolate(userid, honks)
2219 j := junk.New()
2220 j["honks"] = honks
2221 j.Write(w)
2222 case "sendactivity":
2223 public := r.FormValue("public") == "1"
2224 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2225 msg := []byte(r.FormValue("msg"))
2226 for rcpt := range rcpts {
2227 go deliverate(0, userid, rcpt, msg)
2228 }
2229 default:
2230 http.Error(w, "unknown action", http.StatusNotFound)
2231 return
2232 }
2233}
2234
2235var endoftheworld = make(chan bool)
2236var readyalready = make(chan bool)
2237
2238func enditall() {
2239 sig := make(chan os.Signal)
2240 signal.Notify(sig, os.Interrupt)
2241 signal.Notify(sig, syscall.SIGTERM)
2242 <-sig
2243 count := 0
2244 log.Printf("stopping...")
2245sendloop:
2246 for {
2247 select {
2248 case endoftheworld <- true:
2249 count++
2250 default:
2251 break sendloop
2252 }
2253 }
2254 log.Printf("waiting...")
2255 for i := 0; i < count; i++ {
2256 <-readyalready
2257 }
2258 log.Printf("apocalypse")
2259 os.Exit(0)
2260}
2261
2262var preservehooks []func()
2263
2264func serve() {
2265 db := opendatabase()
2266 login.Init(db)
2267
2268 listener, err := openListener()
2269 if err != nil {
2270 log.Fatal(err)
2271 }
2272 startBackendServer()
2273 go enditall()
2274 go redeliverator()
2275 go tracker()
2276
2277 getconfig("debug", &debugMode)
2278 readviews = templates.Load(debugMode,
2279 viewDir+"/views/honkpage.html",
2280 viewDir+"/views/honkfrags.html",
2281 viewDir+"/views/honkers.html",
2282 viewDir+"/views/hfcs.html",
2283 viewDir+"/views/combos.html",
2284 viewDir+"/views/honkform.html",
2285 viewDir+"/views/honk.html",
2286 viewDir+"/views/account.html",
2287 viewDir+"/views/about.html",
2288 viewDir+"/views/funzone.html",
2289 viewDir+"/views/login.html",
2290 viewDir+"/views/xzone.html",
2291 viewDir+"/views/msg.html",
2292 viewDir+"/views/header.html",
2293 viewDir+"/views/onts.html",
2294 viewDir+"/views/honkpage.js",
2295 )
2296 if !debugMode {
2297 assets := []string{viewDir + "/views/style.css", dataDir + "/views/local.css", viewDir + "/views/honkpage.js"}
2298 for _, s := range assets {
2299 savedassetparams[s] = getassetparam(s)
2300 }
2301 loadAvatarColors()
2302 }
2303
2304 for _, h := range preservehooks {
2305 h()
2306 }
2307
2308 mux := mux.NewRouter()
2309 mux.Use(login.Checker)
2310
2311 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2312
2313 posters := mux.Methods("POST").Subrouter()
2314 getters := mux.Methods("GET").Subrouter()
2315
2316 getters.HandleFunc("/", homepage)
2317 getters.HandleFunc("/home", homepage)
2318 getters.HandleFunc("/front", homepage)
2319 getters.HandleFunc("/events", homepage)
2320 getters.HandleFunc("/robots.txt", nomoroboto)
2321 getters.HandleFunc("/rss", showrss)
2322 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
2323 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showonehonk)
2324 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
2325 posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
2326 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
2327 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
2328 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
2329 getters.HandleFunc("/a", avatate)
2330 getters.HandleFunc("/o", thelistingoftheontologies)
2331 getters.HandleFunc("/o/{name:.+}", showontology)
2332 getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
2333 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2334 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2335 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2336
2337 getters.HandleFunc("/server", serveractor)
2338 posters.HandleFunc("/server/inbox", serverinbox)
2339
2340 getters.HandleFunc("/style.css", serveasset)
2341 getters.HandleFunc("/local.css", serveasset)
2342 getters.HandleFunc("/honkpage.js", serveasset)
2343 getters.HandleFunc("/about", servehtml)
2344 getters.HandleFunc("/login", servehtml)
2345 posters.HandleFunc("/dologin", login.LoginFunc)
2346 getters.HandleFunc("/logout", login.LogoutFunc)
2347 getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
2348
2349 loggedin := mux.NewRoute().Subrouter()
2350 loggedin.Use(login.Required)
2351 loggedin.HandleFunc("/first", homepage)
2352 loggedin.HandleFunc("/saved", homepage)
2353 loggedin.HandleFunc("/account", accountpage)
2354 loggedin.HandleFunc("/funzone", showfunzone)
2355 loggedin.HandleFunc("/chpass", dochpass)
2356 loggedin.HandleFunc("/atme", homepage)
2357 loggedin.HandleFunc("/hfcs", hfcspage)
2358 loggedin.HandleFunc("/xzone", xzone)
2359 loggedin.HandleFunc("/newhonk", newhonkpage)
2360 loggedin.HandleFunc("/edit", edithonkpage)
2361 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitwebhonk)))
2362 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2363 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2364 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2365 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2366 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2367 loggedin.HandleFunc("/honkers", showhonkers)
2368 loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
2369 loggedin.HandleFunc("/h", showhonker)
2370 loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
2371 loggedin.HandleFunc("/c", showcombos)
2372 loggedin.HandleFunc("/t", showconvoy)
2373 loggedin.HandleFunc("/q", showsearch)
2374 loggedin.HandleFunc("/hydra", webhydra)
2375 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
2376
2377 err = http.Serve(listener, mux)
2378 if err != nil {
2379 log.Fatal(err)
2380 }
2381}