all repos — honk @ 778afecc80653b23afadeaa3cc9b9a42c0b8dbb3

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