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("mentionall") == "mentionall" {
1137 options.MentionAll = true
1138 } else {
1139 options.MentionAll = false
1140 }
1141 if r.FormValue("maps") == "apple" {
1142 options.MapLink = "apple"
1143 } else {
1144 options.MapLink = ""
1145 }
1146 options.Reaction = r.FormValue("reaction")
1147
1148 sendupdate := false
1149 ava := re_avatar.FindString(whatabout)
1150 if ava != "" {
1151 whatabout = re_avatar.ReplaceAllString(whatabout, "")
1152 ava = ava[7:]
1153 if ava[0] == ' ' {
1154 ava = ava[1:]
1155 }
1156 ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1157 }
1158 if ava != options.Avatar {
1159 options.Avatar = ava
1160 sendupdate = true
1161 }
1162 whatabout = strings.TrimSpace(whatabout)
1163 if whatabout != user.About {
1164 sendupdate = true
1165 }
1166 j, err := jsonify(options)
1167 if err == nil {
1168 _, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1169 }
1170 if err != nil {
1171 log.Printf("error bouting what: %s", err)
1172 }
1173 somenamedusers.Clear(u.Username)
1174 somenumberedusers.Clear(u.UserID)
1175 oldjonkers.Clear(u.Username)
1176
1177 if sendupdate {
1178 updateMe(u.Username)
1179 }
1180
1181 http.Redirect(w, r, "/account", http.StatusSeeOther)
1182}
1183
1184func bonkit(xid string, user *WhatAbout) {
1185 log.Printf("bonking %s", xid)
1186
1187 xonk := getxonk(user.ID, xid)
1188 if xonk == nil {
1189 return
1190 }
1191 if !xonk.Public {
1192 return
1193 }
1194 if xonk.IsBonked() {
1195 return
1196 }
1197 donksforhonks([]*Honk{xonk})
1198
1199 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1200 if err != nil {
1201 log.Printf("error acking bonk: %s", err)
1202 }
1203
1204 oonker := xonk.Oonker
1205 if oonker == "" {
1206 oonker = xonk.Honker
1207 }
1208 dt := time.Now().UTC()
1209 bonk := &Honk{
1210 UserID: user.ID,
1211 Username: user.Name,
1212 What: "bonk",
1213 Honker: user.URL,
1214 Oonker: oonker,
1215 XID: xonk.XID,
1216 RID: xonk.RID,
1217 Noise: xonk.Noise,
1218 Precis: xonk.Precis,
1219 URL: xonk.URL,
1220 Date: dt,
1221 Donks: xonk.Donks,
1222 Whofore: 2,
1223 Convoy: xonk.Convoy,
1224 Audience: []string{thewholeworld, oonker},
1225 Public: true,
1226 Format: "html",
1227 Place: xonk.Place,
1228 Onts: xonk.Onts,
1229 Time: xonk.Time,
1230 }
1231
1232 err = savehonk(bonk)
1233 if err != nil {
1234 log.Printf("uh oh")
1235 return
1236 }
1237
1238 go honkworldwide(user, bonk)
1239}
1240
1241func submitbonk(w http.ResponseWriter, r *http.Request) {
1242 xid := r.FormValue("xid")
1243 userinfo := login.GetUserInfo(r)
1244 user, _ := butwhatabout(userinfo.Username)
1245
1246 bonkit(xid, user)
1247
1248 if r.FormValue("js") != "1" {
1249 templinfo := getInfo(r)
1250 templinfo["ServerMessage"] = "Bonked!"
1251 err := readviews.Execute(w, "msg.html", templinfo)
1252 if err != nil {
1253 log.Print(err)
1254 }
1255 }
1256}
1257
1258func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1259 zonk := &Honk{
1260 What: what,
1261 XID: xonk.XID,
1262 Date: time.Now().UTC(),
1263 Audience: oneofakind(xonk.Audience),
1264 Noise: aux,
1265 }
1266 zonk.Public = loudandproud(zonk.Audience)
1267
1268 log.Printf("announcing %sed honk: %s", what, xonk.XID)
1269 go honkworldwide(user, zonk)
1270}
1271
1272func zonkit(w http.ResponseWriter, r *http.Request) {
1273 wherefore := r.FormValue("wherefore")
1274 what := r.FormValue("what")
1275 userinfo := login.GetUserInfo(r)
1276 user, _ := butwhatabout(userinfo.Username)
1277
1278 if wherefore == "save" {
1279 xonk := getxonk(userinfo.UserID, what)
1280 if xonk != nil {
1281 _, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1282 if err != nil {
1283 log.Printf("error saving: %s", err)
1284 }
1285 }
1286 return
1287 }
1288
1289 if wherefore == "unsave" {
1290 xonk := getxonk(userinfo.UserID, what)
1291 if xonk != nil {
1292 _, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1293 if err != nil {
1294 log.Printf("error unsaving: %s", err)
1295 }
1296 }
1297 return
1298 }
1299
1300 if wherefore == "react" {
1301 reaction := user.Options.Reaction
1302 if r2 := r.FormValue("reaction"); r2 != "" {
1303 reaction = r2
1304 }
1305 if reaction == "none" {
1306 return
1307 }
1308 xonk := getxonk(userinfo.UserID, what)
1309 if xonk != nil {
1310 _, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1311 if err != nil {
1312 log.Printf("error saving: %s", err)
1313 }
1314 sendzonkofsorts(xonk, user, "react", reaction)
1315 }
1316 return
1317 }
1318
1319 // my hammer is too big, oh well
1320 defer oldjonks.Flush()
1321
1322 if wherefore == "ack" {
1323 xonk := getxonk(userinfo.UserID, what)
1324 if xonk != nil && !xonk.IsAcked() {
1325 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1326 if err != nil {
1327 log.Printf("error acking: %s", err)
1328 }
1329 sendzonkofsorts(xonk, user, "ack", "")
1330 }
1331 return
1332 }
1333
1334 if wherefore == "deack" {
1335 xonk := getxonk(userinfo.UserID, what)
1336 if xonk != nil && xonk.IsAcked() {
1337 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1338 if err != nil {
1339 log.Printf("error deacking: %s", err)
1340 }
1341 sendzonkofsorts(xonk, user, "deack", "")
1342 }
1343 return
1344 }
1345
1346 if wherefore == "bonk" {
1347 user, _ := butwhatabout(userinfo.Username)
1348 bonkit(what, user)
1349 return
1350 }
1351
1352 if wherefore == "unbonk" {
1353 xonk := getbonk(userinfo.UserID, what)
1354 if xonk != nil {
1355 deletehonk(xonk.ID)
1356 xonk = getxonk(userinfo.UserID, what)
1357 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1358 if err != nil {
1359 log.Printf("error unbonking: %s", err)
1360 }
1361 sendzonkofsorts(xonk, user, "unbonk", "")
1362 }
1363 return
1364 }
1365
1366 if wherefore == "untag" {
1367 xonk := getxonk(userinfo.UserID, what)
1368 if xonk != nil {
1369 _, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1370 if err != nil {
1371 log.Printf("error untagging: %s", err)
1372 }
1373 }
1374 var badparents map[string]bool
1375 untagged.GetAndLock(userinfo.UserID, &badparents)
1376 badparents[what] = true
1377 untagged.Unlock()
1378 return
1379 }
1380
1381 log.Printf("zonking %s %s", wherefore, what)
1382 if wherefore == "zonk" {
1383 xonk := getxonk(userinfo.UserID, what)
1384 if xonk != nil {
1385 deletehonk(xonk.ID)
1386 if xonk.Whofore == 2 || xonk.Whofore == 3 {
1387 sendzonkofsorts(xonk, user, "zonk", "")
1388 }
1389 }
1390 }
1391 _, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1392 if err != nil {
1393 log.Printf("error saving zonker: %s", err)
1394 return
1395 }
1396}
1397
1398func edithonkpage(w http.ResponseWriter, r *http.Request) {
1399 u := login.GetUserInfo(r)
1400 user, _ := butwhatabout(u.Username)
1401 xid := r.FormValue("xid")
1402 honk := getxonk(u.UserID, xid)
1403 if !canedithonk(user, honk) {
1404 http.Error(w, "no editing that please", http.StatusInternalServerError)
1405 return
1406 }
1407
1408 noise := honk.Noise
1409
1410 honks := []*Honk{honk}
1411 donksforhonks(honks)
1412 reverbolate(u.UserID, honks)
1413 templinfo := getInfo(r)
1414 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1415 templinfo["Honks"] = honks
1416 templinfo["MapLink"] = getmaplink(u)
1417 templinfo["Noise"] = noise
1418 templinfo["SavedPlace"] = honk.Place
1419 if tm := honk.Time; tm != nil {
1420 templinfo["ShowTime"] = ";"
1421 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 03:04")
1422 templinfo["Duration"] = tm.Duration
1423 }
1424 templinfo["ServerMessage"] = "honk edit 2"
1425 templinfo["IsPreview"] = true
1426 templinfo["UpdateXID"] = honk.XID
1427 if len(honk.Donks) > 0 {
1428 templinfo["SavedFile"] = honk.Donks[0].XID
1429 }
1430 err := readviews.Execute(w, "honkpage.html", templinfo)
1431 if err != nil {
1432 log.Print(err)
1433 }
1434}
1435
1436func newhonkpage(w http.ResponseWriter, r *http.Request) {
1437 u := login.GetUserInfo(r)
1438 rid := r.FormValue("rid")
1439 noise := ""
1440
1441 xonk := getxonk(u.UserID, rid)
1442 if xonk != nil {
1443 _, replto := handles(xonk.Honker)
1444 if replto != "" {
1445 noise = "@" + replto + " "
1446 }
1447 }
1448
1449 templinfo := getInfo(r)
1450 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1451 templinfo["InReplyTo"] = rid
1452 templinfo["Noise"] = noise
1453 templinfo["ServerMessage"] = "compose honk"
1454 templinfo["IsPreview"] = true
1455 err := readviews.Execute(w, "honkpage.html", templinfo)
1456 if err != nil {
1457 log.Print(err)
1458 }
1459}
1460
1461func canedithonk(user *WhatAbout, honk *Honk) bool {
1462 if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1463 return false
1464 }
1465 return true
1466}
1467
1468func submitdonk(w http.ResponseWriter, r *http.Request) (*Donk, error) {
1469 file, filehdr, err := r.FormFile("donk")
1470 if err != nil {
1471 if err != http.ErrMissingFile {
1472 log.Printf("error reading donk: %s", err)
1473 http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1474 }
1475 return nil, err
1476 }
1477 var buf bytes.Buffer
1478 io.Copy(&buf, file)
1479 file.Close()
1480 data := buf.Bytes()
1481 xid := xfiltrate()
1482 var media, name string
1483 img, err := shrinkit(data)
1484 if err == nil {
1485 data = img.Data
1486 format := img.Format
1487 media = "image/" + format
1488 if format == "jpeg" {
1489 format = "jpg"
1490 }
1491 name = xid + "." + format
1492 xid = name
1493 } else {
1494 ct := http.DetectContentType(data)
1495 switch ct {
1496 case "application/pdf":
1497 maxsize := 10000000
1498 if len(data) > maxsize {
1499 log.Printf("bad image: %s too much pdf: %d", err, len(data))
1500 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1501 return nil, err
1502 }
1503 media = ct
1504 xid += ".pdf"
1505 name = filehdr.Filename
1506 if name == "" {
1507 name = xid
1508 }
1509 default:
1510 maxsize := 100000
1511 if len(data) > maxsize {
1512 log.Printf("bad image: %s too much text: %d", err, len(data))
1513 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1514 return nil, err
1515 }
1516 for i := 0; i < len(data); i++ {
1517 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1518 log.Printf("bad image: %s not text: %d", err, data[i])
1519 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1520 return nil, err
1521 }
1522 }
1523 media = "text/plain"
1524 xid += ".txt"
1525 name = filehdr.Filename
1526 if name == "" {
1527 name = xid
1528 }
1529 }
1530 }
1531 desc := strings.TrimSpace(r.FormValue("donkdesc"))
1532 if desc == "" {
1533 desc = name
1534 }
1535 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1536 fileid, err := savefile(xid, name, desc, url, media, true, data)
1537 if err != nil {
1538 log.Printf("unable to save image: %s", err)
1539 http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1540 return nil, err
1541 }
1542 d := &Donk{
1543 FileID: fileid,
1544 XID: xid,
1545 Desc: desc,
1546 URL: url,
1547 Local: true,
1548 }
1549 return d, nil
1550}
1551
1552func submitwebhonk(w http.ResponseWriter, r *http.Request) {
1553 h := submithonk(w, r)
1554 if h == nil {
1555 return
1556 }
1557 http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1558}
1559
1560// what a hot mess this function is
1561func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1562 rid := r.FormValue("rid")
1563 noise := r.FormValue("noise")
1564 format := r.FormValue("format")
1565 if format == "" {
1566 format = "markdown"
1567 }
1568 if !(format == "markdown" || format == "html") {
1569 http.Error(w, "unknown format", 500)
1570 return nil
1571 }
1572
1573 userinfo := login.GetUserInfo(r)
1574 user, _ := butwhatabout(userinfo.Username)
1575
1576 dt := time.Now().UTC()
1577 updatexid := r.FormValue("updatexid")
1578 var honk *Honk
1579 if updatexid != "" {
1580 honk = getxonk(userinfo.UserID, updatexid)
1581 if !canedithonk(user, honk) {
1582 http.Error(w, "no editing that please", http.StatusInternalServerError)
1583 return nil
1584 }
1585 honk.Date = dt
1586 honk.What = "update"
1587 honk.Format = format
1588 } else {
1589 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1590 what := "honk"
1591 if rid != "" {
1592 what = "tonk"
1593 }
1594 honk = &Honk{
1595 UserID: userinfo.UserID,
1596 Username: userinfo.Username,
1597 What: what,
1598 Honker: user.URL,
1599 XID: xid,
1600 Date: dt,
1601 Format: format,
1602 }
1603 }
1604
1605 noise = strings.Replace(noise, "\r", "", -1)
1606 noise = quickrename(noise, userinfo.UserID)
1607 noise = hooterize(noise)
1608 honk.Noise = noise
1609 translate(honk)
1610
1611 var convoy string
1612 if rid != "" {
1613 xonk := getxonk(userinfo.UserID, rid)
1614 if xonk == nil {
1615 http.Error(w, "replyto disappeared", http.StatusNotFound)
1616 return nil
1617 }
1618 if xonk.Public {
1619 honk.Audience = append(honk.Audience, xonk.Audience...)
1620 }
1621 convoy = xonk.Convoy
1622 for i, a := range honk.Audience {
1623 if a == thewholeworld {
1624 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1625 break
1626 }
1627 }
1628 honk.RID = rid
1629 if xonk.Precis != "" && honk.Precis == "" {
1630 honk.Precis = xonk.Precis
1631 if !(strings.HasPrefix(honk.Precis, "DZ:") || strings.HasPrefix(honk.Precis, "re: re: re: ")) {
1632 honk.Precis = "re: " + honk.Precis
1633 }
1634 }
1635 } else {
1636 honk.Audience = []string{thewholeworld}
1637 }
1638 if honk.Noise != "" && honk.Noise[0] == '@' {
1639 honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1640 } else {
1641 honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1642 }
1643
1644 if convoy == "" {
1645 convoy = "data:,electrichonkytonk-" + xfiltrate()
1646 }
1647 butnottooloud(honk.Audience)
1648 honk.Audience = oneofakind(honk.Audience)
1649 if len(honk.Audience) == 0 {
1650 log.Printf("honk to nowhere")
1651 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1652 return nil
1653 }
1654 honk.Public = loudandproud(honk.Audience)
1655 honk.Convoy = convoy
1656
1657 donkxid := r.FormValue("donkxid")
1658 if donkxid == "" {
1659 d, err := submitdonk(w, r)
1660 if err != nil && err != http.ErrMissingFile {
1661 return nil
1662 }
1663 if d != nil {
1664 honk.Donks = append(honk.Donks, d)
1665 donkxid = d.XID
1666 }
1667 } else {
1668 xid := donkxid
1669 url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1670 donk := finddonk(url)
1671 if donk != nil {
1672 honk.Donks = append(honk.Donks, donk)
1673 } else {
1674 log.Printf("can't find file: %s", xid)
1675 }
1676 }
1677 memetize(honk)
1678 imaginate(honk)
1679
1680 placename := strings.TrimSpace(r.FormValue("placename"))
1681 placelat := strings.TrimSpace(r.FormValue("placelat"))
1682 placelong := strings.TrimSpace(r.FormValue("placelong"))
1683 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1684 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1685 p := new(Place)
1686 p.Name = placename
1687 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1688 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1689 p.Url = placeurl
1690 honk.Place = p
1691 }
1692 timestart := strings.TrimSpace(r.FormValue("timestart"))
1693 if timestart != "" {
1694 t := new(Time)
1695 now := time.Now().Local()
1696 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1697 start, err := time.ParseInLocation(layout, timestart, now.Location())
1698 if err == nil {
1699 if start.Year() == 0 {
1700 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1701 }
1702 t.StartTime = start
1703 break
1704 }
1705 }
1706 timeend := r.FormValue("timeend")
1707 dur := parseDuration(timeend)
1708 if dur != 0 {
1709 t.Duration = Duration(dur)
1710 }
1711 if !t.StartTime.IsZero() {
1712 honk.What = "event"
1713 honk.Time = t
1714 }
1715 }
1716
1717 if honk.Public {
1718 honk.Whofore = 2
1719 } else {
1720 honk.Whofore = 3
1721 }
1722
1723 // back to markdown
1724 honk.Noise = noise
1725
1726 if r.FormValue("preview") == "preview" {
1727 honks := []*Honk{honk}
1728 reverbolate(userinfo.UserID, honks)
1729 templinfo := getInfo(r)
1730 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1731 templinfo["Honks"] = honks
1732 templinfo["MapLink"] = getmaplink(userinfo)
1733 templinfo["InReplyTo"] = r.FormValue("rid")
1734 templinfo["Noise"] = r.FormValue("noise")
1735 templinfo["SavedFile"] = donkxid
1736 if tm := honk.Time; tm != nil {
1737 templinfo["ShowTime"] = ";"
1738 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 03:04")
1739 templinfo["Duration"] = tm.Duration
1740 }
1741 templinfo["IsPreview"] = true
1742 templinfo["UpdateXID"] = updatexid
1743 templinfo["ServerMessage"] = "honk preview"
1744 err := readviews.Execute(w, "honkpage.html", templinfo)
1745 if err != nil {
1746 log.Print(err)
1747 }
1748 return nil
1749 }
1750
1751 if updatexid != "" {
1752 updatehonk(honk)
1753 oldjonks.Clear(honk.XID)
1754 } else {
1755 err := savehonk(honk)
1756 if err != nil {
1757 log.Printf("uh oh")
1758 return nil
1759 }
1760 }
1761
1762 // reload for consistency
1763 honk.Donks = nil
1764 donksforhonks([]*Honk{honk})
1765
1766 go honkworldwide(user, honk)
1767
1768 return honk
1769}
1770
1771func showhonkers(w http.ResponseWriter, r *http.Request) {
1772 userinfo := login.GetUserInfo(r)
1773 templinfo := getInfo(r)
1774 templinfo["Honkers"] = gethonkers(userinfo.UserID)
1775 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1776 err := readviews.Execute(w, "honkers.html", templinfo)
1777 if err != nil {
1778 log.Print(err)
1779 }
1780}
1781
1782func showchatter(w http.ResponseWriter, r *http.Request) {
1783 u := login.GetUserInfo(r)
1784 chatter := loadchatter(u.UserID)
1785 for _, chat := range chatter {
1786 for _, ch := range chat.Chonks {
1787 filterchonk(ch)
1788 }
1789 }
1790
1791 templinfo := getInfo(r)
1792 templinfo["Chatter"] = chatter
1793 templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1794 err := readviews.Execute(w, "chatter.html", templinfo)
1795 if err != nil {
1796 log.Print(err)
1797 }
1798}
1799
1800func submitchonk(w http.ResponseWriter, r *http.Request) {
1801 u := login.GetUserInfo(r)
1802 user, _ := butwhatabout(u.Username)
1803 noise := r.FormValue("noise")
1804 target := r.FormValue("target")
1805 format := "markdown"
1806 dt := time.Now().UTC()
1807 xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1808
1809 if !strings.HasPrefix(target, "https://") {
1810 target = fullname(target, u.UserID)
1811 }
1812 if target == "" {
1813 http.Error(w, "who is that?", http.StatusInternalServerError)
1814 return
1815 }
1816 ch := Chonk{
1817 UserID: u.UserID,
1818 XID: xid,
1819 Who: user.URL,
1820 Target: target,
1821 Date: dt,
1822 Noise: noise,
1823 Format: format,
1824 }
1825 d, err := submitdonk(w, r)
1826 if err != nil && err != http.ErrMissingFile {
1827 return
1828 }
1829 if d != nil {
1830 ch.Donks = append(ch.Donks, d)
1831 }
1832
1833 translatechonk(&ch)
1834 savechonk(&ch)
1835 // reload for consistency
1836 ch.Donks = nil
1837 donksforchonks([]*Chonk{&ch})
1838 go sendchonk(user, &ch)
1839
1840 http.Redirect(w, r, "/chatter", http.StatusSeeOther)
1841}
1842
1843var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1844 honkers := gethonkers(userid)
1845 var combos []string
1846 for _, h := range honkers {
1847 combos = append(combos, h.Combos...)
1848 }
1849 for i, c := range combos {
1850 if c == "-" {
1851 combos[i] = ""
1852 }
1853 }
1854 combos = oneofakind(combos)
1855 sort.Strings(combos)
1856 return combos, true
1857}, Invalidator: &honkerinvalidator})
1858
1859func showcombos(w http.ResponseWriter, r *http.Request) {
1860 userinfo := login.GetUserInfo(r)
1861 var combos []string
1862 combocache.Get(userinfo.UserID, &combos)
1863 templinfo := getInfo(r)
1864 err := readviews.Execute(w, "combos.html", templinfo)
1865 if err != nil {
1866 log.Print(err)
1867 }
1868}
1869
1870func submithonker(w http.ResponseWriter, r *http.Request) {
1871 u := login.GetUserInfo(r)
1872 name := strings.TrimSpace(r.FormValue("name"))
1873 url := strings.TrimSpace(r.FormValue("url"))
1874 peep := r.FormValue("peep")
1875 combos := strings.TrimSpace(r.FormValue("combos"))
1876 combos = " " + combos + " "
1877 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1878
1879 var meta HonkerMeta
1880 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
1881 mj, _ := jsonify(&meta)
1882
1883 defer honkerinvalidator.Clear(u.UserID)
1884
1885 if honkerid > 0 {
1886 goodbye := r.FormValue("goodbye")
1887 if goodbye == "F" {
1888 db := opendatabase()
1889 row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1890 honkerid, u.UserID)
1891 err := row.Scan(&url)
1892 if err != nil {
1893 log.Printf("can't get honker xid: %s", err)
1894 return
1895 }
1896 log.Printf("unsubscribing from %s", url)
1897 user, _ := butwhatabout(u.Username)
1898 _, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, name, "sub")
1899 if err != nil {
1900 log.Printf("error updating honker: %s", err)
1901 return
1902 }
1903 go itakeitallback(user, url)
1904
1905 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1906 return
1907 }
1908 if goodbye == "X" {
1909 var owner string
1910 db := opendatabase()
1911 row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1912 honkerid, u.UserID)
1913 err := row.Scan(&url, &owner)
1914 if err != nil {
1915 log.Printf("can't get honker xid: %s", err)
1916 return
1917 }
1918 log.Printf("resubscribing to %s", url)
1919 user, _ := butwhatabout(u.Username)
1920 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "unsub")
1921 if err == nil {
1922 _, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "peep")
1923 }
1924 if err != nil {
1925 log.Printf("error updating honker: %s", err)
1926 return
1927 }
1928 go subsub(user, url, owner)
1929
1930 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1931 return
1932 }
1933 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
1934 if err != nil {
1935 log.Printf("update honker err: %s", err)
1936 return
1937 }
1938 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1939 return
1940 }
1941
1942 if url == "" {
1943 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1944 return
1945 }
1946
1947 flavor := "presub"
1948 if peep == "peep" {
1949 flavor = "peep"
1950 }
1951
1952 if url[0] == '#' {
1953 flavor = "peep"
1954 if name == "" {
1955 name = url
1956 }
1957 _, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url, mj)
1958 if err != nil {
1959 log.Print(err)
1960 return
1961 }
1962 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1963 return
1964 }
1965
1966 info, err := investigate(url)
1967 if err != nil {
1968 http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1969 log.Printf("failed to investigate honker: %s", err)
1970 return
1971 }
1972 url = info.XID
1973
1974 var x string
1975 db := opendatabase()
1976 row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1977 err = row.Scan(&x)
1978 if err != sql.ErrNoRows {
1979 http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1980 if err != nil {
1981 log.Printf("honker scan err: %s", err)
1982 }
1983 return
1984 }
1985
1986 if name == "" {
1987 name = info.Name
1988 }
1989 _, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner, mj)
1990 if err != nil {
1991 log.Print(err)
1992 return
1993 }
1994 if flavor == "presub" {
1995 user, _ := butwhatabout(u.Username)
1996 go subsub(user, url, info.Owner)
1997 }
1998 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1999}
2000
2001func hfcspage(w http.ResponseWriter, r *http.Request) {
2002 userinfo := login.GetUserInfo(r)
2003
2004 filters := getfilters(userinfo.UserID, filtAny)
2005
2006 templinfo := getInfo(r)
2007 templinfo["Filters"] = filters
2008 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2009 err := readviews.Execute(w, "hfcs.html", templinfo)
2010 if err != nil {
2011 log.Print(err)
2012 }
2013}
2014
2015func savehfcs(w http.ResponseWriter, r *http.Request) {
2016 userinfo := login.GetUserInfo(r)
2017 itsok := r.FormValue("itsok")
2018 if itsok == "iforgiveyou" {
2019 hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2020 _, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2021 if err != nil {
2022 log.Printf("error deleting filter: %s", err)
2023 }
2024 filtInvalidator.Clear(userinfo.UserID)
2025 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2026 return
2027 }
2028
2029 filt := new(Filter)
2030 filt.Name = strings.TrimSpace(r.FormValue("name"))
2031 filt.Date = time.Now().UTC()
2032 filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2033 filt.IncludeAudience = r.FormValue("incaud") == "yes"
2034 filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2035 filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2036 filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2037 filt.Reject = r.FormValue("doreject") == "yes"
2038 filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2039 filt.Hide = r.FormValue("dohide") == "yes"
2040 filt.Collapse = r.FormValue("docollapse") == "yes"
2041 filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2042 filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2043 if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2044 filt.Expiration = time.Now().UTC().Add(dur)
2045 }
2046 filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2047
2048 if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2049 log.Printf("blank filter")
2050 http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2051 return
2052 }
2053
2054 j, err := jsonify(filt)
2055 if err == nil {
2056 _, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2057 }
2058 if err != nil {
2059 log.Printf("error saving filter: %s", err)
2060 }
2061
2062 filtInvalidator.Clear(userinfo.UserID)
2063 http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2064}
2065
2066func accountpage(w http.ResponseWriter, r *http.Request) {
2067 u := login.GetUserInfo(r)
2068 user, _ := butwhatabout(u.Username)
2069 templinfo := getInfo(r)
2070 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2071 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2072 templinfo["User"] = user
2073 about := user.About
2074 if ava := user.Options.Avatar; ava != "" {
2075 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2076 }
2077 templinfo["WhatAbout"] = about
2078 err := readviews.Execute(w, "account.html", templinfo)
2079 if err != nil {
2080 log.Print(err)
2081 }
2082}
2083
2084func dochpass(w http.ResponseWriter, r *http.Request) {
2085 err := login.ChangePassword(w, r)
2086 if err != nil {
2087 log.Printf("error changing password: %s", err)
2088 }
2089 http.Redirect(w, r, "/account", http.StatusSeeOther)
2090}
2091
2092func fingerlicker(w http.ResponseWriter, r *http.Request) {
2093 orig := r.FormValue("resource")
2094
2095 log.Printf("finger lick: %s", orig)
2096
2097 if strings.HasPrefix(orig, "acct:") {
2098 orig = orig[5:]
2099 }
2100
2101 name := orig
2102 idx := strings.LastIndexByte(name, '/')
2103 if idx != -1 {
2104 name = name[idx+1:]
2105 if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2106 log.Printf("foreign request rejected")
2107 name = ""
2108 }
2109 } else {
2110 idx = strings.IndexByte(name, '@')
2111 if idx != -1 {
2112 name = name[:idx]
2113 if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2114 log.Printf("foreign request rejected")
2115 name = ""
2116 }
2117 }
2118 }
2119 user, err := butwhatabout(name)
2120 if err != nil {
2121 http.NotFound(w, r)
2122 return
2123 }
2124 if stealthmode(user.ID, r) {
2125 http.NotFound(w, r)
2126 return
2127 }
2128
2129 j := junk.New()
2130 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2131 j["aliases"] = []string{user.URL}
2132 l := junk.New()
2133 l["rel"] = "self"
2134 l["type"] = `application/activity+json`
2135 l["href"] = user.URL
2136 j["links"] = []junk.Junk{l}
2137
2138 w.Header().Set("Content-Type", "application/jrd+json")
2139 j.Write(w)
2140}
2141
2142func somedays() string {
2143 secs := 432000 + notrand.Int63n(432000)
2144 return fmt.Sprintf("%d", secs)
2145}
2146
2147func avatate(w http.ResponseWriter, r *http.Request) {
2148 if debugMode {
2149 loadAvatarColors()
2150 }
2151 n := r.FormValue("a")
2152 a := genAvatar(n)
2153 w.Header().Set("Cache-Control", "max-age="+somedays())
2154 w.Write(a)
2155}
2156
2157func serveasset(w http.ResponseWriter, r *http.Request) {
2158 if !debugMode {
2159 w.Header().Set("Cache-Control", "max-age=7776000")
2160 }
2161 dir := viewDir
2162 if r.URL.Path == "/local.css" {
2163 dir = dataDir
2164 }
2165 http.ServeFile(w, r, dir+"/views"+r.URL.Path)
2166}
2167func servehelp(w http.ResponseWriter, r *http.Request) {
2168 name := mux.Vars(r)["name"]
2169 if !debugMode {
2170 w.Header().Set("Cache-Control", "max-age=3600")
2171 }
2172 http.ServeFile(w, r, viewDir+"/docs/"+name)
2173}
2174func servehtml(w http.ResponseWriter, r *http.Request) {
2175 u := login.GetUserInfo(r)
2176 templinfo := getInfo(r)
2177 templinfo["AboutMsg"] = aboutMsg
2178 templinfo["LoginMsg"] = loginMsg
2179 templinfo["HonkVersion"] = softwareVersion
2180 if r.URL.Path == "/about" {
2181 templinfo["Sensors"] = getSensors()
2182 }
2183 if u == nil && !debugMode {
2184 w.Header().Set("Cache-Control", "max-age=60")
2185 }
2186 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2187 if err != nil {
2188 log.Print(err)
2189 }
2190}
2191func serveemu(w http.ResponseWriter, r *http.Request) {
2192 emu := mux.Vars(r)["emu"]
2193
2194 w.Header().Set("Cache-Control", "max-age="+somedays())
2195 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2196}
2197func servememe(w http.ResponseWriter, r *http.Request) {
2198 meme := mux.Vars(r)["meme"]
2199
2200 w.Header().Set("Cache-Control", "max-age="+somedays())
2201 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2202}
2203
2204func servefile(w http.ResponseWriter, r *http.Request) {
2205 xid := mux.Vars(r)["xid"]
2206 var media string
2207 var data []byte
2208 row := stmtGetFileData.QueryRow(xid)
2209 err := row.Scan(&media, &data)
2210 if err != nil {
2211 log.Printf("error loading file: %s", err)
2212 http.NotFound(w, r)
2213 return
2214 }
2215 w.Header().Set("Content-Type", media)
2216 w.Header().Set("X-Content-Type-Options", "nosniff")
2217 w.Header().Set("Cache-Control", "max-age="+somedays())
2218 w.Write(data)
2219}
2220
2221func nomoroboto(w http.ResponseWriter, r *http.Request) {
2222 io.WriteString(w, "User-agent: *\n")
2223 io.WriteString(w, "Disallow: /a\n")
2224 io.WriteString(w, "Disallow: /d/\n")
2225 io.WriteString(w, "Disallow: /meme/\n")
2226 io.WriteString(w, "Disallow: /o\n")
2227 io.WriteString(w, "Disallow: /o/\n")
2228 for _, u := range allusers() {
2229 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2230 }
2231}
2232
2233func webhydra(w http.ResponseWriter, r *http.Request) {
2234 u := login.GetUserInfo(r)
2235 userid := u.UserID
2236 templinfo := getInfo(r)
2237 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2238 page := r.FormValue("page")
2239
2240 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2241
2242 var honks []*Honk
2243 switch page {
2244 case "atme":
2245 honks = gethonksforme(userid, wanted)
2246 honks = osmosis(honks, userid, false)
2247 templinfo["ServerMessage"] = "at me!"
2248 case "longago":
2249 honks = gethonksfromlongago(userid, wanted)
2250 honks = osmosis(honks, userid, false)
2251 templinfo["ServerMessage"] = "from long ago"
2252 case "home":
2253 honks = gethonksforuser(userid, wanted)
2254 honks = osmosis(honks, userid, true)
2255 templinfo["ServerMessage"] = serverMsg
2256 case "first":
2257 honks = gethonksforuserfirstclass(userid, wanted)
2258 honks = osmosis(honks, userid, true)
2259 templinfo["ServerMessage"] = "first class only"
2260 case "saved":
2261 honks = getsavedhonks(userid, wanted)
2262 templinfo["PageName"] = "saved"
2263 templinfo["ServerMessage"] = "saved honks"
2264 case "combo":
2265 c := r.FormValue("c")
2266 honks = gethonksbycombo(userid, c, wanted)
2267 honks = osmosis(honks, userid, false)
2268 templinfo["ServerMessage"] = "honks by combo: " + c
2269 case "convoy":
2270 c := r.FormValue("c")
2271 honks = gethonksbyconvoy(userid, c, wanted)
2272 honks = osmosis(honks, userid, false)
2273 templinfo["ServerMessage"] = "honks in convoy: " + c
2274 case "honker":
2275 xid := r.FormValue("xid")
2276 honks = gethonksbyxonker(userid, xid, wanted)
2277 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
2278 templinfo["ServerMessage"] = msg
2279 default:
2280 http.NotFound(w, r)
2281 }
2282 if len(honks) > 0 {
2283 templinfo["TopHID"] = honks[0].ID
2284 } else {
2285 templinfo["TopHID"] = wanted
2286 }
2287 reverbolate(userid, honks)
2288 templinfo["Honks"] = honks
2289 templinfo["MapLink"] = getmaplink(u)
2290 templinfo["User"], _ = butwhatabout(u.Username)
2291 w.Header().Set("Content-Type", "text/html; charset=utf-8")
2292 err := readviews.Execute(w, "honkfrags.html", templinfo)
2293 if err != nil {
2294 log.Printf("frag error: %s", err)
2295 }
2296}
2297
2298var honkline = make(chan bool)
2299
2300func honkhonkline() {
2301 for {
2302 select {
2303 case honkline <- true:
2304 default:
2305 return
2306 }
2307 }
2308}
2309
2310func apihandler(w http.ResponseWriter, r *http.Request) {
2311 u := login.GetUserInfo(r)
2312 userid := u.UserID
2313 user, _ := butwhatabout(u.Username)
2314 action := r.FormValue("action")
2315 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2316 log.Printf("api request '%s' on behalf of %s", action, u.Username)
2317 switch action {
2318 case "honk":
2319 h := submithonk(w, r)
2320 if h == nil {
2321 return
2322 }
2323 w.Write([]byte(h.XID))
2324 case "donk":
2325 d, err := submitdonk(w, r)
2326 if err != nil {
2327 if err == http.ErrMissingFile {
2328 http.Error(w, "missing donk", http.StatusBadRequest)
2329 }
2330 return
2331 }
2332 w.Write([]byte(d.XID))
2333 case "zonkit":
2334 zonkit(w, r)
2335 case "gethonks":
2336 var honks []*Honk
2337 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2338 page := r.FormValue("page")
2339 var waitchan <-chan time.Time
2340 requery:
2341 switch page {
2342 case "atme":
2343 honks = gethonksforme(userid, wanted)
2344 honks = osmosis(honks, userid, false)
2345 case "longago":
2346 honks = gethonksfromlongago(userid, wanted)
2347 honks = osmosis(honks, userid, false)
2348 case "home":
2349 honks = gethonksforuser(userid, wanted)
2350 honks = osmosis(honks, userid, true)
2351 default:
2352 http.Error(w, "unknown page", http.StatusNotFound)
2353 return
2354 }
2355 if len(honks) == 0 && wait > 0 {
2356 if waitchan == nil {
2357 waitchan = time.After(time.Duration(wait) * time.Second)
2358 }
2359 select {
2360 case <-honkline:
2361 goto requery
2362 case <-waitchan:
2363 }
2364 }
2365 reverbolate(userid, honks)
2366 j := junk.New()
2367 j["honks"] = honks
2368 j.Write(w)
2369 case "sendactivity":
2370 public := r.FormValue("public") == "1"
2371 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2372 msg := []byte(r.FormValue("msg"))
2373 for rcpt := range rcpts {
2374 go deliverate(0, userid, rcpt, msg)
2375 }
2376 default:
2377 http.Error(w, "unknown action", http.StatusNotFound)
2378 return
2379 }
2380}
2381
2382var endoftheworld = make(chan bool)
2383var readyalready = make(chan bool)
2384var workinprogress = 0
2385
2386func enditall() {
2387 sig := make(chan os.Signal)
2388 signal.Notify(sig, os.Interrupt)
2389 signal.Notify(sig, syscall.SIGTERM)
2390 <-sig
2391 log.Printf("stopping...")
2392 for i := 0; i < workinprogress; i++ {
2393 endoftheworld <- true
2394 }
2395 log.Printf("waiting...")
2396 for i := 0; i < workinprogress; i++ {
2397 <-readyalready
2398 }
2399 log.Printf("apocalypse")
2400 os.Exit(0)
2401}
2402
2403var preservehooks []func()
2404
2405func wait100ms() chan struct{} {
2406 c := make(chan struct{})
2407 go func() {
2408 time.Sleep(100 * time.Millisecond)
2409 close(c)
2410 }()
2411 return c
2412}
2413
2414func bgmonitor() {
2415 for {
2416 time.Sleep(50 * time.Minute)
2417 }
2418}
2419
2420func serve() {
2421 db := opendatabase()
2422 login.Init(db)
2423
2424 listener, err := openListener()
2425 if err != nil {
2426 log.Fatal(err)
2427 }
2428 go runBackendServer()
2429 go enditall()
2430 go redeliverator()
2431 go tracker()
2432 go bgmonitor()
2433 w100 := wait100ms()
2434
2435 readviews = templates.Load(debugMode,
2436 viewDir+"/views/honkpage.html",
2437 viewDir+"/views/honkfrags.html",
2438 viewDir+"/views/honkers.html",
2439 viewDir+"/views/chatter.html",
2440 viewDir+"/views/hfcs.html",
2441 viewDir+"/views/combos.html",
2442 viewDir+"/views/honkform.html",
2443 viewDir+"/views/honk.html",
2444 viewDir+"/views/account.html",
2445 viewDir+"/views/about.html",
2446 viewDir+"/views/funzone.html",
2447 viewDir+"/views/login.html",
2448 viewDir+"/views/xzone.html",
2449 viewDir+"/views/msg.html",
2450 viewDir+"/views/header.html",
2451 viewDir+"/views/onts.html",
2452 viewDir+"/views/honkpage.js",
2453 )
2454 if !debugMode {
2455 assets := []string{viewDir + "/views/style.css", dataDir + "/views/local.css", viewDir + "/views/honkpage.js"}
2456 for _, s := range assets {
2457 savedassetparams[s] = getassetparam(s)
2458 }
2459 loadAvatarColors()
2460 }
2461 <-w100
2462
2463 for _, h := range preservehooks {
2464 h()
2465 }
2466
2467 mux := mux.NewRouter()
2468 mux.Use(login.Checker)
2469
2470 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2471
2472 posters := mux.Methods("POST").Subrouter()
2473 getters := mux.Methods("GET").Subrouter()
2474
2475 getters.HandleFunc("/", homepage)
2476 getters.HandleFunc("/home", homepage)
2477 getters.HandleFunc("/front", homepage)
2478 getters.HandleFunc("/events", homepage)
2479 getters.HandleFunc("/robots.txt", nomoroboto)
2480 getters.HandleFunc("/rss", showrss)
2481 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
2482 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showonehonk)
2483 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
2484 posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
2485 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
2486 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
2487 getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
2488 getters.HandleFunc("/a", avatate)
2489 getters.HandleFunc("/o", thelistingoftheontologies)
2490 getters.HandleFunc("/o/{name:.+}", showontology)
2491 getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
2492 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2493 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2494 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2495
2496 getters.HandleFunc("/flag/{code:.+}", showflag)
2497
2498 getters.HandleFunc("/server", serveractor)
2499 posters.HandleFunc("/server/inbox", serverinbox)
2500 posters.HandleFunc("/inbox", serverinbox)
2501
2502 getters.HandleFunc("/style.css", serveasset)
2503 getters.HandleFunc("/local.css", serveasset)
2504 getters.HandleFunc("/honkpage.js", serveasset)
2505 getters.HandleFunc("/about", servehtml)
2506 getters.HandleFunc("/login", servehtml)
2507 posters.HandleFunc("/dologin", login.LoginFunc)
2508 getters.HandleFunc("/logout", login.LogoutFunc)
2509 getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
2510
2511 loggedin := mux.NewRoute().Subrouter()
2512 loggedin.Use(login.Required)
2513 loggedin.HandleFunc("/first", homepage)
2514 loggedin.HandleFunc("/chatter", showchatter)
2515 loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2516 loggedin.HandleFunc("/saved", homepage)
2517 loggedin.HandleFunc("/account", accountpage)
2518 loggedin.HandleFunc("/funzone", showfunzone)
2519 loggedin.HandleFunc("/chpass", dochpass)
2520 loggedin.HandleFunc("/atme", homepage)
2521 loggedin.HandleFunc("/longago", homepage)
2522 loggedin.HandleFunc("/hfcs", hfcspage)
2523 loggedin.HandleFunc("/xzone", xzone)
2524 loggedin.HandleFunc("/newhonk", newhonkpage)
2525 loggedin.HandleFunc("/edit", edithonkpage)
2526 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitwebhonk)))
2527 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2528 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2529 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2530 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2531 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2532 loggedin.HandleFunc("/honkers", showhonkers)
2533 loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
2534 loggedin.HandleFunc("/h", showhonker)
2535 loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
2536 loggedin.HandleFunc("/c", showcombos)
2537 loggedin.HandleFunc("/t", showconvoy)
2538 loggedin.HandleFunc("/q", showsearch)
2539 loggedin.HandleFunc("/hydra", webhydra)
2540 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
2541
2542 err = http.Serve(listener, mux)
2543 if err != nil {
2544 log.Fatal(err)
2545 }
2546}