all repos — honk @ 9ab52255236a098266c5b01968a891d06de137bd

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