all repos — honk @ c8fa51ec3cb7addf83cbd703585e4500ab64076c

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		if uinfo != nil {
2344			j, err := GetJunkFast(uinfo.UserID, n)
2345			if err != nil {
2346				dlog.Println("avatating: getting junk:", err)
2347				a = avatateautogen(r)
2348			}
2349			pfpurl, _ := j.GetString("icon", "url")
2350			res, err := http.Get(pfpurl)
2351			if err != nil {
2352				dlog.Println("avatating: getting pfp url:", err)
2353				a = avatateautogen(r)
2354			} else {
2355				defer res.Body.Close()
2356
2357				pfpbytes, err := io.ReadAll(res.Body)
2358				if err != nil {
2359					dlog.Println("avatating: bruh shits clapped:", err)
2360					a = avatateautogen(r)
2361				}
2362				a = pfpbytes
2363			}
2364		} else {
2365			a = avatateautogen(r)
2366		}
2367	} else {
2368		a = avatateautogen(r)
2369	}
2370
2371	if !develMode {
2372		w.Header().Set("Cache-Control", "max-age="+somedays())
2373	}
2374
2375	w.Write(a)
2376}
2377
2378func serveviewasset(w http.ResponseWriter, r *http.Request) {
2379	serveasset(w, r, viewDir)
2380}
2381func servedataasset(w http.ResponseWriter, r *http.Request) {
2382	if r.URL.Path == "/favicon.ico" {
2383		r.URL.Path = "/icon.png"
2384	}
2385	serveasset(w, r, dataDir)
2386}
2387
2388func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2389	if !develMode {
2390		w.Header().Set("Cache-Control", "max-age=7776000")
2391	}
2392	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2393}
2394func servehelp(w http.ResponseWriter, r *http.Request) {
2395	name := mux.Vars(r)["name"]
2396	if !develMode {
2397		w.Header().Set("Cache-Control", "max-age=3600")
2398	}
2399	http.ServeFile(w, r, viewDir+"/docs/"+name)
2400}
2401func servehtml(w http.ResponseWriter, r *http.Request) {
2402	u := login.GetUserInfo(r)
2403	templinfo := getInfo(r)
2404	templinfo["AboutMsg"] = aboutMsg
2405	templinfo["LoginMsg"] = loginMsg
2406	templinfo["HonkVersion"] = softwareVersion
2407	if r.URL.Path == "/about" {
2408		templinfo["Sensors"] = getSensors()
2409	}
2410	if u == nil && !develMode {
2411		w.Header().Set("Cache-Control", "max-age=60")
2412	}
2413	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2414	if err != nil {
2415		elog.Print(err)
2416	}
2417}
2418func serveemu(w http.ResponseWriter, r *http.Request) {
2419	emu := mux.Vars(r)["emu"]
2420
2421	w.Header().Set("Cache-Control", "max-age="+somedays())
2422	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2423}
2424func servememe(w http.ResponseWriter, r *http.Request) {
2425	meme := mux.Vars(r)["meme"]
2426
2427	w.Header().Set("Cache-Control", "max-age="+somedays())
2428	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2429}
2430
2431func servefile(w http.ResponseWriter, r *http.Request) {
2432	xid := mux.Vars(r)["xid"]
2433	var media string
2434	var data []byte
2435	row := stmtGetFileData.QueryRow(xid)
2436	err := row.Scan(&media, &data)
2437	if err != nil {
2438		elog.Printf("error loading file: %s", err)
2439		http.NotFound(w, r)
2440		return
2441	}
2442	w.Header().Set("Content-Type", media)
2443	w.Header().Set("X-Content-Type-Options", "nosniff")
2444	w.Header().Set("Cache-Control", "max-age="+somedays())
2445	w.Write(data)
2446}
2447
2448func nomoroboto(w http.ResponseWriter, r *http.Request) {
2449	io.WriteString(w, "User-agent: *\n")
2450	io.WriteString(w, "Disallow: /a\n")
2451	io.WriteString(w, "Disallow: /d/\n")
2452	io.WriteString(w, "Disallow: /meme/\n")
2453	io.WriteString(w, "Disallow: /o\n")
2454	io.WriteString(w, "Disallow: /o/\n")
2455	io.WriteString(w, "Disallow: /help/\n")
2456	for _, u := range allusers() {
2457		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2458	}
2459}
2460
2461type Hydration struct {
2462	Tophid    int64
2463	Srvmsg    template.HTML
2464	Honks     string
2465	MeCount   int64
2466	ChatCount int64
2467}
2468
2469func webhydra(w http.ResponseWriter, r *http.Request) {
2470	u := login.GetUserInfo(r)
2471	userid := u.UserID
2472	templinfo := getInfo(r)
2473	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2474	page := r.FormValue("page")
2475
2476	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2477
2478	var hydra Hydration
2479
2480	var honks []*Honk
2481	switch page {
2482	case "atme":
2483		honks = gethonksforme(userid, wanted)
2484		honks = osmosis(honks, userid, false)
2485		menewnone(userid)
2486		hydra.Srvmsg = "at me!"
2487	case "longago":
2488		honks = gethonksfromlongago(userid, wanted)
2489		honks = osmosis(honks, userid, false)
2490		hydra.Srvmsg = "from long ago"
2491	case "home":
2492		honks = gethonksforuser(userid, wanted)
2493		honks = osmosis(honks, userid, true)
2494		hydra.Srvmsg = serverMsg
2495	case "first":
2496		honks = gethonksforuserfirstclass(userid, wanted)
2497		honks = osmosis(honks, userid, true)
2498		hydra.Srvmsg = "first class only"
2499	case "saved":
2500		honks = getsavedhonks(userid, wanted)
2501		templinfo["PageName"] = "saved"
2502		hydra.Srvmsg = "saved honks"
2503	case "combo":
2504		c := r.FormValue("c")
2505		honks = gethonksbycombo(userid, c, wanted)
2506		honks = osmosis(honks, userid, false)
2507		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2508	case "convoy":
2509		c := r.FormValue("c")
2510		honks = gethonksbyconvoy(userid, c, wanted)
2511		honks = osmosis(honks, userid, false)
2512		honks = threadsort(honks)
2513		reversehonks(honks)
2514		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2515	case "honker":
2516		xid := r.FormValue("xid")
2517		honks = gethonksbyxonker(userid, xid, wanted)
2518		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2519			<input type="hidden" name="CSRF" value="%s">
2520			<input type="hidden" name="url" value="%s">
2521			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2522			</form>`, login.GetCSRF("submithonker", r), xid)
2523		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2524		hydra.Srvmsg = msg
2525	case "user":
2526		uname := r.FormValue("uname")
2527		honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2528		hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2529	default:
2530		http.NotFound(w, r)
2531	}
2532
2533	if len(honks) > 0 {
2534		hydra.Tophid = honks[0].ID
2535	} else {
2536		hydra.Tophid = wanted
2537	}
2538	reverbolate(userid, honks)
2539
2540	user, _ := butwhatabout(u.Username)
2541
2542	var buf strings.Builder
2543	templinfo["Honks"] = honks
2544	templinfo["MapLink"] = getmaplink(u)
2545	templinfo["User"], _ = butwhatabout(u.Username)
2546	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2547	if err != nil {
2548		elog.Printf("frag error: %s", err)
2549		return
2550	}
2551	hydra.Honks = buf.String()
2552	hydra.MeCount = user.Options.MeCount
2553	hydra.ChatCount = user.Options.ChatCount
2554	w.Header().Set("Content-Type", "application/json")
2555	j, _ := jsonify(&hydra)
2556	io.WriteString(w, j)
2557}
2558
2559var honkline = make(chan bool)
2560
2561func honkhonkline() {
2562	for {
2563		select {
2564		case honkline <- true:
2565		default:
2566			return
2567		}
2568	}
2569}
2570
2571func apihandler(w http.ResponseWriter, r *http.Request) {
2572	u := login.GetUserInfo(r)
2573	userid := u.UserID
2574	action := r.FormValue("action")
2575	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2576	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2577	switch action {
2578	case "honk":
2579		h := submithonk(w, r)
2580		if h == nil {
2581			return
2582		}
2583
2584		fmt.Fprintf(w, "%s", h.XID)
2585	case "donk":
2586		d, err := submitdonk(w, r)
2587		if err != nil {
2588			http.Error(w, err.Error(), http.StatusBadRequest)
2589			return
2590		}
2591		if d == nil {
2592			http.Error(w, "missing donk", http.StatusBadRequest)
2593			return
2594		}
2595		w.Write([]byte(d.XID))
2596	case "zonkit":
2597		zonkit(w, r)
2598	case "gethonks":
2599		var honks []*Honk
2600		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2601		page := r.FormValue("page")
2602		var waitchan <-chan time.Time
2603	requery:
2604		switch page {
2605		case "atme":
2606			honks = gethonksforme(userid, wanted)
2607			honks = osmosis(honks, userid, false)
2608			menewnone(userid)
2609		case "longago":
2610			honks = gethonksfromlongago(userid, wanted)
2611			honks = osmosis(honks, userid, false)
2612		case "home":
2613			honks = gethonksforuser(userid, wanted)
2614			honks = osmosis(honks, userid, true)
2615		case "myhonks":
2616			honks = gethonksbyuser(u.Username, true, wanted)
2617			honks = osmosis(honks, userid, true)
2618		default:
2619			http.Error(w, "unknown page", http.StatusNotFound)
2620			return
2621		}
2622		if len(honks) == 0 && wait > 0 {
2623			if waitchan == nil {
2624				waitchan = time.After(time.Duration(wait) * time.Second)
2625			}
2626			select {
2627			case <-honkline:
2628				goto requery
2629			case <-waitchan:
2630			}
2631		}
2632		reverbolate(userid, honks)
2633		j := junk.New()
2634		j["honks"] = honks
2635		j.Write(w)
2636	case "sendactivity":
2637		user, _ := butwhatabout(u.Username)
2638		public := r.FormValue("public") == "1"
2639		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2640		msg := []byte(r.FormValue("msg"))
2641		for rcpt := range rcpts {
2642			go deliverate(userid, rcpt, msg)
2643		}
2644	case "gethonkers":
2645		j := junk.New()
2646		j["honkers"] = gethonkers(u.UserID)
2647		j.Write(w)
2648	case "savehonker":
2649		h := submithonker(w, r)
2650		if h == nil {
2651			return
2652		}
2653		fmt.Fprintf(w, "%d", h.ID)
2654	default:
2655		http.Error(w, "unknown action", http.StatusNotFound)
2656		return
2657	}
2658}
2659
2660func fiveoh(w http.ResponseWriter, r *http.Request) {
2661	fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2662	if err != nil {
2663		elog.Printf("error opening violations! %s", err)
2664		return
2665	}
2666	defer fd.Close()
2667	io.Copy(fd, r.Body)
2668	fd.WriteString("\n")
2669}
2670
2671var endoftheworld = make(chan bool)
2672var readyalready = make(chan bool)
2673var workinprogress = 0
2674
2675func enditall() {
2676	sig := make(chan os.Signal, 1)
2677	signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
2678	<-sig
2679	ilog.Printf("stopping...")
2680	for i := 0; i < workinprogress; i++ {
2681		endoftheworld <- true
2682	}
2683	ilog.Printf("waiting...")
2684	for i := 0; i < workinprogress; i++ {
2685		<-readyalready
2686	}
2687	ilog.Printf("apocalypse")
2688	os.Exit(0)
2689}
2690
2691var preservehooks []func()
2692
2693func bgmonitor() {
2694	for {
2695		when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2696		_, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2697		if err != nil {
2698			elog.Printf("error deleting old xonkers: %s", err)
2699		}
2700		zaggies.Flush()
2701		time.Sleep(50 * time.Minute)
2702	}
2703}
2704
2705func emuinit() {
2706	var emunames []string
2707	dir, err := os.Open(dataDir + "/emus")
2708	if err == nil {
2709		emunames, _ = dir.Readdirnames(0)
2710		dir.Close()
2711	}
2712	for _, e := range emunames {
2713		if len(e) <= 4 {
2714			continue
2715		}
2716		ext := e[len(e)-4:]
2717		emu := Emu{
2718			ID:   fmt.Sprintf("/emu/%s", e),
2719			Name: e[:len(e)-4],
2720			Type: "image/" + ext[1:],
2721		}
2722		allemus = append(allemus, emu)
2723	}
2724	sort.Slice(allemus, func(i, j int) bool {
2725		return allemus[i].Name < allemus[j].Name
2726	})
2727}
2728
2729func redirectPretty(w http.ResponseWriter, r *http.Request) {
2730	last := path.Base(r.URL.Path)
2731	name := mux.Vars(r)["name"]
2732	aturl := "/@" + name
2733
2734	if last == name {
2735		last = ""
2736	}
2737	http.Redirect(w, r, path.Join(aturl, last), http.StatusMovedPermanently)
2738}
2739
2740func serve() {
2741	db := opendatabase()
2742	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2743
2744	listener, err := openListener()
2745	if err != nil {
2746		elog.Fatal(err)
2747	}
2748	runBackendServer()
2749	go enditall()
2750	go redeliverator()
2751	go tracker()
2752	go bgmonitor()
2753	loadLingo()
2754	emuinit()
2755
2756	readviews = templates.Load(develMode,
2757		viewDir+"/views/honkpage.html",
2758		viewDir+"/views/honkfrags.html",
2759		viewDir+"/views/honkers.html",
2760		viewDir+"/views/chatter.html",
2761		viewDir+"/views/hfcs.html",
2762		viewDir+"/views/combos.html",
2763		viewDir+"/views/honkform.html",
2764		viewDir+"/views/honk.html",
2765		viewDir+"/views/account.html",
2766		viewDir+"/views/about.html",
2767		viewDir+"/views/funzone.html",
2768		viewDir+"/views/login.html",
2769		viewDir+"/views/xzone.html",
2770		viewDir+"/views/msg.html",
2771		viewDir+"/views/header.html",
2772		viewDir+"/views/onts.html",
2773		viewDir+"/views/emus.html",
2774		viewDir+"/views/honkpage.js",
2775	)
2776	if !develMode {
2777		assets := []string{
2778			viewDir + "/views/style.css",
2779			dataDir + "/views/local.css",
2780			viewDir + "/views/honkpage.js",
2781			dataDir + "/views/local.js",
2782			viewDir + "/views/manifest.webmanifest",
2783			viewDir + "/views/sw.js",
2784		}
2785		for _, s := range assets {
2786			savedassetparams[s] = getassetparam(s)
2787		}
2788		loadAvatarColors()
2789	}
2790
2791	for _, h := range preservehooks {
2792		h()
2793	}
2794
2795	mux := mux.NewRouter()
2796	mux.Use(login.Checker)
2797
2798	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2799
2800	posters := mux.Methods("POST").Subrouter()
2801	getters := mux.Methods("GET").Subrouter()
2802
2803	getters.HandleFunc("/", homepage)
2804	getters.HandleFunc("/home", homepage)
2805	getters.HandleFunc("/front", homepage)
2806	getters.HandleFunc("/events", homepage)
2807	getters.HandleFunc("/robots.txt", nomoroboto)
2808	getters.HandleFunc("/rss", showrss)
2809	getters.HandleFunc("/@{name:[\\pL[:digit:]]+}", showuser)
2810	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", redirectPretty)
2811	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
2812	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
2813	posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
2814	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
2815	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
2816	getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
2817	getters.HandleFunc("/a", avatate)
2818	getters.HandleFunc("/o", thelistingoftheontologies)
2819	getters.HandleFunc("/o/{name:.+}", showontology)
2820	getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
2821	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2822	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2823	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2824	getters.HandleFunc("/.well-known/nodeinfo", knowninformation)
2825	getters.HandleFunc("/nodeinfo/2.0", actualinformation)
2826
2827	getters.HandleFunc("/flag/{code:.+}", showflag)
2828
2829	getters.HandleFunc("/server", serveractor)
2830	posters.HandleFunc("/server/inbox", serverinbox)
2831	posters.HandleFunc("/inbox", serverinbox)
2832
2833	posters.HandleFunc("/csp-violation", fiveoh)
2834
2835	getters.HandleFunc("/style.css", serveviewasset)
2836	getters.HandleFunc("/sw.js", serveviewasset)
2837	getters.HandleFunc("/honkpage.js", serveviewasset)
2838	getters.HandleFunc("/misc.js", serveviewasset)
2839	getters.HandleFunc("/local.css", servedataasset)
2840	getters.HandleFunc("/local.js", servedataasset)
2841	getters.HandleFunc("/icon.png", servedataasset)
2842	getters.HandleFunc("/favicon.ico", servedataasset)
2843	getters.HandleFunc("/manifest.webmanifest", serveviewasset)
2844
2845	getters.HandleFunc("/about", servehtml)
2846	getters.HandleFunc("/login", servehtml)
2847	posters.HandleFunc("/dologin", login.LoginFunc)
2848	getters.HandleFunc("/logout", login.LogoutFunc)
2849	getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
2850
2851	loggedin := mux.NewRoute().Subrouter()
2852	loggedin.Use(login.Required)
2853	loggedin.HandleFunc("/first", homepage)
2854	loggedin.HandleFunc("/chatter", showchatter)
2855	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2856	loggedin.HandleFunc("/saved", homepage)
2857	loggedin.HandleFunc("/account", accountpage)
2858	loggedin.HandleFunc("/funzone", showfunzone)
2859	loggedin.HandleFunc("/chpass", dochpass)
2860	loggedin.HandleFunc("/atme", homepage)
2861	loggedin.HandleFunc("/longago", homepage)
2862	loggedin.HandleFunc("/hfcs", hfcspage)
2863	loggedin.HandleFunc("/xzone", xzone)
2864	loggedin.HandleFunc("/newhonk", newhonkpage)
2865	loggedin.HandleFunc("/edit", edithonkpage)
2866	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
2867	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2868	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2869	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2870	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2871	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2872	loggedin.HandleFunc("/honkers", showhonkers)
2873	loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
2874	loggedin.HandleFunc("/h", showhonker)
2875	loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
2876	loggedin.HandleFunc("/c", showcombos)
2877	loggedin.HandleFunc("/t", showconvoy)
2878	loggedin.HandleFunc("/q", showsearch)
2879	loggedin.HandleFunc("/hydra", webhydra)
2880	loggedin.HandleFunc("/emus", showemus)
2881	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
2882
2883	// mastoshit
2884	getters.HandleFunc("/oauth/authorize", oauthorize)
2885	getters.HandleFunc("/api/v1/instance", instance)
2886	posters.HandleFunc("/api/v1/apps", apiapps)
2887
2888	err = http.Serve(listener, mux)
2889	if err != nil {
2890		elog.Fatal(err)
2891	}
2892}