all repos — honk @ 4b0764e21d2eab5ab1bf47324bbe6a4110f0eadb

my fork of honk

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