all repos — honk @ facf1bba11595ec5a5e51801ae170755924f4c9c

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	"fmt"
  21	"html"
  22	"html/template"
  23	"io"
  24	"log"
  25	notrand "math/rand"
  26	"net/http"
  27	"net/url"
  28	"os"
  29	"sort"
  30	"strconv"
  31	"strings"
  32	"time"
  33
  34	"github.com/gorilla/mux"
  35	"humungus.tedunangst.com/r/webs/css"
  36	"humungus.tedunangst.com/r/webs/htfilter"
  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.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("views/style.css")
  65	templinfo["LocalStyleParam"] = getassetparam("views/local.css")
  66	templinfo["JSParam"] = getassetparam("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	if r.URL.Path == "/front" || u == nil {
  86		honks = getpublichonks()
  87	} else {
  88		userid = u.UserID
  89		if r.URL.Path == "/atme" {
  90			templinfo["PageName"] = "atme"
  91			honks = gethonksforme(userid)
  92		} else if r.URL.Path == "/first" {
  93			templinfo["PageName"] = "first"
  94			honks = gethonksforuser(userid)
  95			honks = osmosis(honks, userid)
  96		} else {
  97			templinfo["PageName"] = "home"
  98			honks = gethonksforuser(userid)
  99			honks = osmosis(honks, userid)
 100		}
 101		if len(honks) > 0 {
 102			templinfo["TopXID"] = honks[0].XID
 103		}
 104		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 105	}
 106
 107	templinfo["ShowRSS"] = true
 108	templinfo["ServerMessage"] = serverMsg
 109	honkpage(w, u, honks, templinfo)
 110}
 111
 112func showfunzone(w http.ResponseWriter, r *http.Request) {
 113	var emunames, memenames []string
 114	dir, err := os.Open("emus")
 115	if err == nil {
 116		emunames, _ = dir.Readdirnames(0)
 117		dir.Close()
 118	}
 119	for i, e := range emunames {
 120		if len(e) > 4 {
 121			emunames[i] = e[:len(e)-4]
 122		}
 123	}
 124	dir, err = os.Open("memes")
 125	if err == nil {
 126		memenames, _ = dir.Readdirnames(0)
 127		dir.Close()
 128	}
 129	templinfo := getInfo(r)
 130	templinfo["Emus"] = emunames
 131	templinfo["Memes"] = memenames
 132	err = readviews.Execute(w, "funzone.html", templinfo)
 133	if err != nil {
 134		log.Print(err)
 135	}
 136}
 137
 138func showrss(w http.ResponseWriter, r *http.Request) {
 139	name := mux.Vars(r)["name"]
 140
 141	var honks []*Honk
 142	if name != "" {
 143		honks = gethonksbyuser(name, false)
 144	} else {
 145		honks = getpublichonks()
 146	}
 147	if len(honks) > 20 {
 148		honks = honks[0:20]
 149	}
 150	reverbolate(-1, honks)
 151
 152	home := fmt.Sprintf("https://%s/", serverName)
 153	base := home
 154	if name != "" {
 155		home += "u/" + name
 156		name += " "
 157	}
 158	feed := rss.Feed{
 159		Title:       name + "honk",
 160		Link:        home,
 161		Description: name + "honk rss",
 162		Image: &rss.Image{
 163			URL:   base + "icon.png",
 164			Title: name + "honk rss",
 165			Link:  home,
 166		},
 167	}
 168	var modtime time.Time
 169	for _, honk := range honks {
 170		if !firstclass(honk) {
 171			continue
 172		}
 173		desc := string(honk.HTML)
 174		for _, d := range honk.Donks {
 175			desc += fmt.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
 176				d.URL, html.EscapeString(d.Name))
 177		}
 178
 179		feed.Items = append(feed.Items, &rss.Item{
 180			Title:       fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
 181			Description: rss.CData{desc},
 182			Link:        honk.URL,
 183			PubDate:     honk.Date.Format(time.RFC1123),
 184			Guid:        &rss.Guid{IsPermaLink: true, Value: honk.URL},
 185		})
 186		if honk.Date.After(modtime) {
 187			modtime = honk.Date
 188		}
 189	}
 190	w.Header().Set("Cache-Control", "max-age=300")
 191	w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
 192
 193	err := feed.Write(w)
 194	if err != nil {
 195		log.Printf("error writing rss: %s", err)
 196	}
 197}
 198
 199func crappola(j junk.Junk) bool {
 200	t, _ := j.GetString("type")
 201	a, _ := j.GetString("actor")
 202	o, _ := j.GetString("object")
 203	if t == "Delete" && a == o {
 204		log.Printf("crappola from %s", a)
 205		return true
 206	}
 207	return false
 208}
 209
 210func ping(user *WhatAbout, who string) {
 211	box, err := getboxes(who)
 212	if err != nil {
 213		log.Printf("no inbox for ping: %s", err)
 214		return
 215	}
 216	j := junk.New()
 217	j["@context"] = itiswhatitis
 218	j["type"] = "Ping"
 219	j["id"] = user.URL + "/ping/" + xfiltrate()
 220	j["actor"] = user.URL
 221	j["to"] = who
 222	keyname, key := ziggy(user.Name)
 223	err = PostJunk(keyname, key, box.In, j)
 224	if err != nil {
 225		log.Printf("can't send ping: %s", err)
 226		return
 227	}
 228	log.Printf("sent ping to %s: %s", who, j["id"])
 229}
 230
 231func pong(user *WhatAbout, who string, obj string) {
 232	box, err := getboxes(who)
 233	if err != nil {
 234		log.Printf("no inbox for pong %s : %s", who, err)
 235		return
 236	}
 237	j := junk.New()
 238	j["@context"] = itiswhatitis
 239	j["type"] = "Pong"
 240	j["id"] = user.URL + "/pong/" + xfiltrate()
 241	j["actor"] = user.URL
 242	j["to"] = who
 243	j["object"] = obj
 244	keyname, key := ziggy(user.Name)
 245	err = PostJunk(keyname, key, box.In, j)
 246	if err != nil {
 247		log.Printf("can't send pong: %s", err)
 248		return
 249	}
 250}
 251
 252func inbox(w http.ResponseWriter, r *http.Request) {
 253	name := mux.Vars(r)["name"]
 254	user, err := butwhatabout(name)
 255	if err != nil {
 256		http.NotFound(w, r)
 257		return
 258	}
 259	if stealthmode(user.ID, r) {
 260		http.NotFound(w, r)
 261		return
 262	}
 263	var buf bytes.Buffer
 264	io.Copy(&buf, r.Body)
 265	payload := buf.Bytes()
 266	j, err := junk.Read(bytes.NewReader(payload))
 267	if err != nil {
 268		log.Printf("bad payload: %s", err)
 269		io.WriteString(os.Stdout, "bad payload\n")
 270		os.Stdout.Write(payload)
 271		io.WriteString(os.Stdout, "\n")
 272		return
 273	}
 274	if crappola(j) {
 275		return
 276	}
 277	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 278	if err != nil {
 279		log.Printf("inbox message failed signature: %s", err)
 280		if keyname != "" {
 281			keyname, err = makeitworksomehowwithoutregardforkeycontinuity(keyname, r, payload)
 282			if err != nil {
 283				log.Printf("still failed: %s", err)
 284			}
 285		}
 286		if err != nil {
 287			return
 288		}
 289	}
 290	what, _ := j.GetString("type")
 291	if what == "Like" {
 292		return
 293	}
 294	who, _ := j.GetString("actor")
 295	origin := keymatch(keyname, who)
 296	if origin == "" {
 297		log.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 298		return
 299	}
 300	objid, _ := j.GetString("id")
 301	if thoudostbitethythumb(user.ID, []string{who}, objid) {
 302		log.Printf("ignoring thumb sucker %s", who)
 303		return
 304	}
 305	switch what {
 306	case "Ping":
 307		obj, _ := j.GetString("id")
 308		log.Printf("ping from %s: %s", who, obj)
 309		pong(user, who, obj)
 310	case "Pong":
 311		obj, _ := j.GetString("object")
 312		log.Printf("pong from %s: %s", who, obj)
 313	case "Follow":
 314		obj, _ := j.GetString("object")
 315		if obj == user.URL {
 316			log.Printf("updating honker follow: %s", who)
 317			stmtSaveDub.Exec(user.ID, who, who, "dub")
 318			go rubadubdub(user, j)
 319		} else {
 320			log.Printf("can't follow %s", obj)
 321		}
 322	case "Accept":
 323		log.Printf("updating honker accept: %s", who)
 324		_, err = stmtUpdateFlavor.Exec("sub", user.ID, who, "presub")
 325		if err != nil {
 326			log.Printf("error updating honker: %s", err)
 327			return
 328		}
 329	case "Update":
 330		obj, ok := j.GetMap("object")
 331		if ok {
 332			what, _ := obj.GetString("type")
 333			switch what {
 334			case "Person":
 335				return
 336			case "Question":
 337				return
 338			case "Note":
 339				go consumeactivity(user, j, origin)
 340				return
 341			}
 342		}
 343		log.Printf("unknown Update activity")
 344		fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 345		j.Write(fd)
 346		io.WriteString(fd, "\n")
 347		fd.Close()
 348
 349	case "Undo":
 350		obj, ok := j.GetMap("object")
 351		if !ok {
 352			log.Printf("unknown undo no object")
 353		} else {
 354			what, _ := obj.GetString("type")
 355			switch what {
 356			case "Follow":
 357				log.Printf("updating honker undo: %s", who)
 358				_, err = stmtUpdateFlavor.Exec("undub", user.ID, who, "dub")
 359				if err != nil {
 360					log.Printf("error updating honker: %s", err)
 361					return
 362				}
 363			case "Announce":
 364				xid, _ := obj.GetString("object")
 365				log.Printf("undo announce: %s", xid)
 366			case "Like":
 367			default:
 368				log.Printf("unknown undo: %s", what)
 369			}
 370		}
 371	default:
 372		go consumeactivity(user, j, origin)
 373	}
 374}
 375
 376func ximport(w http.ResponseWriter, r *http.Request) {
 377	xid := r.FormValue("xid")
 378	p, _ := investigate(xid)
 379	if p != nil {
 380		xid = p.XID
 381	}
 382	j, err := GetJunk(xid)
 383	if err != nil {
 384		http.Error(w, "error getting external object", http.StatusInternalServerError)
 385		log.Printf("error getting external object: %s", err)
 386		return
 387	}
 388	log.Printf("importing %s", xid)
 389	u := login.GetUserInfo(r)
 390	user, _ := butwhatabout(u.Username)
 391
 392	what, _ := j.GetString("type")
 393	if isactor(what) {
 394		outbox, _ := j.GetString("outbox")
 395		gimmexonks(user, outbox)
 396		http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
 397		return
 398	}
 399	xonk := xonkxonk(user, j, originate(xid))
 400	convoy := ""
 401	if xonk != nil {
 402		convoy = xonk.Convoy
 403		savexonk(xonk)
 404	}
 405	http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
 406}
 407
 408func xzone(w http.ResponseWriter, r *http.Request) {
 409	u := login.GetUserInfo(r)
 410	rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
 411	if err != nil {
 412		log.Printf("query err: %s", err)
 413		return
 414	}
 415	defer rows.Close()
 416	var honkers []Honker
 417	for rows.Next() {
 418		var xid string
 419		rows.Scan(&xid)
 420		honkers = append(honkers, Honker{XID: xid})
 421	}
 422	rows.Close()
 423	for i, _ := range honkers {
 424		_, honkers[i].Handle = handles(honkers[i].XID)
 425	}
 426	templinfo := getInfo(r)
 427	templinfo["XCSRF"] = login.GetCSRF("ximport", r)
 428	templinfo["Honkers"] = honkers
 429	err = readviews.Execute(w, "xzone.html", templinfo)
 430	if err != nil {
 431		log.Print(err)
 432	}
 433}
 434
 435func outbox(w http.ResponseWriter, r *http.Request) {
 436	name := mux.Vars(r)["name"]
 437	user, err := butwhatabout(name)
 438	if err != nil {
 439		http.NotFound(w, r)
 440		return
 441	}
 442	if stealthmode(user.ID, r) {
 443		http.NotFound(w, r)
 444		return
 445	}
 446
 447	honks := gethonksbyuser(name, false)
 448	if len(honks) > 20 {
 449		honks = honks[0:20]
 450	}
 451
 452	var jonks []junk.Junk
 453	for _, h := range honks {
 454		j, _ := jonkjonk(user, h)
 455		jonks = append(jonks, j)
 456	}
 457
 458	j := junk.New()
 459	j["@context"] = itiswhatitis
 460	j["id"] = user.URL + "/outbox"
 461	j["type"] = "OrderedCollection"
 462	j["totalItems"] = len(jonks)
 463	j["orderedItems"] = jonks
 464
 465	w.Header().Set("Content-Type", theonetruename)
 466	j.Write(w)
 467}
 468
 469func emptiness(w http.ResponseWriter, r *http.Request) {
 470	name := mux.Vars(r)["name"]
 471	user, err := butwhatabout(name)
 472	if err != nil {
 473		http.NotFound(w, r)
 474		return
 475	}
 476	if stealthmode(user.ID, r) {
 477		http.NotFound(w, r)
 478		return
 479	}
 480	colname := "/followers"
 481	if strings.HasSuffix(r.URL.Path, "/following") {
 482		colname = "/following"
 483	}
 484	j := junk.New()
 485	j["@context"] = itiswhatitis
 486	j["id"] = user.URL + colname
 487	j["type"] = "OrderedCollection"
 488	j["totalItems"] = 0
 489	j["orderedItems"] = []junk.Junk{}
 490
 491	w.Header().Set("Content-Type", theonetruename)
 492	j.Write(w)
 493}
 494
 495func showuser(w http.ResponseWriter, r *http.Request) {
 496	name := mux.Vars(r)["name"]
 497	user, err := butwhatabout(name)
 498	if err != nil {
 499		log.Printf("user not found %s: %s", name, err)
 500		http.NotFound(w, r)
 501		return
 502	}
 503	if stealthmode(user.ID, r) {
 504		http.NotFound(w, r)
 505		return
 506	}
 507	if friendorfoe(r.Header.Get("Accept")) {
 508		j := asjonker(user)
 509		w.Header().Set("Content-Type", theonetruename)
 510		j.Write(w)
 511		return
 512	}
 513	u := login.GetUserInfo(r)
 514	honks := gethonksbyuser(name, u != nil && u.Username == name)
 515	templinfo := getInfo(r)
 516	filt := htfilter.New()
 517	templinfo["Name"] = user.Name
 518	whatabout := user.About
 519	whatabout = obfusbreak(user.About)
 520	templinfo["WhatAbout"], _ = filt.String(whatabout)
 521	templinfo["ServerMessage"] = ""
 522	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 523	honkpage(w, u, honks, templinfo)
 524}
 525
 526func showhonker(w http.ResponseWriter, r *http.Request) {
 527	u := login.GetUserInfo(r)
 528	name := mux.Vars(r)["name"]
 529	var honks []*Honk
 530	if name == "" {
 531		name = r.FormValue("xid")
 532		honks = gethonksbyxonker(u.UserID, name)
 533	} else {
 534		honks = gethonksbyhonker(u.UserID, name)
 535	}
 536	name = html.EscapeString(name)
 537	msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, name, name)
 538	templinfo := getInfo(r)
 539	templinfo["PageName"] = "honker"
 540	templinfo["ServerMessage"] = template.HTML(msg)
 541	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 542	honkpage(w, u, honks, templinfo)
 543}
 544
 545func showcombo(w http.ResponseWriter, r *http.Request) {
 546	name := mux.Vars(r)["name"]
 547	u := login.GetUserInfo(r)
 548	honks := gethonksbycombo(u.UserID, name)
 549	honks = osmosis(honks, u.UserID)
 550	templinfo := getInfo(r)
 551	templinfo["PageName"] = "combo"
 552	templinfo["PageArg"] = "name"
 553	templinfo["ServerMessage"] = "honks by combo: " + name
 554	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 555	if len(honks) > 0 {
 556		templinfo["TopXID"] = honks[0].XID
 557	}
 558	honkpage(w, u, honks, templinfo)
 559}
 560func showconvoy(w http.ResponseWriter, r *http.Request) {
 561	c := r.FormValue("c")
 562	u := login.GetUserInfo(r)
 563	honks := gethonksbyconvoy(u.UserID, c)
 564	templinfo := getInfo(r)
 565	templinfo["ServerMessage"] = "honks in convoy: " + c
 566	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 567	honkpage(w, u, honks, templinfo)
 568}
 569func showsearch(w http.ResponseWriter, r *http.Request) {
 570	q := r.FormValue("q")
 571	u := login.GetUserInfo(r)
 572	honks := gethonksbysearch(u.UserID, q)
 573	templinfo := getInfo(r)
 574	templinfo["ServerMessage"] = "honks for search: " + q
 575	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 576	honkpage(w, u, honks, templinfo)
 577}
 578func showontology(w http.ResponseWriter, r *http.Request) {
 579	name := mux.Vars(r)["name"]
 580	u := login.GetUserInfo(r)
 581	var userid int64 = -1
 582	if u != nil {
 583		userid = u.UserID
 584	}
 585	honks := gethonksbyontology(userid, "#"+name)
 586	templinfo := getInfo(r)
 587	templinfo["ServerMessage"] = "honks by ontology: " + name
 588	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 589	honkpage(w, u, honks, templinfo)
 590}
 591
 592func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 593	u := login.GetUserInfo(r)
 594	var userid int64 = -1
 595	if u != nil {
 596		userid = u.UserID
 597	}
 598	rows, err := stmtSelectOnts.Query(userid)
 599	if err != nil {
 600		log.Printf("selection error: %s", err)
 601		return
 602	}
 603	defer rows.Close()
 604	var onts [][]string
 605	for rows.Next() {
 606		var o string
 607		err := rows.Scan(&o)
 608		if err != nil {
 609			log.Printf("error scanning ont: %s", err)
 610			continue
 611		}
 612		onts = append(onts, []string{o, o[1:]})
 613	}
 614	if u == nil {
 615		w.Header().Set("Cache-Control", "max-age=300")
 616	}
 617	templinfo := getInfo(r)
 618	templinfo["Onts"] = onts
 619	err = readviews.Execute(w, "onts.html", templinfo)
 620	if err != nil {
 621		log.Print(err)
 622	}
 623}
 624
 625func showhonk(w http.ResponseWriter, r *http.Request) {
 626	name := mux.Vars(r)["name"]
 627	user, err := butwhatabout(name)
 628	if err != nil {
 629		http.NotFound(w, r)
 630		return
 631	}
 632	if stealthmode(user.ID, r) {
 633		http.NotFound(w, r)
 634		return
 635	}
 636
 637	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
 638	honk := getxonk(user.ID, xid)
 639	if honk == nil {
 640		http.NotFound(w, r)
 641		return
 642	}
 643	u := login.GetUserInfo(r)
 644	if u != nil && u.UserID != user.ID {
 645		u = nil
 646	}
 647	if !honk.Public {
 648		if u == nil {
 649			http.NotFound(w, r)
 650			return
 651
 652		}
 653		templinfo := getInfo(r)
 654		templinfo["ServerMessage"] = "one honk maybe more"
 655		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 656		honkpage(w, u, []*Honk{honk}, templinfo)
 657		return
 658	}
 659	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
 660	if friendorfoe(r.Header.Get("Accept")) {
 661		for _, h := range rawhonks {
 662			if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
 663				honk.Replies = append(honk.Replies, h)
 664			}
 665		}
 666		donksforhonks([]*Honk{honk})
 667		_, j := jonkjonk(user, honk)
 668		j["@context"] = itiswhatitis
 669		w.Header().Set("Content-Type", theonetruename)
 670		j.Write(w)
 671		return
 672	}
 673	var honks []*Honk
 674	for _, h := range rawhonks {
 675		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
 676			honks = append(honks, h)
 677		}
 678	}
 679
 680	templinfo := getInfo(r)
 681	templinfo["ServerMessage"] = "one honk maybe more"
 682	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 683	honkpage(w, u, honks, templinfo)
 684}
 685
 686func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
 687	var userid int64 = -1
 688	if u != nil {
 689		userid = u.UserID
 690	}
 691	if u == nil {
 692		w.Header().Set("Cache-Control", "max-age=60")
 693	}
 694	reverbolate(userid, honks)
 695	templinfo["Honks"] = honks
 696	err := readviews.Execute(w, "honkpage.html", templinfo)
 697	if err != nil {
 698		log.Print(err)
 699	}
 700}
 701
 702func saveuser(w http.ResponseWriter, r *http.Request) {
 703	whatabout := r.FormValue("whatabout")
 704	u := login.GetUserInfo(r)
 705	db := opendatabase()
 706	options := ""
 707	if r.FormValue("skinny") == "skinny" {
 708		options += " skinny "
 709	}
 710	_, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
 711	if err != nil {
 712		log.Printf("error bouting what: %s", err)
 713	}
 714
 715	http.Redirect(w, r, "/account", http.StatusSeeOther)
 716}
 717
 718func submitbonk(w http.ResponseWriter, r *http.Request) {
 719	xid := r.FormValue("xid")
 720	userinfo := login.GetUserInfo(r)
 721	user, _ := butwhatabout(userinfo.Username)
 722
 723	log.Printf("bonking %s", xid)
 724
 725	xonk := getxonk(userinfo.UserID, xid)
 726	if xonk == nil {
 727		return
 728	}
 729	if !xonk.Public {
 730		return
 731	}
 732	donksforhonks([]*Honk{xonk})
 733
 734	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
 735	if err != nil {
 736		log.Printf("error acking bonk: %s", err)
 737	}
 738
 739	oonker := xonk.Oonker
 740	if oonker == "" {
 741		oonker = xonk.Honker
 742	}
 743	dt := time.Now().UTC()
 744	bonk := Honk{
 745		UserID:   userinfo.UserID,
 746		Username: userinfo.Username,
 747		What:     "bonk",
 748		Honker:   user.URL,
 749		Oonker:   oonker,
 750		XID:      xonk.XID,
 751		RID:      xonk.RID,
 752		Noise:    xonk.Noise,
 753		Precis:   xonk.Precis,
 754		URL:      xonk.URL,
 755		Date:     dt,
 756		Donks:    xonk.Donks,
 757		Whofore:  2,
 758		Convoy:   xonk.Convoy,
 759		Audience: []string{thewholeworld, oonker},
 760		Public:   true,
 761	}
 762
 763	bonk.Format = "html"
 764
 765	err = savehonk(&bonk)
 766	if err != nil {
 767		log.Printf("uh oh")
 768		return
 769	}
 770
 771	go honkworldwide(user, &bonk)
 772}
 773
 774func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
 775	zonk := Honk{
 776		What:     what,
 777		XID:      xonk.XID,
 778		Date:     time.Now().UTC(),
 779		Audience: oneofakind(xonk.Audience),
 780	}
 781	zonk.Public = !keepitquiet(zonk.Audience)
 782
 783	log.Printf("announcing %sed honk: %s", what, xonk.XID)
 784	go honkworldwide(user, &zonk)
 785}
 786
 787func zonkit(w http.ResponseWriter, r *http.Request) {
 788	wherefore := r.FormValue("wherefore")
 789	what := r.FormValue("what")
 790	userinfo := login.GetUserInfo(r)
 791	user, _ := butwhatabout(userinfo.Username)
 792
 793	if wherefore == "ack" {
 794		xonk := getxonk(userinfo.UserID, what)
 795		if xonk != nil {
 796			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
 797			if err != nil {
 798				log.Printf("error acking: %s", err)
 799			}
 800			sendzonkofsorts(xonk, user, "ack")
 801		}
 802		return
 803	}
 804
 805	if wherefore == "deack" {
 806		xonk := getxonk(userinfo.UserID, what)
 807		if xonk != nil {
 808			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
 809			if err != nil {
 810				log.Printf("error deacking: %s", err)
 811			}
 812			sendzonkofsorts(xonk, user, "deack")
 813		}
 814		return
 815	}
 816
 817	if wherefore == "unbonk" {
 818		xonk := getbonk(userinfo.UserID, what)
 819		if xonk != nil {
 820			deletehonk(xonk.ID)
 821			xonk = getxonk(userinfo.UserID, what)
 822			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
 823			if err != nil {
 824				log.Printf("error unbonking: %s", err)
 825			}
 826			sendzonkofsorts(xonk, user, "unbonk")
 827		}
 828		return
 829	}
 830
 831	log.Printf("zonking %s %s", wherefore, what)
 832	if wherefore == "zonk" {
 833		xonk := getxonk(userinfo.UserID, what)
 834		if xonk != nil {
 835			deletehonk(xonk.ID)
 836			if xonk.Whofore == 2 || xonk.Whofore == 3 {
 837				sendzonkofsorts(xonk, user, "zonk")
 838			}
 839		}
 840	}
 841	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
 842	if err != nil {
 843		log.Printf("error saving zonker: %s", err)
 844		return
 845	}
 846}
 847
 848func edithonkpage(w http.ResponseWriter, r *http.Request) {
 849	u := login.GetUserInfo(r)
 850	user, _ := butwhatabout(u.Username)
 851	xid := r.FormValue("xid")
 852	honk := getxonk(u.UserID, xid)
 853	if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 854		log.Printf("no edit")
 855		return
 856	}
 857
 858	noise := honk.Noise
 859	if honk.Precis != "" {
 860		noise = honk.Precis + "\n\n" + noise
 861	}
 862
 863	honks := []*Honk{honk}
 864	donksforhonks(honks)
 865	reverbolate(u.UserID, honks)
 866	templinfo := getInfo(r)
 867	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 868	templinfo["Honks"] = honks
 869	templinfo["Noise"] = noise
 870	templinfo["ServerMessage"] = "honk edit"
 871	templinfo["UpdateXID"] = honk.XID
 872	if len(honk.Donks) > 0 {
 873		templinfo["SavedFile"] = honk.Donks[0].XID
 874	}
 875	err := readviews.Execute(w, "honkpage.html", templinfo)
 876	if err != nil {
 877		log.Print(err)
 878	}
 879}
 880
 881// what a hot mess this function is
 882func submithonk(w http.ResponseWriter, r *http.Request) {
 883	rid := r.FormValue("rid")
 884	noise := r.FormValue("noise")
 885
 886	userinfo := login.GetUserInfo(r)
 887	user, _ := butwhatabout(userinfo.Username)
 888
 889	dt := time.Now().UTC()
 890	updatexid := r.FormValue("updatexid")
 891	var honk *Honk
 892	if updatexid != "" {
 893		honk = getxonk(userinfo.UserID, updatexid)
 894		if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 895			log.Printf("not saving edit")
 896			return
 897		}
 898		honk.Date = dt
 899		honk.What = "update"
 900		honk.Format = "markdown"
 901	} else {
 902		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
 903		what := "honk"
 904		if rid != "" {
 905			what = "tonk"
 906		}
 907		honk = &Honk{
 908			UserID:   userinfo.UserID,
 909			Username: userinfo.Username,
 910			What:     what,
 911			Honker:   user.URL,
 912			XID:      xid,
 913			Date:     dt,
 914			Format:   "markdown",
 915		}
 916	}
 917
 918	noise = hooterize(noise)
 919	honk.Noise = noise
 920	translate(honk)
 921
 922	var convoy string
 923	if rid != "" {
 924		xonk := getxonk(userinfo.UserID, rid)
 925		if xonk != nil {
 926			if xonk.Public {
 927				honk.Audience = append(honk.Audience, xonk.Audience...)
 928			}
 929			convoy = xonk.Convoy
 930		} else {
 931			xonkaud, c := whosthere(rid)
 932			honk.Audience = append(honk.Audience, xonkaud...)
 933			convoy = c
 934		}
 935		for i, a := range honk.Audience {
 936			if a == thewholeworld {
 937				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
 938				break
 939			}
 940		}
 941		honk.RID = rid
 942	} else {
 943		honk.Audience = []string{thewholeworld}
 944	}
 945	if honk.Noise != "" && honk.Noise[0] == '@' {
 946		honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
 947	} else {
 948		honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
 949	}
 950
 951	if convoy == "" {
 952		convoy = "data:,electrichonkytonk-" + xfiltrate()
 953	}
 954	butnottooloud(honk.Audience)
 955	honk.Audience = oneofakind(honk.Audience)
 956	if len(honk.Audience) == 0 {
 957		log.Printf("honk to nowhere")
 958		http.Error(w, "honk to nowhere...", http.StatusNotFound)
 959		return
 960	}
 961	honk.Public = !keepitquiet(honk.Audience)
 962	honk.Convoy = convoy
 963
 964	donkxid := r.FormValue("donkxid")
 965	if donkxid == "" {
 966		file, filehdr, err := r.FormFile("donk")
 967		if err == nil {
 968			var buf bytes.Buffer
 969			io.Copy(&buf, file)
 970			file.Close()
 971			data := buf.Bytes()
 972			xid := xfiltrate()
 973			var media, name string
 974			img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
 975			if err == nil {
 976				data = img.Data
 977				format := img.Format
 978				media = "image/" + format
 979				if format == "jpeg" {
 980					format = "jpg"
 981				}
 982				name = xid + "." + format
 983				xid = name
 984			} else {
 985				maxsize := 100000
 986				if len(data) > maxsize {
 987					log.Printf("bad image: %s too much text: %d", err, len(data))
 988					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
 989					return
 990				}
 991				for i := 0; i < len(data); i++ {
 992					if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
 993						log.Printf("bad image: %s not text: %d", err, data[i])
 994						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
 995						return
 996					}
 997				}
 998				media = "text/plain"
 999				name = filehdr.Filename
1000				if name == "" {
1001					name = xid + ".txt"
1002				}
1003				xid += ".txt"
1004			}
1005			desc := r.FormValue("donkdesc")
1006			if desc == "" {
1007				desc = name
1008			}
1009			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1010			res, err := stmtSaveFile.Exec(xid, name, desc, url, media, 1, data)
1011			if err != nil {
1012				log.Printf("unable to save image: %s", err)
1013				return
1014			}
1015			var d Donk
1016			d.FileID, _ = res.LastInsertId()
1017			honk.Donks = append(honk.Donks, &d)
1018			donkxid = d.XID
1019		}
1020	} else {
1021		xid := donkxid
1022		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1023		var donk Donk
1024		row := stmtFindFile.QueryRow(url)
1025		err := row.Scan(&donk.FileID)
1026		if err == nil {
1027			honk.Donks = append(honk.Donks, &donk)
1028		} else {
1029			log.Printf("can't find file: %s", xid)
1030		}
1031	}
1032	herd := herdofemus(honk.Noise)
1033	for _, e := range herd {
1034		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1035		if donk != nil {
1036			donk.Name = e.Name
1037			honk.Donks = append(honk.Donks, donk)
1038		}
1039	}
1040	memetize(honk)
1041
1042	if honk.Public {
1043		honk.Whofore = 2
1044	} else {
1045		honk.Whofore = 3
1046	}
1047
1048	// back to markdown
1049	honk.Noise = noise
1050
1051	if r.FormValue("preview") == "preview" {
1052		honks := []*Honk{honk}
1053		reverbolate(userinfo.UserID, honks)
1054		templinfo := getInfo(r)
1055		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1056		templinfo["Honks"] = honks
1057		templinfo["InReplyTo"] = r.FormValue("rid")
1058		templinfo["Noise"] = r.FormValue("noise")
1059		templinfo["SavedFile"] = donkxid
1060		templinfo["ServerMessage"] = "honk preview"
1061		err := readviews.Execute(w, "honkpage.html", templinfo)
1062		if err != nil {
1063			log.Print(err)
1064		}
1065		return
1066	}
1067
1068	if updatexid != "" {
1069		updatehonk(honk)
1070	} else {
1071		err := savehonk(honk)
1072		if err != nil {
1073			log.Printf("uh oh")
1074			return
1075		}
1076	}
1077
1078	// reload for consistency
1079	honk.Donks = nil
1080	donksforhonks([]*Honk{honk})
1081
1082	go honkworldwide(user, honk)
1083
1084	http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1085}
1086
1087func showhonkers(w http.ResponseWriter, r *http.Request) {
1088	userinfo := login.GetUserInfo(r)
1089	templinfo := getInfo(r)
1090	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1091	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1092	err := readviews.Execute(w, "honkers.html", templinfo)
1093	if err != nil {
1094		log.Print(err)
1095	}
1096}
1097
1098var combocache = cacheNew(func(key interface{}) (interface{}, bool) {
1099	userid := key.(int64)
1100	honkers := gethonkers(userid)
1101	var combos []string
1102	for _, h := range honkers {
1103		combos = append(combos, h.Combos...)
1104	}
1105	for i, c := range combos {
1106		if c == "-" {
1107			combos[i] = ""
1108		}
1109	}
1110	combos = oneofakind(combos)
1111	sort.Strings(combos)
1112	return combos, true
1113})
1114
1115func showcombos(w http.ResponseWriter, r *http.Request) {
1116	userinfo := login.GetUserInfo(r)
1117	var combos []string
1118	combocache.Get(userinfo.UserID, &combos)
1119	templinfo := getInfo(r)
1120	err := readviews.Execute(w, "combos.html", templinfo)
1121	if err != nil {
1122		log.Print(err)
1123	}
1124}
1125
1126func submithonker(w http.ResponseWriter, r *http.Request) {
1127	u := login.GetUserInfo(r)
1128	name := r.FormValue("name")
1129	url := r.FormValue("url")
1130	peep := r.FormValue("peep")
1131	combos := r.FormValue("combos")
1132	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1133
1134	defer combocache.Clear(u.UserID)
1135
1136	if honkerid > 0 {
1137		goodbye := r.FormValue("goodbye")
1138		if goodbye == "F" {
1139			db := opendatabase()
1140			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ?",
1141				honkerid, u.UserID)
1142			var xid string
1143			err := row.Scan(&xid)
1144			if err != nil {
1145				log.Printf("can't get honker xid: %s", err)
1146				return
1147			}
1148			log.Printf("unsubscribing from %s", xid)
1149			user, _ := butwhatabout(u.Username)
1150			go itakeitallback(user, xid)
1151			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, xid, "sub")
1152			if err != nil {
1153				log.Printf("error updating honker: %s", err)
1154				return
1155			}
1156
1157			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1158			return
1159		}
1160		combos = " " + strings.TrimSpace(combos) + " "
1161		_, err := stmtUpdateCombos.Exec(combos, honkerid, u.UserID)
1162		if err != nil {
1163			log.Printf("update honker err: %s", err)
1164			return
1165		}
1166		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1167		return
1168	}
1169
1170	flavor := "presub"
1171	if peep == "peep" {
1172		flavor = "peep"
1173	}
1174	p, err := investigate(url)
1175	if err != nil {
1176		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1177		log.Printf("failed to investigate honker")
1178		return
1179	}
1180	url = p.XID
1181	if name == "" {
1182		name = p.Handle
1183	}
1184	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1185	if err != nil {
1186		log.Print(err)
1187		return
1188	}
1189	if flavor == "presub" {
1190		user, _ := butwhatabout(u.Username)
1191		go subsub(user, url)
1192	}
1193	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1194}
1195
1196func zonkzone(w http.ResponseWriter, r *http.Request) {
1197	userinfo := login.GetUserInfo(r)
1198	rows, err := stmtGetZonkers.Query(userinfo.UserID)
1199	if err != nil {
1200		log.Printf("err: %s", err)
1201		return
1202	}
1203	defer rows.Close()
1204	var zonkers []Zonker
1205	for rows.Next() {
1206		var z Zonker
1207		rows.Scan(&z.ID, &z.Name, &z.Wherefore)
1208		zonkers = append(zonkers, z)
1209	}
1210	sort.Slice(zonkers, func(i, j int) bool {
1211		w1 := zonkers[i].Wherefore
1212		w2 := zonkers[j].Wherefore
1213		if w1 == w2 {
1214			return zonkers[i].Name < zonkers[j].Name
1215		}
1216		if w1 == "zonvoy" {
1217			w1 = "zzzzzzz"
1218		}
1219		if w2 == "zonvoy" {
1220			w2 = "zzzzzzz"
1221		}
1222		return w1 < w2
1223	})
1224
1225	templinfo := getInfo(r)
1226	templinfo["Zonkers"] = zonkers
1227	templinfo["ZonkCSRF"] = login.GetCSRF("zonkzonk", r)
1228	err = readviews.Execute(w, "zonkers.html", templinfo)
1229	if err != nil {
1230		log.Print(err)
1231	}
1232}
1233
1234func zonkzonk(w http.ResponseWriter, r *http.Request) {
1235	userinfo := login.GetUserInfo(r)
1236	itsok := r.FormValue("itsok")
1237	if itsok == "iforgiveyou" {
1238		zonkerid, _ := strconv.ParseInt(r.FormValue("zonkerid"), 10, 0)
1239		db := opendatabase()
1240		db.Exec("delete from zonkers where userid = ? and zonkerid = ?",
1241			userinfo.UserID, zonkerid)
1242		bitethethumbs()
1243		http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1244		return
1245	}
1246	wherefore := r.FormValue("wherefore")
1247	name := r.FormValue("name")
1248	if name == "" {
1249		return
1250	}
1251	switch wherefore {
1252	case "zonker":
1253	case "zomain":
1254	case "zonvoy":
1255	case "zord":
1256	case "zilence":
1257	default:
1258		return
1259	}
1260	db := opendatabase()
1261	db.Exec("insert into zonkers (userid, name, wherefore) values (?, ?, ?)",
1262		userinfo.UserID, name, wherefore)
1263	if wherefore == "zonker" || wherefore == "zomain" || wherefore == "zord" || wherefore == "zilence" {
1264		bitethethumbs()
1265	}
1266
1267	http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1268}
1269
1270func accountpage(w http.ResponseWriter, r *http.Request) {
1271	u := login.GetUserInfo(r)
1272	user, _ := butwhatabout(u.Username)
1273	templinfo := getInfo(r)
1274	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1275	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1276	templinfo["User"] = user
1277	err := readviews.Execute(w, "account.html", templinfo)
1278	if err != nil {
1279		log.Print(err)
1280	}
1281}
1282
1283func dochpass(w http.ResponseWriter, r *http.Request) {
1284	err := login.ChangePassword(w, r)
1285	if err != nil {
1286		log.Printf("error changing password: %s", err)
1287	}
1288	http.Redirect(w, r, "/account", http.StatusSeeOther)
1289}
1290
1291func fingerlicker(w http.ResponseWriter, r *http.Request) {
1292	orig := r.FormValue("resource")
1293
1294	log.Printf("finger lick: %s", orig)
1295
1296	if strings.HasPrefix(orig, "acct:") {
1297		orig = orig[5:]
1298	}
1299
1300	name := orig
1301	idx := strings.LastIndexByte(name, '/')
1302	if idx != -1 {
1303		name = name[idx+1:]
1304		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1305			log.Printf("foreign request rejected")
1306			name = ""
1307		}
1308	} else {
1309		idx = strings.IndexByte(name, '@')
1310		if idx != -1 {
1311			name = name[:idx]
1312			if name+"@"+serverName != orig {
1313				log.Printf("foreign request rejected")
1314				name = ""
1315			}
1316		}
1317	}
1318	user, err := butwhatabout(name)
1319	if err != nil {
1320		http.NotFound(w, r)
1321		return
1322	}
1323	if stealthmode(user.ID, r) {
1324		http.NotFound(w, r)
1325		return
1326	}
1327
1328	j := junk.New()
1329	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1330	j["aliases"] = []string{user.URL}
1331	var links []junk.Junk
1332	l := junk.New()
1333	l["rel"] = "self"
1334	l["type"] = `application/activity+json`
1335	l["href"] = user.URL
1336	links = append(links, l)
1337	j["links"] = links
1338
1339	w.Header().Set("Cache-Control", "max-age=3600")
1340	w.Header().Set("Content-Type", "application/jrd+json")
1341	j.Write(w)
1342}
1343
1344func somedays() string {
1345	secs := 432000 + notrand.Int63n(432000)
1346	return fmt.Sprintf("%d", secs)
1347}
1348
1349func avatate(w http.ResponseWriter, r *http.Request) {
1350	n := r.FormValue("a")
1351	a := avatar(n)
1352	w.Header().Set("Cache-Control", "max-age="+somedays())
1353	w.Write(a)
1354}
1355
1356func servecss(w http.ResponseWriter, r *http.Request) {
1357	fd, err := os.Open("views" + r.URL.Path)
1358	if err != nil {
1359		http.NotFound(w, r)
1360		return
1361	}
1362	w.Header().Set("Cache-Control", "max-age=0")
1363	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1364	err = css.Filter(fd, w)
1365	if err != nil {
1366		log.Printf("error filtering css: %s", err)
1367	}
1368}
1369func serveasset(w http.ResponseWriter, r *http.Request) {
1370	w.Header().Set("Cache-Control", "max-age=7776000")
1371	http.ServeFile(w, r, "views"+r.URL.Path)
1372}
1373func servehtml(w http.ResponseWriter, r *http.Request) {
1374	templinfo := getInfo(r)
1375	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1376	if err != nil {
1377		log.Print(err)
1378	}
1379}
1380func serveemu(w http.ResponseWriter, r *http.Request) {
1381	xid := mux.Vars(r)["xid"]
1382	w.Header().Set("Cache-Control", "max-age="+somedays())
1383	http.ServeFile(w, r, "emus/"+xid)
1384}
1385func servememe(w http.ResponseWriter, r *http.Request) {
1386	xid := mux.Vars(r)["xid"]
1387	w.Header().Set("Cache-Control", "max-age="+somedays())
1388	http.ServeFile(w, r, "memes/"+xid)
1389}
1390
1391func servefile(w http.ResponseWriter, r *http.Request) {
1392	xid := mux.Vars(r)["xid"]
1393	row := stmtFileData.QueryRow(xid)
1394	var media string
1395	var data []byte
1396	err := row.Scan(&media, &data)
1397	if err != nil {
1398		log.Printf("error loading file: %s", err)
1399		http.NotFound(w, r)
1400		return
1401	}
1402	w.Header().Set("Content-Type", media)
1403	w.Header().Set("X-Content-Type-Options", "nosniff")
1404	w.Header().Set("Cache-Control", "max-age="+somedays())
1405	w.Write(data)
1406}
1407
1408func nomoroboto(w http.ResponseWriter, r *http.Request) {
1409	io.WriteString(w, "User-agent: *\n")
1410	io.WriteString(w, "Disallow: /a\n")
1411	io.WriteString(w, "Disallow: /d\n")
1412	io.WriteString(w, "Disallow: /meme\n")
1413	for _, u := range allusers() {
1414		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1415	}
1416}
1417
1418func webhydra(w http.ResponseWriter, r *http.Request) {
1419	u := login.GetUserInfo(r)
1420	userid := u.UserID
1421	templinfo := getInfo(r)
1422	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1423	page := r.FormValue("page")
1424	var honks []*Honk
1425	switch page {
1426	case "atme":
1427		honks = gethonksforme(userid)
1428	case "home":
1429		honks = gethonksforuser(userid)
1430		honks = osmosis(honks, userid)
1431	case "first":
1432		honks = gethonksforuserfirstclass(userid)
1433		honks = osmosis(honks, userid)
1434	case "combo":
1435		c := r.FormValue("c")
1436		honks = gethonksbycombo(userid, c)
1437	case "convoy":
1438		c := r.FormValue("c")
1439		honks = gethonksbyconvoy(userid, c)
1440	default:
1441		http.NotFound(w, r)
1442	}
1443	if len(honks) > 0 {
1444		templinfo["TopXID"] = honks[0].XID
1445	}
1446	if topxid := r.FormValue("topxid"); topxid != "" {
1447		for i, h := range honks {
1448			if h.XID == topxid {
1449				honks = honks[0:i]
1450				break
1451			}
1452		}
1453		log.Printf("topxid %d frags", len(honks))
1454	}
1455	reverbolate(userid, honks)
1456	templinfo["Honks"] = honks
1457	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1458	err := readviews.Execute(w, "honkfrags.html", templinfo)
1459	if err != nil {
1460		log.Printf("frag error: %s", err)
1461	}
1462}
1463
1464func serve() {
1465	db := opendatabase()
1466	login.Init(db)
1467
1468	listener, err := openListener()
1469	if err != nil {
1470		log.Fatal(err)
1471	}
1472	go redeliverator()
1473
1474	debug := false
1475	getconfig("debug", &debug)
1476	readviews = templates.Load(debug,
1477		"views/honkpage.html",
1478		"views/honkfrags.html",
1479		"views/honkers.html",
1480		"views/zonkers.html",
1481		"views/combos.html",
1482		"views/honkform.html",
1483		"views/honk.html",
1484		"views/account.html",
1485		"views/about.html",
1486		"views/funzone.html",
1487		"views/login.html",
1488		"views/xzone.html",
1489		"views/header.html",
1490		"views/onts.html",
1491		"views/honkpage.js",
1492	)
1493	if !debug {
1494		assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1495		for _, s := range assets {
1496			savedassetparams[s] = getassetparam(s)
1497		}
1498	}
1499
1500	bitethethumbs()
1501
1502	mux := mux.NewRouter()
1503	mux.Use(login.Checker)
1504
1505	posters := mux.Methods("POST").Subrouter()
1506	getters := mux.Methods("GET").Subrouter()
1507
1508	getters.HandleFunc("/", homepage)
1509	getters.HandleFunc("/home", homepage)
1510	getters.HandleFunc("/front", homepage)
1511	getters.HandleFunc("/robots.txt", nomoroboto)
1512	getters.HandleFunc("/rss", showrss)
1513	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1514	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1515	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1516	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1517	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1518	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1519	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1520	getters.HandleFunc("/a", avatate)
1521	getters.HandleFunc("/o", thelistingoftheontologies)
1522	getters.HandleFunc("/o/{name:.+}", showontology)
1523	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1524	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1525	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1526	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1527
1528	getters.HandleFunc("/style.css", servecss)
1529	getters.HandleFunc("/local.css", servecss)
1530	getters.HandleFunc("/honkpage.js", serveasset)
1531	getters.HandleFunc("/about", servehtml)
1532	getters.HandleFunc("/login", servehtml)
1533	posters.HandleFunc("/dologin", login.LoginFunc)
1534	getters.HandleFunc("/logout", login.LogoutFunc)
1535
1536	loggedin := mux.NewRoute().Subrouter()
1537	loggedin.Use(login.Required)
1538	loggedin.HandleFunc("/account", accountpage)
1539	loggedin.HandleFunc("/funzone", showfunzone)
1540	loggedin.HandleFunc("/chpass", dochpass)
1541	loggedin.HandleFunc("/atme", homepage)
1542	loggedin.HandleFunc("/zonkzone", zonkzone)
1543	loggedin.HandleFunc("/xzone", xzone)
1544	loggedin.HandleFunc("/edit", edithonkpage)
1545	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1546	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1547	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1548	loggedin.Handle("/zonkzonk", login.CSRFWrap("zonkzonk", http.HandlerFunc(zonkzonk)))
1549	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1550	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1551	loggedin.HandleFunc("/honkers", showhonkers)
1552	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1553	loggedin.HandleFunc("/h", showhonker)
1554	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1555	loggedin.HandleFunc("/c", showcombos)
1556	loggedin.HandleFunc("/t", showconvoy)
1557	loggedin.HandleFunc("/q", showsearch)
1558	loggedin.HandleFunc("/hydra", webhydra)
1559	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1560
1561	err = http.Serve(listener, mux)
1562	if err != nil {
1563		log.Fatal(err)
1564	}
1565}