all repos — honk @ 8bf51b5a21cfda42dd8e3b97cad9bbdfd3551426

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