all repos — honk @ 7473567cf7c74e629b8bf7c5149540931ea16db5

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