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