all repos — honk @ 552c9898818450dd43dbfe145f6dcdb059e8b416

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	"log"
  25	notrand "math/rand"
  26	"net/http"
  27	"net/url"
  28	"os"
  29	"regexp"
  30	"sort"
  31	"strconv"
  32	"strings"
  33	"time"
  34
  35	"github.com/gorilla/mux"
  36	"humungus.tedunangst.com/r/webs/cache"
  37	"humungus.tedunangst.com/r/webs/httpsig"
  38	"humungus.tedunangst.com/r/webs/image"
  39	"humungus.tedunangst.com/r/webs/junk"
  40	"humungus.tedunangst.com/r/webs/login"
  41	"humungus.tedunangst.com/r/webs/rss"
  42	"humungus.tedunangst.com/r/webs/templates"
  43)
  44
  45var readviews *templates.Template
  46
  47var userSep = "u"
  48var honkSep = "h"
  49
  50func getuserstyle(u *login.UserInfo) template.CSS {
  51	if u == nil {
  52		return ""
  53	}
  54	user, _ := butwhatabout(u.Username)
  55	if user.Options.SkinnyCSS {
  56		return "main { max-width: 700px; }"
  57	}
  58	return ""
  59}
  60
  61func getInfo(r *http.Request) map[string]interface{} {
  62	u := login.GetUserInfo(r)
  63	templinfo := make(map[string]interface{})
  64	templinfo["StyleParam"] = getassetparam(viewDir + "/views/style.css")
  65	templinfo["LocalStyleParam"] = getassetparam(viewDir + "/views/local.css")
  66	templinfo["JSParam"] = getassetparam(viewDir + "/views/honkpage.js")
  67	templinfo["UserStyle"] = getuserstyle(u)
  68	templinfo["ServerName"] = serverName
  69	templinfo["IconName"] = iconName
  70	templinfo["UserInfo"] = u
  71	templinfo["UserSep"] = userSep
  72	if u != nil {
  73		var combos []string
  74		combocache.Get(u.UserID, &combos)
  75		templinfo["Combos"] = combos
  76	}
  77	return templinfo
  78}
  79
  80func homepage(w http.ResponseWriter, r *http.Request) {
  81	templinfo := getInfo(r)
  82	u := login.GetUserInfo(r)
  83	var honks []*Honk
  84	var userid int64 = -1
  85
  86	templinfo["ServerMessage"] = serverMsg
  87	if u == nil || r.URL.Path == "/front" {
  88		switch r.URL.Path {
  89		case "/events":
  90			honks = geteventhonks(userid)
  91			templinfo["ServerMessage"] = "some recent and upcoming events"
  92		default:
  93			templinfo["ShowRSS"] = true
  94			honks = getpublichonks()
  95		}
  96	} else {
  97		userid = u.UserID
  98		switch r.URL.Path {
  99		case "/atme":
 100			templinfo["ServerMessage"] = "at me!"
 101			templinfo["PageName"] = "atme"
 102			honks = gethonksforme(userid, 0)
 103			honks = osmosis(honks, userid, false)
 104		case "/events":
 105			templinfo["ServerMessage"] = "some recent and upcoming events"
 106			templinfo["PageName"] = "events"
 107			honks = geteventhonks(userid)
 108			honks = osmosis(honks, userid, true)
 109		case "/first":
 110			templinfo["PageName"] = "first"
 111			honks = gethonksforuserfirstclass(userid, 0)
 112			honks = osmosis(honks, userid, true)
 113		case "/saved":
 114			templinfo["ServerMessage"] = "saved honks"
 115			templinfo["PageName"] = "saved"
 116			honks = getsavedhonks(userid, 0)
 117		default:
 118			templinfo["PageName"] = "home"
 119			honks = gethonksforuser(userid, 0)
 120			honks = osmosis(honks, userid, true)
 121		}
 122		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 123	}
 124
 125	honkpage(w, u, honks, templinfo)
 126}
 127
 128func showfunzone(w http.ResponseWriter, r *http.Request) {
 129	var emunames, memenames []string
 130	dir, err := os.Open(dataDir + "/emus")
 131	if err == nil {
 132		emunames, _ = dir.Readdirnames(0)
 133		dir.Close()
 134	}
 135	for i, e := range emunames {
 136		if len(e) > 4 {
 137			emunames[i] = e[:len(e)-4]
 138		}
 139	}
 140	dir, err = os.Open(dataDir + "/memes")
 141	if err == nil {
 142		memenames, _ = dir.Readdirnames(0)
 143		dir.Close()
 144	}
 145	templinfo := getInfo(r)
 146	templinfo["Emus"] = emunames
 147	templinfo["Memes"] = memenames
 148	err = readviews.Execute(w, "funzone.html", templinfo)
 149	if err != nil {
 150		log.Print(err)
 151	}
 152}
 153
 154func showrss(w http.ResponseWriter, r *http.Request) {
 155	name := mux.Vars(r)["name"]
 156
 157	var honks []*Honk
 158	if name != "" {
 159		honks = gethonksbyuser(name, false, 0)
 160	} else {
 161		honks = getpublichonks()
 162	}
 163	if len(honks) > 20 {
 164		honks = honks[0:20]
 165	}
 166	reverbolate(-1, honks)
 167
 168	home := fmt.Sprintf("https://%s/", serverName)
 169	base := home
 170	if name != "" {
 171		home += "u/" + name
 172		name += " "
 173	}
 174	feed := rss.Feed{
 175		Title:       name + "honk",
 176		Link:        home,
 177		Description: name + "honk rss",
 178		Image: &rss.Image{
 179			URL:   base + "icon.png",
 180			Title: name + "honk rss",
 181			Link:  home,
 182		},
 183	}
 184	var modtime time.Time
 185	for _, honk := range honks {
 186		if !firstclass(honk) {
 187			continue
 188		}
 189		desc := string(honk.HTML)
 190		if t := honk.Time; t != nil {
 191			desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM EDT Mon Jan 02"))
 192			if t.Duration != 0 {
 193				desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
 194			}
 195		}
 196		if p := honk.Place; p != nil {
 197			desc += string(templates.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
 198				p.Url, p.Name, p.Latitude, p.Longitude))
 199		}
 200		for _, d := range honk.Donks {
 201			desc += string(templates.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
 202				d.URL, d.Name))
 203		}
 204
 205		feed.Items = append(feed.Items, &rss.Item{
 206			Title:       fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
 207			Description: rss.CData{Data: desc},
 208			Link:        honk.URL,
 209			PubDate:     honk.Date.Format(time.RFC1123),
 210			Guid:        &rss.Guid{IsPermaLink: true, Value: honk.URL},
 211		})
 212		if honk.Date.After(modtime) {
 213			modtime = honk.Date
 214		}
 215	}
 216	w.Header().Set("Cache-Control", "max-age=300")
 217	w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
 218
 219	err := feed.Write(w)
 220	if err != nil {
 221		log.Printf("error writing rss: %s", err)
 222	}
 223}
 224
 225func crappola(j junk.Junk) bool {
 226	t, _ := j.GetString("type")
 227	a, _ := j.GetString("actor")
 228	o, _ := j.GetString("object")
 229	if t == "Delete" && a == o {
 230		log.Printf("crappola from %s", a)
 231		return true
 232	}
 233	return false
 234}
 235
 236func ping(user *WhatAbout, who string) {
 237	var box *Box
 238	ok := boxofboxes.Get(who, &box)
 239	if !ok {
 240		log.Printf("no inbox to ping %s", who)
 241		return
 242	}
 243	j := junk.New()
 244	j["@context"] = itiswhatitis
 245	j["type"] = "Ping"
 246	j["id"] = user.URL + "/ping/" + xfiltrate()
 247	j["actor"] = user.URL
 248	j["to"] = who
 249	ki := ziggy(user.ID)
 250	if ki == nil {
 251		return
 252	}
 253	err := PostJunk(ki.keyname, ki.seckey, box.In, j)
 254	if err != nil {
 255		log.Printf("can't send ping: %s", err)
 256		return
 257	}
 258	log.Printf("sent ping to %s: %s", who, j["id"])
 259}
 260
 261func pong(user *WhatAbout, who string, obj string) {
 262	var box *Box
 263	ok := boxofboxes.Get(who, &box)
 264	if !ok {
 265		log.Printf("no inbox to pong %s", who)
 266		return
 267	}
 268	j := junk.New()
 269	j["@context"] = itiswhatitis
 270	j["type"] = "Pong"
 271	j["id"] = user.URL + "/pong/" + xfiltrate()
 272	j["actor"] = user.URL
 273	j["to"] = who
 274	j["object"] = obj
 275	ki := ziggy(user.ID)
 276	if ki == nil {
 277		return
 278	}
 279	err := PostJunk(ki.keyname, ki.seckey, box.In, j)
 280	if err != nil {
 281		log.Printf("can't send pong: %s", err)
 282		return
 283	}
 284}
 285
 286func inbox(w http.ResponseWriter, r *http.Request) {
 287	name := mux.Vars(r)["name"]
 288	user, err := butwhatabout(name)
 289	if err != nil {
 290		http.NotFound(w, r)
 291		return
 292	}
 293	if stealthmode(user.ID, r) {
 294		http.NotFound(w, r)
 295		return
 296	}
 297	var buf bytes.Buffer
 298	io.Copy(&buf, r.Body)
 299	payload := buf.Bytes()
 300	j, err := junk.FromBytes(payload)
 301	if err != nil {
 302		log.Printf("bad payload: %s", err)
 303		io.WriteString(os.Stdout, "bad payload\n")
 304		os.Stdout.Write(payload)
 305		io.WriteString(os.Stdout, "\n")
 306		return
 307	}
 308
 309	if crappola(j) {
 310		return
 311	}
 312	what, _ := j.GetString("type")
 313	if what == "Like" {
 314		return
 315	}
 316	who, _ := j.GetString("actor")
 317	if rejectactor(user.ID, who) {
 318		return
 319	}
 320
 321	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 322	if err != nil {
 323		log.Printf("inbox message failed signature for %s from %s", keyname, r.Header.Get("X-Forwarded-For"))
 324		if keyname != "" {
 325			log.Printf("bad signature from %s", keyname)
 326			io.WriteString(os.Stdout, "bad payload\n")
 327			os.Stdout.Write(payload)
 328			io.WriteString(os.Stdout, "\n")
 329		}
 330		http.Error(w, "what did you call me?", http.StatusTeapot)
 331		return
 332	}
 333	origin := keymatch(keyname, who)
 334	if origin == "" {
 335		log.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 336		return
 337	}
 338
 339	switch what {
 340	case "Ping":
 341		obj, _ := j.GetString("id")
 342		log.Printf("ping from %s: %s", who, obj)
 343		pong(user, who, obj)
 344	case "Pong":
 345		obj, _ := j.GetString("object")
 346		log.Printf("pong from %s: %s", who, obj)
 347	case "Follow":
 348		obj, _ := j.GetString("object")
 349		if obj != user.URL {
 350			log.Printf("can't follow %s", obj)
 351			return
 352		}
 353		log.Printf("updating honker follow: %s", who)
 354
 355		db := opendatabase()
 356		row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('dub', 'undub')", who, user.ID)
 357		var x string
 358		err = row.Scan(&x)
 359		if err != sql.ErrNoRows {
 360			log.Printf("duplicate follow request: %s", who)
 361			_, err = stmtUpdateFlavor.Exec("dub", user.ID, who, who, "undub")
 362			if err != nil {
 363				log.Printf("error updating honker: %s", err)
 364			}
 365		} else {
 366			stmtSaveDub.Exec(user.ID, who, who, "dub")
 367		}
 368		go rubadubdub(user, j)
 369	case "Accept":
 370		log.Printf("updating honker accept: %s", who)
 371		db := opendatabase()
 372		row := db.QueryRow("select name from honkers where userid = ? and xid = ? and flavor in ('presub')",
 373			user.ID, who)
 374		var name string
 375		err := row.Scan(&name)
 376		if err != nil {
 377			log.Printf("can't get honker name: %s", err)
 378			return
 379		}
 380		_, err = stmtUpdateFlavor.Exec("sub", user.ID, who, name, "presub")
 381		if err != nil {
 382			log.Printf("error updating honker: %s", err)
 383			return
 384		}
 385	case "Update":
 386		obj, ok := j.GetMap("object")
 387		if ok {
 388			what, _ := obj.GetString("type")
 389			switch what {
 390			case "Person":
 391				return
 392			case "Question":
 393				return
 394			case "Note":
 395				go xonksaver(user, j, origin)
 396				return
 397			}
 398		}
 399		log.Printf("unknown Update activity")
 400		fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 401		j.Write(fd)
 402		io.WriteString(fd, "\n")
 403		fd.Close()
 404
 405	case "Undo":
 406		obj, ok := j.GetMap("object")
 407		if !ok {
 408			log.Printf("unknown undo no object")
 409			return
 410		}
 411		what, _ := obj.GetString("type")
 412		switch what {
 413		case "Follow":
 414			log.Printf("updating honker undo: %s", who)
 415			_, err = stmtUpdateFlavor.Exec("undub", user.ID, who, who, "dub")
 416			if err != nil {
 417				log.Printf("error updating honker: %s", err)
 418				return
 419			}
 420		case "Announce":
 421			xid, _ := obj.GetString("object")
 422			log.Printf("undo announce: %s", xid)
 423		case "Like":
 424		default:
 425			log.Printf("unknown undo: %s", what)
 426		}
 427	default:
 428		go xonksaver(user, j, origin)
 429	}
 430}
 431
 432func serverinbox(w http.ResponseWriter, r *http.Request) {
 433	if stealthmode(serverUID, r) {
 434		http.NotFound(w, r)
 435		return
 436	}
 437	var buf bytes.Buffer
 438	io.Copy(&buf, r.Body)
 439	payload := buf.Bytes()
 440	j, err := junk.FromBytes(payload)
 441	if err != nil {
 442		log.Printf("bad payload: %s", err)
 443		io.WriteString(os.Stdout, "bad payload\n")
 444		os.Stdout.Write(payload)
 445		io.WriteString(os.Stdout, "\n")
 446		return
 447	}
 448	if crappola(j) {
 449		return
 450	}
 451	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 452	if err != nil {
 453		log.Printf("inbox message failed signature for %s from %s", keyname, r.Header.Get("X-Forwarded-For"))
 454		if keyname != "" {
 455			log.Printf("bad signature from %s", keyname)
 456			io.WriteString(os.Stdout, "bad payload\n")
 457			os.Stdout.Write(payload)
 458			io.WriteString(os.Stdout, "\n")
 459		}
 460		http.Error(w, "what did you call me?", http.StatusTeapot)
 461		return
 462	}
 463	user := getserveruser()
 464	who, _ := j.GetString("actor")
 465	origin := keymatch(keyname, who)
 466	if origin == "" {
 467		log.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 468		return
 469	}
 470	if rejectactor(user.ID, who) {
 471		return
 472	}
 473	re_ont := regexp.MustCompile("https://" + serverName + "/o/([[:alnum:]]+)")
 474	what, _ := j.GetString("type")
 475	log.Printf("server got a %s", what)
 476	switch what {
 477	case "Follow":
 478		obj, _ := j.GetString("object")
 479		if obj == user.URL {
 480			log.Printf("can't follow the server!")
 481			return
 482		}
 483		m := re_ont.FindStringSubmatch(obj)
 484		if len(m) != 2 {
 485			log.Printf("not sure how to handle this")
 486			return
 487		}
 488		ont := "#" + m[1]
 489		log.Printf("%s wants to follow %s", who, ont)
 490		db := opendatabase()
 491		row := db.QueryRow("select xid from honkers where name = ? and xid = ? and userid = ? and flavor in ('dub', 'undub')", ont, who, user.ID)
 492		var x string
 493		err = row.Scan(&x)
 494		if err != sql.ErrNoRows {
 495			log.Printf("duplicate follow request: %s", who)
 496			_, err = stmtUpdateFlavor.Exec("dub", user.ID, who, ont, "undub")
 497			if err != nil {
 498				log.Printf("error updating honker: %s", err)
 499			}
 500		} else {
 501			stmtSaveDub.Exec(user.ID, ont, who, "dub")
 502		}
 503		go rubadubdub(user, j)
 504	case "Undo":
 505		obj, ok := j.GetMap("object")
 506		if !ok {
 507			log.Printf("unknown undo no object")
 508			return
 509		}
 510		what, _ := obj.GetString("type")
 511		if what != "Follow" {
 512			log.Printf("unknown undo: %s", what)
 513		}
 514		targ, _ := obj.GetString("object")
 515		m := re_ont.FindStringSubmatch(targ)
 516		if len(m) != 2 {
 517			log.Printf("not sure how to handle this")
 518			return
 519		}
 520		ont := "#" + m[1]
 521		log.Printf("updating honker undo: %s %s", who, ont)
 522		_, err = stmtUpdateFlavor.Exec("undub", user.ID, who, ont, "dub")
 523		if err != nil {
 524			log.Printf("error updating honker: %s", err)
 525			return
 526		}
 527	}
 528}
 529
 530func serveractor(w http.ResponseWriter, r *http.Request) {
 531	if stealthmode(serverUID, r) {
 532		http.NotFound(w, r)
 533		return
 534	}
 535	user := getserveruser()
 536	j := junkuser(user)
 537	w.Write(j)
 538}
 539
 540func ximport(w http.ResponseWriter, r *http.Request) {
 541	u := login.GetUserInfo(r)
 542	xid := strings.TrimSpace(r.FormValue("xid"))
 543	xonk := getxonk(u.UserID, xid)
 544	if xonk == nil {
 545		p, _ := investigate(xid)
 546		if p != nil {
 547			xid = p.XID
 548		}
 549		j, err := GetJunk(xid)
 550		if err != nil {
 551			http.Error(w, "error getting external object", http.StatusInternalServerError)
 552			log.Printf("error getting external object: %s", err)
 553			return
 554		}
 555		log.Printf("importing %s", xid)
 556		user, _ := butwhatabout(u.Username)
 557
 558		info, _ := somethingabout(j)
 559		if info == nil {
 560			xonk = xonksaver(user, j, originate(xid))
 561		} else if info.What == SomeActor {
 562			outbox, _ := j.GetString("outbox")
 563			gimmexonks(user, outbox)
 564			http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
 565			return
 566		} else if info.What == SomeCollection {
 567			gimmexonks(user, xid)
 568			http.Redirect(w, r, "/xzone", http.StatusSeeOther)
 569			return
 570		}
 571	}
 572	convoy := ""
 573	if xonk != nil {
 574		convoy = xonk.Convoy
 575	}
 576	http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
 577}
 578
 579func xzone(w http.ResponseWriter, r *http.Request) {
 580	u := login.GetUserInfo(r)
 581	rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
 582	if err != nil {
 583		log.Printf("query err: %s", err)
 584		return
 585	}
 586	defer rows.Close()
 587	var honkers []Honker
 588	for rows.Next() {
 589		var xid string
 590		rows.Scan(&xid)
 591		honkers = append(honkers, Honker{XID: xid})
 592	}
 593	rows.Close()
 594	for i, _ := range honkers {
 595		_, honkers[i].Handle = handles(honkers[i].XID)
 596	}
 597	templinfo := getInfo(r)
 598	templinfo["XCSRF"] = login.GetCSRF("ximport", r)
 599	templinfo["Honkers"] = honkers
 600	err = readviews.Execute(w, "xzone.html", templinfo)
 601	if err != nil {
 602		log.Print(err)
 603	}
 604}
 605
 606var oldoutbox = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
 607	user, err := butwhatabout(name)
 608	if err != nil {
 609		return nil, false
 610	}
 611	honks := gethonksbyuser(name, false, 0)
 612	if len(honks) > 20 {
 613		honks = honks[0:20]
 614	}
 615
 616	var jonks []junk.Junk
 617	for _, h := range honks {
 618		j, _ := jonkjonk(user, h)
 619		jonks = append(jonks, j)
 620	}
 621
 622	j := junk.New()
 623	j["@context"] = itiswhatitis
 624	j["id"] = user.URL + "/outbox"
 625	j["attributedTo"] = user.URL
 626	j["type"] = "OrderedCollection"
 627	j["totalItems"] = len(jonks)
 628	j["orderedItems"] = jonks
 629
 630	return j.ToBytes(), true
 631}, Duration: 1 * time.Minute})
 632
 633func outbox(w http.ResponseWriter, r *http.Request) {
 634	name := mux.Vars(r)["name"]
 635	user, err := butwhatabout(name)
 636	if err != nil {
 637		http.NotFound(w, r)
 638		return
 639	}
 640	if stealthmode(user.ID, r) {
 641		http.NotFound(w, r)
 642		return
 643	}
 644	var j []byte
 645	ok := oldoutbox.Get(name, &j)
 646	if ok {
 647		w.Header().Set("Content-Type", theonetruename)
 648		w.Write(j)
 649	} else {
 650		http.NotFound(w, r)
 651	}
 652}
 653
 654func emptiness(w http.ResponseWriter, r *http.Request) {
 655	name := mux.Vars(r)["name"]
 656	user, err := butwhatabout(name)
 657	if err != nil {
 658		http.NotFound(w, r)
 659		return
 660	}
 661	if stealthmode(user.ID, r) {
 662		http.NotFound(w, r)
 663		return
 664	}
 665	colname := "/followers"
 666	if strings.HasSuffix(r.URL.Path, "/following") {
 667		colname = "/following"
 668	}
 669	j := junk.New()
 670	j["@context"] = itiswhatitis
 671	j["id"] = user.URL + colname
 672	j["attributedTo"] = user.URL
 673	j["type"] = "OrderedCollection"
 674	j["totalItems"] = 0
 675	j["orderedItems"] = []junk.Junk{}
 676
 677	w.Header().Set("Content-Type", theonetruename)
 678	j.Write(w)
 679}
 680
 681func showuser(w http.ResponseWriter, r *http.Request) {
 682	name := mux.Vars(r)["name"]
 683	user, err := butwhatabout(name)
 684	if err != nil {
 685		log.Printf("user not found %s: %s", name, err)
 686		http.NotFound(w, r)
 687		return
 688	}
 689	if stealthmode(user.ID, r) {
 690		http.NotFound(w, r)
 691		return
 692	}
 693	if friendorfoe(r.Header.Get("Accept")) {
 694		j, ok := asjonker(name)
 695		if ok {
 696			w.Header().Set("Content-Type", theonetruename)
 697			w.Write(j)
 698		} else {
 699			http.NotFound(w, r)
 700		}
 701		return
 702	}
 703	u := login.GetUserInfo(r)
 704	honks := gethonksbyuser(name, u != nil && u.Username == name, 0)
 705	templinfo := getInfo(r)
 706	templinfo["Name"] = user.Name
 707	whatabout := user.About
 708	whatabout = markitzero(user.About)
 709	templinfo["WhatAbout"] = template.HTML(whatabout)
 710	templinfo["ServerMessage"] = ""
 711	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 712	honkpage(w, u, honks, templinfo)
 713}
 714
 715func showhonker(w http.ResponseWriter, r *http.Request) {
 716	u := login.GetUserInfo(r)
 717	name := mux.Vars(r)["name"]
 718	var honks []*Honk
 719	if name == "" {
 720		name = r.FormValue("xid")
 721		honks = gethonksbyxonker(u.UserID, name, 0)
 722	} else {
 723		honks = gethonksbyhonker(u.UserID, name, 0)
 724	}
 725	msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, name, name)
 726	templinfo := getInfo(r)
 727	templinfo["PageName"] = "honker"
 728	templinfo["PageArg"] = name
 729	templinfo["ServerMessage"] = msg
 730	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 731	honkpage(w, u, honks, templinfo)
 732}
 733
 734func showcombo(w http.ResponseWriter, r *http.Request) {
 735	name := mux.Vars(r)["name"]
 736	u := login.GetUserInfo(r)
 737	honks := gethonksbycombo(u.UserID, name, 0)
 738	honks = osmosis(honks, u.UserID, true)
 739	templinfo := getInfo(r)
 740	templinfo["PageName"] = "combo"
 741	templinfo["PageArg"] = name
 742	templinfo["ServerMessage"] = "honks by combo: " + name
 743	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 744	honkpage(w, u, honks, templinfo)
 745}
 746func showconvoy(w http.ResponseWriter, r *http.Request) {
 747	c := r.FormValue("c")
 748	u := login.GetUserInfo(r)
 749	honks := gethonksbyconvoy(u.UserID, c, 0)
 750	templinfo := getInfo(r)
 751	if len(honks) > 0 {
 752		templinfo["TopHID"] = honks[0].ID
 753	}
 754	honks = osmosis(honks, u.UserID, false)
 755	reversehonks(honks)
 756	templinfo["PageName"] = "convoy"
 757	templinfo["PageArg"] = c
 758	templinfo["ServerMessage"] = "honks in convoy: " + c
 759	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 760	honkpage(w, u, honks, templinfo)
 761}
 762func showsearch(w http.ResponseWriter, r *http.Request) {
 763	q := r.FormValue("q")
 764	u := login.GetUserInfo(r)
 765	honks := gethonksbysearch(u.UserID, q, 0)
 766	templinfo := getInfo(r)
 767	templinfo["PageName"] = "search"
 768	templinfo["PageArg"] = q
 769	templinfo["ServerMessage"] = "honks for search: " + q
 770	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 771	honkpage(w, u, honks, templinfo)
 772}
 773func showontology(w http.ResponseWriter, r *http.Request) {
 774	name := mux.Vars(r)["name"]
 775	u := login.GetUserInfo(r)
 776	var userid int64 = -1
 777	if u != nil {
 778		userid = u.UserID
 779	}
 780	honks := gethonksbyontology(userid, "#"+name, 0)
 781	if friendorfoe(r.Header.Get("Accept")) {
 782		if len(honks) > 40 {
 783			honks = honks[0:40]
 784		}
 785
 786		var xids []string
 787		for _, h := range honks {
 788			xids = append(xids, h.XID)
 789		}
 790
 791		user := getserveruser()
 792
 793		j := junk.New()
 794		j["@context"] = itiswhatitis
 795		j["id"] = fmt.Sprintf("https://%s/o/%s", serverName, name)
 796		j["name"] = "#" + name
 797		j["attributedTo"] = user.URL
 798		j["type"] = "OrderedCollection"
 799		j["totalItems"] = len(xids)
 800		j["orderedItems"] = xids
 801
 802		j.Write(w)
 803		return
 804	}
 805
 806	templinfo := getInfo(r)
 807	templinfo["ServerMessage"] = "honks by ontology: " + name
 808	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 809	honkpage(w, u, honks, templinfo)
 810}
 811
 812type Ont struct {
 813	Name  string
 814	Count int64
 815}
 816
 817func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 818	u := login.GetUserInfo(r)
 819	var userid int64 = -1
 820	if u != nil {
 821		userid = u.UserID
 822	}
 823	rows, err := stmtAllOnts.Query(userid)
 824	if err != nil {
 825		log.Printf("selection error: %s", err)
 826		return
 827	}
 828	defer rows.Close()
 829	var onts []Ont
 830	for rows.Next() {
 831		var o Ont
 832		err := rows.Scan(&o.Name, &o.Count)
 833		if err != nil {
 834			log.Printf("error scanning ont: %s", err)
 835			continue
 836		}
 837		if len(o.Name) > 24 {
 838			continue
 839		}
 840		o.Name = o.Name[1:]
 841		onts = append(onts, o)
 842	}
 843	sort.Slice(onts, func(i, j int) bool {
 844		return onts[i].Name < onts[j].Name
 845	})
 846	if u == nil {
 847		w.Header().Set("Cache-Control", "max-age=300")
 848	}
 849	templinfo := getInfo(r)
 850	templinfo["Onts"] = onts
 851	err = readviews.Execute(w, "onts.html", templinfo)
 852	if err != nil {
 853		log.Print(err)
 854	}
 855}
 856
 857type Track struct {
 858	xid string
 859	who string
 860}
 861
 862func savetracks(tracks map[string][]string) {
 863	db := opendatabase()
 864	tx, err := db.Begin()
 865	if err != nil {
 866		log.Printf("savetracks begin error: %s", err)
 867		return
 868	}
 869	defer func() {
 870		err := tx.Commit()
 871		if err != nil {
 872			log.Printf("savetracks commit error: %s", err)
 873		}
 874
 875	}()
 876	stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
 877	if err != nil {
 878		log.Printf("savetracks error: %s", err)
 879		return
 880	}
 881	stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
 882	if err != nil {
 883		log.Printf("savetracks error: %s", err)
 884		return
 885	}
 886	stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
 887	if err != nil {
 888		log.Printf("savetracks error: %s", err)
 889		return
 890	}
 891	count := 0
 892	for xid, f := range tracks {
 893		count += len(f)
 894		var prev string
 895		row := stmtGetTracks.QueryRow(xid)
 896		err := row.Scan(&prev)
 897		if err == sql.ErrNoRows {
 898			f = oneofakind(f)
 899			stmtNewTracks.Exec(xid, strings.Join(f, " "))
 900		} else if err == nil {
 901			all := append(strings.Split(prev, " "), f...)
 902			all = oneofakind(all)
 903			stmtUpdateTracks.Exec(strings.Join(all, " "))
 904		} else {
 905			log.Printf("savetracks error: %s", err)
 906		}
 907	}
 908	log.Printf("saved %d new fetches", count)
 909}
 910
 911var trackchan = make(chan Track)
 912
 913func tracker() {
 914	timeout := 4 * time.Minute
 915	sleeper := time.NewTimer(timeout)
 916	tracks := make(map[string][]string)
 917	for {
 918		select {
 919		case track := <-trackchan:
 920			tracks[track.xid] = append(tracks[track.xid], track.who)
 921		case <-sleeper.C:
 922			if len(tracks) > 0 {
 923				go savetracks(tracks)
 924				tracks = make(map[string][]string)
 925			}
 926			sleeper.Reset(timeout)
 927		}
 928	}
 929}
 930
 931var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
 932
 933func trackback(xid string, r *http.Request) {
 934	agent := r.UserAgent()
 935	who := originate(agent)
 936	sig := r.Header.Get("Signature")
 937	if sig != "" {
 938		m := re_keyholder.FindStringSubmatch(sig)
 939		if len(m) == 2 {
 940			who = m[1]
 941		}
 942	}
 943	if who != "" {
 944		trackchan <- Track{xid: xid, who: who}
 945	}
 946}
 947
 948func showonehonk(w http.ResponseWriter, r *http.Request) {
 949	name := mux.Vars(r)["name"]
 950	user, err := butwhatabout(name)
 951	if err != nil {
 952		http.NotFound(w, r)
 953		return
 954	}
 955	if stealthmode(user.ID, r) {
 956		http.NotFound(w, r)
 957		return
 958	}
 959	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
 960
 961	if friendorfoe(r.Header.Get("Accept")) {
 962		j, ok := gimmejonk(xid)
 963		if ok {
 964			trackback(xid, r)
 965			w.Header().Set("Content-Type", theonetruename)
 966			w.Write(j)
 967		} else {
 968			http.NotFound(w, r)
 969		}
 970		return
 971	}
 972	honk := getxonk(user.ID, xid)
 973	if honk == nil {
 974		http.NotFound(w, r)
 975		return
 976	}
 977	u := login.GetUserInfo(r)
 978	if u != nil && u.UserID != user.ID {
 979		u = nil
 980	}
 981	if !honk.Public {
 982		if u == nil {
 983			http.NotFound(w, r)
 984			return
 985
 986		}
 987		templinfo := getInfo(r)
 988		templinfo["ServerMessage"] = "one honk maybe more"
 989		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 990		honkpage(w, u, []*Honk{honk}, templinfo)
 991		return
 992	}
 993	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
 994	reversehonks(rawhonks)
 995	var honks []*Honk
 996	for _, h := range rawhonks {
 997		if h.XID == xid && len(honks) != 0 {
 998			h.Style += " glow"
 999		}
1000		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1001			honks = append(honks, h)
1002		}
1003	}
1004
1005	templinfo := getInfo(r)
1006	templinfo["ServerMessage"] = "one honk maybe more"
1007	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1008	honkpage(w, u, honks, templinfo)
1009}
1010
1011func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1012	var userid int64 = -1
1013	if u != nil {
1014		userid = u.UserID
1015	}
1016	reverbolate(userid, honks)
1017	templinfo["Honks"] = honks
1018	if templinfo["TopHID"] == nil {
1019		if len(honks) > 0 {
1020			templinfo["TopHID"] = honks[0].ID
1021		} else {
1022			templinfo["TopHID"] = 0
1023		}
1024	}
1025	if u == nil {
1026		w.Header().Set("Cache-Control", "max-age=60")
1027	}
1028	err := readviews.Execute(w, "honkpage.html", templinfo)
1029	if err != nil {
1030		log.Print(err)
1031	}
1032}
1033
1034func saveuser(w http.ResponseWriter, r *http.Request) {
1035	whatabout := r.FormValue("whatabout")
1036	u := login.GetUserInfo(r)
1037	db := opendatabase()
1038	var options UserOptions
1039	if r.FormValue("skinny") == "skinny" {
1040		options.SkinnyCSS = true
1041	}
1042	j, err := jsonify(options)
1043	if err == nil {
1044		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1045	}
1046	if err != nil {
1047		log.Printf("error bouting what: %s", err)
1048	}
1049	somenamedusers.Clear(u.Username)
1050	somenumberedusers.Clear(u.UserID)
1051
1052	http.Redirect(w, r, "/account", http.StatusSeeOther)
1053}
1054
1055func submitbonk(w http.ResponseWriter, r *http.Request) {
1056	xid := r.FormValue("xid")
1057	userinfo := login.GetUserInfo(r)
1058	user, _ := butwhatabout(userinfo.Username)
1059
1060	log.Printf("bonking %s", xid)
1061
1062	xonk := getxonk(userinfo.UserID, xid)
1063	if xonk == nil {
1064		return
1065	}
1066	if !xonk.Public {
1067		return
1068	}
1069	if xonk.IsBonked() {
1070		return
1071	}
1072	donksforhonks([]*Honk{xonk})
1073
1074	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1075	if err != nil {
1076		log.Printf("error acking bonk: %s", err)
1077	}
1078
1079	oonker := xonk.Oonker
1080	if oonker == "" {
1081		oonker = xonk.Honker
1082	}
1083	dt := time.Now().UTC()
1084	bonk := &Honk{
1085		UserID:   userinfo.UserID,
1086		Username: userinfo.Username,
1087		What:     "bonk",
1088		Honker:   user.URL,
1089		Oonker:   oonker,
1090		XID:      xonk.XID,
1091		RID:      xonk.RID,
1092		Noise:    xonk.Noise,
1093		Precis:   xonk.Precis,
1094		URL:      xonk.URL,
1095		Date:     dt,
1096		Donks:    xonk.Donks,
1097		Whofore:  2,
1098		Convoy:   xonk.Convoy,
1099		Audience: []string{thewholeworld, oonker},
1100		Public:   true,
1101		Format:   "html",
1102		Place:    xonk.Place,
1103		Onts:     xonk.Onts,
1104		Time:     xonk.Time,
1105	}
1106
1107	err = savehonk(bonk)
1108	if err != nil {
1109		log.Printf("uh oh")
1110		return
1111	}
1112
1113	go honkworldwide(user, bonk)
1114
1115	if r.FormValue("js") != "1" {
1116		templinfo := getInfo(r)
1117		templinfo["ServerMessage"] = "Bonked!"
1118		err = readviews.Execute(w, "msg.html", templinfo)
1119		if err != nil {
1120			log.Print(err)
1121		}
1122	}
1123}
1124
1125func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
1126	zonk := &Honk{
1127		What:     what,
1128		XID:      xonk.XID,
1129		Date:     time.Now().UTC(),
1130		Audience: oneofakind(xonk.Audience),
1131	}
1132	zonk.Public = loudandproud(zonk.Audience)
1133
1134	log.Printf("announcing %sed honk: %s", what, xonk.XID)
1135	go honkworldwide(user, zonk)
1136}
1137
1138func zonkit(w http.ResponseWriter, r *http.Request) {
1139	wherefore := r.FormValue("wherefore")
1140	what := r.FormValue("what")
1141	userinfo := login.GetUserInfo(r)
1142	user, _ := butwhatabout(userinfo.Username)
1143
1144	if wherefore == "save" {
1145		xonk := getxonk(userinfo.UserID, what)
1146		if xonk != nil {
1147			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1148			if err != nil {
1149				log.Printf("error saving: %s", err)
1150			}
1151		}
1152		return
1153	}
1154
1155	if wherefore == "unsave" {
1156		xonk := getxonk(userinfo.UserID, what)
1157		if xonk != nil {
1158			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1159			if err != nil {
1160				log.Printf("error unsaving: %s", err)
1161			}
1162		}
1163		return
1164	}
1165
1166	// my hammer is too big, oh well
1167	defer oldjonks.Flush()
1168
1169	if wherefore == "ack" {
1170		xonk := getxonk(userinfo.UserID, what)
1171		if xonk != nil && !xonk.IsAcked() {
1172			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1173			if err != nil {
1174				log.Printf("error acking: %s", err)
1175			}
1176			sendzonkofsorts(xonk, user, "ack")
1177		}
1178		return
1179	}
1180
1181	if wherefore == "deack" {
1182		xonk := getxonk(userinfo.UserID, what)
1183		if xonk != nil && xonk.IsAcked() {
1184			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1185			if err != nil {
1186				log.Printf("error deacking: %s", err)
1187			}
1188			sendzonkofsorts(xonk, user, "deack")
1189		}
1190		return
1191	}
1192
1193	if wherefore == "unbonk" {
1194		xonk := getbonk(userinfo.UserID, what)
1195		if xonk != nil {
1196			deletehonk(xonk.ID)
1197			xonk = getxonk(userinfo.UserID, what)
1198			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1199			if err != nil {
1200				log.Printf("error unbonking: %s", err)
1201			}
1202			sendzonkofsorts(xonk, user, "unbonk")
1203		}
1204		return
1205	}
1206
1207	if wherefore == "untag" {
1208		xonk := getxonk(userinfo.UserID, what)
1209		if xonk != nil {
1210			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1211			if err != nil {
1212				log.Printf("error untagging: %s", err)
1213			}
1214		}
1215		var badparents map[string]bool
1216		untagged.GetAndLock(userinfo.UserID, &badparents)
1217		badparents[what] = true
1218		untagged.Unlock()
1219		return
1220	}
1221
1222	log.Printf("zonking %s %s", wherefore, what)
1223	if wherefore == "zonk" {
1224		xonk := getxonk(userinfo.UserID, what)
1225		if xonk != nil {
1226			deletehonk(xonk.ID)
1227			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1228				sendzonkofsorts(xonk, user, "zonk")
1229			}
1230		}
1231	}
1232	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1233	if err != nil {
1234		log.Printf("error saving zonker: %s", err)
1235		return
1236	}
1237}
1238
1239func edithonkpage(w http.ResponseWriter, r *http.Request) {
1240	u := login.GetUserInfo(r)
1241	user, _ := butwhatabout(u.Username)
1242	xid := r.FormValue("xid")
1243	honk := getxonk(u.UserID, xid)
1244	if !canedithonk(user, honk) {
1245		http.Error(w, "no editing that please", http.StatusInternalServerError)
1246		return
1247	}
1248
1249	noise := honk.Noise
1250
1251	honks := []*Honk{honk}
1252	donksforhonks(honks)
1253	reverbolate(u.UserID, honks)
1254	templinfo := getInfo(r)
1255	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1256	templinfo["Honks"] = honks
1257	templinfo["Noise"] = noise
1258	templinfo["SavedPlace"] = honk.Place
1259	templinfo["ServerMessage"] = "honk edit"
1260	templinfo["IsPreview"] = true
1261	templinfo["UpdateXID"] = honk.XID
1262	if len(honk.Donks) > 0 {
1263		templinfo["SavedFile"] = honk.Donks[0].XID
1264	}
1265	err := readviews.Execute(w, "honkpage.html", templinfo)
1266	if err != nil {
1267		log.Print(err)
1268	}
1269}
1270
1271func newhonkpage(w http.ResponseWriter, r *http.Request) {
1272	u := login.GetUserInfo(r)
1273	rid := r.FormValue("rid")
1274	noise := ""
1275
1276	xonk := getxonk(u.UserID, rid)
1277	if xonk != nil {
1278		_, replto := handles(xonk.Honker)
1279		if replto != "" {
1280			noise = "@" + replto + " "
1281		}
1282	}
1283
1284	templinfo := getInfo(r)
1285	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1286	templinfo["InReplyTo"] = rid
1287	templinfo["Noise"] = noise
1288	templinfo["ServerMessage"] = "compose honk"
1289	templinfo["IsPreview"] = true
1290	err := readviews.Execute(w, "honkpage.html", templinfo)
1291	if err != nil {
1292		log.Print(err)
1293	}
1294}
1295
1296func canedithonk(user *WhatAbout, honk *Honk) bool {
1297	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1298		return false
1299	}
1300	return true
1301}
1302
1303// what a hot mess this function is
1304func submithonk(w http.ResponseWriter, r *http.Request) {
1305	rid := r.FormValue("rid")
1306	noise := r.FormValue("noise")
1307
1308	userinfo := login.GetUserInfo(r)
1309	user, _ := butwhatabout(userinfo.Username)
1310
1311	dt := time.Now().UTC()
1312	updatexid := r.FormValue("updatexid")
1313	var honk *Honk
1314	if updatexid != "" {
1315		honk = getxonk(userinfo.UserID, updatexid)
1316		if !canedithonk(user, honk) {
1317			http.Error(w, "no editing that please", http.StatusInternalServerError)
1318			return
1319		}
1320		honk.Date = dt
1321		honk.What = "update"
1322		honk.Format = "markdown"
1323	} else {
1324		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1325		what := "honk"
1326		if rid != "" {
1327			what = "tonk"
1328		}
1329		honk = &Honk{
1330			UserID:   userinfo.UserID,
1331			Username: userinfo.Username,
1332			What:     what,
1333			Honker:   user.URL,
1334			XID:      xid,
1335			Date:     dt,
1336			Format:   "markdown",
1337		}
1338	}
1339
1340	noise = hooterize(noise)
1341	honk.Noise = noise
1342	translate(honk, false)
1343
1344	var convoy string
1345	if rid != "" {
1346		xonk := getxonk(userinfo.UserID, rid)
1347		if xonk != nil {
1348			if xonk.Public {
1349				honk.Audience = append(honk.Audience, xonk.Audience...)
1350			}
1351			convoy = xonk.Convoy
1352		} else {
1353			xonkaud, c := whosthere(rid)
1354			honk.Audience = append(honk.Audience, xonkaud...)
1355			convoy = c
1356		}
1357		for i, a := range honk.Audience {
1358			if a == thewholeworld {
1359				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1360				break
1361			}
1362		}
1363		honk.RID = rid
1364	} else {
1365		honk.Audience = []string{thewholeworld}
1366	}
1367	if honk.Noise != "" && honk.Noise[0] == '@' {
1368		honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
1369	} else {
1370		honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
1371	}
1372
1373	if convoy == "" {
1374		convoy = "data:,electrichonkytonk-" + xfiltrate()
1375	}
1376	butnottooloud(honk.Audience)
1377	honk.Audience = oneofakind(honk.Audience)
1378	if len(honk.Audience) == 0 {
1379		log.Printf("honk to nowhere")
1380		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1381		return
1382	}
1383	honk.Public = loudandproud(honk.Audience)
1384	honk.Convoy = convoy
1385
1386	donkxid := r.FormValue("donkxid")
1387	if donkxid == "" {
1388		file, filehdr, err := r.FormFile("donk")
1389		if err == nil {
1390			var buf bytes.Buffer
1391			io.Copy(&buf, file)
1392			file.Close()
1393			data := buf.Bytes()
1394			xid := xfiltrate()
1395			var media, name string
1396			img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
1397			if err == nil {
1398				data = img.Data
1399				format := img.Format
1400				media = "image/" + format
1401				if format == "jpeg" {
1402					format = "jpg"
1403				}
1404				name = xid + "." + format
1405				xid = name
1406			} else {
1407				ct := http.DetectContentType(data)
1408				switch ct {
1409				case "application/pdf":
1410					maxsize := 1000000
1411					if len(data) > maxsize {
1412						log.Printf("bad image: %s too much pdf: %d", err, len(data))
1413						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1414						return
1415					}
1416					media = ct
1417					xid += ".pdf"
1418					name = filehdr.Filename
1419					if name == "" {
1420						name = xid
1421					}
1422				default:
1423					maxsize := 100000
1424					if len(data) > maxsize {
1425						log.Printf("bad image: %s too much text: %d", err, len(data))
1426						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1427						return
1428					}
1429					for i := 0; i < len(data); i++ {
1430						if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1431							log.Printf("bad image: %s not text: %d", err, data[i])
1432							http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1433							return
1434						}
1435					}
1436					media = "text/plain"
1437					xid += ".txt"
1438					name = filehdr.Filename
1439					if name == "" {
1440						name = xid
1441					}
1442				}
1443			}
1444			desc := strings.TrimSpace(r.FormValue("donkdesc"))
1445			if desc == "" {
1446				desc = name
1447			}
1448			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1449			fileid, err := savefile(xid, name, desc, url, media, true, data)
1450			if err != nil {
1451				log.Printf("unable to save image: %s", err)
1452				return
1453			}
1454			d := &Donk{
1455				FileID: fileid,
1456				XID:    xid,
1457				Desc:   desc,
1458				URL:    url,
1459				Local:  true,
1460			}
1461			honk.Donks = append(honk.Donks, d)
1462			donkxid = xid
1463		}
1464	} else {
1465		xid := donkxid
1466		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1467		donk := finddonk(url)
1468		if donk != nil {
1469			honk.Donks = append(honk.Donks, donk)
1470		} else {
1471			log.Printf("can't find file: %s", xid)
1472		}
1473	}
1474	herd := herdofemus(noise)
1475	for _, e := range herd {
1476		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1477		if donk != nil {
1478			donk.Name = e.Name
1479			honk.Donks = append(honk.Donks, donk)
1480		}
1481	}
1482	memetize(honk)
1483	imaginate(honk)
1484
1485	placename := strings.TrimSpace(r.FormValue("placename"))
1486	placelat := strings.TrimSpace(r.FormValue("placelat"))
1487	placelong := strings.TrimSpace(r.FormValue("placelong"))
1488	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1489	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1490		p := new(Place)
1491		p.Name = placename
1492		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1493		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1494		p.Url = placeurl
1495		honk.Place = p
1496	}
1497	timestart := strings.TrimSpace(r.FormValue("timestart"))
1498	if timestart != "" {
1499		t := new(Time)
1500		now := time.Now().Local()
1501		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1502			start, err := time.ParseInLocation(layout, timestart, now.Location())
1503			if err == nil {
1504				if start.Year() == 0 {
1505					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1506				}
1507				t.StartTime = start
1508				break
1509			}
1510		}
1511		timeend := r.FormValue("timeend")
1512		dur := parseDuration(timeend)
1513		if dur != 0 {
1514			t.Duration = Duration(dur)
1515		}
1516		if !t.StartTime.IsZero() {
1517			honk.What = "event"
1518			honk.Time = t
1519		}
1520	}
1521
1522	if honk.Public {
1523		honk.Whofore = 2
1524	} else {
1525		honk.Whofore = 3
1526	}
1527
1528	// back to markdown
1529	honk.Noise = noise
1530
1531	if r.FormValue("preview") == "preview" {
1532		honks := []*Honk{honk}
1533		reverbolate(userinfo.UserID, honks)
1534		templinfo := getInfo(r)
1535		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1536		templinfo["Honks"] = honks
1537		templinfo["InReplyTo"] = r.FormValue("rid")
1538		templinfo["Noise"] = r.FormValue("noise")
1539		templinfo["SavedFile"] = donkxid
1540		templinfo["IsPreview"] = true
1541		templinfo["ServerMessage"] = "honk preview"
1542		err := readviews.Execute(w, "honkpage.html", templinfo)
1543		if err != nil {
1544			log.Print(err)
1545		}
1546		return
1547	}
1548
1549	if updatexid != "" {
1550		updatehonk(honk)
1551		oldjonks.Clear(honk.XID)
1552	} else {
1553		err := savehonk(honk)
1554		if err != nil {
1555			log.Printf("uh oh")
1556			return
1557		}
1558	}
1559
1560	// reload for consistency
1561	honk.Donks = nil
1562	donksforhonks([]*Honk{honk})
1563
1564	go honkworldwide(user, honk)
1565
1566	http.Redirect(w, r, honk.XID[len(serverName)+8:], http.StatusSeeOther)
1567}
1568
1569func showhonkers(w http.ResponseWriter, r *http.Request) {
1570	userinfo := login.GetUserInfo(r)
1571	templinfo := getInfo(r)
1572	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1573	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1574	err := readviews.Execute(w, "honkers.html", templinfo)
1575	if err != nil {
1576		log.Print(err)
1577	}
1578}
1579
1580var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1581	honkers := gethonkers(userid)
1582	var combos []string
1583	for _, h := range honkers {
1584		combos = append(combos, h.Combos...)
1585	}
1586	for i, c := range combos {
1587		if c == "-" {
1588			combos[i] = ""
1589		}
1590	}
1591	combos = oneofakind(combos)
1592	sort.Strings(combos)
1593	return combos, true
1594}, Invalidator: &honkerinvalidator})
1595
1596func showcombos(w http.ResponseWriter, r *http.Request) {
1597	userinfo := login.GetUserInfo(r)
1598	var combos []string
1599	combocache.Get(userinfo.UserID, &combos)
1600	templinfo := getInfo(r)
1601	err := readviews.Execute(w, "combos.html", templinfo)
1602	if err != nil {
1603		log.Print(err)
1604	}
1605}
1606
1607func submithonker(w http.ResponseWriter, r *http.Request) {
1608	u := login.GetUserInfo(r)
1609	name := strings.TrimSpace(r.FormValue("name"))
1610	url := strings.TrimSpace(r.FormValue("url"))
1611	peep := r.FormValue("peep")
1612	combos := strings.TrimSpace(r.FormValue("combos"))
1613	combos = " " + combos + " "
1614	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1615
1616	defer honkerinvalidator.Clear(u.UserID)
1617
1618	if honkerid > 0 {
1619		goodbye := r.FormValue("goodbye")
1620		if goodbye == "F" {
1621			db := opendatabase()
1622			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1623				honkerid, u.UserID)
1624			err := row.Scan(&url)
1625			if err != nil {
1626				log.Printf("can't get honker xid: %s", err)
1627				return
1628			}
1629			log.Printf("unsubscribing from %s", url)
1630			user, _ := butwhatabout(u.Username)
1631			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, name, "sub")
1632			if err != nil {
1633				log.Printf("error updating honker: %s", err)
1634				return
1635			}
1636			go itakeitallback(user, url)
1637
1638			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1639			return
1640		}
1641		if goodbye == "X" {
1642			var owner string
1643			db := opendatabase()
1644			row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1645				honkerid, u.UserID)
1646			err := row.Scan(&url, &owner)
1647			if err != nil {
1648				log.Printf("can't get honker xid: %s", err)
1649				return
1650			}
1651			log.Printf("resubscribing to %s", url)
1652			user, _ := butwhatabout(u.Username)
1653			_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "unsub")
1654			if err == nil {
1655				_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "peep")
1656			}
1657			if err != nil {
1658				log.Printf("error updating honker: %s", err)
1659				return
1660			}
1661			go subsub(user, url, owner)
1662
1663			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1664			return
1665		}
1666		_, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1667		if err != nil {
1668			log.Printf("update honker err: %s", err)
1669			return
1670		}
1671		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1672		return
1673	}
1674
1675	if url == "" {
1676		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1677		return
1678	}
1679
1680	flavor := "presub"
1681	if peep == "peep" {
1682		flavor = "peep"
1683	}
1684
1685	if url[0] == '#' {
1686		flavor = "peep"
1687		if name == "" {
1688			name = url
1689		}
1690		_, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url)
1691		if err != nil {
1692			log.Print(err)
1693			return
1694		}
1695		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1696		return
1697	}
1698
1699	info, err := investigate(url)
1700	if err != nil {
1701		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1702		log.Printf("failed to investigate honker: %s", err)
1703		return
1704	}
1705	url = info.XID
1706
1707	db := opendatabase()
1708	row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1709	var x string
1710	err = row.Scan(&x)
1711	if err != sql.ErrNoRows {
1712		http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1713		if err != nil {
1714			log.Printf("honker scan err: %s", err)
1715		}
1716		return
1717	}
1718
1719	if name == "" {
1720		name = info.Name
1721	}
1722	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner)
1723	if err != nil {
1724		log.Print(err)
1725		return
1726	}
1727	if flavor == "presub" {
1728		user, _ := butwhatabout(u.Username)
1729		go subsub(user, url, info.Owner)
1730	}
1731	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1732}
1733
1734func hfcspage(w http.ResponseWriter, r *http.Request) {
1735	userinfo := login.GetUserInfo(r)
1736
1737	filters := getfilters(userinfo.UserID, filtAny)
1738
1739	templinfo := getInfo(r)
1740	templinfo["Filters"] = filters
1741	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1742	err := readviews.Execute(w, "hfcs.html", templinfo)
1743	if err != nil {
1744		log.Print(err)
1745	}
1746}
1747
1748func savehfcs(w http.ResponseWriter, r *http.Request) {
1749	userinfo := login.GetUserInfo(r)
1750	itsok := r.FormValue("itsok")
1751	if itsok == "iforgiveyou" {
1752		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1753		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1754		if err != nil {
1755			log.Printf("error deleting filter: %s", err)
1756		}
1757		filtcache.Clear(userinfo.UserID)
1758		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1759		return
1760	}
1761
1762	filt := new(Filter)
1763	filt.Name = strings.TrimSpace(r.FormValue("name"))
1764	filt.Date = time.Now().UTC()
1765	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1766	filt.IncludeAudience = r.FormValue("incaud") == "yes"
1767	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1768	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1769	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1770	filt.Reject = r.FormValue("doreject") == "yes"
1771	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1772	filt.Hide = r.FormValue("dohide") == "yes"
1773	filt.Collapse = r.FormValue("docollapse") == "yes"
1774	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1775	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1776	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
1777		filt.Expiration = time.Now().UTC().Add(dur)
1778	}
1779
1780	if filt.Actor == "" && filt.Text == "" {
1781		log.Printf("blank filter")
1782		return
1783	}
1784
1785	j, err := jsonify(filt)
1786	if err == nil {
1787		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1788	}
1789	if err != nil {
1790		log.Printf("error saving filter: %s", err)
1791	}
1792
1793	filtcache.Clear(userinfo.UserID)
1794	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1795}
1796
1797func accountpage(w http.ResponseWriter, r *http.Request) {
1798	u := login.GetUserInfo(r)
1799	user, _ := butwhatabout(u.Username)
1800	templinfo := getInfo(r)
1801	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1802	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1803	templinfo["User"] = user
1804	err := readviews.Execute(w, "account.html", templinfo)
1805	if err != nil {
1806		log.Print(err)
1807	}
1808}
1809
1810func dochpass(w http.ResponseWriter, r *http.Request) {
1811	err := login.ChangePassword(w, r)
1812	if err != nil {
1813		log.Printf("error changing password: %s", err)
1814	}
1815	http.Redirect(w, r, "/account", http.StatusSeeOther)
1816}
1817
1818func fingerlicker(w http.ResponseWriter, r *http.Request) {
1819	orig := r.FormValue("resource")
1820
1821	log.Printf("finger lick: %s", orig)
1822
1823	if strings.HasPrefix(orig, "acct:") {
1824		orig = orig[5:]
1825	}
1826
1827	name := orig
1828	idx := strings.LastIndexByte(name, '/')
1829	if idx != -1 {
1830		name = name[idx+1:]
1831		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1832			log.Printf("foreign request rejected")
1833			name = ""
1834		}
1835	} else {
1836		idx = strings.IndexByte(name, '@')
1837		if idx != -1 {
1838			name = name[:idx]
1839			if name+"@"+serverName != orig {
1840				log.Printf("foreign request rejected")
1841				name = ""
1842			}
1843		}
1844	}
1845	user, err := butwhatabout(name)
1846	if err != nil {
1847		http.NotFound(w, r)
1848		return
1849	}
1850	if stealthmode(user.ID, r) {
1851		http.NotFound(w, r)
1852		return
1853	}
1854
1855	j := junk.New()
1856	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1857	j["aliases"] = []string{user.URL}
1858	l := junk.New()
1859	l["rel"] = "self"
1860	l["type"] = `application/activity+json`
1861	l["href"] = user.URL
1862	j["links"] = []junk.Junk{l}
1863
1864	w.Header().Set("Content-Type", "application/jrd+json")
1865	j.Write(w)
1866}
1867
1868func somedays() string {
1869	secs := 432000 + notrand.Int63n(432000)
1870	return fmt.Sprintf("%d", secs)
1871}
1872
1873func avatate(w http.ResponseWriter, r *http.Request) {
1874	n := r.FormValue("a")
1875	a := avatar(n)
1876	w.Header().Set("Cache-Control", "max-age="+somedays())
1877	w.Write(a)
1878}
1879
1880func serveasset(w http.ResponseWriter, r *http.Request) {
1881	w.Header().Set("Cache-Control", "max-age=7776000")
1882	dir := viewDir
1883	if r.URL.Path == "/local.css" {
1884		dir = dataDir
1885	}
1886	http.ServeFile(w, r, dir+"/views"+r.URL.Path)
1887}
1888func servehelp(w http.ResponseWriter, r *http.Request) {
1889	name := mux.Vars(r)["name"]
1890	w.Header().Set("Cache-Control", "max-age=3600")
1891	http.ServeFile(w, r, viewDir+"/docs/"+name)
1892}
1893func servehtml(w http.ResponseWriter, r *http.Request) {
1894	u := login.GetUserInfo(r)
1895	templinfo := getInfo(r)
1896	templinfo["AboutMsg"] = aboutMsg
1897	templinfo["LoginMsg"] = loginMsg
1898	templinfo["HonkVersion"] = honkVersion
1899	if u == nil {
1900		w.Header().Set("Cache-Control", "max-age=60")
1901	}
1902	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1903	if err != nil {
1904		log.Print(err)
1905	}
1906}
1907func serveemu(w http.ResponseWriter, r *http.Request) {
1908	xid := mux.Vars(r)["xid"]
1909	w.Header().Set("Cache-Control", "max-age="+somedays())
1910	http.ServeFile(w, r, dataDir+"/emus/"+xid)
1911}
1912func servememe(w http.ResponseWriter, r *http.Request) {
1913	xid := mux.Vars(r)["xid"]
1914	w.Header().Set("Cache-Control", "max-age="+somedays())
1915	http.ServeFile(w, r, dataDir+"/memes/"+xid)
1916}
1917
1918func servefile(w http.ResponseWriter, r *http.Request) {
1919	xid := mux.Vars(r)["xid"]
1920	row := stmtGetFileData.QueryRow(xid)
1921	var media string
1922	var data []byte
1923	err := row.Scan(&media, &data)
1924	if err != nil {
1925		log.Printf("error loading file: %s", err)
1926		http.NotFound(w, r)
1927		return
1928	}
1929	w.Header().Set("Content-Type", media)
1930	w.Header().Set("X-Content-Type-Options", "nosniff")
1931	w.Header().Set("Cache-Control", "max-age="+somedays())
1932	w.Write(data)
1933}
1934
1935func nomoroboto(w http.ResponseWriter, r *http.Request) {
1936	io.WriteString(w, "User-agent: *\n")
1937	io.WriteString(w, "Disallow: /a\n")
1938	io.WriteString(w, "Disallow: /d\n")
1939	io.WriteString(w, "Disallow: /meme\n")
1940	io.WriteString(w, "Disallow: /o\n")
1941	for _, u := range allusers() {
1942		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1943	}
1944}
1945
1946func webhydra(w http.ResponseWriter, r *http.Request) {
1947	u := login.GetUserInfo(r)
1948	userid := u.UserID
1949	templinfo := getInfo(r)
1950	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1951	page := r.FormValue("page")
1952
1953	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
1954
1955	var honks []*Honk
1956	switch page {
1957	case "atme":
1958		honks = gethonksforme(userid, wanted)
1959		honks = osmosis(honks, userid, false)
1960		templinfo["ServerMessage"] = "at me!"
1961	case "home":
1962		honks = gethonksforuser(userid, wanted)
1963		honks = osmosis(honks, userid, true)
1964		templinfo["ServerMessage"] = serverMsg
1965	case "first":
1966		honks = gethonksforuserfirstclass(userid, wanted)
1967		honks = osmosis(honks, userid, true)
1968		templinfo["ServerMessage"] = "first class only"
1969	case "saved":
1970		honks = getsavedhonks(userid, wanted)
1971		templinfo["PageName"] = "saved"
1972		templinfo["ServerMessage"] = "saved honks"
1973	case "combo":
1974		c := r.FormValue("c")
1975		honks = gethonksbycombo(userid, c, wanted)
1976		honks = osmosis(honks, userid, false)
1977		templinfo["ServerMessage"] = "honks by combo: " + c
1978	case "convoy":
1979		c := r.FormValue("c")
1980		honks = gethonksbyconvoy(userid, c, wanted)
1981		honks = osmosis(honks, userid, false)
1982		templinfo["ServerMessage"] = "honks in convoy: " + c
1983	case "honker":
1984		xid := r.FormValue("xid")
1985		if strings.IndexByte(xid, '@') != -1 {
1986			xid = gofish(xid)
1987		}
1988		honks = gethonksbyxonker(userid, xid, wanted)
1989		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
1990		templinfo["ServerMessage"] = msg
1991	default:
1992		http.NotFound(w, r)
1993	}
1994	if len(honks) > 0 {
1995		templinfo["TopHID"] = honks[0].ID
1996	} else {
1997		templinfo["TopHID"] = wanted
1998	}
1999	reverbolate(userid, honks)
2000	templinfo["Honks"] = honks
2001	w.Header().Set("Content-Type", "text/html; charset=utf-8")
2002	err := readviews.Execute(w, "honkfrags.html", templinfo)
2003	if err != nil {
2004		log.Printf("frag error: %s", err)
2005	}
2006}
2007
2008func apihandler(w http.ResponseWriter, r *http.Request) {
2009	u := login.GetUserInfo(r)
2010	action := r.FormValue("action")
2011	log.Printf("api request '%s' on behalf of %s", action, u.Username)
2012	switch action {
2013	case "honk":
2014		submithonk(w, r)
2015	default:
2016		http.Error(w, "unknown action", http.StatusNotFound)
2017	}
2018}
2019
2020func serve() {
2021	db := opendatabase()
2022	login.Init(db)
2023
2024	listener, err := openListener()
2025	if err != nil {
2026		log.Fatal(err)
2027	}
2028	go redeliverator()
2029	go tracker()
2030
2031	debug := false
2032	getconfig("debug", &debug)
2033	readviews = templates.Load(debug,
2034		viewDir+"/views/honkpage.html",
2035		viewDir+"/views/honkfrags.html",
2036		viewDir+"/views/honkers.html",
2037		viewDir+"/views/hfcs.html",
2038		viewDir+"/views/combos.html",
2039		viewDir+"/views/honkform.html",
2040		viewDir+"/views/honk.html",
2041		viewDir+"/views/account.html",
2042		viewDir+"/views/about.html",
2043		viewDir+"/views/funzone.html",
2044		viewDir+"/views/login.html",
2045		viewDir+"/views/xzone.html",
2046		viewDir+"/views/msg.html",
2047		viewDir+"/views/header.html",
2048		viewDir+"/views/onts.html",
2049		viewDir+"/views/honkpage.js",
2050	)
2051	if !debug {
2052		assets := []string{viewDir + "/views/style.css", dataDir + "/views/local.css", viewDir + "/views/honkpage.js"}
2053		for _, s := range assets {
2054			savedassetparams[s] = getassetparam(s)
2055		}
2056	}
2057
2058	mux := mux.NewRouter()
2059	mux.Use(login.Checker)
2060
2061	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2062
2063	posters := mux.Methods("POST").Subrouter()
2064	getters := mux.Methods("GET").Subrouter()
2065
2066	getters.HandleFunc("/", homepage)
2067	getters.HandleFunc("/home", homepage)
2068	getters.HandleFunc("/front", homepage)
2069	getters.HandleFunc("/events", homepage)
2070	getters.HandleFunc("/robots.txt", nomoroboto)
2071	getters.HandleFunc("/rss", showrss)
2072	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
2073	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showonehonk)
2074	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
2075	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
2076	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
2077	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
2078	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
2079	getters.HandleFunc("/a", avatate)
2080	getters.HandleFunc("/o", thelistingoftheontologies)
2081	getters.HandleFunc("/o/{name:.+}", showontology)
2082	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
2083	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
2084	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
2085	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2086
2087	getters.HandleFunc("/server", serveractor)
2088	posters.HandleFunc("/server/inbox", serverinbox)
2089
2090	getters.HandleFunc("/style.css", serveasset)
2091	getters.HandleFunc("/local.css", serveasset)
2092	getters.HandleFunc("/honkpage.js", serveasset)
2093	getters.HandleFunc("/about", servehtml)
2094	getters.HandleFunc("/login", servehtml)
2095	posters.HandleFunc("/dologin", login.LoginFunc)
2096	getters.HandleFunc("/logout", login.LogoutFunc)
2097	getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
2098
2099	loggedin := mux.NewRoute().Subrouter()
2100	loggedin.Use(login.Required)
2101	loggedin.HandleFunc("/first", homepage)
2102	loggedin.HandleFunc("/saved", homepage)
2103	loggedin.HandleFunc("/account", accountpage)
2104	loggedin.HandleFunc("/funzone", showfunzone)
2105	loggedin.HandleFunc("/chpass", dochpass)
2106	loggedin.HandleFunc("/atme", homepage)
2107	loggedin.HandleFunc("/hfcs", hfcspage)
2108	loggedin.HandleFunc("/xzone", xzone)
2109	loggedin.HandleFunc("/newhonk", newhonkpage)
2110	loggedin.HandleFunc("/edit", edithonkpage)
2111	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
2112	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2113	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2114	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2115	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2116	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2117	loggedin.HandleFunc("/honkers", showhonkers)
2118	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
2119	loggedin.HandleFunc("/h", showhonker)
2120	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
2121	loggedin.HandleFunc("/c", showcombos)
2122	loggedin.HandleFunc("/t", showconvoy)
2123	loggedin.HandleFunc("/q", showsearch)
2124	loggedin.HandleFunc("/hydra", webhydra)
2125	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
2126
2127	err = http.Serve(listener, mux)
2128	if err != nil {
2129		log.Fatal(err)
2130	}
2131}