all repos — honk @ 74409de06d55508eaf85daefb3312dc260055579

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 == "Dislike" || (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	if u != nil && u.Username != name {
 728		u = nil
 729	}
 730	honks := gethonksbyuser(name, u != nil, 0)
 731	templinfo := getInfo(r)
 732	templinfo["PageName"] = "user"
 733	templinfo["PageArg"] = name
 734	templinfo["Name"] = user.Name
 735	templinfo["WhatAbout"] = user.HTAbout
 736	templinfo["ServerMessage"] = ""
 737	if u != nil {
 738		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 739	}
 740	honkpage(w, u, honks, templinfo)
 741}
 742
 743func showhonker(w http.ResponseWriter, r *http.Request) {
 744	u := login.GetUserInfo(r)
 745	name := mux.Vars(r)["name"]
 746	var honks []*Honk
 747	if name == "" {
 748		name = r.FormValue("xid")
 749		honks = gethonksbyxonker(u.UserID, name, 0)
 750	} else {
 751		honks = gethonksbyhonker(u.UserID, name, 0)
 752	}
 753	miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
 754<input type="hidden" name="CSRF" value="%s">
 755<input type="hidden" name="url" value="%s">
 756<button tabindex=1 name="add honker" value="add honker">add honker</button>
 757</form>`, login.GetCSRF("submithonker", r), name)
 758	msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, name, name, miniform)
 759	templinfo := getInfo(r)
 760	templinfo["PageName"] = "honker"
 761	templinfo["PageArg"] = name
 762	templinfo["ServerMessage"] = msg
 763	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 764	honkpage(w, u, honks, templinfo)
 765}
 766
 767func showcombo(w http.ResponseWriter, r *http.Request) {
 768	name := mux.Vars(r)["name"]
 769	u := login.GetUserInfo(r)
 770	honks := gethonksbycombo(u.UserID, name, 0)
 771	honks = osmosis(honks, u.UserID, true)
 772	templinfo := getInfo(r)
 773	templinfo["PageName"] = "combo"
 774	templinfo["PageArg"] = name
 775	templinfo["ServerMessage"] = "honks by combo: " + name
 776	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 777	honkpage(w, u, honks, templinfo)
 778}
 779func showconvoy(w http.ResponseWriter, r *http.Request) {
 780	c := r.FormValue("c")
 781	u := login.GetUserInfo(r)
 782	honks := gethonksbyconvoy(u.UserID, c, 0)
 783	templinfo := getInfo(r)
 784	if len(honks) > 0 {
 785		templinfo["TopHID"] = honks[0].ID
 786	}
 787	honks = osmosis(honks, u.UserID, false)
 788	//reversehonks(honks)
 789	honks = threadsort(honks)
 790	templinfo["PageName"] = "convoy"
 791	templinfo["PageArg"] = c
 792	templinfo["ServerMessage"] = "honks in convoy: " + c
 793	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 794	honkpage(w, u, honks, templinfo)
 795}
 796func showsearch(w http.ResponseWriter, r *http.Request) {
 797	q := r.FormValue("q")
 798	if strings.HasPrefix(q, "https://") {
 799		ximport(w, r)
 800		return
 801	}
 802	u := login.GetUserInfo(r)
 803	honks := gethonksbysearch(u.UserID, q, 0)
 804	templinfo := getInfo(r)
 805	templinfo["PageName"] = "search"
 806	templinfo["PageArg"] = q
 807	templinfo["ServerMessage"] = "honks for search: " + q
 808	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 809	honkpage(w, u, honks, templinfo)
 810}
 811func showontology(w http.ResponseWriter, r *http.Request) {
 812	name := mux.Vars(r)["name"]
 813	u := login.GetUserInfo(r)
 814	var userid int64 = -1
 815	if u != nil {
 816		userid = u.UserID
 817	}
 818	honks := gethonksbyontology(userid, "#"+name, 0)
 819	if friendorfoe(r.Header.Get("Accept")) {
 820		if len(honks) > 40 {
 821			honks = honks[0:40]
 822		}
 823
 824		var xids []string
 825		for _, h := range honks {
 826			xids = append(xids, h.XID)
 827		}
 828
 829		user := getserveruser()
 830
 831		j := junk.New()
 832		j["@context"] = itiswhatitis
 833		j["id"] = fmt.Sprintf("https://%s/o/%s", serverName, name)
 834		j["name"] = "#" + name
 835		j["attributedTo"] = user.URL
 836		j["type"] = "OrderedCollection"
 837		j["totalItems"] = len(xids)
 838		j["orderedItems"] = xids
 839
 840		j.Write(w)
 841		return
 842	}
 843
 844	templinfo := getInfo(r)
 845	templinfo["ServerMessage"] = "honks by ontology: " + name
 846	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 847	honkpage(w, u, honks, templinfo)
 848}
 849
 850type Ont struct {
 851	Name  string
 852	Count int64
 853}
 854
 855func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 856	u := login.GetUserInfo(r)
 857	var userid int64 = -1
 858	if u != nil {
 859		userid = u.UserID
 860	}
 861	rows, err := stmtAllOnts.Query(userid)
 862	if err != nil {
 863		elog.Printf("selection error: %s", err)
 864		return
 865	}
 866	defer rows.Close()
 867	var onts []Ont
 868	for rows.Next() {
 869		var o Ont
 870		err := rows.Scan(&o.Name, &o.Count)
 871		if err != nil {
 872			elog.Printf("error scanning ont: %s", err)
 873			continue
 874		}
 875		if utf8.RuneCountInString(o.Name) > 24 {
 876			continue
 877		}
 878		o.Name = o.Name[1:]
 879		onts = append(onts, o)
 880	}
 881	sort.Slice(onts, func(i, j int) bool {
 882		return onts[i].Name < onts[j].Name
 883	})
 884	if u == nil && !develMode {
 885		w.Header().Set("Cache-Control", "max-age=300")
 886	}
 887	templinfo := getInfo(r)
 888	templinfo["Onts"] = onts
 889	templinfo["FirstRune"] = func(s string) rune { r, _ := utf8.DecodeRuneInString(s); return r }
 890	err = readviews.Execute(w, "onts.html", templinfo)
 891	if err != nil {
 892		elog.Print(err)
 893	}
 894}
 895
 896type Track struct {
 897	xid string
 898	who string
 899}
 900
 901func getbacktracks(xid string) []string {
 902	c := make(chan bool)
 903	dumptracks <- c
 904	<-c
 905	row := stmtGetTracks.QueryRow(xid)
 906	var rawtracks string
 907	err := row.Scan(&rawtracks)
 908	if err != nil {
 909		if err != sql.ErrNoRows {
 910			elog.Printf("error scanning tracks: %s", err)
 911		}
 912		return nil
 913	}
 914	var rcpts []string
 915	for _, f := range strings.Split(rawtracks, " ") {
 916		idx := strings.LastIndexByte(f, '#')
 917		if idx != -1 {
 918			f = f[:idx]
 919		}
 920		if !strings.HasPrefix(f, "https://") {
 921			f = fmt.Sprintf("%%https://%s/inbox", f)
 922		}
 923		rcpts = append(rcpts, f)
 924	}
 925	return rcpts
 926}
 927
 928func savetracks(tracks map[string][]string) {
 929	db := opendatabase()
 930	tx, err := db.Begin()
 931	if err != nil {
 932		elog.Printf("savetracks begin error: %s", err)
 933		return
 934	}
 935	defer func() {
 936		err := tx.Commit()
 937		if err != nil {
 938			elog.Printf("savetracks commit error: %s", err)
 939		}
 940
 941	}()
 942	stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
 943	if err != nil {
 944		elog.Printf("savetracks error: %s", err)
 945		return
 946	}
 947	stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
 948	if err != nil {
 949		elog.Printf("savetracks error: %s", err)
 950		return
 951	}
 952	stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
 953	if err != nil {
 954		elog.Printf("savetracks error: %s", err)
 955		return
 956	}
 957	count := 0
 958	for xid, f := range tracks {
 959		count += len(f)
 960		var prev string
 961		row := stmtGetTracks.QueryRow(xid)
 962		err := row.Scan(&prev)
 963		if err == sql.ErrNoRows {
 964			f = oneofakind(f)
 965			stmtNewTracks.Exec(xid, strings.Join(f, " "))
 966		} else if err == nil {
 967			all := append(strings.Split(prev, " "), f...)
 968			all = oneofakind(all)
 969			stmtUpdateTracks.Exec(strings.Join(all, " "))
 970		} else {
 971			elog.Printf("savetracks error: %s", err)
 972		}
 973	}
 974	dlog.Printf("saved %d new fetches", count)
 975}
 976
 977var trackchan = make(chan Track)
 978var dumptracks = make(chan chan bool)
 979
 980func tracker() {
 981	timeout := 4 * time.Minute
 982	sleeper := time.NewTimer(timeout)
 983	tracks := make(map[string][]string)
 984	workinprogress++
 985	for {
 986		select {
 987		case track := <-trackchan:
 988			tracks[track.xid] = append(tracks[track.xid], track.who)
 989		case <-sleeper.C:
 990			if len(tracks) > 0 {
 991				go savetracks(tracks)
 992				tracks = make(map[string][]string)
 993			}
 994			sleeper.Reset(timeout)
 995		case c := <-dumptracks:
 996			if len(tracks) > 0 {
 997				savetracks(tracks)
 998			}
 999			c <- true
1000		case <-endoftheworld:
1001			if len(tracks) > 0 {
1002				savetracks(tracks)
1003			}
1004			readyalready <- true
1005			return
1006		}
1007	}
1008}
1009
1010var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
1011
1012func trackback(xid string, r *http.Request) {
1013	agent := r.UserAgent()
1014	who := originate(agent)
1015	sig := r.Header.Get("Signature")
1016	if sig != "" {
1017		m := re_keyholder.FindStringSubmatch(sig)
1018		if len(m) == 2 {
1019			who = m[1]
1020		}
1021	}
1022	if who != "" {
1023		trackchan <- Track{xid: xid, who: who}
1024	}
1025}
1026
1027func sameperson(h1, h2 *Honk) bool {
1028	n1, n2 := h1.Honker, h2.Honker
1029	if h1.Oonker != "" {
1030		n1 = h1.Oonker
1031	}
1032	if h2.Oonker != "" {
1033		n2 = h2.Oonker
1034	}
1035	return n1 == n2
1036}
1037
1038func threadsort(honks []*Honk) []*Honk {
1039	sort.Slice(honks, func(i, j int) bool {
1040		return honks[i].Date.Before(honks[j].Date)
1041	})
1042	honkx := make(map[string]*Honk)
1043	kids := make(map[string][]*Honk)
1044	for _, h := range honks {
1045		honkx[h.XID] = h
1046		rid := h.RID
1047		kids[rid] = append(kids[rid], h)
1048	}
1049	done := make(map[*Honk]bool)
1050	var thread []*Honk
1051	var nextlevel func(p *Honk)
1052	level := 0
1053	nextlevel = func(p *Honk) {
1054		levelup := level < 4
1055		if pp := honkx[p.RID]; p.RID == "" || (pp != nil && sameperson(p, pp)) {
1056			levelup = false
1057		}
1058		if level > 0 && len(kids[p.RID]) == 1 {
1059			if pp := honkx[p.RID]; pp != nil && len(kids[pp.RID]) == 1 {
1060				levelup = false
1061			}
1062		}
1063		if levelup {
1064			level++
1065		}
1066		p.Style += fmt.Sprintf(" level%d", level)
1067		childs := kids[p.XID]
1068		sort.SliceStable(childs, func(i, j int) bool {
1069			return sameperson(childs[i], p) && !sameperson(childs[j], p)
1070		})
1071		for _, h := range childs {
1072			if !done[h] {
1073				done[h] = true
1074				thread = append(thread, h)
1075				nextlevel(h)
1076			}
1077		}
1078		if levelup {
1079			level--
1080		}
1081	}
1082	for _, h := range honks {
1083		if !done[h] && h.RID == "" {
1084			done[h] = true
1085			thread = append(thread, h)
1086			nextlevel(h)
1087		}
1088	}
1089	for _, h := range honks {
1090		if !done[h] {
1091			done[h] = true
1092			thread = append(thread, h)
1093			nextlevel(h)
1094		}
1095	}
1096	return thread
1097}
1098
1099func honkology(honk *Honk) template.HTML {
1100	var user *WhatAbout
1101	ok := somenumberedusers.Get(honk.UserID, &user)
1102	if !ok {
1103		return ""
1104	}
1105	title := fmt.Sprintf("%s: %s", user.Display, honk.Precis)
1106	imgurl := avatarURL(user)
1107	for _, d := range honk.Donks {
1108		if d.Local && strings.HasPrefix(d.Media, "image") {
1109			imgurl = d.URL
1110			break
1111		}
1112	}
1113	short := honk.Noise
1114	if len(short) > 160 {
1115		short = short[0:160] + "..."
1116	}
1117	return templates.Sprintf(
1118		`<meta property="og:title" content="%s" />
1119<meta property="og:type" content="article" />
1120<meta property="article:author" content="%s" />
1121<meta property="og:url" content="%s" />
1122<meta property="og:image" content="%s" />
1123<meta property="og:description" content="%s" />`,
1124		title, user.URL, honk.XID, imgurl, short)
1125}
1126
1127func showonehonk(w http.ResponseWriter, r *http.Request) {
1128	name := mux.Vars(r)["name"]
1129	user, err := butwhatabout(name)
1130	if err != nil {
1131		http.NotFound(w, r)
1132		return
1133	}
1134	if stealthmode(user.ID, r) {
1135		http.NotFound(w, r)
1136		return
1137	}
1138	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1139
1140	if friendorfoe(r.Header.Get("Accept")) {
1141		j, ok := gimmejonk(xid)
1142		if ok {
1143			trackback(xid, r)
1144			w.Header().Set("Content-Type", theonetruename)
1145			w.Write(j)
1146		} else {
1147			http.NotFound(w, r)
1148		}
1149		return
1150	}
1151	honk := getxonk(user.ID, xid)
1152	if honk == nil {
1153		http.NotFound(w, r)
1154		return
1155	}
1156	u := login.GetUserInfo(r)
1157	if u != nil && u.UserID != user.ID {
1158		u = nil
1159	}
1160	if !honk.Public {
1161		if u == nil {
1162			http.NotFound(w, r)
1163			return
1164
1165		}
1166		honks := []*Honk{honk}
1167		donksforhonks(honks)
1168		templinfo := getInfo(r)
1169		templinfo["ServerMessage"] = "one honk maybe more"
1170		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1171		honkpage(w, u, honks, templinfo)
1172		return
1173	}
1174
1175	templinfo := getInfo(r)
1176	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1177	//reversehonks(rawhonks)
1178	rawhonks = threadsort(rawhonks)
1179	var honks []*Honk
1180	for _, h := range rawhonks {
1181		if h.XID == xid {
1182			templinfo["Honkology"] = honkology(h)
1183			if len(honks) != 0 {
1184				h.Style += " glow"
1185			}
1186		}
1187		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1188			honks = append(honks, h)
1189		}
1190	}
1191
1192	templinfo["ServerMessage"] = "one honk maybe more"
1193	if u != nil {
1194		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1195	}
1196	templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1197	honkpage(w, u, honks, templinfo)
1198}
1199
1200func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1201	var emunames []string
1202	dir, err := os.Open(dataDir + "/emus")
1203	if err == nil {
1204		emunames, _ = dir.Readdirnames(0)
1205		dir.Close()
1206	}
1207	for i, e := range emunames {
1208		if len(e) > 4 {
1209			emunames[i] = e[:len(e)-4]
1210		}
1211	}
1212	templinfo["Emus"] = emunames
1213	var userid int64 = -1
1214	if u != nil {
1215		userid = u.UserID
1216		templinfo["User"], _ = butwhatabout(u.Username)
1217	}
1218	reverbolate(userid, honks)
1219	templinfo["Honks"] = honks
1220	templinfo["MapLink"] = getmaplink(u)
1221	if templinfo["TopHID"] == nil {
1222		if len(honks) > 0 {
1223			templinfo["TopHID"] = honks[0].ID
1224		} else {
1225			templinfo["TopHID"] = 0
1226		}
1227	}
1228	if u == nil && !develMode {
1229		w.Header().Set("Cache-Control", "max-age=60")
1230	}
1231	err = readviews.Execute(w, "honkpage.html", templinfo)
1232	if err != nil {
1233		elog.Print(err)
1234	}
1235}
1236
1237func saveuser(w http.ResponseWriter, r *http.Request) {
1238	whatabout := r.FormValue("whatabout")
1239	whatabout = strings.Replace(whatabout, "\r", "", -1)
1240	u := login.GetUserInfo(r)
1241	user, _ := butwhatabout(u.Username)
1242	db := opendatabase()
1243
1244	options := user.Options
1245	if r.FormValue("skinny") == "skinny" {
1246		options.SkinnyCSS = true
1247	} else {
1248		options.SkinnyCSS = false
1249	}
1250	if r.FormValue("omitimages") == "omitimages" {
1251		options.OmitImages = true
1252	} else {
1253		options.OmitImages = false
1254	}
1255	if r.FormValue("mentionall") == "mentionall" {
1256		options.MentionAll = true
1257	} else {
1258		options.MentionAll = false
1259	}
1260	if r.FormValue("inlineqts") == "inlineqts" {
1261		options.InlineQuotes = true
1262	} else {
1263		options.InlineQuotes = false
1264	}
1265	if r.FormValue("maps") == "apple" {
1266		options.MapLink = "apple"
1267	} else {
1268		options.MapLink = ""
1269	}
1270
1271	sendupdate := false
1272	if r.FormValue("displayname") != "" {
1273		options.CustomDisplay = r.FormValue("displayname")
1274		_, err := db.Exec("update users set displayname = ? where username = ?", options.CustomDisplay, u.Username)
1275		if err != nil {
1276			elog.Printf("error setting displayname: %s", err)
1277		}
1278		sendupdate = true
1279	} else {
1280		options.CustomDisplay = ""
1281	}
1282
1283	options.Reaction = r.FormValue("reaction")
1284
1285	ava := re_avatar.FindString(whatabout)
1286	if ava != "" {
1287		whatabout = re_avatar.ReplaceAllString(whatabout, "")
1288		ava = ava[7:]
1289		if ava[0] == ' ' {
1290			ava = ava[1:]
1291		}
1292		ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1293	}
1294	if ava != options.Avatar {
1295		options.Avatar = ava
1296		sendupdate = true
1297	}
1298	ban := re_banner.FindString(whatabout)
1299	if ban != "" {
1300		whatabout = re_banner.ReplaceAllString(whatabout, "")
1301		ban = ban[7:]
1302		if ban[0] == ' ' {
1303			ban = ban[1:]
1304		}
1305		ban = fmt.Sprintf("https://%s/meme/%s", serverName, ban)
1306	}
1307	if ban != options.Banner {
1308		options.Banner = ban
1309		sendupdate = true
1310	}
1311	whatabout = strings.TrimSpace(whatabout)
1312	if whatabout != user.About {
1313		sendupdate = true
1314	}
1315	j, err := jsonify(options)
1316	if err == nil {
1317		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1318	}
1319	if err != nil {
1320		elog.Printf("error bouting what: %s", err)
1321	}
1322	somenamedusers.Clear(u.Username)
1323	somenumberedusers.Clear(u.UserID)
1324	oldjonkers.Clear(u.Username)
1325
1326	if sendupdate {
1327		updateMe(u.Username)
1328	}
1329
1330	http.Redirect(w, r, "/account", http.StatusSeeOther)
1331}
1332
1333func bonkit(xid string, user *WhatAbout) {
1334	dlog.Printf("bonking %s", xid)
1335
1336	xonk := getxonk(user.ID, xid)
1337	if xonk == nil {
1338		return
1339	}
1340	if !xonk.Public {
1341		return
1342	}
1343	if xonk.IsBonked() {
1344		return
1345	}
1346	donksforhonks([]*Honk{xonk})
1347
1348	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1349	if err != nil {
1350		elog.Printf("error acking bonk: %s", err)
1351	}
1352
1353	oonker := xonk.Oonker
1354	if oonker == "" {
1355		oonker = xonk.Honker
1356	}
1357	dt := time.Now().UTC()
1358	bonk := &Honk{
1359		UserID:   user.ID,
1360		Username: user.Name,
1361		What:     "bonk",
1362		Honker:   user.URL,
1363		Oonker:   oonker,
1364		XID:      xonk.XID,
1365		RID:      xonk.RID,
1366		Noise:    xonk.Noise,
1367		Precis:   xonk.Precis,
1368		URL:      xonk.URL,
1369		Date:     dt,
1370		Donks:    xonk.Donks,
1371		Whofore:  2,
1372		Convoy:   xonk.Convoy,
1373		Audience: []string{thewholeworld, oonker},
1374		Public:   true,
1375		Format:   xonk.Format,
1376		Place:    xonk.Place,
1377		Onts:     xonk.Onts,
1378		Time:     xonk.Time,
1379	}
1380
1381	err = savehonk(bonk)
1382	if err != nil {
1383		elog.Printf("uh oh")
1384		return
1385	}
1386
1387	go honkworldwide(user, bonk)
1388}
1389
1390func submitbonk(w http.ResponseWriter, r *http.Request) {
1391	xid := r.FormValue("xid")
1392	userinfo := login.GetUserInfo(r)
1393	user, _ := butwhatabout(userinfo.Username)
1394
1395	bonkit(xid, user)
1396
1397	if r.FormValue("js") != "1" {
1398		templinfo := getInfo(r)
1399		templinfo["ServerMessage"] = "Bonked!"
1400		err := readviews.Execute(w, "msg.html", templinfo)
1401		if err != nil {
1402			elog.Print(err)
1403		}
1404	}
1405}
1406
1407func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1408	zonk := &Honk{
1409		What:     what,
1410		XID:      xonk.XID,
1411		Date:     time.Now().UTC(),
1412		Audience: oneofakind(xonk.Audience),
1413		Noise:    aux,
1414	}
1415	zonk.Public = loudandproud(zonk.Audience)
1416
1417	dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1418	go honkworldwide(user, zonk)
1419}
1420
1421func zonkit(w http.ResponseWriter, r *http.Request) {
1422	wherefore := r.FormValue("wherefore")
1423	what := r.FormValue("what")
1424	userinfo := login.GetUserInfo(r)
1425	user, _ := butwhatabout(userinfo.Username)
1426
1427	if wherefore == "save" {
1428		xonk := getxonk(userinfo.UserID, what)
1429		if xonk != nil {
1430			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1431			if err != nil {
1432				elog.Printf("error saving: %s", err)
1433			}
1434		}
1435		return
1436	}
1437
1438	if wherefore == "unsave" {
1439		xonk := getxonk(userinfo.UserID, what)
1440		if xonk != nil {
1441			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1442			if err != nil {
1443				elog.Printf("error unsaving: %s", err)
1444			}
1445		}
1446		return
1447	}
1448
1449	if wherefore == "react" {
1450		reaction := user.Options.Reaction
1451		if r2 := r.FormValue("reaction"); r2 != "" {
1452			reaction = r2
1453		}
1454		if reaction == "none" {
1455			return
1456		}
1457		xonk := getxonk(userinfo.UserID, what)
1458		if xonk != nil {
1459			_, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1460			if err != nil {
1461				elog.Printf("error saving: %s", err)
1462			}
1463			sendzonkofsorts(xonk, user, "react", reaction)
1464		}
1465		return
1466	}
1467
1468	// my hammer is too big, oh well
1469	defer oldjonks.Flush()
1470
1471	if wherefore == "ack" {
1472		xonk := getxonk(userinfo.UserID, what)
1473		if xonk != nil && !xonk.IsAcked() {
1474			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1475			if err != nil {
1476				elog.Printf("error acking: %s", err)
1477			}
1478			sendzonkofsorts(xonk, user, "ack", "")
1479		}
1480		return
1481	}
1482
1483	if wherefore == "deack" {
1484		xonk := getxonk(userinfo.UserID, what)
1485		if xonk != nil && xonk.IsAcked() {
1486			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1487			if err != nil {
1488				elog.Printf("error deacking: %s", err)
1489			}
1490			sendzonkofsorts(xonk, user, "deack", "")
1491		}
1492		return
1493	}
1494
1495	if wherefore == "bonk" {
1496		user, _ := butwhatabout(userinfo.Username)
1497		bonkit(what, user)
1498		return
1499	}
1500
1501	if wherefore == "unbonk" {
1502		xonk := getbonk(userinfo.UserID, what)
1503		if xonk != nil {
1504			deletehonk(xonk.ID)
1505			xonk = getxonk(userinfo.UserID, what)
1506			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1507			if err != nil {
1508				elog.Printf("error unbonking: %s", err)
1509			}
1510			sendzonkofsorts(xonk, user, "unbonk", "")
1511		}
1512		return
1513	}
1514
1515	if wherefore == "untag" {
1516		xonk := getxonk(userinfo.UserID, what)
1517		if xonk != nil {
1518			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1519			if err != nil {
1520				elog.Printf("error untagging: %s", err)
1521			}
1522		}
1523		var badparents map[string]bool
1524		untagged.GetAndLock(userinfo.UserID, &badparents)
1525		badparents[what] = true
1526		untagged.Unlock()
1527		return
1528	}
1529
1530	ilog.Printf("zonking %s %s", wherefore, what)
1531	if wherefore == "zonk" {
1532		xonk := getxonk(userinfo.UserID, what)
1533		if xonk != nil {
1534			deletehonk(xonk.ID)
1535			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1536				sendzonkofsorts(xonk, user, "zonk", "")
1537			}
1538		}
1539	}
1540	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1541	if err != nil {
1542		elog.Printf("error saving zonker: %s", err)
1543		return
1544	}
1545}
1546
1547func edithonkpage(w http.ResponseWriter, r *http.Request) {
1548	u := login.GetUserInfo(r)
1549	user, _ := butwhatabout(u.Username)
1550	xid := r.FormValue("xid")
1551	honk := getxonk(u.UserID, xid)
1552	if !canedithonk(user, honk) {
1553		http.Error(w, "no editing that please", http.StatusInternalServerError)
1554		return
1555	}
1556
1557	noise := honk.Noise
1558
1559	honks := []*Honk{honk}
1560	donksforhonks(honks)
1561	reverbolate(u.UserID, honks)
1562	templinfo := getInfo(r)
1563	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1564	templinfo["Honks"] = honks
1565	templinfo["MapLink"] = getmaplink(u)
1566	templinfo["Noise"] = noise
1567	templinfo["SavedPlace"] = honk.Place
1568	if tm := honk.Time; tm != nil {
1569		templinfo["ShowTime"] = " "
1570		templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1571		if tm.Duration != 0 {
1572			templinfo["Duration"] = tm.Duration
1573		}
1574	}
1575	templinfo["ServerMessage"] = "honk edit 2"
1576	templinfo["IsPreview"] = true
1577	templinfo["UpdateXID"] = honk.XID
1578	if len(honk.Donks) > 0 {
1579		templinfo["SavedFile"] = honk.Donks[0].XID
1580	}
1581	err := readviews.Execute(w, "honkpage.html", templinfo)
1582	if err != nil {
1583		elog.Print(err)
1584	}
1585}
1586
1587func newhonkpage(w http.ResponseWriter, r *http.Request) {
1588	u := login.GetUserInfo(r)
1589	rid := r.FormValue("rid")
1590	noise := ""
1591
1592	xonk := getxonk(u.UserID, rid)
1593	if xonk != nil {
1594		_, replto := handles(xonk.Honker)
1595		if replto != "" {
1596			noise = "@" + replto + " "
1597		}
1598	}
1599
1600	templinfo := getInfo(r)
1601	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1602	templinfo["InReplyTo"] = rid
1603	templinfo["Noise"] = noise
1604	templinfo["ServerMessage"] = "compose honk"
1605	templinfo["IsPreview"] = true
1606	err := readviews.Execute(w, "honkpage.html", templinfo)
1607	if err != nil {
1608		elog.Print(err)
1609	}
1610}
1611
1612func canedithonk(user *WhatAbout, honk *Honk) bool {
1613	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1614		return false
1615	}
1616	return true
1617}
1618
1619func submitdonk(w http.ResponseWriter, r *http.Request) (*Donk, error) {
1620	if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1621		return nil, nil
1622	}
1623	file, filehdr, err := r.FormFile("donk")
1624	if err != nil {
1625		if err == http.ErrMissingFile {
1626			return nil, nil
1627		}
1628		elog.Printf("error reading donk: %s", err)
1629		http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1630		return nil, err
1631	}
1632	var buf bytes.Buffer
1633	io.Copy(&buf, file)
1634	file.Close()
1635	data := buf.Bytes()
1636	var media, name string
1637	img, err := shrinkit(data)
1638	if err == nil {
1639		data = img.Data
1640		format := img.Format
1641		media = "image/" + format
1642		if format == "jpeg" {
1643			format = "jpg"
1644		}
1645		if format == "svg+xml" {
1646			format = "svg"
1647		}
1648		name = xfiltrate() + "." + format
1649	} else {
1650		ct := http.DetectContentType(data)
1651		switch ct {
1652		case "application/pdf":
1653			maxsize := 10000000
1654			if len(data) > maxsize {
1655				ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1656				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1657				return nil, err
1658			}
1659			media = ct
1660			name = filehdr.Filename
1661			if name == "" {
1662				name = xfiltrate() + ".pdf"
1663			}
1664		default:
1665			maxsize := 100000
1666			if len(data) > maxsize {
1667				ilog.Printf("bad image: %s too much text: %d", err, len(data))
1668				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1669				return nil, err
1670			}
1671			for i := 0; i < len(data); i++ {
1672				if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1673					ilog.Printf("bad image: %s not text: %d", err, data[i])
1674					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1675					return nil, err
1676				}
1677			}
1678			media = "text/plain"
1679			name = filehdr.Filename
1680			if name == "" {
1681				name = xfiltrate() + ".txt"
1682			}
1683		}
1684	}
1685	desc := strings.TrimSpace(r.FormValue("donkdesc"))
1686	if desc == "" {
1687		desc = name
1688	}
1689	fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1690	if err != nil {
1691		elog.Printf("unable to save image: %s", err)
1692		http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1693		return nil, err
1694	}
1695	d := &Donk{
1696		FileID: fileid,
1697		XID:    xid,
1698		Desc:   desc,
1699		Local:  true,
1700	}
1701	return d, nil
1702}
1703
1704func websubmithonk(w http.ResponseWriter, r *http.Request) {
1705	h := submithonk(w, r)
1706	if h == nil {
1707		return
1708	}
1709	http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1710}
1711
1712// what a hot mess this function is
1713func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1714	rid := r.FormValue("rid")
1715	noise := r.FormValue("noise")
1716	format := r.FormValue("format")
1717	if format == "" {
1718		format = "markdown"
1719	}
1720	if !(format == "markdown" || format == "html") {
1721		http.Error(w, "unknown format", 500)
1722		return nil
1723	}
1724
1725	userinfo := login.GetUserInfo(r)
1726	user, _ := butwhatabout(userinfo.Username)
1727
1728	dt := time.Now().UTC()
1729	updatexid := r.FormValue("updatexid")
1730	var honk *Honk
1731	if updatexid != "" {
1732		honk = getxonk(userinfo.UserID, updatexid)
1733		if !canedithonk(user, honk) {
1734			http.Error(w, "no editing that please", http.StatusInternalServerError)
1735			return nil
1736		}
1737		honk.Date = dt
1738		honk.What = "update"
1739		honk.Format = format
1740	} else {
1741		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1742		what := "honk"
1743		honk = &Honk{
1744			UserID:   userinfo.UserID,
1745			Username: userinfo.Username,
1746			What:     what,
1747			Honker:   user.URL,
1748			XID:      xid,
1749			Date:     dt,
1750			Format:   format,
1751		}
1752	}
1753
1754	var convoy string
1755	noise = strings.Replace(noise, "\r", "", -1)
1756	if updatexid == "" && rid == "" {
1757		noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1758			convoy = m[7:]
1759			convoy = strings.TrimSpace(convoy)
1760			if !re_convalidate.MatchString(convoy) {
1761				convoy = ""
1762			}
1763			return ""
1764		})
1765	}
1766	noise = quickrename(noise, userinfo.UserID)
1767	noise = hooterize(noise)
1768	honk.Noise = noise
1769	precipitate(honk)
1770	noise = honk.Noise
1771	translate(honk)
1772
1773	if rid != "" {
1774		xonk := getxonk(userinfo.UserID, rid)
1775		if xonk == nil {
1776			http.Error(w, "replyto disappeared", http.StatusNotFound)
1777			return nil
1778		}
1779		if xonk.Public {
1780			honk.Audience = append(honk.Audience, xonk.Audience...)
1781		}
1782		convoy = xonk.Convoy
1783		for i, a := range honk.Audience {
1784			if a == thewholeworld {
1785				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1786				break
1787			}
1788		}
1789		honk.RID = rid
1790		if xonk.Precis != "" && honk.Precis == "" {
1791			honk.Precis = xonk.Precis
1792			if !re_dangerous.MatchString(honk.Precis) {
1793				honk.Precis = "re: " + honk.Precis
1794			}
1795		}
1796	} else {
1797		honk.Audience = []string{thewholeworld}
1798	}
1799	if honk.Noise != "" && honk.Noise[0] == '@' {
1800		honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1801	} else {
1802		honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1803	}
1804
1805	if convoy == "" {
1806		convoy = fmt.Sprintf("data:,%s-", masqName) + xfiltrate()
1807	}
1808	butnottooloud(honk.Audience)
1809	honk.Audience = oneofakind(honk.Audience)
1810	if len(honk.Audience) == 0 {
1811		ilog.Printf("honk to nowhere")
1812		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1813		return nil
1814	}
1815	honk.Public = loudandproud(honk.Audience)
1816	honk.Convoy = convoy
1817
1818	donkxid := r.FormValue("donkxid")
1819	if donkxid == "" {
1820		d, err := submitdonk(w, r)
1821		if err != nil && err != http.ErrMissingFile {
1822			return nil
1823		}
1824		if d != nil {
1825			honk.Donks = append(honk.Donks, d)
1826			donkxid = fmt.Sprintf("%s:%d", d.XID, d.FileID)
1827		}
1828	} else {
1829		for _, d := range r.Form["donkxid"] {
1830			p := strings.Split(d, ":")
1831			xid := p[0]
1832			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1833			var donk *Donk
1834			if len(p) > 1 {
1835				fileid, _ := strconv.ParseInt(p[1], 10, 0)
1836				donk = finddonkid(fileid, url)
1837			} else {
1838				donk = finddonk(url)
1839			}
1840			if donk != nil {
1841				honk.Donks = append(honk.Donks, donk)
1842			} else {
1843				ilog.Printf("can't find file: %s", xid)
1844			}
1845		}
1846	}
1847	memetize(honk)
1848	imaginate(honk)
1849
1850	placename := strings.TrimSpace(r.FormValue("placename"))
1851	placelat := strings.TrimSpace(r.FormValue("placelat"))
1852	placelong := strings.TrimSpace(r.FormValue("placelong"))
1853	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1854	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1855		p := new(Place)
1856		p.Name = placename
1857		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1858		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1859		p.Url = placeurl
1860		honk.Place = p
1861	}
1862	timestart := strings.TrimSpace(r.FormValue("timestart"))
1863	if timestart != "" {
1864		t := new(Time)
1865		now := time.Now().Local()
1866		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1867			start, err := time.ParseInLocation(layout, timestart, now.Location())
1868			if err == nil {
1869				if start.Year() == 0 {
1870					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1871				}
1872				t.StartTime = start
1873				break
1874			}
1875		}
1876		timeend := r.FormValue("timeend")
1877		dur := parseDuration(timeend)
1878		if dur != 0 {
1879			t.Duration = Duration(dur)
1880		}
1881		if !t.StartTime.IsZero() {
1882			honk.What = "event"
1883			honk.Time = t
1884		}
1885	}
1886
1887	if honk.Public {
1888		honk.Whofore = 2
1889	} else {
1890		honk.Whofore = 3
1891	}
1892
1893	// back to markdown
1894	honk.Noise = noise
1895
1896	if r.FormValue("preview") == "preview" {
1897		honks := []*Honk{honk}
1898		reverbolate(userinfo.UserID, honks)
1899		templinfo := getInfo(r)
1900		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1901		templinfo["Honks"] = honks
1902		templinfo["MapLink"] = getmaplink(userinfo)
1903		templinfo["InReplyTo"] = r.FormValue("rid")
1904		templinfo["Noise"] = r.FormValue("noise")
1905		templinfo["SavedFile"] = donkxid
1906		if tm := honk.Time; tm != nil {
1907			templinfo["ShowTime"] = " "
1908			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1909			if tm.Duration != 0 {
1910				templinfo["Duration"] = tm.Duration
1911			}
1912		}
1913		templinfo["IsPreview"] = true
1914		templinfo["UpdateXID"] = updatexid
1915		templinfo["ServerMessage"] = "honk preview"
1916		err := readviews.Execute(w, "honkpage.html", templinfo)
1917		if err != nil {
1918			elog.Print(err)
1919		}
1920		return nil
1921	}
1922
1923	if updatexid != "" {
1924		updatehonk(honk)
1925		oldjonks.Clear(honk.XID)
1926	} else {
1927		err := savehonk(honk)
1928		if err != nil {
1929			elog.Printf("uh oh")
1930			return nil
1931		}
1932	}
1933
1934	// reload for consistency
1935	honk.Donks = nil
1936	donksforhonks([]*Honk{honk})
1937
1938	go honkworldwide(user, honk)
1939
1940	return honk
1941}
1942
1943func showhonkers(w http.ResponseWriter, r *http.Request) {
1944	userinfo := login.GetUserInfo(r)
1945	templinfo := getInfo(r)
1946	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1947	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1948	err := readviews.Execute(w, "honkers.html", templinfo)
1949	if err != nil {
1950		elog.Print(err)
1951	}
1952}
1953
1954func showchatter(w http.ResponseWriter, r *http.Request) {
1955	u := login.GetUserInfo(r)
1956	chatnewnone(u.UserID)
1957	chatter := loadchatter(u.UserID)
1958	for _, chat := range chatter {
1959		for _, ch := range chat.Chonks {
1960			filterchonk(ch)
1961		}
1962	}
1963
1964	templinfo := getInfo(r)
1965	templinfo["Chatter"] = chatter
1966	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1967	err := readviews.Execute(w, "chatter.html", templinfo)
1968	if err != nil {
1969		elog.Print(err)
1970	}
1971}
1972
1973func submitchonk(w http.ResponseWriter, r *http.Request) {
1974	u := login.GetUserInfo(r)
1975	user, _ := butwhatabout(u.Username)
1976	noise := r.FormValue("noise")
1977	target := r.FormValue("target")
1978	format := "markdown"
1979	dt := time.Now().UTC()
1980	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1981
1982	if !strings.HasPrefix(target, "https://") {
1983		target = fullname(target, u.UserID)
1984	}
1985	if target == "" {
1986		http.Error(w, "who is that?", http.StatusInternalServerError)
1987		return
1988	}
1989	ch := Chonk{
1990		UserID: u.UserID,
1991		XID:    xid,
1992		Who:    user.URL,
1993		Target: target,
1994		Date:   dt,
1995		Noise:  noise,
1996		Format: format,
1997	}
1998	d, err := submitdonk(w, r)
1999	if err != nil && err != http.ErrMissingFile {
2000		return
2001	}
2002	if d != nil {
2003		ch.Donks = append(ch.Donks, d)
2004	}
2005
2006	translatechonk(&ch)
2007	savechonk(&ch)
2008	// reload for consistency
2009	ch.Donks = nil
2010	donksforchonks([]*Chonk{&ch})
2011	go sendchonk(user, &ch)
2012
2013	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2014}
2015
2016var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
2017	honkers := gethonkers(userid)
2018	var combos []string
2019	for _, h := range honkers {
2020		combos = append(combos, h.Combos...)
2021	}
2022	for i, c := range combos {
2023		if c == "-" {
2024			combos[i] = ""
2025		}
2026	}
2027	combos = oneofakind(combos)
2028	sort.Strings(combos)
2029	return combos, true
2030}, Invalidator: &honkerinvalidator})
2031
2032func showcombos(w http.ResponseWriter, r *http.Request) {
2033	userinfo := login.GetUserInfo(r)
2034	var combos []string
2035	combocache.Get(userinfo.UserID, &combos)
2036	templinfo := getInfo(r)
2037	err := readviews.Execute(w, "combos.html", templinfo)
2038	if err != nil {
2039		elog.Print(err)
2040	}
2041}
2042
2043func websubmithonker(w http.ResponseWriter, r *http.Request) {
2044	h := submithonker(w, r)
2045	if h == nil {
2046		return
2047	}
2048	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2049}
2050
2051func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2052	u := login.GetUserInfo(r)
2053	user, _ := butwhatabout(u.Username)
2054	name := strings.TrimSpace(r.FormValue("name"))
2055	url := strings.TrimSpace(r.FormValue("url"))
2056	peep := r.FormValue("peep")
2057	combos := strings.TrimSpace(r.FormValue("combos"))
2058	combos = " " + combos + " "
2059	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2060
2061	re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2062	if name != "" && !re_namecheck.MatchString(name) {
2063		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2064		return nil
2065	}
2066
2067	var meta HonkerMeta
2068	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2069	mj, _ := jsonify(&meta)
2070
2071	defer honkerinvalidator.Clear(u.UserID)
2072
2073	// mostly dummy, fill in later...
2074	h := &Honker{
2075		ID: honkerid,
2076	}
2077
2078	if honkerid > 0 {
2079		if r.FormValue("delete") == "delete" {
2080			unfollowyou(user, honkerid, false)
2081			stmtDeleteHonker.Exec(honkerid)
2082			return h
2083		}
2084		if r.FormValue("unsub") == "unsub" {
2085			unfollowyou(user, honkerid, false)
2086		}
2087		if r.FormValue("sub") == "sub" {
2088			followyou(user, honkerid, false)
2089		}
2090		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2091		if err != nil {
2092			elog.Printf("update honker err: %s", err)
2093			return nil
2094		}
2095		return h
2096	}
2097
2098	if url == "" {
2099		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2100		return nil
2101	}
2102
2103	flavor := "presub"
2104	if peep == "peep" {
2105		flavor = "peep"
2106	}
2107
2108	var err error
2109	honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2110	if err != nil {
2111		http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2112		return nil
2113	}
2114	if flavor == "presub" {
2115		followyou(user, honkerid, false)
2116	}
2117	h.ID = honkerid
2118	return h
2119}
2120
2121func hfcspage(w http.ResponseWriter, r *http.Request) {
2122	userinfo := login.GetUserInfo(r)
2123
2124	filters := getfilters(userinfo.UserID, filtAny)
2125
2126	templinfo := getInfo(r)
2127	templinfo["Filters"] = filters
2128	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2129	err := readviews.Execute(w, "hfcs.html", templinfo)
2130	if err != nil {
2131		elog.Print(err)
2132	}
2133}
2134
2135func savehfcs(w http.ResponseWriter, r *http.Request) {
2136	userinfo := login.GetUserInfo(r)
2137	itsok := r.FormValue("itsok")
2138	if itsok == "iforgiveyou" {
2139		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2140		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2141		if err != nil {
2142			elog.Printf("error deleting filter: %s", err)
2143		}
2144		filtInvalidator.Clear(userinfo.UserID)
2145		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2146		return
2147	}
2148
2149	filt := new(Filter)
2150	filt.Name = strings.TrimSpace(r.FormValue("name"))
2151	filt.Date = time.Now().UTC()
2152	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2153	filt.IncludeAudience = r.FormValue("incaud") == "yes"
2154	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2155	filt.IsReply = r.FormValue("isreply") == "yes"
2156	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2157	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2158	filt.Reject = r.FormValue("doreject") == "yes"
2159	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2160	filt.Hide = r.FormValue("dohide") == "yes"
2161	filt.Collapse = r.FormValue("docollapse") == "yes"
2162	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2163	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2164	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2165		filt.Expiration = time.Now().UTC().Add(dur)
2166	}
2167	filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2168
2169	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2170		ilog.Printf("blank filter")
2171		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2172		return
2173	}
2174
2175	j, err := jsonify(filt)
2176	if err == nil {
2177		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2178	}
2179	if err != nil {
2180		elog.Printf("error saving filter: %s", err)
2181	}
2182
2183	filtInvalidator.Clear(userinfo.UserID)
2184	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2185}
2186
2187func accountpage(w http.ResponseWriter, r *http.Request) {
2188	u := login.GetUserInfo(r)
2189	user, _ := butwhatabout(u.Username)
2190	templinfo := getInfo(r)
2191	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2192	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2193	templinfo["User"] = user
2194	about := user.About
2195	if ava := user.Options.Avatar; ava != "" {
2196		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2197	}
2198	if ban := user.Options.Banner; ban != "" {
2199		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2200	}
2201	templinfo["WhatAbout"] = about
2202	err := readviews.Execute(w, "account.html", templinfo)
2203	if err != nil {
2204		elog.Print(err)
2205	}
2206}
2207
2208func dochpass(w http.ResponseWriter, r *http.Request) {
2209	err := login.ChangePassword(w, r)
2210	if err != nil {
2211		elog.Printf("error changing password: %s", err)
2212	}
2213	http.Redirect(w, r, "/account", http.StatusSeeOther)
2214}
2215
2216var oldfingers = cache.New(cache.Options{Filler: func(orig string) ([]byte, bool) {
2217	if strings.HasPrefix(orig, "acct:") {
2218		orig = orig[5:]
2219	}
2220	name := orig
2221	idx := strings.LastIndexByte(name, '/')
2222	if idx != -1 {
2223		name = name[idx+1:]
2224		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2225			ilog.Printf("foreign request rejected")
2226			name = ""
2227		}
2228	} else {
2229		idx = strings.IndexByte(name, '@')
2230		if idx != -1 {
2231			name = name[:idx]
2232			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2233				ilog.Printf("foreign request rejected")
2234				name = ""
2235			}
2236		}
2237	}
2238	user, err := butwhatabout(name)
2239	if err != nil {
2240		return nil, false
2241	}
2242
2243	j := junk.New()
2244	pretty := fmt.Sprintf("https://%s/@%s", serverName, name)
2245	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2246	j["aliases"] = []string{pretty, user.URL}
2247	l := junk.New()
2248	l["rel"] = "self"
2249	l["type"] = `application/activity+json`
2250	l["href"] = user.URL
2251	j["links"] = []junk.Junk{l}
2252	l2 := junk.New()
2253	l2["rel"] = "http://webfinger.net/rel/profile-page"
2254	l2["type"] = "text/html"
2255	l2["href"] = pretty
2256	j["links"] = []junk.Junk{l, l2}
2257
2258	return j.ToBytes(), true
2259}})
2260
2261func fingerlicker(w http.ResponseWriter, r *http.Request) {
2262	orig := r.FormValue("resource")
2263
2264	dlog.Printf("finger lick: %s", orig)
2265
2266	var j []byte
2267	ok := oldfingers.Get(orig, &j)
2268	if ok {
2269		w.Header().Set("Content-Type", "application/jrd+json")
2270		w.Write(j)
2271	} else {
2272		http.NotFound(w, r)
2273	}
2274}
2275
2276func knowninformation(w http.ResponseWriter, r *http.Request) {
2277	j := junk.New()
2278	l := junk.New()
2279
2280	l["rel"] = `http://nodeinfo.diaspora.software/ns/schema/2.0`
2281	l["href"] = fmt.Sprintf("https://%s/nodeinfo/2.0", serverName)
2282	j["links"] = []junk.Junk{l}
2283
2284	w.Header().Set("Content-Type", "application/json")
2285	j.Write(w)
2286}
2287
2288func actualinformation(w http.ResponseWriter, r *http.Request) {
2289	j := junk.New()
2290
2291	soft := junk.New()
2292	soft["name"] = "honk"
2293	soft["version"] = softwareVersion
2294
2295	services := junk.New()
2296	services["inbound"] = []string{}
2297	services["outbound"] = []string{"rss2.0"}
2298
2299	users := junk.New()
2300	users["total"] = getusercount()
2301	users["activeHalfyear"] = getactiveusercount(6)
2302	users["activeMonth"] = getactiveusercount(1)
2303
2304	usage := junk.New()
2305	usage["users"] = users
2306	usage["localPosts"] = getlocalhonkcount()
2307
2308	j["version"] = "2.0"
2309	j["protocols"] = []string{"activitypub"}
2310	j["software"] = soft
2311	j["services"] = services
2312	j["openRegistrations"] = false
2313	j["usage"] = usage
2314
2315	w.Header().Set("Content-Type", "application/json")
2316	j.Write(w)
2317}
2318
2319func somedays() string {
2320	secs := 432000 + notrand.Int63n(432000)
2321	return fmt.Sprintf("%d", secs)
2322}
2323
2324func isurl(s string) bool {
2325	u, err := url.Parse(s)
2326	return err == nil && u.Scheme != "" && u.Host != ""
2327}
2328
2329func avatateautogen(r *http.Request) []byte {
2330	n := r.FormValue("a")
2331	return genAvatar(n)
2332}
2333
2334func avatate(w http.ResponseWriter, r *http.Request) {
2335	if develMode {
2336		loadAvatarColors()
2337	}
2338	var a []byte
2339	n := r.FormValue("a")
2340
2341	if isurl(n) {
2342		uinfo := login.GetUserInfo(r)
2343		j, err := GetJunkFast(uinfo.UserID, n)
2344		if err != nil {
2345			dlog.Println("avatating: getting junk:", err)
2346			a = avatateautogen(r)
2347		}
2348		pfpurl, _ := j.GetString("icon", "url")
2349		res, err := http.Get(pfpurl)
2350		if err != nil {
2351			dlog.Println("avatating: getting pfp url:", err)
2352			a = avatateautogen(r)
2353		} else {
2354			defer res.Body.Close()
2355
2356			pfpbytes, err := io.ReadAll(res.Body)
2357			if err != nil {
2358				dlog.Println("avatating: bruh shits clapped:", err)
2359				a = avatateautogen(r)
2360			}
2361			a = pfpbytes
2362		}
2363	} else {
2364		a = avatateautogen(r)
2365	}
2366
2367	if !develMode {
2368		w.Header().Set("Cache-Control", "max-age="+somedays())
2369	}
2370
2371	w.Write(a)
2372}
2373
2374func serveviewasset(w http.ResponseWriter, r *http.Request) {
2375	serveasset(w, r, viewDir)
2376}
2377func servedataasset(w http.ResponseWriter, r *http.Request) {
2378	if r.URL.Path == "/favicon.ico" {
2379		r.URL.Path = "/icon.png"
2380	}
2381	serveasset(w, r, dataDir)
2382}
2383
2384func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2385	if !develMode {
2386		w.Header().Set("Cache-Control", "max-age=7776000")
2387	}
2388	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2389}
2390func servehelp(w http.ResponseWriter, r *http.Request) {
2391	name := mux.Vars(r)["name"]
2392	if !develMode {
2393		w.Header().Set("Cache-Control", "max-age=3600")
2394	}
2395	http.ServeFile(w, r, viewDir+"/docs/"+name)
2396}
2397func servehtml(w http.ResponseWriter, r *http.Request) {
2398	u := login.GetUserInfo(r)
2399	templinfo := getInfo(r)
2400	templinfo["AboutMsg"] = aboutMsg
2401	templinfo["LoginMsg"] = loginMsg
2402	templinfo["HonkVersion"] = softwareVersion
2403	if r.URL.Path == "/about" {
2404		templinfo["Sensors"] = getSensors()
2405	}
2406	if u == nil && !develMode {
2407		w.Header().Set("Cache-Control", "max-age=60")
2408	}
2409	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2410	if err != nil {
2411		elog.Print(err)
2412	}
2413}
2414func serveemu(w http.ResponseWriter, r *http.Request) {
2415	emu := mux.Vars(r)["emu"]
2416
2417	w.Header().Set("Cache-Control", "max-age="+somedays())
2418	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2419}
2420func servememe(w http.ResponseWriter, r *http.Request) {
2421	meme := mux.Vars(r)["meme"]
2422
2423	w.Header().Set("Cache-Control", "max-age="+somedays())
2424	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2425}
2426
2427func servefile(w http.ResponseWriter, r *http.Request) {
2428	xid := mux.Vars(r)["xid"]
2429	var media string
2430	var data []byte
2431	row := stmtGetFileData.QueryRow(xid)
2432	err := row.Scan(&media, &data)
2433	if err != nil {
2434		elog.Printf("error loading file: %s", err)
2435		http.NotFound(w, r)
2436		return
2437	}
2438	w.Header().Set("Content-Type", media)
2439	w.Header().Set("X-Content-Type-Options", "nosniff")
2440	w.Header().Set("Cache-Control", "max-age="+somedays())
2441	w.Write(data)
2442}
2443
2444func nomoroboto(w http.ResponseWriter, r *http.Request) {
2445	io.WriteString(w, "User-agent: *\n")
2446	io.WriteString(w, "Disallow: /a\n")
2447	io.WriteString(w, "Disallow: /d/\n")
2448	io.WriteString(w, "Disallow: /meme/\n")
2449	io.WriteString(w, "Disallow: /o\n")
2450	io.WriteString(w, "Disallow: /o/\n")
2451	io.WriteString(w, "Disallow: /help/\n")
2452	for _, u := range allusers() {
2453		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2454	}
2455}
2456
2457type Hydration struct {
2458	Tophid    int64
2459	Srvmsg    template.HTML
2460	Honks     string
2461	MeCount   int64
2462	ChatCount int64
2463}
2464
2465func webhydra(w http.ResponseWriter, r *http.Request) {
2466	u := login.GetUserInfo(r)
2467	userid := u.UserID
2468	templinfo := getInfo(r)
2469	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2470	page := r.FormValue("page")
2471
2472	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2473
2474	var hydra Hydration
2475
2476	var honks []*Honk
2477	switch page {
2478	case "atme":
2479		honks = gethonksforme(userid, wanted)
2480		honks = osmosis(honks, userid, false)
2481		menewnone(userid)
2482		hydra.Srvmsg = "at me!"
2483	case "longago":
2484		honks = gethonksfromlongago(userid, wanted)
2485		honks = osmosis(honks, userid, false)
2486		hydra.Srvmsg = "from long ago"
2487	case "home":
2488		honks = gethonksforuser(userid, wanted)
2489		honks = osmosis(honks, userid, true)
2490		hydra.Srvmsg = serverMsg
2491	case "first":
2492		honks = gethonksforuserfirstclass(userid, wanted)
2493		honks = osmosis(honks, userid, true)
2494		hydra.Srvmsg = "first class only"
2495	case "saved":
2496		honks = getsavedhonks(userid, wanted)
2497		templinfo["PageName"] = "saved"
2498		hydra.Srvmsg = "saved honks"
2499	case "combo":
2500		c := r.FormValue("c")
2501		honks = gethonksbycombo(userid, c, wanted)
2502		honks = osmosis(honks, userid, false)
2503		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2504	case "convoy":
2505		c := r.FormValue("c")
2506		honks = gethonksbyconvoy(userid, c, wanted)
2507		honks = osmosis(honks, userid, false)
2508		honks = threadsort(honks)
2509		reversehonks(honks)
2510		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2511	case "honker":
2512		xid := r.FormValue("xid")
2513		honks = gethonksbyxonker(userid, xid, wanted)
2514		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2515			<input type="hidden" name="CSRF" value="%s">
2516			<input type="hidden" name="url" value="%s">
2517			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2518			</form>`, login.GetCSRF("submithonker", r), xid)
2519		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2520		hydra.Srvmsg = msg
2521	case "user":
2522		uname := r.FormValue("uname")
2523		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2524		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2525	default:
2526		http.NotFound(w, r)
2527	}
2528
2529	if len(honks) > 0 {
2530		hydra.Tophid = honks[0].ID
2531	} else {
2532		hydra.Tophid = wanted
2533	}
2534	reverbolate(userid, honks)
2535
2536	user, _ := butwhatabout(u.Username)
2537
2538	var buf strings.Builder
2539	templinfo["Honks"] = honks
2540	templinfo["MapLink"] = getmaplink(u)
2541	templinfo["User"], _ = butwhatabout(u.Username)
2542	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2543	if err != nil {
2544		elog.Printf("frag error: %s", err)
2545		return
2546	}
2547	hydra.Honks = buf.String()
2548	hydra.MeCount = user.Options.MeCount
2549	hydra.ChatCount = user.Options.ChatCount
2550	w.Header().Set("Content-Type", "application/json")
2551	j, _ := jsonify(&hydra)
2552	io.WriteString(w, j)
2553}
2554
2555var honkline = make(chan bool)
2556
2557func honkhonkline() {
2558	for {
2559		select {
2560		case honkline <- true:
2561		default:
2562			return
2563		}
2564	}
2565}
2566
2567func apihandler(w http.ResponseWriter, r *http.Request) {
2568	u := login.GetUserInfo(r)
2569	userid := u.UserID
2570	action := r.FormValue("action")
2571	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2572	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2573	switch action {
2574	case "honk":
2575		h := submithonk(w, r)
2576		if h == nil {
2577			return
2578		}
2579
2580		fmt.Fprintf(w, "%s", h.XID)
2581	case "donk":
2582		d, err := submitdonk(w, r)
2583		if err != nil {
2584			http.Error(w, err.Error(), http.StatusBadRequest)
2585			return
2586		}
2587		if d == nil {
2588			http.Error(w, "missing donk", http.StatusBadRequest)
2589			return
2590		}
2591		w.Write([]byte(d.XID))
2592	case "zonkit":
2593		zonkit(w, r)
2594	case "gethonks":
2595		var honks []*Honk
2596		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2597		page := r.FormValue("page")
2598		var waitchan <-chan time.Time
2599	requery:
2600		switch page {
2601		case "atme":
2602			honks = gethonksforme(userid, wanted)
2603			honks = osmosis(honks, userid, false)
2604			menewnone(userid)
2605		case "longago":
2606			honks = gethonksfromlongago(userid, wanted)
2607			honks = osmosis(honks, userid, false)
2608		case "home":
2609			honks = gethonksforuser(userid, wanted)
2610			honks = osmosis(honks, userid, true)
2611		case "myhonks":
2612			honks = gethonksbyuser(u.Username, true, wanted)
2613			honks = osmosis(honks, userid, true)
2614		default:
2615			http.Error(w, "unknown page", http.StatusNotFound)
2616			return
2617		}
2618		if len(honks) == 0 && wait > 0 {
2619			if waitchan == nil {
2620				waitchan = time.After(time.Duration(wait) * time.Second)
2621			}
2622			select {
2623			case <-honkline:
2624				goto requery
2625			case <-waitchan:
2626			}
2627		}
2628		reverbolate(userid, honks)
2629		j := junk.New()
2630		j["honks"] = honks
2631		j.Write(w)
2632	case "sendactivity":
2633		user, _ := butwhatabout(u.Username)
2634		public := r.FormValue("public") == "1"
2635		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2636		msg := []byte(r.FormValue("msg"))
2637		for rcpt := range rcpts {
2638			go deliverate(userid, rcpt, msg)
2639		}
2640	case "gethonkers":
2641		j := junk.New()
2642		j["honkers"] = gethonkers(u.UserID)
2643		j.Write(w)
2644	case "savehonker":
2645		h := submithonker(w, r)
2646		if h == nil {
2647			return
2648		}
2649		fmt.Fprintf(w, "%d", h.ID)
2650	default:
2651		http.Error(w, "unknown action", http.StatusNotFound)
2652		return
2653	}
2654}
2655
2656func fiveoh(w http.ResponseWriter, r *http.Request) {
2657	fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2658	if err != nil {
2659		elog.Printf("error opening violations! %s", err)
2660		return
2661	}
2662	defer fd.Close()
2663	io.Copy(fd, r.Body)
2664	fd.WriteString("\n")
2665}
2666
2667var endoftheworld = make(chan bool)
2668var readyalready = make(chan bool)
2669var workinprogress = 0
2670
2671func enditall() {
2672	sig := make(chan os.Signal, 1)
2673	signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
2674	<-sig
2675	ilog.Printf("stopping...")
2676	for i := 0; i < workinprogress; i++ {
2677		endoftheworld <- true
2678	}
2679	ilog.Printf("waiting...")
2680	for i := 0; i < workinprogress; i++ {
2681		<-readyalready
2682	}
2683	ilog.Printf("apocalypse")
2684	os.Exit(0)
2685}
2686
2687var preservehooks []func()
2688
2689func bgmonitor() {
2690	for {
2691		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2692		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2693		if err != nil {
2694			elog.Printf("error deleting old xonkers: %s", err)
2695		}
2696		zaggies.Flush()
2697		time.Sleep(50 * time.Minute)
2698	}
2699}
2700
2701func emuinit() {
2702	var emunames []string
2703	dir, err := os.Open(dataDir + "/emus")
2704	if err == nil {
2705		emunames, _ = dir.Readdirnames(0)
2706		dir.Close()
2707	}
2708	for _, e := range emunames {
2709		if len(e) <= 4 {
2710			continue
2711		}
2712		ext := e[len(e)-4:]
2713		emu := Emu{
2714			ID:   fmt.Sprintf("/emu/%s", e),
2715			Name: e[:len(e)-4],
2716			Type: "image/" + ext[1:],
2717		}
2718		allemus = append(allemus, emu)
2719	}
2720	sort.Slice(allemus, func(i, j int) bool {
2721		return allemus[i].Name < allemus[j].Name
2722	})
2723}
2724
2725func redirectPretty(w http.ResponseWriter, r *http.Request) {
2726	last := path.Base(r.URL.Path)
2727	name := mux.Vars(r)["name"]
2728	aturl := "/@" + name
2729
2730	if last == name {
2731		last = ""
2732	}
2733	http.Redirect(w, r, path.Join(aturl, last), http.StatusMovedPermanently)
2734}
2735
2736func serve() {
2737	db := opendatabase()
2738	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2739
2740	listener, err := openListener()
2741	if err != nil {
2742		elog.Fatal(err)
2743	}
2744	runBackendServer()
2745	go enditall()
2746	go redeliverator()
2747	go tracker()
2748	go bgmonitor()
2749	loadLingo()
2750	emuinit()
2751
2752	readviews = templates.Load(develMode,
2753		viewDir+"/views/honkpage.html",
2754		viewDir+"/views/honkfrags.html",
2755		viewDir+"/views/honkers.html",
2756		viewDir+"/views/chatter.html",
2757		viewDir+"/views/hfcs.html",
2758		viewDir+"/views/combos.html",
2759		viewDir+"/views/honkform.html",
2760		viewDir+"/views/honk.html",
2761		viewDir+"/views/account.html",
2762		viewDir+"/views/about.html",
2763		viewDir+"/views/funzone.html",
2764		viewDir+"/views/login.html",
2765		viewDir+"/views/xzone.html",
2766		viewDir+"/views/msg.html",
2767		viewDir+"/views/header.html",
2768		viewDir+"/views/onts.html",
2769		viewDir+"/views/emus.html",
2770		viewDir+"/views/honkpage.js",
2771	)
2772	if !develMode {
2773		assets := []string{
2774			viewDir + "/views/style.css",
2775			dataDir + "/views/local.css",
2776			viewDir + "/views/honkpage.js",
2777			dataDir + "/views/local.js",
2778			viewDir + "/views/manifest.webmanifest",
2779			viewDir + "/views/sw.js",
2780		}
2781		for _, s := range assets {
2782			savedassetparams[s] = getassetparam(s)
2783		}
2784		loadAvatarColors()
2785	}
2786
2787	for _, h := range preservehooks {
2788		h()
2789	}
2790
2791	mux := mux.NewRouter()
2792	mux.Use(login.Checker)
2793
2794	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2795
2796	posters := mux.Methods("POST").Subrouter()
2797	getters := mux.Methods("GET").Subrouter()
2798
2799	getters.HandleFunc("/", homepage)
2800	getters.HandleFunc("/home", homepage)
2801	getters.HandleFunc("/front", homepage)
2802	getters.HandleFunc("/events", homepage)
2803	getters.HandleFunc("/robots.txt", nomoroboto)
2804	getters.HandleFunc("/rss", showrss)
2805	getters.HandleFunc("/@{name:[\\pL[:digit:]]+}", showuser)
2806	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", redirectPretty)
2807	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2808	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2809	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2810	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2811	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2812	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2813	getters.HandleFunc("/a", avatate)
2814	getters.HandleFunc("/o", thelistingoftheontologies)
2815	getters.HandleFunc("/o/{name:.+}", showontology)
2816	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2817	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2818	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2819	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2820	getters.HandleFunc("/.well-known/nodeinfo", knowninformation)
2821	getters.HandleFunc("/nodeinfo/2.0", actualinformation)
2822
2823	getters.HandleFunc("/flag/{code:.+}", showflag)
2824
2825	getters.HandleFunc("/server", serveractor)
2826	posters.HandleFunc("/server/inbox", serverinbox)
2827	posters.HandleFunc("/inbox", serverinbox)
2828
2829	posters.HandleFunc("/csp-violation", fiveoh)
2830
2831	getters.HandleFunc("/style.css", serveviewasset)
2832	getters.HandleFunc("/sw.js", serveviewasset)
2833	getters.HandleFunc("/honkpage.js", serveviewasset)
2834	getters.HandleFunc("/misc.js", serveviewasset)
2835	getters.HandleFunc("/local.css", servedataasset)
2836	getters.HandleFunc("/local.js", servedataasset)
2837	getters.HandleFunc("/icon.png", servedataasset)
2838	getters.HandleFunc("/favicon.ico", servedataasset)
2839	getters.HandleFunc("/manifest.webmanifest", serveviewasset)
2840
2841	getters.HandleFunc("/about", servehtml)
2842	getters.HandleFunc("/login", servehtml)
2843	posters.HandleFunc("/dologin", login.LoginFunc)
2844	getters.HandleFunc("/logout", login.LogoutFunc)
2845	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2846
2847	loggedin := mux.NewRoute().Subrouter()
2848	loggedin.Use(login.Required)
2849	loggedin.HandleFunc("/first", homepage)
2850	loggedin.HandleFunc("/chatter", showchatter)
2851	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2852	loggedin.HandleFunc("/saved", homepage)
2853	loggedin.HandleFunc("/account", accountpage)
2854	loggedin.HandleFunc("/funzone", showfunzone)
2855	loggedin.HandleFunc("/chpass", dochpass)
2856	loggedin.HandleFunc("/atme", homepage)
2857	loggedin.HandleFunc("/longago", homepage)
2858	loggedin.HandleFunc("/hfcs", hfcspage)
2859	loggedin.HandleFunc("/xzone", xzone)
2860	loggedin.HandleFunc("/newhonk", newhonkpage)
2861	loggedin.HandleFunc("/edit", edithonkpage)
2862	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2863	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2864	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2865	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2866	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2867	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2868	loggedin.HandleFunc("/honkers", showhonkers)
2869	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2870	loggedin.HandleFunc("/h", showhonker)
2871	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2872	loggedin.HandleFunc("/c", showcombos)
2873	loggedin.HandleFunc("/t", showconvoy)
2874	loggedin.HandleFunc("/q", showsearch)
2875	loggedin.HandleFunc("/hydra", webhydra)
2876	loggedin.HandleFunc("/emus", showemus)
2877	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2878
2879	// mastoshit
2880	getters.HandleFunc("/oauth/authorize", oauthorize)
2881	getters.HandleFunc("/api/v1/instance", instance)
2882	posters.HandleFunc("/api/v1/apps", apiapps)
2883
2884	err = http.Serve(listener, mux)
2885	if err != nil {
2886		elog.Fatal(err)
2887	}
2888}