all repos — honk @ 73ad26f01d1da2b0c0d5745294b003ef9e2eac0d

my fork of honk

web.go (view raw)

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