all repos — honk @ b8baa2f32d97b62764e84d59d0f2ca7b969475c3

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