all repos — honk @ 8c83d43769dcc56c595892bb38d338267492ce8e

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