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