all repos — honk @ d68f92598e63effde3bfcc0af7de626104dc7e6b

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 xonksaver(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 xonksaver(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 := xonksaver(user, j, originate(xid))
 400	convoy := ""
 401	if xonk != nil {
 402		convoy = xonk.Convoy
 403	}
 404	http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
 405}
 406
 407func xzone(w http.ResponseWriter, r *http.Request) {
 408	u := login.GetUserInfo(r)
 409	rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
 410	if err != nil {
 411		log.Printf("query err: %s", err)
 412		return
 413	}
 414	defer rows.Close()
 415	var honkers []Honker
 416	for rows.Next() {
 417		var xid string
 418		rows.Scan(&xid)
 419		honkers = append(honkers, Honker{XID: xid})
 420	}
 421	rows.Close()
 422	for i, _ := range honkers {
 423		_, honkers[i].Handle = handles(honkers[i].XID)
 424	}
 425	templinfo := getInfo(r)
 426	templinfo["XCSRF"] = login.GetCSRF("ximport", r)
 427	templinfo["Honkers"] = honkers
 428	err = readviews.Execute(w, "xzone.html", templinfo)
 429	if err != nil {
 430		log.Print(err)
 431	}
 432}
 433
 434func outbox(w http.ResponseWriter, r *http.Request) {
 435	name := mux.Vars(r)["name"]
 436	user, err := butwhatabout(name)
 437	if err != nil {
 438		http.NotFound(w, r)
 439		return
 440	}
 441	if stealthmode(user.ID, r) {
 442		http.NotFound(w, r)
 443		return
 444	}
 445
 446	honks := gethonksbyuser(name, false)
 447	if len(honks) > 20 {
 448		honks = honks[0:20]
 449	}
 450
 451	var jonks []junk.Junk
 452	for _, h := range honks {
 453		j, _ := jonkjonk(user, h)
 454		jonks = append(jonks, j)
 455	}
 456
 457	j := junk.New()
 458	j["@context"] = itiswhatitis
 459	j["id"] = user.URL + "/outbox"
 460	j["type"] = "OrderedCollection"
 461	j["totalItems"] = len(jonks)
 462	j["orderedItems"] = jonks
 463
 464	w.Header().Set("Content-Type", theonetruename)
 465	j.Write(w)
 466}
 467
 468func emptiness(w http.ResponseWriter, r *http.Request) {
 469	name := mux.Vars(r)["name"]
 470	user, err := butwhatabout(name)
 471	if err != nil {
 472		http.NotFound(w, r)
 473		return
 474	}
 475	if stealthmode(user.ID, r) {
 476		http.NotFound(w, r)
 477		return
 478	}
 479	colname := "/followers"
 480	if strings.HasSuffix(r.URL.Path, "/following") {
 481		colname = "/following"
 482	}
 483	j := junk.New()
 484	j["@context"] = itiswhatitis
 485	j["id"] = user.URL + colname
 486	j["type"] = "OrderedCollection"
 487	j["totalItems"] = 0
 488	j["orderedItems"] = []junk.Junk{}
 489
 490	w.Header().Set("Content-Type", theonetruename)
 491	j.Write(w)
 492}
 493
 494func showuser(w http.ResponseWriter, r *http.Request) {
 495	name := mux.Vars(r)["name"]
 496	user, err := butwhatabout(name)
 497	if err != nil {
 498		log.Printf("user not found %s: %s", name, err)
 499		http.NotFound(w, r)
 500		return
 501	}
 502	if stealthmode(user.ID, r) {
 503		http.NotFound(w, r)
 504		return
 505	}
 506	if friendorfoe(r.Header.Get("Accept")) {
 507		j := asjonker(user)
 508		w.Header().Set("Content-Type", theonetruename)
 509		j.Write(w)
 510		return
 511	}
 512	u := login.GetUserInfo(r)
 513	honks := gethonksbyuser(name, u != nil && u.Username == name)
 514	templinfo := getInfo(r)
 515	filt := htfilter.New()
 516	templinfo["Name"] = user.Name
 517	whatabout := user.About
 518	whatabout = obfusbreak(user.About)
 519	templinfo["WhatAbout"], _ = filt.String(whatabout)
 520	templinfo["ServerMessage"] = ""
 521	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 522	honkpage(w, u, honks, templinfo)
 523}
 524
 525func showhonker(w http.ResponseWriter, r *http.Request) {
 526	u := login.GetUserInfo(r)
 527	name := mux.Vars(r)["name"]
 528	var honks []*Honk
 529	if name == "" {
 530		name = r.FormValue("xid")
 531		honks = gethonksbyxonker(u.UserID, name)
 532	} else {
 533		honks = gethonksbyhonker(u.UserID, name)
 534	}
 535	name = html.EscapeString(name)
 536	msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, name, name)
 537	templinfo := getInfo(r)
 538	templinfo["PageName"] = "honker"
 539	templinfo["ServerMessage"] = template.HTML(msg)
 540	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 541	honkpage(w, u, honks, templinfo)
 542}
 543
 544func showcombo(w http.ResponseWriter, r *http.Request) {
 545	name := mux.Vars(r)["name"]
 546	u := login.GetUserInfo(r)
 547	honks := gethonksbycombo(u.UserID, name)
 548	honks = osmosis(honks, u.UserID)
 549	templinfo := getInfo(r)
 550	templinfo["PageName"] = "combo"
 551	templinfo["PageArg"] = "name"
 552	templinfo["ServerMessage"] = "honks by combo: " + name
 553	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 554	if len(honks) > 0 {
 555		templinfo["TopXID"] = honks[0].XID
 556	}
 557	honkpage(w, u, honks, templinfo)
 558}
 559func showconvoy(w http.ResponseWriter, r *http.Request) {
 560	c := r.FormValue("c")
 561	u := login.GetUserInfo(r)
 562	honks := gethonksbyconvoy(u.UserID, c)
 563	templinfo := getInfo(r)
 564	templinfo["ServerMessage"] = "honks in convoy: " + c
 565	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 566	honkpage(w, u, honks, templinfo)
 567}
 568func showsearch(w http.ResponseWriter, r *http.Request) {
 569	q := r.FormValue("q")
 570	u := login.GetUserInfo(r)
 571	honks := gethonksbysearch(u.UserID, q)
 572	templinfo := getInfo(r)
 573	templinfo["ServerMessage"] = "honks for search: " + q
 574	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 575	honkpage(w, u, honks, templinfo)
 576}
 577func showontology(w http.ResponseWriter, r *http.Request) {
 578	name := mux.Vars(r)["name"]
 579	u := login.GetUserInfo(r)
 580	var userid int64 = -1
 581	if u != nil {
 582		userid = u.UserID
 583	}
 584	honks := gethonksbyontology(userid, "#"+name)
 585	templinfo := getInfo(r)
 586	templinfo["ServerMessage"] = "honks by ontology: " + name
 587	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 588	honkpage(w, u, honks, templinfo)
 589}
 590
 591func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 592	u := login.GetUserInfo(r)
 593	var userid int64 = -1
 594	if u != nil {
 595		userid = u.UserID
 596	}
 597	rows, err := stmtSelectOnts.Query(userid)
 598	if err != nil {
 599		log.Printf("selection error: %s", err)
 600		return
 601	}
 602	defer rows.Close()
 603	var onts [][]string
 604	for rows.Next() {
 605		var o string
 606		err := rows.Scan(&o)
 607		if err != nil {
 608			log.Printf("error scanning ont: %s", err)
 609			continue
 610		}
 611		onts = append(onts, []string{o, o[1:]})
 612	}
 613	if u == nil {
 614		w.Header().Set("Cache-Control", "max-age=300")
 615	}
 616	templinfo := getInfo(r)
 617	templinfo["Onts"] = onts
 618	err = readviews.Execute(w, "onts.html", templinfo)
 619	if err != nil {
 620		log.Print(err)
 621	}
 622}
 623
 624func showhonk(w http.ResponseWriter, r *http.Request) {
 625	name := mux.Vars(r)["name"]
 626	user, err := butwhatabout(name)
 627	if err != nil {
 628		http.NotFound(w, r)
 629		return
 630	}
 631	if stealthmode(user.ID, r) {
 632		http.NotFound(w, r)
 633		return
 634	}
 635
 636	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
 637	honk := getxonk(user.ID, xid)
 638	if honk == nil {
 639		http.NotFound(w, r)
 640		return
 641	}
 642	u := login.GetUserInfo(r)
 643	if u != nil && u.UserID != user.ID {
 644		u = nil
 645	}
 646	if !honk.Public {
 647		if u == nil {
 648			http.NotFound(w, r)
 649			return
 650
 651		}
 652		templinfo := getInfo(r)
 653		templinfo["ServerMessage"] = "one honk maybe more"
 654		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 655		honkpage(w, u, []*Honk{honk}, templinfo)
 656		return
 657	}
 658	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
 659	if friendorfoe(r.Header.Get("Accept")) {
 660		for _, h := range rawhonks {
 661			if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
 662				honk.Replies = append(honk.Replies, h)
 663			}
 664		}
 665		donksforhonks([]*Honk{honk})
 666		_, j := jonkjonk(user, honk)
 667		j["@context"] = itiswhatitis
 668		w.Header().Set("Content-Type", theonetruename)
 669		j.Write(w)
 670		return
 671	}
 672	var honks []*Honk
 673	for _, h := range rawhonks {
 674		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
 675			honks = append(honks, h)
 676		}
 677	}
 678
 679	templinfo := getInfo(r)
 680	templinfo["ServerMessage"] = "one honk maybe more"
 681	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 682	honkpage(w, u, honks, templinfo)
 683}
 684
 685func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
 686	var userid int64 = -1
 687	if u != nil {
 688		userid = u.UserID
 689	}
 690	if u == nil {
 691		w.Header().Set("Cache-Control", "max-age=60")
 692	}
 693	reverbolate(userid, honks)
 694	templinfo["Honks"] = honks
 695	err := readviews.Execute(w, "honkpage.html", templinfo)
 696	if err != nil {
 697		log.Print(err)
 698	}
 699}
 700
 701func saveuser(w http.ResponseWriter, r *http.Request) {
 702	whatabout := r.FormValue("whatabout")
 703	u := login.GetUserInfo(r)
 704	db := opendatabase()
 705	options := ""
 706	if r.FormValue("skinny") == "skinny" {
 707		options += " skinny "
 708	}
 709	_, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
 710	if err != nil {
 711		log.Printf("error bouting what: %s", err)
 712	}
 713
 714	http.Redirect(w, r, "/account", http.StatusSeeOther)
 715}
 716
 717func submitbonk(w http.ResponseWriter, r *http.Request) {
 718	xid := r.FormValue("xid")
 719	userinfo := login.GetUserInfo(r)
 720	user, _ := butwhatabout(userinfo.Username)
 721
 722	log.Printf("bonking %s", xid)
 723
 724	xonk := getxonk(userinfo.UserID, xid)
 725	if xonk == nil {
 726		return
 727	}
 728	if !xonk.Public {
 729		return
 730	}
 731	donksforhonks([]*Honk{xonk})
 732
 733	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
 734	if err != nil {
 735		log.Printf("error acking bonk: %s", err)
 736	}
 737
 738	oonker := xonk.Oonker
 739	if oonker == "" {
 740		oonker = xonk.Honker
 741	}
 742	dt := time.Now().UTC()
 743	bonk := Honk{
 744		UserID:   userinfo.UserID,
 745		Username: userinfo.Username,
 746		What:     "bonk",
 747		Honker:   user.URL,
 748		Oonker:   oonker,
 749		XID:      xonk.XID,
 750		RID:      xonk.RID,
 751		Noise:    xonk.Noise,
 752		Precis:   xonk.Precis,
 753		URL:      xonk.URL,
 754		Date:     dt,
 755		Donks:    xonk.Donks,
 756		Whofore:  2,
 757		Convoy:   xonk.Convoy,
 758		Audience: []string{thewholeworld, oonker},
 759		Public:   true,
 760	}
 761
 762	bonk.Format = "html"
 763
 764	err = savehonk(&bonk)
 765	if err != nil {
 766		log.Printf("uh oh")
 767		return
 768	}
 769
 770	go honkworldwide(user, &bonk)
 771}
 772
 773func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
 774	zonk := Honk{
 775		What:     what,
 776		XID:      xonk.XID,
 777		Date:     time.Now().UTC(),
 778		Audience: oneofakind(xonk.Audience),
 779	}
 780	zonk.Public = !keepitquiet(zonk.Audience)
 781
 782	log.Printf("announcing %sed honk: %s", what, xonk.XID)
 783	go honkworldwide(user, &zonk)
 784}
 785
 786func zonkit(w http.ResponseWriter, r *http.Request) {
 787	wherefore := r.FormValue("wherefore")
 788	what := r.FormValue("what")
 789	userinfo := login.GetUserInfo(r)
 790	user, _ := butwhatabout(userinfo.Username)
 791
 792	if wherefore == "ack" {
 793		xonk := getxonk(userinfo.UserID, what)
 794		if xonk != nil {
 795			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
 796			if err != nil {
 797				log.Printf("error acking: %s", err)
 798			}
 799			sendzonkofsorts(xonk, user, "ack")
 800		}
 801		return
 802	}
 803
 804	if wherefore == "deack" {
 805		xonk := getxonk(userinfo.UserID, what)
 806		if xonk != nil {
 807			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
 808			if err != nil {
 809				log.Printf("error deacking: %s", err)
 810			}
 811			sendzonkofsorts(xonk, user, "deack")
 812		}
 813		return
 814	}
 815
 816	if wherefore == "unbonk" {
 817		xonk := getbonk(userinfo.UserID, what)
 818		if xonk != nil {
 819			deletehonk(xonk.ID)
 820			xonk = getxonk(userinfo.UserID, what)
 821			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
 822			if err != nil {
 823				log.Printf("error unbonking: %s", err)
 824			}
 825			sendzonkofsorts(xonk, user, "unbonk")
 826		}
 827		return
 828	}
 829
 830	log.Printf("zonking %s %s", wherefore, what)
 831	if wherefore == "zonk" {
 832		xonk := getxonk(userinfo.UserID, what)
 833		if xonk != nil {
 834			deletehonk(xonk.ID)
 835			if xonk.Whofore == 2 || xonk.Whofore == 3 {
 836				sendzonkofsorts(xonk, user, "zonk")
 837			}
 838		}
 839	}
 840	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
 841	if err != nil {
 842		log.Printf("error saving zonker: %s", err)
 843		return
 844	}
 845}
 846
 847func edithonkpage(w http.ResponseWriter, r *http.Request) {
 848	u := login.GetUserInfo(r)
 849	user, _ := butwhatabout(u.Username)
 850	xid := r.FormValue("xid")
 851	honk := getxonk(u.UserID, xid)
 852	if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 853		log.Printf("no edit")
 854		return
 855	}
 856
 857	noise := honk.Noise
 858	if honk.Precis != "" {
 859		noise = honk.Precis + "\n\n" + noise
 860	}
 861
 862	honks := []*Honk{honk}
 863	donksforhonks(honks)
 864	reverbolate(u.UserID, honks)
 865	templinfo := getInfo(r)
 866	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 867	templinfo["Honks"] = honks
 868	templinfo["Noise"] = noise
 869	templinfo["ServerMessage"] = "honk edit"
 870	templinfo["UpdateXID"] = honk.XID
 871	if len(honk.Donks) > 0 {
 872		templinfo["SavedFile"] = honk.Donks[0].XID
 873	}
 874	err := readviews.Execute(w, "honkpage.html", templinfo)
 875	if err != nil {
 876		log.Print(err)
 877	}
 878}
 879
 880// what a hot mess this function is
 881func submithonk(w http.ResponseWriter, r *http.Request) {
 882	rid := r.FormValue("rid")
 883	noise := r.FormValue("noise")
 884
 885	userinfo := login.GetUserInfo(r)
 886	user, _ := butwhatabout(userinfo.Username)
 887
 888	dt := time.Now().UTC()
 889	updatexid := r.FormValue("updatexid")
 890	var honk *Honk
 891	if updatexid != "" {
 892		honk = getxonk(userinfo.UserID, updatexid)
 893		if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 894			log.Printf("not saving edit")
 895			return
 896		}
 897		honk.Date = dt
 898		honk.What = "update"
 899		honk.Format = "markdown"
 900	} else {
 901		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
 902		what := "honk"
 903		if rid != "" {
 904			what = "tonk"
 905		}
 906		honk = &Honk{
 907			UserID:   userinfo.UserID,
 908			Username: userinfo.Username,
 909			What:     what,
 910			Honker:   user.URL,
 911			XID:      xid,
 912			Date:     dt,
 913			Format:   "markdown",
 914		}
 915	}
 916
 917	noise = hooterize(noise)
 918	honk.Noise = noise
 919	translate(honk)
 920
 921	var convoy string
 922	if rid != "" {
 923		xonk := getxonk(userinfo.UserID, rid)
 924		if xonk != nil {
 925			if xonk.Public {
 926				honk.Audience = append(honk.Audience, xonk.Audience...)
 927			}
 928			convoy = xonk.Convoy
 929		} else {
 930			xonkaud, c := whosthere(rid)
 931			honk.Audience = append(honk.Audience, xonkaud...)
 932			convoy = c
 933		}
 934		for i, a := range honk.Audience {
 935			if a == thewholeworld {
 936				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
 937				break
 938			}
 939		}
 940		honk.RID = rid
 941	} else {
 942		honk.Audience = []string{thewholeworld}
 943	}
 944	if honk.Noise != "" && honk.Noise[0] == '@' {
 945		honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
 946	} else {
 947		honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
 948	}
 949
 950	if convoy == "" {
 951		convoy = "data:,electrichonkytonk-" + xfiltrate()
 952	}
 953	butnottooloud(honk.Audience)
 954	honk.Audience = oneofakind(honk.Audience)
 955	if len(honk.Audience) == 0 {
 956		log.Printf("honk to nowhere")
 957		http.Error(w, "honk to nowhere...", http.StatusNotFound)
 958		return
 959	}
 960	honk.Public = !keepitquiet(honk.Audience)
 961	honk.Convoy = convoy
 962
 963	donkxid := r.FormValue("donkxid")
 964	if donkxid == "" {
 965		file, filehdr, err := r.FormFile("donk")
 966		if err == nil {
 967			var buf bytes.Buffer
 968			io.Copy(&buf, file)
 969			file.Close()
 970			data := buf.Bytes()
 971			xid := xfiltrate()
 972			var media, name string
 973			img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
 974			if err == nil {
 975				data = img.Data
 976				format := img.Format
 977				media = "image/" + format
 978				if format == "jpeg" {
 979					format = "jpg"
 980				}
 981				name = xid + "." + format
 982				xid = name
 983			} else {
 984				maxsize := 100000
 985				if len(data) > maxsize {
 986					log.Printf("bad image: %s too much text: %d", err, len(data))
 987					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
 988					return
 989				}
 990				for i := 0; i < len(data); i++ {
 991					if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
 992						log.Printf("bad image: %s not text: %d", err, data[i])
 993						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
 994						return
 995					}
 996				}
 997				media = "text/plain"
 998				name = filehdr.Filename
 999				if name == "" {
1000					name = xid + ".txt"
1001				}
1002				xid += ".txt"
1003			}
1004			desc := r.FormValue("donkdesc")
1005			if desc == "" {
1006				desc = name
1007			}
1008			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1009			fileid, err := savefile(xid, name, desc, url, media, true, data)
1010			if err != nil {
1011				log.Printf("unable to save image: %s", err)
1012				return
1013			}
1014			var d Donk
1015			d.FileID = fileid
1016			honk.Donks = append(honk.Donks, &d)
1017			donkxid = d.XID
1018		}
1019	} else {
1020		xid := donkxid
1021		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1022		var donk Donk
1023		row := stmtFindFile.QueryRow(url)
1024		err := row.Scan(&donk.FileID)
1025		if err == nil {
1026			honk.Donks = append(honk.Donks, &donk)
1027		} else {
1028			log.Printf("can't find file: %s", xid)
1029		}
1030	}
1031	herd := herdofemus(honk.Noise)
1032	for _, e := range herd {
1033		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1034		if donk != nil {
1035			donk.Name = e.Name
1036			honk.Donks = append(honk.Donks, donk)
1037		}
1038	}
1039	memetize(honk)
1040
1041	placename := r.FormValue("placename")
1042	placelat := r.FormValue("placelat")
1043	placelong := r.FormValue("placelong")
1044	if placename != "" || placelat != "" || placelong != "" {
1045		p := new(Place)
1046		p.Name = placename
1047		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1048		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1049		p.Url = r.FormValue("placeurl")
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	case "zoggle":
1269	default:
1270		return
1271	}
1272	db := opendatabase()
1273	db.Exec("insert into zonkers (userid, name, wherefore) values (?, ?, ?)",
1274		userinfo.UserID, name, wherefore)
1275
1276	if wherefore != "zonvoy" {
1277		bitethethumbs()
1278	}
1279
1280	http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1281}
1282
1283func accountpage(w http.ResponseWriter, r *http.Request) {
1284	u := login.GetUserInfo(r)
1285	user, _ := butwhatabout(u.Username)
1286	templinfo := getInfo(r)
1287	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1288	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1289	templinfo["User"] = user
1290	err := readviews.Execute(w, "account.html", templinfo)
1291	if err != nil {
1292		log.Print(err)
1293	}
1294}
1295
1296func dochpass(w http.ResponseWriter, r *http.Request) {
1297	err := login.ChangePassword(w, r)
1298	if err != nil {
1299		log.Printf("error changing password: %s", err)
1300	}
1301	http.Redirect(w, r, "/account", http.StatusSeeOther)
1302}
1303
1304func fingerlicker(w http.ResponseWriter, r *http.Request) {
1305	orig := r.FormValue("resource")
1306
1307	log.Printf("finger lick: %s", orig)
1308
1309	if strings.HasPrefix(orig, "acct:") {
1310		orig = orig[5:]
1311	}
1312
1313	name := orig
1314	idx := strings.LastIndexByte(name, '/')
1315	if idx != -1 {
1316		name = name[idx+1:]
1317		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1318			log.Printf("foreign request rejected")
1319			name = ""
1320		}
1321	} else {
1322		idx = strings.IndexByte(name, '@')
1323		if idx != -1 {
1324			name = name[:idx]
1325			if name+"@"+serverName != orig {
1326				log.Printf("foreign request rejected")
1327				name = ""
1328			}
1329		}
1330	}
1331	user, err := butwhatabout(name)
1332	if err != nil {
1333		http.NotFound(w, r)
1334		return
1335	}
1336	if stealthmode(user.ID, r) {
1337		http.NotFound(w, r)
1338		return
1339	}
1340
1341	j := junk.New()
1342	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1343	j["aliases"] = []string{user.URL}
1344	var links []junk.Junk
1345	l := junk.New()
1346	l["rel"] = "self"
1347	l["type"] = `application/activity+json`
1348	l["href"] = user.URL
1349	links = append(links, l)
1350	j["links"] = links
1351
1352	w.Header().Set("Cache-Control", "max-age=3600")
1353	w.Header().Set("Content-Type", "application/jrd+json")
1354	j.Write(w)
1355}
1356
1357func somedays() string {
1358	secs := 432000 + notrand.Int63n(432000)
1359	return fmt.Sprintf("%d", secs)
1360}
1361
1362func avatate(w http.ResponseWriter, r *http.Request) {
1363	n := r.FormValue("a")
1364	a := avatar(n)
1365	w.Header().Set("Cache-Control", "max-age="+somedays())
1366	w.Write(a)
1367}
1368
1369func servecss(w http.ResponseWriter, r *http.Request) {
1370	fd, err := os.Open("views" + r.URL.Path)
1371	if err != nil {
1372		http.NotFound(w, r)
1373		return
1374	}
1375	w.Header().Set("Cache-Control", "max-age=0")
1376	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1377	err = css.Filter(fd, w)
1378	if err != nil {
1379		log.Printf("error filtering css: %s", err)
1380	}
1381}
1382func serveasset(w http.ResponseWriter, r *http.Request) {
1383	w.Header().Set("Cache-Control", "max-age=7776000")
1384	http.ServeFile(w, r, "views"+r.URL.Path)
1385}
1386func servehtml(w http.ResponseWriter, r *http.Request) {
1387	templinfo := getInfo(r)
1388	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1389	if err != nil {
1390		log.Print(err)
1391	}
1392}
1393func serveemu(w http.ResponseWriter, r *http.Request) {
1394	xid := mux.Vars(r)["xid"]
1395	w.Header().Set("Cache-Control", "max-age="+somedays())
1396	http.ServeFile(w, r, "emus/"+xid)
1397}
1398func servememe(w http.ResponseWriter, r *http.Request) {
1399	xid := mux.Vars(r)["xid"]
1400	w.Header().Set("Cache-Control", "max-age="+somedays())
1401	http.ServeFile(w, r, "memes/"+xid)
1402}
1403
1404func servefile(w http.ResponseWriter, r *http.Request) {
1405	xid := mux.Vars(r)["xid"]
1406	row := stmtGetFileData.QueryRow(xid)
1407	var media string
1408	var data []byte
1409	err := row.Scan(&media, &data)
1410	if err != nil {
1411		log.Printf("error loading file: %s", err)
1412		http.NotFound(w, r)
1413		return
1414	}
1415	w.Header().Set("Content-Type", media)
1416	w.Header().Set("X-Content-Type-Options", "nosniff")
1417	w.Header().Set("Cache-Control", "max-age="+somedays())
1418	w.Write(data)
1419}
1420
1421func nomoroboto(w http.ResponseWriter, r *http.Request) {
1422	io.WriteString(w, "User-agent: *\n")
1423	io.WriteString(w, "Disallow: /a\n")
1424	io.WriteString(w, "Disallow: /d\n")
1425	io.WriteString(w, "Disallow: /meme\n")
1426	for _, u := range allusers() {
1427		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1428	}
1429}
1430
1431func webhydra(w http.ResponseWriter, r *http.Request) {
1432	u := login.GetUserInfo(r)
1433	userid := u.UserID
1434	templinfo := getInfo(r)
1435	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1436	page := r.FormValue("page")
1437	var honks []*Honk
1438	switch page {
1439	case "atme":
1440		honks = gethonksforme(userid)
1441	case "home":
1442		honks = gethonksforuser(userid)
1443		honks = osmosis(honks, userid)
1444	case "first":
1445		honks = gethonksforuserfirstclass(userid)
1446		honks = osmosis(honks, userid)
1447	case "combo":
1448		c := r.FormValue("c")
1449		honks = gethonksbycombo(userid, c)
1450	case "convoy":
1451		c := r.FormValue("c")
1452		honks = gethonksbyconvoy(userid, c)
1453	case "honker":
1454		xid := r.FormValue("xid")
1455		if strings.IndexByte(xid, '@') != -1 {
1456			xid = gofish(xid)
1457		}
1458		honks = gethonksbyxonker(userid, xid)
1459	default:
1460		http.NotFound(w, r)
1461	}
1462	if len(honks) > 0 {
1463		templinfo["TopXID"] = honks[0].XID
1464	}
1465	if topxid := r.FormValue("topxid"); topxid != "" {
1466		for i, h := range honks {
1467			if h.XID == topxid {
1468				honks = honks[0:i]
1469				break
1470			}
1471		}
1472		log.Printf("topxid %d frags", len(honks))
1473	}
1474	reverbolate(userid, honks)
1475	templinfo["Honks"] = honks
1476	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1477	err := readviews.Execute(w, "honkfrags.html", templinfo)
1478	if err != nil {
1479		log.Printf("frag error: %s", err)
1480	}
1481}
1482
1483func serve() {
1484	db := opendatabase()
1485	login.Init(db)
1486
1487	listener, err := openListener()
1488	if err != nil {
1489		log.Fatal(err)
1490	}
1491	go redeliverator()
1492
1493	debug := false
1494	getconfig("debug", &debug)
1495	readviews = templates.Load(debug,
1496		"views/honkpage.html",
1497		"views/honkfrags.html",
1498		"views/honkers.html",
1499		"views/zonkers.html",
1500		"views/combos.html",
1501		"views/honkform.html",
1502		"views/honk.html",
1503		"views/account.html",
1504		"views/about.html",
1505		"views/funzone.html",
1506		"views/login.html",
1507		"views/xzone.html",
1508		"views/header.html",
1509		"views/onts.html",
1510		"views/honkpage.js",
1511	)
1512	if !debug {
1513		assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1514		for _, s := range assets {
1515			savedassetparams[s] = getassetparam(s)
1516		}
1517	}
1518
1519	bitethethumbs()
1520
1521	mux := mux.NewRouter()
1522	mux.Use(login.Checker)
1523
1524	posters := mux.Methods("POST").Subrouter()
1525	getters := mux.Methods("GET").Subrouter()
1526
1527	getters.HandleFunc("/", homepage)
1528	getters.HandleFunc("/home", homepage)
1529	getters.HandleFunc("/front", homepage)
1530	getters.HandleFunc("/robots.txt", nomoroboto)
1531	getters.HandleFunc("/rss", showrss)
1532	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1533	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1534	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1535	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1536	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1537	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1538	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1539	getters.HandleFunc("/a", avatate)
1540	getters.HandleFunc("/o", thelistingoftheontologies)
1541	getters.HandleFunc("/o/{name:.+}", showontology)
1542	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1543	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1544	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1545	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1546
1547	getters.HandleFunc("/style.css", servecss)
1548	getters.HandleFunc("/local.css", servecss)
1549	getters.HandleFunc("/honkpage.js", serveasset)
1550	getters.HandleFunc("/about", servehtml)
1551	getters.HandleFunc("/login", servehtml)
1552	posters.HandleFunc("/dologin", login.LoginFunc)
1553	getters.HandleFunc("/logout", login.LogoutFunc)
1554
1555	loggedin := mux.NewRoute().Subrouter()
1556	loggedin.Use(login.Required)
1557	loggedin.HandleFunc("/account", accountpage)
1558	loggedin.HandleFunc("/funzone", showfunzone)
1559	loggedin.HandleFunc("/chpass", dochpass)
1560	loggedin.HandleFunc("/atme", homepage)
1561	loggedin.HandleFunc("/zonkzone", zonkzone)
1562	loggedin.HandleFunc("/xzone", xzone)
1563	loggedin.HandleFunc("/edit", edithonkpage)
1564	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1565	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1566	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1567	loggedin.Handle("/zonkzonk", login.CSRFWrap("zonkzonk", http.HandlerFunc(zonkzonk)))
1568	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1569	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1570	loggedin.HandleFunc("/honkers", showhonkers)
1571	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1572	loggedin.HandleFunc("/h", showhonker)
1573	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1574	loggedin.HandleFunc("/c", showcombos)
1575	loggedin.HandleFunc("/t", showconvoy)
1576	loggedin.HandleFunc("/q", showsearch)
1577	loggedin.HandleFunc("/hydra", webhydra)
1578	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1579
1580	err = http.Serve(listener, mux)
1581	if err != nil {
1582		log.Fatal(err)
1583	}
1584}