all repos — honk @ dc081988e58738d4f2b6749d088bd5dd2753b46b

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		p := strings.Split(donkxid, ":")
1830		xid := p[0]
1831		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1832		var donk *Donk
1833		if len(p) > 1 {
1834			fileid, _ := strconv.ParseInt(p[1], 10, 0)
1835			donk = finddonkid(fileid, url)
1836		} else {
1837			donk = finddonk(url)
1838		}
1839		if donk != nil {
1840			honk.Donks = append(honk.Donks, donk)
1841		} else {
1842			ilog.Printf("can't find file: %s", xid)
1843		}
1844	}
1845	memetize(honk)
1846	imaginate(honk)
1847
1848	placename := strings.TrimSpace(r.FormValue("placename"))
1849	placelat := strings.TrimSpace(r.FormValue("placelat"))
1850	placelong := strings.TrimSpace(r.FormValue("placelong"))
1851	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1852	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1853		p := new(Place)
1854		p.Name = placename
1855		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1856		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1857		p.Url = placeurl
1858		honk.Place = p
1859	}
1860	timestart := strings.TrimSpace(r.FormValue("timestart"))
1861	if timestart != "" {
1862		t := new(Time)
1863		now := time.Now().Local()
1864		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1865			start, err := time.ParseInLocation(layout, timestart, now.Location())
1866			if err == nil {
1867				if start.Year() == 0 {
1868					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1869				}
1870				t.StartTime = start
1871				break
1872			}
1873		}
1874		timeend := r.FormValue("timeend")
1875		dur := parseDuration(timeend)
1876		if dur != 0 {
1877			t.Duration = Duration(dur)
1878		}
1879		if !t.StartTime.IsZero() {
1880			honk.What = "event"
1881			honk.Time = t
1882		}
1883	}
1884
1885	if honk.Public {
1886		honk.Whofore = 2
1887	} else {
1888		honk.Whofore = 3
1889	}
1890
1891	// back to markdown
1892	honk.Noise = noise
1893
1894	if r.FormValue("preview") == "preview" {
1895		honks := []*Honk{honk}
1896		reverbolate(userinfo.UserID, honks)
1897		templinfo := getInfo(r)
1898		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1899		templinfo["Honks"] = honks
1900		templinfo["MapLink"] = getmaplink(userinfo)
1901		templinfo["InReplyTo"] = r.FormValue("rid")
1902		templinfo["Noise"] = r.FormValue("noise")
1903		templinfo["SavedFile"] = donkxid
1904		if tm := honk.Time; tm != nil {
1905			templinfo["ShowTime"] = " "
1906			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1907			if tm.Duration != 0 {
1908				templinfo["Duration"] = tm.Duration
1909			}
1910		}
1911		templinfo["IsPreview"] = true
1912		templinfo["UpdateXID"] = updatexid
1913		templinfo["ServerMessage"] = "honk preview"
1914		err := readviews.Execute(w, "honkpage.html", templinfo)
1915		if err != nil {
1916			elog.Print(err)
1917		}
1918		return nil
1919	}
1920
1921	if updatexid != "" {
1922		updatehonk(honk)
1923		oldjonks.Clear(honk.XID)
1924	} else {
1925		err := savehonk(honk)
1926		if err != nil {
1927			elog.Printf("uh oh")
1928			return nil
1929		}
1930	}
1931
1932	// reload for consistency
1933	honk.Donks = nil
1934	donksforhonks([]*Honk{honk})
1935
1936	go honkworldwide(user, honk)
1937
1938	return honk
1939}
1940
1941func showhonkers(w http.ResponseWriter, r *http.Request) {
1942	userinfo := login.GetUserInfo(r)
1943	templinfo := getInfo(r)
1944	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1945	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1946	err := readviews.Execute(w, "honkers.html", templinfo)
1947	if err != nil {
1948		elog.Print(err)
1949	}
1950}
1951
1952func showchatter(w http.ResponseWriter, r *http.Request) {
1953	u := login.GetUserInfo(r)
1954	chatnewnone(u.UserID)
1955	chatter := loadchatter(u.UserID)
1956	for _, chat := range chatter {
1957		for _, ch := range chat.Chonks {
1958			filterchonk(ch)
1959		}
1960	}
1961
1962	templinfo := getInfo(r)
1963	templinfo["Chatter"] = chatter
1964	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1965	err := readviews.Execute(w, "chatter.html", templinfo)
1966	if err != nil {
1967		elog.Print(err)
1968	}
1969}
1970
1971func submitchonk(w http.ResponseWriter, r *http.Request) {
1972	u := login.GetUserInfo(r)
1973	user, _ := butwhatabout(u.Username)
1974	noise := r.FormValue("noise")
1975	target := r.FormValue("target")
1976	format := "markdown"
1977	dt := time.Now().UTC()
1978	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1979
1980	if !strings.HasPrefix(target, "https://") {
1981		target = fullname(target, u.UserID)
1982	}
1983	if target == "" {
1984		http.Error(w, "who is that?", http.StatusInternalServerError)
1985		return
1986	}
1987	ch := Chonk{
1988		UserID: u.UserID,
1989		XID:    xid,
1990		Who:    user.URL,
1991		Target: target,
1992		Date:   dt,
1993		Noise:  noise,
1994		Format: format,
1995	}
1996	d, err := submitdonk(w, r)
1997	if err != nil && err != http.ErrMissingFile {
1998		return
1999	}
2000	if d != nil {
2001		ch.Donks = append(ch.Donks, d)
2002	}
2003
2004	translatechonk(&ch)
2005	savechonk(&ch)
2006	// reload for consistency
2007	ch.Donks = nil
2008	donksforchonks([]*Chonk{&ch})
2009	go sendchonk(user, &ch)
2010
2011	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2012}
2013
2014var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
2015	honkers := gethonkers(userid)
2016	var combos []string
2017	for _, h := range honkers {
2018		combos = append(combos, h.Combos...)
2019	}
2020	for i, c := range combos {
2021		if c == "-" {
2022			combos[i] = ""
2023		}
2024	}
2025	combos = oneofakind(combos)
2026	sort.Strings(combos)
2027	return combos, true
2028}, Invalidator: &honkerinvalidator})
2029
2030func showcombos(w http.ResponseWriter, r *http.Request) {
2031	userinfo := login.GetUserInfo(r)
2032	var combos []string
2033	combocache.Get(userinfo.UserID, &combos)
2034	templinfo := getInfo(r)
2035	err := readviews.Execute(w, "combos.html", templinfo)
2036	if err != nil {
2037		elog.Print(err)
2038	}
2039}
2040
2041func websubmithonker(w http.ResponseWriter, r *http.Request) {
2042	h := submithonker(w, r)
2043	if h == nil {
2044		return
2045	}
2046	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2047}
2048
2049func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2050	u := login.GetUserInfo(r)
2051	user, _ := butwhatabout(u.Username)
2052	name := strings.TrimSpace(r.FormValue("name"))
2053	url := strings.TrimSpace(r.FormValue("url"))
2054	peep := r.FormValue("peep")
2055	combos := strings.TrimSpace(r.FormValue("combos"))
2056	combos = " " + combos + " "
2057	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2058
2059	re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2060	if name != "" && !re_namecheck.MatchString(name) {
2061		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2062		return nil
2063	}
2064
2065	var meta HonkerMeta
2066	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2067	mj, _ := jsonify(&meta)
2068
2069	defer honkerinvalidator.Clear(u.UserID)
2070
2071	// mostly dummy, fill in later...
2072	h := &Honker{
2073		ID: honkerid,
2074	}
2075
2076	if honkerid > 0 {
2077		if r.FormValue("delete") == "delete" {
2078			unfollowyou(user, honkerid, false)
2079			stmtDeleteHonker.Exec(honkerid)
2080			return h
2081		}
2082		if r.FormValue("unsub") == "unsub" {
2083			unfollowyou(user, honkerid, false)
2084		}
2085		if r.FormValue("sub") == "sub" {
2086			followyou(user, honkerid, false)
2087		}
2088		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
2089		if err != nil {
2090			elog.Printf("update honker err: %s", err)
2091			return nil
2092		}
2093		return h
2094	}
2095
2096	if url == "" {
2097		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2098		return nil
2099	}
2100
2101	flavor := "presub"
2102	if peep == "peep" {
2103		flavor = "peep"
2104	}
2105
2106	var err error
2107	honkerid, err = savehonker(user, url, name, flavor, combos, mj)
2108	if err != nil {
2109		http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2110		return nil
2111	}
2112	if flavor == "presub" {
2113		followyou(user, honkerid, false)
2114	}
2115	h.ID = honkerid
2116	return h
2117}
2118
2119func hfcspage(w http.ResponseWriter, r *http.Request) {
2120	userinfo := login.GetUserInfo(r)
2121
2122	filters := getfilters(userinfo.UserID, filtAny)
2123
2124	templinfo := getInfo(r)
2125	templinfo["Filters"] = filters
2126	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2127	err := readviews.Execute(w, "hfcs.html", templinfo)
2128	if err != nil {
2129		elog.Print(err)
2130	}
2131}
2132
2133func savehfcs(w http.ResponseWriter, r *http.Request) {
2134	userinfo := login.GetUserInfo(r)
2135	itsok := r.FormValue("itsok")
2136	if itsok == "iforgiveyou" {
2137		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
2138		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
2139		if err != nil {
2140			elog.Printf("error deleting filter: %s", err)
2141		}
2142		filtInvalidator.Clear(userinfo.UserID)
2143		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2144		return
2145	}
2146
2147	filt := new(Filter)
2148	filt.Name = strings.TrimSpace(r.FormValue("name"))
2149	filt.Date = time.Now().UTC()
2150	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2151	filt.IncludeAudience = r.FormValue("incaud") == "yes"
2152	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2153	filt.IsReply = r.FormValue("isreply") == "yes"
2154	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2155	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2156	filt.Reject = r.FormValue("doreject") == "yes"
2157	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2158	filt.Hide = r.FormValue("dohide") == "yes"
2159	filt.Collapse = r.FormValue("docollapse") == "yes"
2160	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2161	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2162	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2163		filt.Expiration = time.Now().UTC().Add(dur)
2164	}
2165	filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2166
2167	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2168		ilog.Printf("blank filter")
2169		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2170		return
2171	}
2172
2173	j, err := jsonify(filt)
2174	if err == nil {
2175		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2176	}
2177	if err != nil {
2178		elog.Printf("error saving filter: %s", err)
2179	}
2180
2181	filtInvalidator.Clear(userinfo.UserID)
2182	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2183}
2184
2185func accountpage(w http.ResponseWriter, r *http.Request) {
2186	u := login.GetUserInfo(r)
2187	user, _ := butwhatabout(u.Username)
2188	templinfo := getInfo(r)
2189	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2190	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2191	templinfo["User"] = user
2192	about := user.About
2193	if ava := user.Options.Avatar; ava != "" {
2194		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2195	}
2196	if ban := user.Options.Banner; ban != "" {
2197		about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2198	}
2199	templinfo["WhatAbout"] = about
2200	err := readviews.Execute(w, "account.html", templinfo)
2201	if err != nil {
2202		elog.Print(err)
2203	}
2204}
2205
2206func dochpass(w http.ResponseWriter, r *http.Request) {
2207	err := login.ChangePassword(w, r)
2208	if err != nil {
2209		elog.Printf("error changing password: %s", err)
2210	}
2211	http.Redirect(w, r, "/account", http.StatusSeeOther)
2212}
2213
2214var oldfingers = cache.New(cache.Options{Filler: func(orig string) ([]byte, bool) {
2215	if strings.HasPrefix(orig, "acct:") {
2216		orig = orig[5:]
2217	}
2218	name := orig
2219	idx := strings.LastIndexByte(name, '/')
2220	if idx != -1 {
2221		name = name[idx+1:]
2222		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2223			ilog.Printf("foreign request rejected")
2224			name = ""
2225		}
2226	} else {
2227		idx = strings.IndexByte(name, '@')
2228		if idx != -1 {
2229			name = name[:idx]
2230			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2231				ilog.Printf("foreign request rejected")
2232				name = ""
2233			}
2234		}
2235	}
2236	user, err := butwhatabout(name)
2237	if err != nil {
2238		return nil, false
2239	}
2240
2241	j := junk.New()
2242	pretty := fmt.Sprintf("https://%s/@%s", serverName, name)
2243	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2244	j["aliases"] = []string{pretty, user.URL}
2245	l := junk.New()
2246	l["rel"] = "self"
2247	l["type"] = `application/activity+json`
2248	l["href"] = user.URL
2249	j["links"] = []junk.Junk{l}
2250	l2 := junk.New()
2251	l2["rel"] = "http://webfinger.net/rel/profile-page"
2252	l2["type"] = "text/html"
2253	l2["href"] = pretty
2254	j["links"] = []junk.Junk{l, l2}
2255
2256	return j.ToBytes(), true
2257}})
2258
2259func fingerlicker(w http.ResponseWriter, r *http.Request) {
2260	orig := r.FormValue("resource")
2261
2262	dlog.Printf("finger lick: %s", orig)
2263
2264	var j []byte
2265	ok := oldfingers.Get(orig, &j)
2266	if ok {
2267		w.Header().Set("Content-Type", "application/jrd+json")
2268		w.Write(j)
2269	} else {
2270		http.NotFound(w, r)
2271	}
2272}
2273
2274func knowninformation(w http.ResponseWriter, r *http.Request) {
2275	j := junk.New()
2276	l := junk.New()
2277
2278	l["rel"] = `http://nodeinfo.diaspora.software/ns/schema/2.0`
2279	l["href"] = fmt.Sprintf("https://%s/nodeinfo/2.0", serverName)
2280	j["links"] = []junk.Junk{l}
2281
2282	w.Header().Set("Content-Type", "application/json")
2283	j.Write(w)
2284}
2285
2286func actualinformation(w http.ResponseWriter, r *http.Request) {
2287	j := junk.New()
2288
2289	soft := junk.New()
2290	soft["name"] = "honk"
2291	soft["version"] = softwareVersion
2292
2293	services := junk.New()
2294	services["inbound"] = []string{}
2295	services["outbound"] = []string{"rss2.0"}
2296
2297	users := junk.New()
2298	users["total"] = getusercount()
2299	users["activeHalfyear"] = getactiveusercount(6)
2300	users["activeMonth"] = getactiveusercount(1)
2301
2302	usage := junk.New()
2303	usage["users"] = users
2304	usage["localPosts"] = getlocalhonkcount()
2305
2306	j["version"] = "2.0"
2307	j["protocols"] = []string{"activitypub"}
2308	j["software"] = soft
2309	j["services"] = services
2310	j["openRegistrations"] = false
2311	j["usage"] = usage
2312
2313	w.Header().Set("Content-Type", "application/json")
2314	j.Write(w)
2315}
2316
2317func somedays() string {
2318	secs := 432000 + notrand.Int63n(432000)
2319	return fmt.Sprintf("%d", secs)
2320}
2321
2322func isurl(s string) bool {
2323	u, err := url.Parse(s)
2324	return err == nil && u.Scheme != "" && u.Host != ""
2325}
2326
2327func avatateautogen(r *http.Request) []byte {
2328	n := r.FormValue("a")
2329	return genAvatar(n)
2330}
2331
2332func avatate(w http.ResponseWriter, r *http.Request) {
2333	if develMode {
2334		loadAvatarColors()
2335	}
2336	var a []byte
2337	n := r.FormValue("a")
2338
2339	if isurl(n) {
2340		uinfo := login.GetUserInfo(r)
2341		j, err := GetJunkFast(uinfo.UserID, n)
2342		if err != nil {
2343			dlog.Println("avatating: getting junk:", err)
2344			a = avatateautogen(r)
2345		}
2346		pfpurl, _ := j.GetString("icon", "url")
2347		res, err := http.Get(pfpurl)
2348		if err != nil {
2349			dlog.Println("avatating: getting pfp url:", err)
2350			a = avatateautogen(r)
2351		} else {
2352			defer res.Body.Close()
2353
2354			pfpbytes, err := io.ReadAll(res.Body)
2355			if err != nil {
2356				dlog.Println("avatating: bruh shits clapped:", err)
2357				a = avatateautogen(r)
2358			}
2359			a = pfpbytes
2360		}
2361	} else {
2362		a = avatateautogen(r)
2363	}
2364
2365	if !develMode {
2366		w.Header().Set("Cache-Control", "max-age="+somedays())
2367	}
2368
2369	w.Write(a)
2370}
2371
2372func serveviewasset(w http.ResponseWriter, r *http.Request) {
2373	serveasset(w, r, viewDir)
2374}
2375func servedataasset(w http.ResponseWriter, r *http.Request) {
2376	if r.URL.Path == "/favicon.ico" {
2377		r.URL.Path = "/icon.png"
2378	}
2379	serveasset(w, r, dataDir)
2380}
2381
2382func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2383	if !develMode {
2384		w.Header().Set("Cache-Control", "max-age=7776000")
2385	}
2386	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2387}
2388func servehelp(w http.ResponseWriter, r *http.Request) {
2389	name := mux.Vars(r)["name"]
2390	if !develMode {
2391		w.Header().Set("Cache-Control", "max-age=3600")
2392	}
2393	http.ServeFile(w, r, viewDir+"/docs/"+name)
2394}
2395func servehtml(w http.ResponseWriter, r *http.Request) {
2396	u := login.GetUserInfo(r)
2397	templinfo := getInfo(r)
2398	templinfo["AboutMsg"] = aboutMsg
2399	templinfo["LoginMsg"] = loginMsg
2400	templinfo["HonkVersion"] = softwareVersion
2401	if r.URL.Path == "/about" {
2402		templinfo["Sensors"] = getSensors()
2403	}
2404	if u == nil && !develMode {
2405		w.Header().Set("Cache-Control", "max-age=60")
2406	}
2407	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2408	if err != nil {
2409		elog.Print(err)
2410	}
2411}
2412func serveemu(w http.ResponseWriter, r *http.Request) {
2413	emu := mux.Vars(r)["emu"]
2414
2415	w.Header().Set("Cache-Control", "max-age="+somedays())
2416	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2417}
2418func servememe(w http.ResponseWriter, r *http.Request) {
2419	meme := mux.Vars(r)["meme"]
2420
2421	w.Header().Set("Cache-Control", "max-age="+somedays())
2422	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2423}
2424
2425func servefile(w http.ResponseWriter, r *http.Request) {
2426	xid := mux.Vars(r)["xid"]
2427	var media string
2428	var data []byte
2429	row := stmtGetFileData.QueryRow(xid)
2430	err := row.Scan(&media, &data)
2431	if err != nil {
2432		elog.Printf("error loading file: %s", err)
2433		http.NotFound(w, r)
2434		return
2435	}
2436	w.Header().Set("Content-Type", media)
2437	w.Header().Set("X-Content-Type-Options", "nosniff")
2438	w.Header().Set("Cache-Control", "max-age="+somedays())
2439	w.Write(data)
2440}
2441
2442func nomoroboto(w http.ResponseWriter, r *http.Request) {
2443	io.WriteString(w, "User-agent: *\n")
2444	io.WriteString(w, "Disallow: /a\n")
2445	io.WriteString(w, "Disallow: /d/\n")
2446	io.WriteString(w, "Disallow: /meme/\n")
2447	io.WriteString(w, "Disallow: /o\n")
2448	io.WriteString(w, "Disallow: /o/\n")
2449	io.WriteString(w, "Disallow: /help/\n")
2450	for _, u := range allusers() {
2451		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2452	}
2453}
2454
2455type Hydration struct {
2456	Tophid    int64
2457	Srvmsg    template.HTML
2458	Honks     string
2459	MeCount   int64
2460	ChatCount int64
2461}
2462
2463func webhydra(w http.ResponseWriter, r *http.Request) {
2464	u := login.GetUserInfo(r)
2465	userid := u.UserID
2466	templinfo := getInfo(r)
2467	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2468	page := r.FormValue("page")
2469
2470	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2471
2472	var hydra Hydration
2473
2474	var honks []*Honk
2475	switch page {
2476	case "atme":
2477		honks = gethonksforme(userid, wanted)
2478		honks = osmosis(honks, userid, false)
2479		menewnone(userid)
2480		hydra.Srvmsg = "at me!"
2481	case "longago":
2482		honks = gethonksfromlongago(userid, wanted)
2483		honks = osmosis(honks, userid, false)
2484		hydra.Srvmsg = "from long ago"
2485	case "home":
2486		honks = gethonksforuser(userid, wanted)
2487		honks = osmosis(honks, userid, true)
2488		hydra.Srvmsg = serverMsg
2489	case "first":
2490		honks = gethonksforuserfirstclass(userid, wanted)
2491		honks = osmosis(honks, userid, true)
2492		hydra.Srvmsg = "first class only"
2493	case "saved":
2494		honks = getsavedhonks(userid, wanted)
2495		templinfo["PageName"] = "saved"
2496		hydra.Srvmsg = "saved honks"
2497	case "combo":
2498		c := r.FormValue("c")
2499		honks = gethonksbycombo(userid, c, wanted)
2500		honks = osmosis(honks, userid, false)
2501		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2502	case "convoy":
2503		c := r.FormValue("c")
2504		honks = gethonksbyconvoy(userid, c, wanted)
2505		honks = osmosis(honks, userid, false)
2506		honks = threadsort(honks)
2507		reversehonks(honks)
2508		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2509	case "honker":
2510		xid := r.FormValue("xid")
2511		honks = gethonksbyxonker(userid, xid, wanted)
2512		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2513			<input type="hidden" name="CSRF" value="%s">
2514			<input type="hidden" name="url" value="%s">
2515			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2516			</form>`, login.GetCSRF("submithonker", r), xid)
2517		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2518		hydra.Srvmsg = msg
2519	case "user":
2520		uname := r.FormValue("uname")
2521		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2522		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2523	default:
2524		http.NotFound(w, r)
2525	}
2526
2527	if len(honks) > 0 {
2528		hydra.Tophid = honks[0].ID
2529	} else {
2530		hydra.Tophid = wanted
2531	}
2532	reverbolate(userid, honks)
2533
2534	user, _ := butwhatabout(u.Username)
2535
2536	var buf strings.Builder
2537	templinfo["Honks"] = honks
2538	templinfo["MapLink"] = getmaplink(u)
2539	templinfo["User"], _ = butwhatabout(u.Username)
2540	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2541	if err != nil {
2542		elog.Printf("frag error: %s", err)
2543		return
2544	}
2545	hydra.Honks = buf.String()
2546	hydra.MeCount = user.Options.MeCount
2547	hydra.ChatCount = user.Options.ChatCount
2548	w.Header().Set("Content-Type", "application/json")
2549	j, _ := jsonify(&hydra)
2550	io.WriteString(w, j)
2551}
2552
2553var honkline = make(chan bool)
2554
2555func honkhonkline() {
2556	for {
2557		select {
2558		case honkline <- true:
2559		default:
2560			return
2561		}
2562	}
2563}
2564
2565func apihandler(w http.ResponseWriter, r *http.Request) {
2566	u := login.GetUserInfo(r)
2567	userid := u.UserID
2568	action := r.FormValue("action")
2569	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2570	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2571	switch action {
2572	case "honk":
2573		h := submithonk(w, r)
2574		if h == nil {
2575			return
2576		}
2577
2578		fmt.Fprintf(w, "%s", h.XID)
2579	case "donk":
2580		d, err := submitdonk(w, r)
2581		if err != nil {
2582			http.Error(w, err.Error(), http.StatusBadRequest)
2583			return
2584		}
2585		if d == nil {
2586			http.Error(w, "missing donk", http.StatusBadRequest)
2587			return
2588		}
2589		w.Write([]byte(d.XID))
2590	case "zonkit":
2591		zonkit(w, r)
2592	case "gethonks":
2593		var honks []*Honk
2594		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2595		page := r.FormValue("page")
2596		var waitchan <-chan time.Time
2597	requery:
2598		switch page {
2599		case "atme":
2600			honks = gethonksforme(userid, wanted)
2601			honks = osmosis(honks, userid, false)
2602			menewnone(userid)
2603		case "longago":
2604			honks = gethonksfromlongago(userid, wanted)
2605			honks = osmosis(honks, userid, false)
2606		case "home":
2607			honks = gethonksforuser(userid, wanted)
2608			honks = osmosis(honks, userid, true)
2609		case "myhonks":
2610			honks = gethonksbyuser(u.Username, true, wanted)
2611			honks = osmosis(honks, userid, true)
2612		default:
2613			http.Error(w, "unknown page", http.StatusNotFound)
2614			return
2615		}
2616		if len(honks) == 0 && wait > 0 {
2617			if waitchan == nil {
2618				waitchan = time.After(time.Duration(wait) * time.Second)
2619			}
2620			select {
2621			case <-honkline:
2622				goto requery
2623			case <-waitchan:
2624			}
2625		}
2626		reverbolate(userid, honks)
2627		j := junk.New()
2628		j["honks"] = honks
2629		j.Write(w)
2630	case "sendactivity":
2631		user, _ := butwhatabout(u.Username)
2632		public := r.FormValue("public") == "1"
2633		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2634		msg := []byte(r.FormValue("msg"))
2635		for rcpt := range rcpts {
2636			go deliverate(userid, rcpt, msg)
2637		}
2638	case "gethonkers":
2639		j := junk.New()
2640		j["honkers"] = gethonkers(u.UserID)
2641		j.Write(w)
2642	case "savehonker":
2643		h := submithonker(w, r)
2644		if h == nil {
2645			return
2646		}
2647		fmt.Fprintf(w, "%d", h.ID)
2648	default:
2649		http.Error(w, "unknown action", http.StatusNotFound)
2650		return
2651	}
2652}
2653
2654func fiveoh(w http.ResponseWriter, r *http.Request) {
2655	fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2656	if err != nil {
2657		elog.Printf("error opening violations! %s", err)
2658		return
2659	}
2660	defer fd.Close()
2661	io.Copy(fd, r.Body)
2662	fd.WriteString("\n")
2663}
2664
2665var endoftheworld = make(chan bool)
2666var readyalready = make(chan bool)
2667var workinprogress = 0
2668
2669func enditall() {
2670	sig := make(chan os.Signal, 1)
2671	signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
2672	<-sig
2673	ilog.Printf("stopping...")
2674	for i := 0; i < workinprogress; i++ {
2675		endoftheworld <- true
2676	}
2677	ilog.Printf("waiting...")
2678	for i := 0; i < workinprogress; i++ {
2679		<-readyalready
2680	}
2681	ilog.Printf("apocalypse")
2682	os.Exit(0)
2683}
2684
2685var preservehooks []func()
2686
2687func bgmonitor() {
2688	for {
2689		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2690		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2691		if err != nil {
2692			elog.Printf("error deleting old xonkers: %s", err)
2693		}
2694		zaggies.Flush()
2695		time.Sleep(50 * time.Minute)
2696	}
2697}
2698
2699func emuinit() {
2700	var emunames []string
2701	dir, err := os.Open(dataDir + "/emus")
2702	if err == nil {
2703		emunames, _ = dir.Readdirnames(0)
2704		dir.Close()
2705	}
2706	for _, e := range emunames {
2707		if len(e) <= 4 {
2708			continue
2709		}
2710		ext := e[len(e)-4:]
2711		emu := Emu{
2712			ID:   fmt.Sprintf("/emu/%s", e),
2713			Name: e[:len(e)-4],
2714			Type: "image/" + ext[1:],
2715		}
2716		allemus = append(allemus, emu)
2717	}
2718	sort.Slice(allemus, func(i, j int) bool {
2719		return allemus[i].Name < allemus[j].Name
2720	})
2721}
2722
2723func redirectPretty(w http.ResponseWriter, r *http.Request) {
2724	last := path.Base(r.URL.Path)
2725	name := mux.Vars(r)["name"]
2726	aturl := "/@" + name
2727
2728	if last == name {
2729		last = ""
2730	}
2731	http.Redirect(w, r, path.Join(aturl, last), http.StatusMovedPermanently)
2732}
2733
2734func serve() {
2735	db := opendatabase()
2736	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2737
2738	listener, err := openListener()
2739	if err != nil {
2740		elog.Fatal(err)
2741	}
2742	runBackendServer()
2743	go enditall()
2744	go redeliverator()
2745	go tracker()
2746	go bgmonitor()
2747	loadLingo()
2748	emuinit()
2749
2750	readviews = templates.Load(develMode,
2751		viewDir+"/views/honkpage.html",
2752		viewDir+"/views/honkfrags.html",
2753		viewDir+"/views/honkers.html",
2754		viewDir+"/views/chatter.html",
2755		viewDir+"/views/hfcs.html",
2756		viewDir+"/views/combos.html",
2757		viewDir+"/views/honkform.html",
2758		viewDir+"/views/honk.html",
2759		viewDir+"/views/account.html",
2760		viewDir+"/views/about.html",
2761		viewDir+"/views/funzone.html",
2762		viewDir+"/views/login.html",
2763		viewDir+"/views/xzone.html",
2764		viewDir+"/views/msg.html",
2765		viewDir+"/views/header.html",
2766		viewDir+"/views/onts.html",
2767		viewDir+"/views/emus.html",
2768		viewDir+"/views/honkpage.js",
2769	)
2770	if !develMode {
2771		assets := []string{
2772			viewDir + "/views/style.css",
2773			dataDir + "/views/local.css",
2774			viewDir + "/views/honkpage.js",
2775			dataDir + "/views/local.js",
2776			viewDir + "/views/manifest.webmanifest",
2777			viewDir + "/views/sw.js",
2778		}
2779		for _, s := range assets {
2780			savedassetparams[s] = getassetparam(s)
2781		}
2782		loadAvatarColors()
2783	}
2784
2785	for _, h := range preservehooks {
2786		h()
2787	}
2788
2789	mux := mux.NewRouter()
2790	mux.Use(login.Checker)
2791
2792	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2793
2794	posters := mux.Methods("POST").Subrouter()
2795	getters := mux.Methods("GET").Subrouter()
2796
2797	getters.HandleFunc("/", homepage)
2798	getters.HandleFunc("/home", homepage)
2799	getters.HandleFunc("/front", homepage)
2800	getters.HandleFunc("/events", homepage)
2801	getters.HandleFunc("/robots.txt", nomoroboto)
2802	getters.HandleFunc("/rss", showrss)
2803	getters.HandleFunc("/@{name:[\\pL[:digit:]]+}", showuser)
2804	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", redirectPretty)
2805	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2806	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2807	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2808	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2809	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2810	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2811	getters.HandleFunc("/a", avatate)
2812	getters.HandleFunc("/o", thelistingoftheontologies)
2813	getters.HandleFunc("/o/{name:.+}", showontology)
2814	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2815	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2816	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2817	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2818	getters.HandleFunc("/.well-known/nodeinfo", knowninformation)
2819	getters.HandleFunc("/nodeinfo/2.0", actualinformation)
2820
2821	getters.HandleFunc("/flag/{code:.+}", showflag)
2822
2823	getters.HandleFunc("/server", serveractor)
2824	posters.HandleFunc("/server/inbox", serverinbox)
2825	posters.HandleFunc("/inbox", serverinbox)
2826
2827	posters.HandleFunc("/csp-violation", fiveoh)
2828
2829	getters.HandleFunc("/style.css", serveviewasset)
2830	getters.HandleFunc("/sw.js", serveviewasset)
2831	getters.HandleFunc("/honkpage.js", serveviewasset)
2832	getters.HandleFunc("/misc.js", serveviewasset)
2833	getters.HandleFunc("/local.css", servedataasset)
2834	getters.HandleFunc("/local.js", servedataasset)
2835	getters.HandleFunc("/icon.png", servedataasset)
2836	getters.HandleFunc("/favicon.ico", servedataasset)
2837	getters.HandleFunc("/manifest.webmanifest", serveviewasset)
2838
2839	getters.HandleFunc("/about", servehtml)
2840	getters.HandleFunc("/login", servehtml)
2841	posters.HandleFunc("/dologin", login.LoginFunc)
2842	getters.HandleFunc("/logout", login.LogoutFunc)
2843	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2844
2845	loggedin := mux.NewRoute().Subrouter()
2846	loggedin.Use(login.Required)
2847	loggedin.HandleFunc("/first", homepage)
2848	loggedin.HandleFunc("/chatter", showchatter)
2849	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2850	loggedin.HandleFunc("/saved", homepage)
2851	loggedin.HandleFunc("/account", accountpage)
2852	loggedin.HandleFunc("/funzone", showfunzone)
2853	loggedin.HandleFunc("/chpass", dochpass)
2854	loggedin.HandleFunc("/atme", homepage)
2855	loggedin.HandleFunc("/longago", homepage)
2856	loggedin.HandleFunc("/hfcs", hfcspage)
2857	loggedin.HandleFunc("/xzone", xzone)
2858	loggedin.HandleFunc("/newhonk", newhonkpage)
2859	loggedin.HandleFunc("/edit", edithonkpage)
2860	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2861	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2862	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2863	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2864	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2865	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2866	loggedin.HandleFunc("/honkers", showhonkers)
2867	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2868	loggedin.HandleFunc("/h", showhonker)
2869	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2870	loggedin.HandleFunc("/c", showcombos)
2871	loggedin.HandleFunc("/t", showconvoy)
2872	loggedin.HandleFunc("/q", showsearch)
2873	loggedin.HandleFunc("/hydra", webhydra)
2874	loggedin.HandleFunc("/emus", showemus)
2875	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2876
2877	// mastoshit
2878	getters.HandleFunc("/oauth/authorize", oauthorize)
2879	getters.HandleFunc("/api/v1/instance", instance)
2880	posters.HandleFunc("/api/v1/apps", apiapps)
2881
2882	err = http.Serve(listener, mux)
2883	if err != nil {
2884		elog.Fatal(err)
2885	}
2886}