all repos — honk @ 750d79ff5a22cc132d6694f0e09393cd2450e52f

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