all repos — honk @ 37c5026e3454448a8e26470981979762d7e5b99e

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