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 herd := herdofemus(noise)
1579 for _, e := range herd {
1580 donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1581 if donk != nil {
1582 donk.Name = e.Name
1583 honk.Donks = append(honk.Donks, donk)
1584 }
1585 }
1586 memetize(honk)
1587 imaginate(honk)
1588
1589 placename := strings.TrimSpace(r.FormValue("placename"))
1590 placelat := strings.TrimSpace(r.FormValue("placelat"))
1591 placelong := strings.TrimSpace(r.FormValue("placelong"))
1592 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1593 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1594 p := new(Place)
1595 p.Name = placename
1596 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1597 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1598 p.Url = placeurl
1599 honk.Place = p
1600 }
1601 timestart := strings.TrimSpace(r.FormValue("timestart"))
1602 if timestart != "" {
1603 t := new(Time)
1604 now := time.Now().Local()
1605 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1606 start, err := time.ParseInLocation(layout, timestart, now.Location())
1607 if err == nil {
1608 if start.Year() == 0 {
1609 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1610 }
1611 t.StartTime = start
1612 break
1613 }
1614 }
1615 timeend := r.FormValue("timeend")
1616 dur := parseDuration(timeend)
1617 if dur != 0 {
1618 t.Duration = Duration(dur)
1619 }
1620 if !t.StartTime.IsZero() {
1621 honk.What = "event"
1622 honk.Time = t
1623 }
1624 }
1625
1626 if honk.Public {
1627 honk.Whofore = 2
1628 } else {
1629 honk.Whofore = 3
1630 }
1631
1632 // back to markdown
1633 honk.Noise = noise
1634
1635 if r.FormValue("preview") == "preview" {
1636 honks := []*Honk{honk}
1637 reverbolate(userinfo.UserID, honks)
1638 templinfo := getInfo(r)
1639 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1640 templinfo["Honks"] = honks
1641 templinfo["MapLink"] = getmaplink(userinfo)
1642 templinfo["InReplyTo"] = r.FormValue("rid")
1643 templinfo["Noise"] = r.FormValue("noise")
1644 templinfo["SavedFile"] = donkxid
1645 templinfo["IsPreview"] = true
1646 templinfo["UpdateXID"] = updatexid
1647 templinfo["ServerMessage"] = "honk preview"
1648 err := readviews.Execute(w, "honkpage.html", templinfo)
1649 if err != nil {
1650 log.Print(err)
1651 }
1652 return
1653 }
1654
1655 if updatexid != "" {
1656 updatehonk(honk)
1657 oldjonks.Clear(honk.XID)
1658 } else {
1659 err := savehonk(honk)
1660 if err != nil {
1661 log.Printf("uh oh")
1662 return
1663 }
1664 }
1665
1666 // reload for consistency
1667 honk.Donks = nil
1668 donksforhonks([]*Honk{honk})
1669
1670 go honkworldwide(user, honk)
1671
1672 if isAPI {
1673 w.Write([]byte(honk.XID))
1674 } else {
1675 http.Redirect(w, r, honk.XID[len(serverName)+8:], http.StatusSeeOther)
1676 }
1677}
1678
1679func showhonkers(w http.ResponseWriter, r *http.Request) {
1680 userinfo := login.GetUserInfo(r)
1681 templinfo := getInfo(r)
1682 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1683 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1684 err := readviews.Execute(w, "honkers.html", templinfo)
1685 if err != nil {
1686 log.Print(err)
1687 }
1688}
1689
1690var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1691 honkers := gethonkers(userid)
1692 var combos []string
1693 for _, h := range honkers {
1694 combos = append(combos, h.Combos...)
1695 }
1696 for i, c := range combos {
1697 if c == "-" {
1698 combos[i] = ""
1699 }
1700 }
1701 combos = oneofakind(combos)
1702 sort.Strings(combos)
1703 return combos, true
1704}, Invalidator: &honkerinvalidator})
1705
1706func showcombos(w http.ResponseWriter, r *http.Request) {
1707 userinfo := login.GetUserInfo(r)
1708 var combos []string
1709 combocache.Get(userinfo.UserID, &combos)
1710 templinfo := getInfo(r)
1711 err := readviews.Execute(w, "combos.html", templinfo)
1712 if err != nil {
1713 log.Print(err)
1714 }
1715}
1716
1717func submithonker(w http.ResponseWriter, r *http.Request) {
1718 u := login.GetUserInfo(r)
1719 name := strings.TrimSpace(r.FormValue("name"))
1720 url := strings.TrimSpace(r.FormValue("url"))
1721 peep := r.FormValue("peep")
1722 combos := strings.TrimSpace(r.FormValue("combos"))
1723 combos = " " + combos + " "
1724 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1725
1726 defer honkerinvalidator.Clear(u.UserID)
1727
1728 if honkerid > 0 {
1729 goodbye := r.FormValue("goodbye")
1730 if goodbye == "F" {
1731 db := opendatabase()
1732 row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1733 honkerid, u.UserID)
1734 err := row.Scan(&url)
1735 if err != nil {
1736 log.Printf("can't get honker xid: %s", err)
1737 return
1738 }
1739 log.Printf("unsubscribing from %s", url)
1740 user, _ := butwhatabout(u.Username)
1741 _, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, name, "sub")
1742 if err != nil {
1743 log.Printf("error updating honker: %s", err)
1744 return
1745 }
1746 go itakeitallback(user, url)
1747
1748 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1749 return
1750 }
1751 if goodbye == "X" {
1752 var owner string
1753 db := opendatabase()
1754 row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1755 honkerid, u.UserID)
1756 err := row.Scan(&url, &owner)
1757 if err != nil {
1758 log.Printf("can't get honker xid: %s", err)
1759 return
1760 }
1761 log.Printf("resubscribing to %s", url)
1762 user, _ := butwhatabout(u.Username)
1763 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "unsub")
1764 if err == nil {
1765 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "peep")
1766 }
1767 if err != nil {
1768 log.Printf("error updating honker: %s", err)
1769 return
1770 }
1771 go subsub(user, url, owner)
1772
1773 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1774 return
1775 }
1776 _, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1777 if err != nil {
1778 log.Printf("update honker err: %s", err)
1779 return
1780 }
1781 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1782 return
1783 }
1784
1785 if url == "" {
1786 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1787 return
1788 }
1789
1790 flavor := "presub"
1791 if peep == "peep" {
1792 flavor = "peep"
1793 }
1794
1795 if url[0] == '#' {
1796 flavor = "peep"
1797 if name == "" {
1798 name = url
1799 }
1800 _, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url)
1801 if err != nil {
1802 log.Print(err)
1803 return
1804 }
1805 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1806 return
1807 }
1808
1809 info, err := investigate(url)
1810 if err != nil {
1811 http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1812 log.Printf("failed to investigate honker: %s", err)
1813 return
1814 }
1815 url = info.XID
1816
1817 var x string
1818 db := opendatabase()
1819 row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1820 err = row.Scan(&x)
1821 if err != sql.ErrNoRows {
1822 http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1823 if err != nil {
1824 log.Printf("honker scan err: %s", err)
1825 }
1826 return
1827 }
1828
1829 if name == "" {
1830 name = info.Name
1831 }
1832 _, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner)
1833 if err != nil {
1834 log.Print(err)
1835 return
1836 }
1837 if flavor == "presub" {
1838 user, _ := butwhatabout(u.Username)
1839 go subsub(user, url, info.Owner)
1840 }
1841 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1842}
1843
1844func hfcspage(w http.ResponseWriter, r *http.Request) {
1845 userinfo := login.GetUserInfo(r)
1846
1847 filters := getfilters(userinfo.UserID, filtAny)
1848
1849 templinfo := getInfo(r)
1850 templinfo["Filters"] = filters
1851 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1852 err := readviews.Execute(w, "hfcs.html", templinfo)
1853 if err != nil {
1854 log.Print(err)
1855 }
1856}
1857
1858func savehfcs(w http.ResponseWriter, r *http.Request) {
1859 userinfo := login.GetUserInfo(r)
1860 itsok := r.FormValue("itsok")
1861 if itsok == "iforgiveyou" {
1862 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1863 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1864 if err != nil {
1865 log.Printf("error deleting filter: %s", err)
1866 }
1867 filtcache.Clear(userinfo.UserID)
1868 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1869 return
1870 }
1871
1872 filt := new(Filter)
1873 filt.Name = strings.TrimSpace(r.FormValue("name"))
1874 filt.Date = time.Now().UTC()
1875 filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1876 filt.IncludeAudience = r.FormValue("incaud") == "yes"
1877 filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1878 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1879 filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1880 filt.Reject = r.FormValue("doreject") == "yes"
1881 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1882 filt.Hide = r.FormValue("dohide") == "yes"
1883 filt.Collapse = r.FormValue("docollapse") == "yes"
1884 filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1885 filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1886 if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
1887 filt.Expiration = time.Now().UTC().Add(dur)
1888 }
1889
1890 if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
1891 log.Printf("blank filter")
1892 http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
1893 return
1894 }
1895
1896 j, err := jsonify(filt)
1897 if err == nil {
1898 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1899 }
1900 if err != nil {
1901 log.Printf("error saving filter: %s", err)
1902 }
1903
1904 filtcache.Clear(userinfo.UserID)
1905 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1906}
1907
1908func accountpage(w http.ResponseWriter, r *http.Request) {
1909 u := login.GetUserInfo(r)
1910 user, _ := butwhatabout(u.Username)
1911 templinfo := getInfo(r)
1912 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1913 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1914 templinfo["User"] = user
1915 about := user.About
1916 if ava := user.Options.Avatar; ava != "" {
1917 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
1918 }
1919 templinfo["WhatAbout"] = about
1920 err := readviews.Execute(w, "account.html", templinfo)
1921 if err != nil {
1922 log.Print(err)
1923 }
1924}
1925
1926func dochpass(w http.ResponseWriter, r *http.Request) {
1927 err := login.ChangePassword(w, r)
1928 if err != nil {
1929 log.Printf("error changing password: %s", err)
1930 }
1931 http.Redirect(w, r, "/account", http.StatusSeeOther)
1932}
1933
1934func fingerlicker(w http.ResponseWriter, r *http.Request) {
1935 orig := r.FormValue("resource")
1936
1937 log.Printf("finger lick: %s", orig)
1938
1939 if strings.HasPrefix(orig, "acct:") {
1940 orig = orig[5:]
1941 }
1942
1943 name := orig
1944 idx := strings.LastIndexByte(name, '/')
1945 if idx != -1 {
1946 name = name[idx+1:]
1947 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1948 log.Printf("foreign request rejected")
1949 name = ""
1950 }
1951 } else {
1952 idx = strings.IndexByte(name, '@')
1953 if idx != -1 {
1954 name = name[:idx]
1955 if name+"@"+serverName != orig {
1956 log.Printf("foreign request rejected")
1957 name = ""
1958 }
1959 }
1960 }
1961 user, err := butwhatabout(name)
1962 if err != nil {
1963 http.NotFound(w, r)
1964 return
1965 }
1966 if stealthmode(user.ID, r) {
1967 http.NotFound(w, r)
1968 return
1969 }
1970
1971 j := junk.New()
1972 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1973 j["aliases"] = []string{user.URL}
1974 l := junk.New()
1975 l["rel"] = "self"
1976 l["type"] = `application/activity+json`
1977 l["href"] = user.URL
1978 j["links"] = []junk.Junk{l}
1979
1980 w.Header().Set("Content-Type", "application/jrd+json")
1981 j.Write(w)
1982}
1983
1984func somedays() string {
1985 secs := 432000 + notrand.Int63n(432000)
1986 return fmt.Sprintf("%d", secs)
1987}
1988
1989func avatate(w http.ResponseWriter, r *http.Request) {
1990 n := r.FormValue("a")
1991 a := avatar(n)
1992 w.Header().Set("Cache-Control", "max-age="+somedays())
1993 w.Write(a)
1994}
1995
1996func serveasset(w http.ResponseWriter, r *http.Request) {
1997 w.Header().Set("Cache-Control", "max-age=7776000")
1998 dir := viewDir
1999 if r.URL.Path == "/local.css" {
2000 dir = dataDir
2001 }
2002 http.ServeFile(w, r, dir+"/views"+r.URL.Path)
2003}
2004func servehelp(w http.ResponseWriter, r *http.Request) {
2005 name := mux.Vars(r)["name"]
2006 w.Header().Set("Cache-Control", "max-age=3600")
2007 http.ServeFile(w, r, viewDir+"/docs/"+name)
2008}
2009func servehtml(w http.ResponseWriter, r *http.Request) {
2010 u := login.GetUserInfo(r)
2011 templinfo := getInfo(r)
2012 templinfo["AboutMsg"] = aboutMsg
2013 templinfo["LoginMsg"] = loginMsg
2014 templinfo["HonkVersion"] = softwareVersion
2015 if r.URL.Path == "/about" {
2016 templinfo["Sensors"] = getSensors()
2017 }
2018 if u == nil {
2019 w.Header().Set("Cache-Control", "max-age=60")
2020 }
2021 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2022 if err != nil {
2023 log.Print(err)
2024 }
2025}
2026func serveemu(w http.ResponseWriter, r *http.Request) {
2027 emu := mux.Vars(r)["emu"]
2028
2029 w.Header().Set("Cache-Control", "max-age="+somedays())
2030 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2031}
2032func servememe(w http.ResponseWriter, r *http.Request) {
2033 meme := mux.Vars(r)["meme"]
2034
2035 w.Header().Set("Cache-Control", "max-age="+somedays())
2036 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2037}
2038
2039func servefile(w http.ResponseWriter, r *http.Request) {
2040 xid := mux.Vars(r)["xid"]
2041 var media string
2042 var data []byte
2043 row := stmtGetFileData.QueryRow(xid)
2044 err := row.Scan(&media, &data)
2045 if err != nil {
2046 log.Printf("error loading file: %s", err)
2047 http.NotFound(w, r)
2048 return
2049 }
2050 w.Header().Set("Content-Type", media)
2051 w.Header().Set("X-Content-Type-Options", "nosniff")
2052 w.Header().Set("Cache-Control", "max-age="+somedays())
2053 w.Write(data)
2054}
2055
2056func nomoroboto(w http.ResponseWriter, r *http.Request) {
2057 io.WriteString(w, "User-agent: *\n")
2058 io.WriteString(w, "Disallow: /a\n")
2059 io.WriteString(w, "Disallow: /d\n")
2060 io.WriteString(w, "Disallow: /meme\n")
2061 io.WriteString(w, "Disallow: /o\n")
2062 for _, u := range allusers() {
2063 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2064 }
2065}
2066
2067func webhydra(w http.ResponseWriter, r *http.Request) {
2068 u := login.GetUserInfo(r)
2069 userid := u.UserID
2070 templinfo := getInfo(r)
2071 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2072 page := r.FormValue("page")
2073
2074 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2075
2076 var honks []*Honk
2077 switch page {
2078 case "atme":
2079 honks = gethonksforme(userid, wanted)
2080 honks = osmosis(honks, userid, false)
2081 templinfo["ServerMessage"] = "at me!"
2082 case "home":
2083 honks = gethonksforuser(userid, wanted)
2084 honks = osmosis(honks, userid, true)
2085 templinfo["ServerMessage"] = serverMsg
2086 case "first":
2087 honks = gethonksforuserfirstclass(userid, wanted)
2088 honks = osmosis(honks, userid, true)
2089 templinfo["ServerMessage"] = "first class only"
2090 case "saved":
2091 honks = getsavedhonks(userid, wanted)
2092 templinfo["PageName"] = "saved"
2093 templinfo["ServerMessage"] = "saved honks"
2094 case "combo":
2095 c := r.FormValue("c")
2096 honks = gethonksbycombo(userid, c, wanted)
2097 honks = osmosis(honks, userid, false)
2098 templinfo["ServerMessage"] = "honks by combo: " + c
2099 case "convoy":
2100 c := r.FormValue("c")
2101 honks = gethonksbyconvoy(userid, c, wanted)
2102 honks = osmosis(honks, userid, false)
2103 templinfo["ServerMessage"] = "honks in convoy: " + c
2104 case "honker":
2105 xid := r.FormValue("xid")
2106 honks = gethonksbyxonker(userid, xid, wanted)
2107 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
2108 templinfo["ServerMessage"] = msg
2109 default:
2110 http.NotFound(w, r)
2111 }
2112 if len(honks) > 0 {
2113 templinfo["TopHID"] = honks[0].ID
2114 } else {
2115 templinfo["TopHID"] = wanted
2116 }
2117 reverbolate(userid, honks)
2118 templinfo["Honks"] = honks
2119 templinfo["MapLink"] = getmaplink(u)
2120 w.Header().Set("Content-Type", "text/html; charset=utf-8")
2121 err := readviews.Execute(w, "honkfrags.html", templinfo)
2122 if err != nil {
2123 log.Printf("frag error: %s", err)
2124 }
2125}
2126
2127var honkline = make(chan bool)
2128
2129func honkhonkline() {
2130 for {
2131 select {
2132 case honkline <- true:
2133 default:
2134 return
2135 }
2136 }
2137}
2138
2139func apihandler(w http.ResponseWriter, r *http.Request) {
2140 u := login.GetUserInfo(r)
2141 userid := u.UserID
2142 user, _ := butwhatabout(u.Username)
2143 action := r.FormValue("action")
2144 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2145 log.Printf("api request '%s' on behalf of %s", action, u.Username)
2146 switch action {
2147 case "honk":
2148 submithonk(w, r, true)
2149 case "gethonks":
2150 var honks []*Honk
2151 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2152 page := r.FormValue("page")
2153 var waitchan <-chan time.Time
2154 requery:
2155 switch page {
2156 case "atme":
2157 honks = gethonksforme(userid, wanted)
2158 honks = osmosis(honks, userid, false)
2159 case "home":
2160 honks = gethonksforuser(userid, wanted)
2161 honks = osmosis(honks, userid, true)
2162 default:
2163 http.Error(w, "unknown page", http.StatusNotFound)
2164 return
2165 }
2166 if len(honks) == 0 && wait > 0 {
2167 if waitchan == nil {
2168 waitchan = time.After(time.Duration(wait) * time.Second)
2169 }
2170 select {
2171 case <-honkline:
2172 goto requery
2173 case <-waitchan:
2174 }
2175 }
2176 reverbolate(userid, honks)
2177 j := junk.New()
2178 j["honks"] = honks
2179 j.Write(w)
2180 case "sendactivity":
2181 public := r.FormValue("public") == "1"
2182 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2183 msg := []byte(r.FormValue("msg"))
2184 for rcpt := range rcpts {
2185 go deliverate(0, userid, rcpt, msg)
2186 }
2187 default:
2188 http.Error(w, "unknown action", http.StatusNotFound)
2189 return
2190 }
2191}
2192
2193var endoftheworld = make(chan bool)
2194var readyalready = make(chan bool)
2195
2196func enditall() {
2197 sig := make(chan os.Signal)
2198 signal.Notify(sig, os.Interrupt)
2199 signal.Notify(sig, syscall.SIGTERM)
2200 <-sig
2201 count := 0
2202 log.Printf("stopping...")
2203sendloop:
2204 for {
2205 select {
2206 case endoftheworld <- true:
2207 count++
2208 default:
2209 break sendloop
2210 }
2211 }
2212 log.Printf("waiting...")
2213 for i := 0; i < count; i++ {
2214 <-readyalready
2215 }
2216 log.Printf("apocalypse")
2217 os.Exit(0)
2218}
2219
2220var preservehooks []func()
2221
2222func serve() {
2223 db := opendatabase()
2224 login.Init(db)
2225
2226 listener, err := openListener()
2227 if err != nil {
2228 log.Fatal(err)
2229 }
2230 startBackendServer()
2231 go enditall()
2232 go redeliverator()
2233 go tracker()
2234
2235 debug := false
2236 getconfig("debug", &debug)
2237 readviews = templates.Load(debug,
2238 viewDir+"/views/honkpage.html",
2239 viewDir+"/views/honkfrags.html",
2240 viewDir+"/views/honkers.html",
2241 viewDir+"/views/hfcs.html",
2242 viewDir+"/views/combos.html",
2243 viewDir+"/views/honkform.html",
2244 viewDir+"/views/honk.html",
2245 viewDir+"/views/account.html",
2246 viewDir+"/views/about.html",
2247 viewDir+"/views/funzone.html",
2248 viewDir+"/views/login.html",
2249 viewDir+"/views/xzone.html",
2250 viewDir+"/views/msg.html",
2251 viewDir+"/views/header.html",
2252 viewDir+"/views/onts.html",
2253 viewDir+"/views/honkpage.js",
2254 )
2255 if !debug {
2256 assets := []string{viewDir + "/views/style.css", dataDir + "/views/local.css", viewDir + "/views/honkpage.js"}
2257 for _, s := range assets {
2258 savedassetparams[s] = getassetparam(s)
2259 }
2260 }
2261
2262 for _, h := range preservehooks {
2263 h()
2264 }
2265
2266 mux := mux.NewRouter()
2267 mux.Use(login.Checker)
2268
2269 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2270
2271 posters := mux.Methods("POST").Subrouter()
2272 getters := mux.Methods("GET").Subrouter()
2273
2274 getters.HandleFunc("/", homepage)
2275 getters.HandleFunc("/home", homepage)
2276 getters.HandleFunc("/front", homepage)
2277 getters.HandleFunc("/events", homepage)
2278 getters.HandleFunc("/robots.txt", nomoroboto)
2279 getters.HandleFunc("/rss", showrss)
2280 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
2281 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showonehonk)
2282 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
2283 posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
2284 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
2285 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
2286 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
2287 getters.HandleFunc("/a", avatate)
2288 getters.HandleFunc("/o", thelistingoftheontologies)
2289 getters.HandleFunc("/o/{name:.+}", showontology)
2290 getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
2291 getters.HandleFunc("/emu/{emu:[^/]+}", serveemu)
2292 getters.HandleFunc("/meme/{meme:[^/]+}", servememe)
2293 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2294
2295 getters.HandleFunc("/server", serveractor)
2296 posters.HandleFunc("/server/inbox", serverinbox)
2297
2298 getters.HandleFunc("/style.css", serveasset)
2299 getters.HandleFunc("/local.css", serveasset)
2300 getters.HandleFunc("/honkpage.js", serveasset)
2301 getters.HandleFunc("/about", servehtml)
2302 getters.HandleFunc("/login", servehtml)
2303 posters.HandleFunc("/dologin", login.LoginFunc)
2304 getters.HandleFunc("/logout", login.LogoutFunc)
2305 getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
2306
2307 loggedin := mux.NewRoute().Subrouter()
2308 loggedin.Use(login.Required)
2309 loggedin.HandleFunc("/first", homepage)
2310 loggedin.HandleFunc("/saved", homepage)
2311 loggedin.HandleFunc("/account", accountpage)
2312 loggedin.HandleFunc("/funzone", showfunzone)
2313 loggedin.HandleFunc("/chpass", dochpass)
2314 loggedin.HandleFunc("/atme", homepage)
2315 loggedin.HandleFunc("/hfcs", hfcspage)
2316 loggedin.HandleFunc("/xzone", xzone)
2317 loggedin.HandleFunc("/newhonk", newhonkpage)
2318 loggedin.HandleFunc("/edit", edithonkpage)
2319 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitwebhonk)))
2320 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2321 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2322 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2323 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2324 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2325 loggedin.HandleFunc("/honkers", showhonkers)
2326 loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
2327 loggedin.HandleFunc("/h", showhonker)
2328 loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
2329 loggedin.HandleFunc("/c", showcombos)
2330 loggedin.HandleFunc("/t", showconvoy)
2331 loggedin.HandleFunc("/q", showsearch)
2332 loggedin.HandleFunc("/hydra", webhydra)
2333 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
2334
2335 err = http.Serve(listener, mux)
2336 if err != nil {
2337 log.Fatal(err)
2338 }
2339}