all repos — honk @ f7bd1d575517bc3e6c312d5a1f112323c2207673

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