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