all repos — honk @ 1714fe90b52de5a2597957cafa609f46c4acaf31

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