all repos — honk @ 6fa77e6b0dd73cb8c9f901e02806264ac6e06063

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