all repos — honk @ 491cb58e560433e806d23a957d94046f1e648c06

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			var d Donk
1164			d.FileID = fileid
1165			d.XID = xid
1166			d.Desc = desc
1167			d.URL = url
1168			d.Local = true
1169			honk.Donks = append(honk.Donks, &d)
1170			donkxid = xid
1171		}
1172	} else {
1173		xid := donkxid
1174		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1175		donk := finddonk(url)
1176		if donk != nil {
1177			honk.Donks = append(honk.Donks, donk)
1178		} else {
1179			log.Printf("can't find file: %s", xid)
1180		}
1181	}
1182	herd := herdofemus(honk.Noise)
1183	for _, e := range herd {
1184		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1185		if donk != nil {
1186			donk.Name = e.Name
1187			honk.Donks = append(honk.Donks, donk)
1188		}
1189	}
1190	memetize(honk)
1191
1192	placename := strings.TrimSpace(r.FormValue("placename"))
1193	placelat := strings.TrimSpace(r.FormValue("placelat"))
1194	placelong := strings.TrimSpace(r.FormValue("placelong"))
1195	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1196	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1197		p := new(Place)
1198		p.Name = placename
1199		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1200		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1201		p.Url = placeurl
1202		honk.Place = p
1203	}
1204	timestart := strings.TrimSpace(r.FormValue("timestart"))
1205	if timestart != "" {
1206		t := new(Time)
1207		now := time.Now().Local()
1208		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1209			start, err := time.ParseInLocation(layout, timestart, now.Location())
1210			if err == nil {
1211				if start.Year() == 0 {
1212					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1213				}
1214				t.StartTime = start
1215				break
1216			}
1217		}
1218		timeend := r.FormValue("timeend")
1219		dur, err := time.ParseDuration(timeend)
1220		if err == nil {
1221			t.Duration = Duration(dur)
1222		}
1223		if !t.StartTime.IsZero() {
1224			honk.What = "event"
1225			honk.Time = t
1226		}
1227	}
1228
1229	if honk.Public {
1230		honk.Whofore = 2
1231	} else {
1232		honk.Whofore = 3
1233	}
1234
1235	// back to markdown
1236	honk.Noise = noise
1237
1238	if r.FormValue("preview") == "preview" {
1239		honks := []*Honk{honk}
1240		reverbolate(userinfo.UserID, honks)
1241		templinfo := getInfo(r)
1242		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1243		templinfo["Honks"] = honks
1244		templinfo["InReplyTo"] = r.FormValue("rid")
1245		templinfo["Noise"] = r.FormValue("noise")
1246		templinfo["SavedFile"] = donkxid
1247		templinfo["IsPreview"] = true
1248		templinfo["ServerMessage"] = "honk preview"
1249		err := readviews.Execute(w, "honkpage.html", templinfo)
1250		if err != nil {
1251			log.Print(err)
1252		}
1253		return
1254	}
1255
1256	if updatexid != "" {
1257		updatehonk(honk)
1258		oldjonks.Clear(honk.XID)
1259	} else {
1260		err := savehonk(honk)
1261		if err != nil {
1262			log.Printf("uh oh")
1263			return
1264		}
1265	}
1266
1267	// reload for consistency
1268	honk.Donks = nil
1269	donksforhonks([]*Honk{honk})
1270
1271	go honkworldwide(user, honk)
1272
1273	http.Redirect(w, r, honk.XID[len(serverName)+8:], http.StatusSeeOther)
1274}
1275
1276func showhonkers(w http.ResponseWriter, r *http.Request) {
1277	userinfo := login.GetUserInfo(r)
1278	templinfo := getInfo(r)
1279	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1280	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1281	err := readviews.Execute(w, "honkers.html", templinfo)
1282	if err != nil {
1283		log.Print(err)
1284	}
1285}
1286
1287var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1288	honkers := gethonkers(userid)
1289	var combos []string
1290	for _, h := range honkers {
1291		combos = append(combos, h.Combos...)
1292	}
1293	for i, c := range combos {
1294		if c == "-" {
1295			combos[i] = ""
1296		}
1297	}
1298	combos = oneofakind(combos)
1299	sort.Strings(combos)
1300	return combos, true
1301}, Invalidator: &honkerinvalidator})
1302
1303func showcombos(w http.ResponseWriter, r *http.Request) {
1304	userinfo := login.GetUserInfo(r)
1305	var combos []string
1306	combocache.Get(userinfo.UserID, &combos)
1307	templinfo := getInfo(r)
1308	err := readviews.Execute(w, "combos.html", templinfo)
1309	if err != nil {
1310		log.Print(err)
1311	}
1312}
1313
1314func submithonker(w http.ResponseWriter, r *http.Request) {
1315	u := login.GetUserInfo(r)
1316	name := strings.TrimSpace(r.FormValue("name"))
1317	url := strings.TrimSpace(r.FormValue("url"))
1318	peep := r.FormValue("peep")
1319	combos := strings.TrimSpace(r.FormValue("combos"))
1320	combos = " " + combos + " "
1321	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1322
1323	defer honkerinvalidator.Clear(u.UserID)
1324
1325	if honkerid > 0 {
1326		goodbye := r.FormValue("goodbye")
1327		if goodbye == "F" {
1328			db := opendatabase()
1329			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1330				honkerid, u.UserID)
1331			err := row.Scan(&url)
1332			if err != nil {
1333				log.Printf("can't get honker xid: %s", err)
1334				return
1335			}
1336			log.Printf("unsubscribing from %s", url)
1337			user, _ := butwhatabout(u.Username)
1338			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, "sub")
1339			if err != nil {
1340				log.Printf("error updating honker: %s", err)
1341				return
1342			}
1343			go itakeitallback(user, url)
1344
1345			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1346			return
1347		}
1348		if goodbye == "X" {
1349			db := opendatabase()
1350			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1351				honkerid, u.UserID)
1352			err := row.Scan(&url)
1353			if err != nil {
1354				log.Printf("can't get honker xid: %s", err)
1355				return
1356			}
1357			log.Printf("resubscribing to %s", url)
1358			user, _ := butwhatabout(u.Username)
1359			_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "unsub")
1360			if err == nil {
1361				_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "peep")
1362			}
1363			if err != nil {
1364				log.Printf("error updating honker: %s", err)
1365				return
1366			}
1367			go subsub(user, url)
1368
1369			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1370			return
1371		}
1372		_, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1373		if err != nil {
1374			log.Printf("update honker err: %s", err)
1375			return
1376		}
1377		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1378		return
1379	}
1380
1381	flavor := "presub"
1382	if peep == "peep" {
1383		flavor = "peep"
1384	}
1385	p, err := investigate(url)
1386	if err != nil {
1387		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1388		log.Printf("failed to investigate honker: %s", err)
1389		return
1390	}
1391	url = p.XID
1392
1393	db := opendatabase()
1394	row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1395	var x string
1396	err = row.Scan(&x)
1397	if err != sql.ErrNoRows {
1398		http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1399		if err != nil {
1400			log.Printf("honker scan err: %s", err)
1401		}
1402		return
1403	}
1404
1405	if name == "" {
1406		name = p.Handle
1407	}
1408	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1409	if err != nil {
1410		log.Print(err)
1411		return
1412	}
1413	if flavor == "presub" {
1414		user, _ := butwhatabout(u.Username)
1415		go subsub(user, url)
1416	}
1417	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1418}
1419
1420func hfcspage(w http.ResponseWriter, r *http.Request) {
1421	userinfo := login.GetUserInfo(r)
1422
1423	filters := getfilters(userinfo.UserID, filtAny)
1424
1425	templinfo := getInfo(r)
1426	templinfo["Filters"] = filters
1427	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1428	err := readviews.Execute(w, "hfcs.html", templinfo)
1429	if err != nil {
1430		log.Print(err)
1431	}
1432}
1433
1434func savehfcs(w http.ResponseWriter, r *http.Request) {
1435	userinfo := login.GetUserInfo(r)
1436	itsok := r.FormValue("itsok")
1437	if itsok == "iforgiveyou" {
1438		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1439		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1440		if err != nil {
1441			log.Printf("error deleting filter: %s", err)
1442		}
1443		filtcache.Clear(userinfo.UserID)
1444		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1445		return
1446	}
1447
1448	filt := new(Filter)
1449	filt.Name = strings.TrimSpace(r.FormValue("name"))
1450	filt.Date = time.Now().UTC()
1451	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1452	filt.IncludeAudience = r.FormValue("incaud") == "yes"
1453	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1454	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1455	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1456	filt.Reject = r.FormValue("doreject") == "yes"
1457	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1458	filt.Hide = r.FormValue("dohide") == "yes"
1459	filt.Collapse = r.FormValue("docollapse") == "yes"
1460	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1461	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1462
1463	if filt.Actor == "" && filt.Text == "" {
1464		log.Printf("blank filter")
1465		return
1466	}
1467
1468	j, err := jsonify(filt)
1469	if err == nil {
1470		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1471	}
1472	if err != nil {
1473		log.Printf("error saving filter: %s", err)
1474	}
1475
1476	filtcache.Clear(userinfo.UserID)
1477	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1478}
1479
1480func accountpage(w http.ResponseWriter, r *http.Request) {
1481	u := login.GetUserInfo(r)
1482	user, _ := butwhatabout(u.Username)
1483	templinfo := getInfo(r)
1484	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1485	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1486	templinfo["User"] = user
1487	err := readviews.Execute(w, "account.html", templinfo)
1488	if err != nil {
1489		log.Print(err)
1490	}
1491}
1492
1493func dochpass(w http.ResponseWriter, r *http.Request) {
1494	err := login.ChangePassword(w, r)
1495	if err != nil {
1496		log.Printf("error changing password: %s", err)
1497	}
1498	http.Redirect(w, r, "/account", http.StatusSeeOther)
1499}
1500
1501func fingerlicker(w http.ResponseWriter, r *http.Request) {
1502	orig := r.FormValue("resource")
1503
1504	log.Printf("finger lick: %s", orig)
1505
1506	if strings.HasPrefix(orig, "acct:") {
1507		orig = orig[5:]
1508	}
1509
1510	name := orig
1511	idx := strings.LastIndexByte(name, '/')
1512	if idx != -1 {
1513		name = name[idx+1:]
1514		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1515			log.Printf("foreign request rejected")
1516			name = ""
1517		}
1518	} else {
1519		idx = strings.IndexByte(name, '@')
1520		if idx != -1 {
1521			name = name[:idx]
1522			if name+"@"+serverName != orig {
1523				log.Printf("foreign request rejected")
1524				name = ""
1525			}
1526		}
1527	}
1528	user, err := butwhatabout(name)
1529	if err != nil {
1530		http.NotFound(w, r)
1531		return
1532	}
1533	if stealthmode(user.ID, r) {
1534		http.NotFound(w, r)
1535		return
1536	}
1537
1538	j := junk.New()
1539	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1540	j["aliases"] = []string{user.URL}
1541	l := junk.New()
1542	l["rel"] = "self"
1543	l["type"] = `application/activity+json`
1544	l["href"] = user.URL
1545	j["links"] = []junk.Junk{l}
1546
1547	w.Header().Set("Cache-Control", "max-age=3600")
1548	w.Header().Set("Content-Type", "application/jrd+json")
1549	j.Write(w)
1550}
1551
1552func somedays() string {
1553	secs := 432000 + notrand.Int63n(432000)
1554	return fmt.Sprintf("%d", secs)
1555}
1556
1557func avatate(w http.ResponseWriter, r *http.Request) {
1558	n := r.FormValue("a")
1559	a := avatar(n)
1560	w.Header().Set("Cache-Control", "max-age="+somedays())
1561	w.Write(a)
1562}
1563
1564func servecss(w http.ResponseWriter, r *http.Request) {
1565	fd, err := os.Open("views" + r.URL.Path)
1566	if err != nil {
1567		http.NotFound(w, r)
1568		return
1569	}
1570	defer fd.Close()
1571	w.Header().Set("Cache-Control", "max-age=0")
1572	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1573	err = css.Filter(fd, w)
1574	if err != nil {
1575		log.Printf("error filtering css: %s", err)
1576	}
1577}
1578func serveasset(w http.ResponseWriter, r *http.Request) {
1579	w.Header().Set("Cache-Control", "max-age=7776000")
1580	http.ServeFile(w, r, "views"+r.URL.Path)
1581}
1582func servehelp(w http.ResponseWriter, r *http.Request) {
1583	name := mux.Vars(r)["name"]
1584	w.Header().Set("Cache-Control", "max-age=600")
1585	http.ServeFile(w, r, "docs/"+name)
1586}
1587func servehtml(w http.ResponseWriter, r *http.Request) {
1588	templinfo := getInfo(r)
1589	templinfo["AboutMsg"] = aboutMsg
1590	templinfo["LoginMsg"] = loginMsg
1591	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1592	if err != nil {
1593		log.Print(err)
1594	}
1595}
1596func serveemu(w http.ResponseWriter, r *http.Request) {
1597	xid := mux.Vars(r)["xid"]
1598	w.Header().Set("Cache-Control", "max-age="+somedays())
1599	http.ServeFile(w, r, "emus/"+xid)
1600}
1601func servememe(w http.ResponseWriter, r *http.Request) {
1602	xid := mux.Vars(r)["xid"]
1603	w.Header().Set("Cache-Control", "max-age="+somedays())
1604	http.ServeFile(w, r, "memes/"+xid)
1605}
1606
1607func servefile(w http.ResponseWriter, r *http.Request) {
1608	xid := mux.Vars(r)["xid"]
1609	row := stmtGetFileData.QueryRow(xid)
1610	var media string
1611	var data []byte
1612	err := row.Scan(&media, &data)
1613	if err != nil {
1614		log.Printf("error loading file: %s", err)
1615		http.NotFound(w, r)
1616		return
1617	}
1618	w.Header().Set("Content-Type", media)
1619	w.Header().Set("X-Content-Type-Options", "nosniff")
1620	w.Header().Set("Cache-Control", "max-age="+somedays())
1621	w.Write(data)
1622}
1623
1624func nomoroboto(w http.ResponseWriter, r *http.Request) {
1625	io.WriteString(w, "User-agent: *\n")
1626	io.WriteString(w, "Disallow: /a\n")
1627	io.WriteString(w, "Disallow: /d\n")
1628	io.WriteString(w, "Disallow: /meme\n")
1629	io.WriteString(w, "Disallow: /o\n")
1630	for _, u := range allusers() {
1631		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1632	}
1633}
1634
1635func webhydra(w http.ResponseWriter, r *http.Request) {
1636	u := login.GetUserInfo(r)
1637	userid := u.UserID
1638	templinfo := getInfo(r)
1639	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1640	page := r.FormValue("page")
1641
1642	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
1643
1644	var honks []*Honk
1645	switch page {
1646	case "atme":
1647		honks = gethonksforme(userid, wanted)
1648		templinfo["ServerMessage"] = "at me!"
1649	case "home":
1650		honks = gethonksforuser(userid, wanted)
1651		honks = osmosis(honks, userid)
1652		templinfo["ServerMessage"] = serverMsg
1653	case "first":
1654		honks = gethonksforuserfirstclass(userid, wanted)
1655		honks = osmosis(honks, userid)
1656		templinfo["ServerMessage"] = "first class only"
1657	case "saved":
1658		honks = getsavedhonks(userid, wanted)
1659		templinfo["PageName"] = "saved"
1660		templinfo["ServerMessage"] = "saved honks"
1661	case "combo":
1662		c := r.FormValue("c")
1663		honks = gethonksbycombo(userid, c, wanted)
1664		honks = osmosis(honks, userid)
1665		templinfo["ServerMessage"] = "honks by combo: " + c
1666	case "convoy":
1667		c := r.FormValue("c")
1668		honks = gethonksbyconvoy(userid, c, wanted)
1669		templinfo["ServerMessage"] = "honks in convoy: " + c
1670	case "honker":
1671		xid := r.FormValue("xid")
1672		if strings.IndexByte(xid, '@') != -1 {
1673			xid = gofish(xid)
1674		}
1675		honks = gethonksbyxonker(userid, xid, wanted)
1676		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
1677		templinfo["ServerMessage"] = msg
1678	default:
1679		http.NotFound(w, r)
1680	}
1681	if len(honks) > 0 {
1682		templinfo["TopHID"] = honks[0].ID
1683	} else {
1684		templinfo["TopHID"] = wanted
1685	}
1686	reverbolate(userid, honks)
1687	templinfo["Honks"] = honks
1688	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1689	err := readviews.Execute(w, "honkfrags.html", templinfo)
1690	if err != nil {
1691		log.Printf("frag error: %s", err)
1692	}
1693}
1694
1695func serve() {
1696	db := opendatabase()
1697	login.Init(db)
1698
1699	listener, err := openListener()
1700	if err != nil {
1701		log.Fatal(err)
1702	}
1703	go redeliverator()
1704
1705	debug := false
1706	getconfig("debug", &debug)
1707	readviews = templates.Load(debug,
1708		"views/honkpage.html",
1709		"views/honkfrags.html",
1710		"views/honkers.html",
1711		"views/hfcs.html",
1712		"views/combos.html",
1713		"views/honkform.html",
1714		"views/honk.html",
1715		"views/account.html",
1716		"views/about.html",
1717		"views/funzone.html",
1718		"views/login.html",
1719		"views/xzone.html",
1720		"views/msg.html",
1721		"views/header.html",
1722		"views/onts.html",
1723		"views/honkpage.js",
1724	)
1725	if !debug {
1726		assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1727		for _, s := range assets {
1728			savedassetparams[s] = getassetparam(s)
1729		}
1730	}
1731
1732	mux := mux.NewRouter()
1733	mux.Use(login.Checker)
1734
1735	posters := mux.Methods("POST").Subrouter()
1736	getters := mux.Methods("GET").Subrouter()
1737
1738	getters.HandleFunc("/", homepage)
1739	getters.HandleFunc("/home", homepage)
1740	getters.HandleFunc("/front", homepage)
1741	getters.HandleFunc("/events", homepage)
1742	getters.HandleFunc("/robots.txt", nomoroboto)
1743	getters.HandleFunc("/rss", showrss)
1744	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1745	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1746	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1747	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1748	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1749	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1750	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1751	getters.HandleFunc("/a", avatate)
1752	getters.HandleFunc("/o", thelistingoftheontologies)
1753	getters.HandleFunc("/o/{name:.+}", showontology)
1754	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1755	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1756	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1757	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1758
1759	getters.HandleFunc("/style.css", servecss)
1760	getters.HandleFunc("/local.css", servecss)
1761	getters.HandleFunc("/honkpage.js", serveasset)
1762	getters.HandleFunc("/about", servehtml)
1763	getters.HandleFunc("/login", servehtml)
1764	posters.HandleFunc("/dologin", login.LoginFunc)
1765	getters.HandleFunc("/logout", login.LogoutFunc)
1766	getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
1767
1768	loggedin := mux.NewRoute().Subrouter()
1769	loggedin.Use(login.Required)
1770	loggedin.HandleFunc("/first", homepage)
1771	loggedin.HandleFunc("/saved", homepage)
1772	loggedin.HandleFunc("/account", accountpage)
1773	loggedin.HandleFunc("/funzone", showfunzone)
1774	loggedin.HandleFunc("/chpass", dochpass)
1775	loggedin.HandleFunc("/atme", homepage)
1776	loggedin.HandleFunc("/hfcs", hfcspage)
1777	loggedin.HandleFunc("/xzone", xzone)
1778	loggedin.HandleFunc("/newhonk", newhonkpage)
1779	loggedin.HandleFunc("/edit", edithonkpage)
1780	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1781	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1782	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1783	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
1784	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1785	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1786	loggedin.HandleFunc("/honkers", showhonkers)
1787	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1788	loggedin.HandleFunc("/h", showhonker)
1789	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1790	loggedin.HandleFunc("/c", showcombos)
1791	loggedin.HandleFunc("/t", showconvoy)
1792	loggedin.HandleFunc("/q", showsearch)
1793	loggedin.HandleFunc("/hydra", webhydra)
1794	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1795
1796	err = http.Serve(listener, mux)
1797	if err != nil {
1798		log.Fatal(err)
1799	}
1800}