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