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