all repos — honk @ 96eeaa709ef0b41e182c73f7c0133277dc62df01

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			fileid, err := savefile(xid, name, desc, url, media, true, data)
1011			if err != nil {
1012				log.Printf("unable to save image: %s", err)
1013				return
1014			}
1015			var d Donk
1016			d.FileID = fileid
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	placename := r.FormValue("placename")
1043	placelat := r.FormValue("placelat")
1044	placelong := r.FormValue("placelong")
1045	if placename != "" || placelat != "" || placelong != "" {
1046		p := new(Place)
1047		p.Name = placename
1048		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1049		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1050		p.Url = r.FormValue("placeurl")
1051		honk.Place = p
1052	}
1053
1054	if honk.Public {
1055		honk.Whofore = 2
1056	} else {
1057		honk.Whofore = 3
1058	}
1059
1060	// back to markdown
1061	honk.Noise = noise
1062
1063	if r.FormValue("preview") == "preview" {
1064		honks := []*Honk{honk}
1065		reverbolate(userinfo.UserID, honks)
1066		templinfo := getInfo(r)
1067		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1068		templinfo["Honks"] = honks
1069		templinfo["InReplyTo"] = r.FormValue("rid")
1070		templinfo["Noise"] = r.FormValue("noise")
1071		templinfo["SavedFile"] = donkxid
1072		templinfo["ServerMessage"] = "honk preview"
1073		err := readviews.Execute(w, "honkpage.html", templinfo)
1074		if err != nil {
1075			log.Print(err)
1076		}
1077		return
1078	}
1079
1080	if updatexid != "" {
1081		updatehonk(honk)
1082	} else {
1083		err := savehonk(honk)
1084		if err != nil {
1085			log.Printf("uh oh")
1086			return
1087		}
1088	}
1089
1090	// reload for consistency
1091	honk.Donks = nil
1092	donksforhonks([]*Honk{honk})
1093
1094	go honkworldwide(user, honk)
1095
1096	http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1097}
1098
1099func showhonkers(w http.ResponseWriter, r *http.Request) {
1100	userinfo := login.GetUserInfo(r)
1101	templinfo := getInfo(r)
1102	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1103	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1104	err := readviews.Execute(w, "honkers.html", templinfo)
1105	if err != nil {
1106		log.Print(err)
1107	}
1108}
1109
1110var combocache = cacheNew(func(key interface{}) (interface{}, bool) {
1111	userid := key.(int64)
1112	honkers := gethonkers(userid)
1113	var combos []string
1114	for _, h := range honkers {
1115		combos = append(combos, h.Combos...)
1116	}
1117	for i, c := range combos {
1118		if c == "-" {
1119			combos[i] = ""
1120		}
1121	}
1122	combos = oneofakind(combos)
1123	sort.Strings(combos)
1124	return combos, true
1125})
1126
1127func showcombos(w http.ResponseWriter, r *http.Request) {
1128	userinfo := login.GetUserInfo(r)
1129	var combos []string
1130	combocache.Get(userinfo.UserID, &combos)
1131	templinfo := getInfo(r)
1132	err := readviews.Execute(w, "combos.html", templinfo)
1133	if err != nil {
1134		log.Print(err)
1135	}
1136}
1137
1138func submithonker(w http.ResponseWriter, r *http.Request) {
1139	u := login.GetUserInfo(r)
1140	name := r.FormValue("name")
1141	url := r.FormValue("url")
1142	peep := r.FormValue("peep")
1143	combos := r.FormValue("combos")
1144	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1145
1146	defer combocache.Clear(u.UserID)
1147
1148	if honkerid > 0 {
1149		goodbye := r.FormValue("goodbye")
1150		if goodbye == "F" {
1151			db := opendatabase()
1152			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ?",
1153				honkerid, u.UserID)
1154			var xid string
1155			err := row.Scan(&xid)
1156			if err != nil {
1157				log.Printf("can't get honker xid: %s", err)
1158				return
1159			}
1160			log.Printf("unsubscribing from %s", xid)
1161			user, _ := butwhatabout(u.Username)
1162			go itakeitallback(user, xid)
1163			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, xid, "sub")
1164			if err != nil {
1165				log.Printf("error updating honker: %s", err)
1166				return
1167			}
1168
1169			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1170			return
1171		}
1172		combos = " " + strings.TrimSpace(combos) + " "
1173		_, err := stmtUpdateCombos.Exec(combos, honkerid, u.UserID)
1174		if err != nil {
1175			log.Printf("update honker err: %s", err)
1176			return
1177		}
1178		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1179		return
1180	}
1181
1182	flavor := "presub"
1183	if peep == "peep" {
1184		flavor = "peep"
1185	}
1186	p, err := investigate(url)
1187	if err != nil {
1188		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1189		log.Printf("failed to investigate honker")
1190		return
1191	}
1192	url = p.XID
1193	if name == "" {
1194		name = p.Handle
1195	}
1196	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1197	if err != nil {
1198		log.Print(err)
1199		return
1200	}
1201	if flavor == "presub" {
1202		user, _ := butwhatabout(u.Username)
1203		go subsub(user, url)
1204	}
1205	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1206}
1207
1208func zonkzone(w http.ResponseWriter, r *http.Request) {
1209	userinfo := login.GetUserInfo(r)
1210	rows, err := stmtGetZonkers.Query(userinfo.UserID)
1211	if err != nil {
1212		log.Printf("err: %s", err)
1213		return
1214	}
1215	defer rows.Close()
1216	var zonkers []Zonker
1217	for rows.Next() {
1218		var z Zonker
1219		rows.Scan(&z.ID, &z.Name, &z.Wherefore)
1220		zonkers = append(zonkers, z)
1221	}
1222	sort.Slice(zonkers, func(i, j int) bool {
1223		w1 := zonkers[i].Wherefore
1224		w2 := zonkers[j].Wherefore
1225		if w1 == w2 {
1226			return zonkers[i].Name < zonkers[j].Name
1227		}
1228		if w1 == "zonvoy" {
1229			w1 = "zzzzzzz"
1230		}
1231		if w2 == "zonvoy" {
1232			w2 = "zzzzzzz"
1233		}
1234		return w1 < w2
1235	})
1236
1237	templinfo := getInfo(r)
1238	templinfo["Zonkers"] = zonkers
1239	templinfo["ZonkCSRF"] = login.GetCSRF("zonkzonk", r)
1240	err = readviews.Execute(w, "zonkers.html", templinfo)
1241	if err != nil {
1242		log.Print(err)
1243	}
1244}
1245
1246func zonkzonk(w http.ResponseWriter, r *http.Request) {
1247	userinfo := login.GetUserInfo(r)
1248	itsok := r.FormValue("itsok")
1249	if itsok == "iforgiveyou" {
1250		zonkerid, _ := strconv.ParseInt(r.FormValue("zonkerid"), 10, 0)
1251		db := opendatabase()
1252		db.Exec("delete from zonkers where userid = ? and zonkerid = ?",
1253			userinfo.UserID, zonkerid)
1254		bitethethumbs()
1255		http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1256		return
1257	}
1258	wherefore := r.FormValue("wherefore")
1259	name := r.FormValue("name")
1260	if name == "" {
1261		return
1262	}
1263	switch wherefore {
1264	case "zonker":
1265	case "zomain":
1266	case "zonvoy":
1267	case "zord":
1268	case "zilence":
1269	case "zoggle":
1270	default:
1271		return
1272	}
1273	db := opendatabase()
1274	db.Exec("insert into zonkers (userid, name, wherefore) values (?, ?, ?)",
1275		userinfo.UserID, name, wherefore)
1276
1277	if wherefore != "zonvoy" {
1278		bitethethumbs()
1279	}
1280
1281	http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1282}
1283
1284func accountpage(w http.ResponseWriter, r *http.Request) {
1285	u := login.GetUserInfo(r)
1286	user, _ := butwhatabout(u.Username)
1287	templinfo := getInfo(r)
1288	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1289	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1290	templinfo["User"] = user
1291	err := readviews.Execute(w, "account.html", templinfo)
1292	if err != nil {
1293		log.Print(err)
1294	}
1295}
1296
1297func dochpass(w http.ResponseWriter, r *http.Request) {
1298	err := login.ChangePassword(w, r)
1299	if err != nil {
1300		log.Printf("error changing password: %s", err)
1301	}
1302	http.Redirect(w, r, "/account", http.StatusSeeOther)
1303}
1304
1305func fingerlicker(w http.ResponseWriter, r *http.Request) {
1306	orig := r.FormValue("resource")
1307
1308	log.Printf("finger lick: %s", orig)
1309
1310	if strings.HasPrefix(orig, "acct:") {
1311		orig = orig[5:]
1312	}
1313
1314	name := orig
1315	idx := strings.LastIndexByte(name, '/')
1316	if idx != -1 {
1317		name = name[idx+1:]
1318		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1319			log.Printf("foreign request rejected")
1320			name = ""
1321		}
1322	} else {
1323		idx = strings.IndexByte(name, '@')
1324		if idx != -1 {
1325			name = name[:idx]
1326			if name+"@"+serverName != orig {
1327				log.Printf("foreign request rejected")
1328				name = ""
1329			}
1330		}
1331	}
1332	user, err := butwhatabout(name)
1333	if err != nil {
1334		http.NotFound(w, r)
1335		return
1336	}
1337	if stealthmode(user.ID, r) {
1338		http.NotFound(w, r)
1339		return
1340	}
1341
1342	j := junk.New()
1343	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1344	j["aliases"] = []string{user.URL}
1345	var links []junk.Junk
1346	l := junk.New()
1347	l["rel"] = "self"
1348	l["type"] = `application/activity+json`
1349	l["href"] = user.URL
1350	links = append(links, l)
1351	j["links"] = links
1352
1353	w.Header().Set("Cache-Control", "max-age=3600")
1354	w.Header().Set("Content-Type", "application/jrd+json")
1355	j.Write(w)
1356}
1357
1358func somedays() string {
1359	secs := 432000 + notrand.Int63n(432000)
1360	return fmt.Sprintf("%d", secs)
1361}
1362
1363func avatate(w http.ResponseWriter, r *http.Request) {
1364	n := r.FormValue("a")
1365	a := avatar(n)
1366	w.Header().Set("Cache-Control", "max-age="+somedays())
1367	w.Write(a)
1368}
1369
1370func servecss(w http.ResponseWriter, r *http.Request) {
1371	fd, err := os.Open("views" + r.URL.Path)
1372	if err != nil {
1373		http.NotFound(w, r)
1374		return
1375	}
1376	w.Header().Set("Cache-Control", "max-age=0")
1377	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1378	err = css.Filter(fd, w)
1379	if err != nil {
1380		log.Printf("error filtering css: %s", err)
1381	}
1382}
1383func serveasset(w http.ResponseWriter, r *http.Request) {
1384	w.Header().Set("Cache-Control", "max-age=7776000")
1385	http.ServeFile(w, r, "views"+r.URL.Path)
1386}
1387func servehtml(w http.ResponseWriter, r *http.Request) {
1388	templinfo := getInfo(r)
1389	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1390	if err != nil {
1391		log.Print(err)
1392	}
1393}
1394func serveemu(w http.ResponseWriter, r *http.Request) {
1395	xid := mux.Vars(r)["xid"]
1396	w.Header().Set("Cache-Control", "max-age="+somedays())
1397	http.ServeFile(w, r, "emus/"+xid)
1398}
1399func servememe(w http.ResponseWriter, r *http.Request) {
1400	xid := mux.Vars(r)["xid"]
1401	w.Header().Set("Cache-Control", "max-age="+somedays())
1402	http.ServeFile(w, r, "memes/"+xid)
1403}
1404
1405func servefile(w http.ResponseWriter, r *http.Request) {
1406	xid := mux.Vars(r)["xid"]
1407	row := stmtGetFileData.QueryRow(xid)
1408	var media string
1409	var data []byte
1410	err := row.Scan(&media, &data)
1411	if err != nil {
1412		log.Printf("error loading file: %s", err)
1413		http.NotFound(w, r)
1414		return
1415	}
1416	w.Header().Set("Content-Type", media)
1417	w.Header().Set("X-Content-Type-Options", "nosniff")
1418	w.Header().Set("Cache-Control", "max-age="+somedays())
1419	w.Write(data)
1420}
1421
1422func nomoroboto(w http.ResponseWriter, r *http.Request) {
1423	io.WriteString(w, "User-agent: *\n")
1424	io.WriteString(w, "Disallow: /a\n")
1425	io.WriteString(w, "Disallow: /d\n")
1426	io.WriteString(w, "Disallow: /meme\n")
1427	for _, u := range allusers() {
1428		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1429	}
1430}
1431
1432func webhydra(w http.ResponseWriter, r *http.Request) {
1433	u := login.GetUserInfo(r)
1434	userid := u.UserID
1435	templinfo := getInfo(r)
1436	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1437	page := r.FormValue("page")
1438	var honks []*Honk
1439	switch page {
1440	case "atme":
1441		honks = gethonksforme(userid)
1442	case "home":
1443		honks = gethonksforuser(userid)
1444		honks = osmosis(honks, userid)
1445	case "first":
1446		honks = gethonksforuserfirstclass(userid)
1447		honks = osmosis(honks, userid)
1448	case "combo":
1449		c := r.FormValue("c")
1450		honks = gethonksbycombo(userid, c)
1451	case "convoy":
1452		c := r.FormValue("c")
1453		honks = gethonksbyconvoy(userid, c)
1454	default:
1455		http.NotFound(w, r)
1456	}
1457	if len(honks) > 0 {
1458		templinfo["TopXID"] = honks[0].XID
1459	}
1460	if topxid := r.FormValue("topxid"); topxid != "" {
1461		for i, h := range honks {
1462			if h.XID == topxid {
1463				honks = honks[0:i]
1464				break
1465			}
1466		}
1467		log.Printf("topxid %d frags", len(honks))
1468	}
1469	reverbolate(userid, honks)
1470	templinfo["Honks"] = honks
1471	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1472	err := readviews.Execute(w, "honkfrags.html", templinfo)
1473	if err != nil {
1474		log.Printf("frag error: %s", err)
1475	}
1476}
1477
1478func serve() {
1479	db := opendatabase()
1480	login.Init(db)
1481
1482	listener, err := openListener()
1483	if err != nil {
1484		log.Fatal(err)
1485	}
1486	go redeliverator()
1487
1488	debug := false
1489	getconfig("debug", &debug)
1490	readviews = templates.Load(debug,
1491		"views/honkpage.html",
1492		"views/honkfrags.html",
1493		"views/honkers.html",
1494		"views/zonkers.html",
1495		"views/combos.html",
1496		"views/honkform.html",
1497		"views/honk.html",
1498		"views/account.html",
1499		"views/about.html",
1500		"views/funzone.html",
1501		"views/login.html",
1502		"views/xzone.html",
1503		"views/header.html",
1504		"views/onts.html",
1505		"views/honkpage.js",
1506	)
1507	if !debug {
1508		assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1509		for _, s := range assets {
1510			savedassetparams[s] = getassetparam(s)
1511		}
1512	}
1513
1514	bitethethumbs()
1515
1516	mux := mux.NewRouter()
1517	mux.Use(login.Checker)
1518
1519	posters := mux.Methods("POST").Subrouter()
1520	getters := mux.Methods("GET").Subrouter()
1521
1522	getters.HandleFunc("/", homepage)
1523	getters.HandleFunc("/home", homepage)
1524	getters.HandleFunc("/front", homepage)
1525	getters.HandleFunc("/robots.txt", nomoroboto)
1526	getters.HandleFunc("/rss", showrss)
1527	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1528	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1529	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1530	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1531	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1532	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1533	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1534	getters.HandleFunc("/a", avatate)
1535	getters.HandleFunc("/o", thelistingoftheontologies)
1536	getters.HandleFunc("/o/{name:.+}", showontology)
1537	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1538	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1539	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1540	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1541
1542	getters.HandleFunc("/style.css", servecss)
1543	getters.HandleFunc("/local.css", servecss)
1544	getters.HandleFunc("/honkpage.js", serveasset)
1545	getters.HandleFunc("/about", servehtml)
1546	getters.HandleFunc("/login", servehtml)
1547	posters.HandleFunc("/dologin", login.LoginFunc)
1548	getters.HandleFunc("/logout", login.LogoutFunc)
1549
1550	loggedin := mux.NewRoute().Subrouter()
1551	loggedin.Use(login.Required)
1552	loggedin.HandleFunc("/account", accountpage)
1553	loggedin.HandleFunc("/funzone", showfunzone)
1554	loggedin.HandleFunc("/chpass", dochpass)
1555	loggedin.HandleFunc("/atme", homepage)
1556	loggedin.HandleFunc("/zonkzone", zonkzone)
1557	loggedin.HandleFunc("/xzone", xzone)
1558	loggedin.HandleFunc("/edit", edithonkpage)
1559	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1560	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1561	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1562	loggedin.Handle("/zonkzonk", login.CSRFWrap("zonkzonk", http.HandlerFunc(zonkzonk)))
1563	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1564	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1565	loggedin.HandleFunc("/honkers", showhonkers)
1566	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1567	loggedin.HandleFunc("/h", showhonker)
1568	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1569	loggedin.HandleFunc("/c", showcombos)
1570	loggedin.HandleFunc("/t", showconvoy)
1571	loggedin.HandleFunc("/q", showsearch)
1572	loggedin.HandleFunc("/hydra", webhydra)
1573	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1574
1575	err = http.Serve(listener, mux)
1576	if err != nil {
1577		log.Fatal(err)
1578	}
1579}