all repos — honk @ d5d1e19de1cd44b2de7efe60a525d317206a5acf

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"
  23	"html/template"
  24	"io"
  25	"log"
  26	notrand "math/rand"
  27	"net/http"
  28	"net/url"
  29	"os"
  30	"sort"
  31	"strconv"
  32	"strings"
  33	"time"
  34
  35	"github.com/gorilla/mux"
  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 {
  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["PageName"] = "atme"
 102			honks = gethonksforme(userid)
 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)
 111			honks = osmosis(honks, userid)
 112		case "/saved":
 113			templinfo["ServerMessage"] = "saved honks"
 114			templinfo["PageName"] = "saved"
 115			honks = getsavedhonks(userid)
 116		default:
 117			templinfo["PageName"] = "home"
 118			honks = gethonksforuser(userid)
 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)
 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 += fmt.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
 197				html.EscapeString(p.Url), html.EscapeString(p.Name), p.Latitude, p.Longitude)
 198		}
 199		for _, d := range honk.Donks {
 200			desc += fmt.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
 201				d.URL, html.EscapeString(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 = cacheNew(cacheOptions{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)
 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)
 573	templinfo := getInfo(r)
 574	filt := htfilter.New()
 575	templinfo["Name"] = user.Name
 576	whatabout := user.About
 577	whatabout = markitzero(user.About)
 578	templinfo["WhatAbout"], _ = filt.String(whatabout)
 579	templinfo["ServerMessage"] = ""
 580	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 581	honkpage(w, u, honks, templinfo)
 582}
 583
 584func showhonker(w http.ResponseWriter, r *http.Request) {
 585	u := login.GetUserInfo(r)
 586	name := mux.Vars(r)["name"]
 587	var honks []*Honk
 588	if name == "" {
 589		name = r.FormValue("xid")
 590		honks = gethonksbyxonker(u.UserID, name)
 591	} else {
 592		honks = gethonksbyhonker(u.UserID, name)
 593	}
 594	name = html.EscapeString(name)
 595	msg := fmt.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"] = template.HTML(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)
 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)
 620	templinfo := getInfo(r)
 621	if len(honks) > 0 {
 622		templinfo["TopXID"] = honks[0].XID
 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)
 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)
 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
 656func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 657	u := login.GetUserInfo(r)
 658	var userid int64 = -1
 659	if u != nil {
 660		userid = u.UserID
 661	}
 662	rows, err := stmtSelectOnts.Query(userid)
 663	if err != nil {
 664		log.Printf("selection error: %s", err)
 665		return
 666	}
 667	defer rows.Close()
 668	var onts [][]string
 669	for rows.Next() {
 670		var o string
 671		err := rows.Scan(&o)
 672		if err != nil {
 673			log.Printf("error scanning ont: %s", err)
 674			continue
 675		}
 676		onts = append(onts, []string{o, o[1:]})
 677	}
 678	if u == nil {
 679		w.Header().Set("Cache-Control", "max-age=300")
 680	}
 681	templinfo := getInfo(r)
 682	templinfo["Onts"] = onts
 683	err = readviews.Execute(w, "onts.html", templinfo)
 684	if err != nil {
 685		log.Print(err)
 686	}
 687}
 688
 689func showhonk(w http.ResponseWriter, r *http.Request) {
 690	name := mux.Vars(r)["name"]
 691	user, err := butwhatabout(name)
 692	if err != nil {
 693		http.NotFound(w, r)
 694		return
 695	}
 696	if stealthmode(user.ID, r) {
 697		http.NotFound(w, r)
 698		return
 699	}
 700	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
 701
 702	if friendorfoe(r.Header.Get("Accept")) {
 703		j, ok := gimmejonk(xid)
 704		if ok {
 705			w.Header().Set("Content-Type", theonetruename)
 706			w.Write(j)
 707		} else {
 708			http.NotFound(w, r)
 709		}
 710		return
 711	}
 712	honk := getxonk(user.ID, xid)
 713	if honk == nil {
 714		http.NotFound(w, r)
 715		return
 716	}
 717	u := login.GetUserInfo(r)
 718	if u != nil && u.UserID != user.ID {
 719		u = nil
 720	}
 721	if !honk.Public {
 722		if u == nil {
 723			http.NotFound(w, r)
 724			return
 725
 726		}
 727		templinfo := getInfo(r)
 728		templinfo["ServerMessage"] = "one honk maybe more"
 729		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 730		honkpage(w, u, []*Honk{honk}, templinfo)
 731		return
 732	}
 733	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
 734	reversehonks(rawhonks)
 735	var honks []*Honk
 736	for _, h := range rawhonks {
 737		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
 738			honks = append(honks, h)
 739		}
 740	}
 741
 742	templinfo := getInfo(r)
 743	templinfo["ServerMessage"] = "one honk maybe more"
 744	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 745	honkpage(w, u, honks, templinfo)
 746}
 747
 748func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
 749	var userid int64 = -1
 750	if u != nil {
 751		userid = u.UserID
 752	}
 753	if u == nil {
 754		w.Header().Set("Cache-Control", "max-age=60")
 755	}
 756	reverbolate(userid, honks)
 757	templinfo["Honks"] = honks
 758	if templinfo["TopXID"] == nil && len(honks) > 0 {
 759		templinfo["TopXID"] = honks[0].XID
 760	}
 761	err := readviews.Execute(w, "honkpage.html", templinfo)
 762	if err != nil {
 763		log.Print(err)
 764	}
 765}
 766
 767func saveuser(w http.ResponseWriter, r *http.Request) {
 768	whatabout := r.FormValue("whatabout")
 769	u := login.GetUserInfo(r)
 770	db := opendatabase()
 771	options := ""
 772	if r.FormValue("skinny") == "skinny" {
 773		options += " skinny "
 774	}
 775	_, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
 776	if err != nil {
 777		log.Printf("error bouting what: %s", err)
 778	}
 779	someusers.Clear(u.Username)
 780
 781	http.Redirect(w, r, "/account", http.StatusSeeOther)
 782}
 783
 784func submitbonk(w http.ResponseWriter, r *http.Request) {
 785	xid := r.FormValue("xid")
 786	userinfo := login.GetUserInfo(r)
 787	user, _ := butwhatabout(userinfo.Username)
 788
 789	log.Printf("bonking %s", xid)
 790
 791	xonk := getxonk(userinfo.UserID, xid)
 792	if xonk == nil {
 793		return
 794	}
 795	if !xonk.Public {
 796		return
 797	}
 798	donksforhonks([]*Honk{xonk})
 799
 800	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
 801	if err != nil {
 802		log.Printf("error acking bonk: %s", err)
 803	}
 804
 805	oonker := xonk.Oonker
 806	if oonker == "" {
 807		oonker = xonk.Honker
 808	}
 809	dt := time.Now().UTC()
 810	bonk := Honk{
 811		UserID:   userinfo.UserID,
 812		Username: userinfo.Username,
 813		What:     "bonk",
 814		Honker:   user.URL,
 815		Oonker:   oonker,
 816		XID:      xonk.XID,
 817		RID:      xonk.RID,
 818		Noise:    xonk.Noise,
 819		Precis:   xonk.Precis,
 820		URL:      xonk.URL,
 821		Date:     dt,
 822		Donks:    xonk.Donks,
 823		Whofore:  2,
 824		Convoy:   xonk.Convoy,
 825		Audience: []string{thewholeworld, oonker},
 826		Public:   true,
 827	}
 828
 829	bonk.Format = "html"
 830
 831	err = savehonk(&bonk)
 832	if err != nil {
 833		log.Printf("uh oh")
 834		return
 835	}
 836
 837	go honkworldwide(user, &bonk)
 838}
 839
 840func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
 841	zonk := Honk{
 842		What:     what,
 843		XID:      xonk.XID,
 844		Date:     time.Now().UTC(),
 845		Audience: oneofakind(xonk.Audience),
 846	}
 847	zonk.Public = !keepitquiet(zonk.Audience)
 848
 849	log.Printf("announcing %sed honk: %s", what, xonk.XID)
 850	go honkworldwide(user, &zonk)
 851}
 852
 853func zonkit(w http.ResponseWriter, r *http.Request) {
 854	wherefore := r.FormValue("wherefore")
 855	what := r.FormValue("what")
 856	userinfo := login.GetUserInfo(r)
 857	user, _ := butwhatabout(userinfo.Username)
 858
 859	if wherefore == "save" {
 860		xonk := getxonk(userinfo.UserID, what)
 861		if xonk != nil {
 862			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
 863			if err != nil {
 864				log.Printf("error saving: %s", err)
 865			}
 866		}
 867		return
 868	}
 869
 870	if wherefore == "unsave" {
 871		xonk := getxonk(userinfo.UserID, what)
 872		if xonk != nil {
 873			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
 874			if err != nil {
 875				log.Printf("error unsaving: %s", err)
 876			}
 877		}
 878		return
 879	}
 880
 881	// my hammer is too big, oh well
 882	defer oldjonks.Flush()
 883
 884	if wherefore == "ack" {
 885		xonk := getxonk(userinfo.UserID, what)
 886		if xonk != nil {
 887			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
 888			if err != nil {
 889				log.Printf("error acking: %s", err)
 890			}
 891			sendzonkofsorts(xonk, user, "ack")
 892		}
 893		return
 894	}
 895
 896	if wherefore == "deack" {
 897		xonk := getxonk(userinfo.UserID, what)
 898		if xonk != nil {
 899			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
 900			if err != nil {
 901				log.Printf("error deacking: %s", err)
 902			}
 903			sendzonkofsorts(xonk, user, "deack")
 904		}
 905		return
 906	}
 907
 908	if wherefore == "unbonk" {
 909		xonk := getbonk(userinfo.UserID, what)
 910		if xonk != nil {
 911			deletehonk(xonk.ID)
 912			xonk = getxonk(userinfo.UserID, what)
 913			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
 914			if err != nil {
 915				log.Printf("error unbonking: %s", err)
 916			}
 917			sendzonkofsorts(xonk, user, "unbonk")
 918		}
 919		return
 920	}
 921
 922	log.Printf("zonking %s %s", wherefore, what)
 923	if wherefore == "zonk" {
 924		xonk := getxonk(userinfo.UserID, what)
 925		if xonk != nil {
 926			deletehonk(xonk.ID)
 927			if xonk.Whofore == 2 || xonk.Whofore == 3 {
 928				sendzonkofsorts(xonk, user, "zonk")
 929			}
 930		}
 931	}
 932	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
 933	if err != nil {
 934		log.Printf("error saving zonker: %s", err)
 935		return
 936	}
 937}
 938
 939func edithonkpage(w http.ResponseWriter, r *http.Request) {
 940	u := login.GetUserInfo(r)
 941	user, _ := butwhatabout(u.Username)
 942	xid := r.FormValue("xid")
 943	honk := getxonk(u.UserID, xid)
 944	if !canedithonk(user, honk) {
 945		http.Error(w, "no editing that please", http.StatusInternalServerError)
 946		return
 947	}
 948
 949	noise := honk.Noise
 950	if honk.Precis != "" {
 951		noise = honk.Precis + "\n\n" + noise
 952	}
 953
 954	honks := []*Honk{honk}
 955	donksforhonks(honks)
 956	reverbolate(u.UserID, honks)
 957	templinfo := getInfo(r)
 958	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 959	templinfo["Honks"] = honks
 960	templinfo["Noise"] = noise
 961	templinfo["ServerMessage"] = "honk edit"
 962	templinfo["UpdateXID"] = honk.XID
 963	if len(honk.Donks) > 0 {
 964		templinfo["SavedFile"] = honk.Donks[0].XID
 965	}
 966	err := readviews.Execute(w, "honkpage.html", templinfo)
 967	if err != nil {
 968		log.Print(err)
 969	}
 970}
 971
 972func canedithonk(user *WhatAbout, honk *Honk) bool {
 973	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
 974		return false
 975	}
 976	return true
 977}
 978
 979// what a hot mess this function is
 980func submithonk(w http.ResponseWriter, r *http.Request) {
 981	rid := r.FormValue("rid")
 982	noise := r.FormValue("noise")
 983
 984	userinfo := login.GetUserInfo(r)
 985	user, _ := butwhatabout(userinfo.Username)
 986
 987	dt := time.Now().UTC()
 988	updatexid := r.FormValue("updatexid")
 989	var honk *Honk
 990	if updatexid != "" {
 991		honk = getxonk(userinfo.UserID, updatexid)
 992		if !canedithonk(user, honk) {
 993			http.Error(w, "no editing that please", http.StatusInternalServerError)
 994			return
 995		}
 996		honk.Date = dt
 997		honk.What = "update"
 998		honk.Format = "markdown"
 999	} else {
1000		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1001		what := "honk"
1002		if rid != "" {
1003			what = "tonk"
1004		}
1005		honk = &Honk{
1006			UserID:   userinfo.UserID,
1007			Username: userinfo.Username,
1008			What:     what,
1009			Honker:   user.URL,
1010			XID:      xid,
1011			Date:     dt,
1012			Format:   "markdown",
1013		}
1014	}
1015
1016	noise = hooterize(noise)
1017	honk.Noise = noise
1018	translate(honk)
1019
1020	var convoy string
1021	if rid != "" {
1022		xonk := getxonk(userinfo.UserID, rid)
1023		if xonk != nil {
1024			if xonk.Public {
1025				honk.Audience = append(honk.Audience, xonk.Audience...)
1026			}
1027			convoy = xonk.Convoy
1028		} else {
1029			xonkaud, c := whosthere(rid)
1030			honk.Audience = append(honk.Audience, xonkaud...)
1031			convoy = c
1032		}
1033		for i, a := range honk.Audience {
1034			if a == thewholeworld {
1035				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1036				break
1037			}
1038		}
1039		honk.RID = rid
1040	} else {
1041		honk.Audience = []string{thewholeworld}
1042	}
1043	if honk.Noise != "" && honk.Noise[0] == '@' {
1044		honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
1045	} else {
1046		honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
1047	}
1048
1049	if convoy == "" {
1050		convoy = "data:,electrichonkytonk-" + xfiltrate()
1051	}
1052	butnottooloud(honk.Audience)
1053	honk.Audience = oneofakind(honk.Audience)
1054	if len(honk.Audience) == 0 {
1055		log.Printf("honk to nowhere")
1056		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1057		return
1058	}
1059	honk.Public = !keepitquiet(honk.Audience)
1060	honk.Convoy = convoy
1061
1062	donkxid := r.FormValue("donkxid")
1063	if donkxid == "" {
1064		file, filehdr, err := r.FormFile("donk")
1065		if err == nil {
1066			var buf bytes.Buffer
1067			io.Copy(&buf, file)
1068			file.Close()
1069			data := buf.Bytes()
1070			xid := xfiltrate()
1071			var media, name string
1072			img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
1073			if err == nil {
1074				data = img.Data
1075				format := img.Format
1076				media = "image/" + format
1077				if format == "jpeg" {
1078					format = "jpg"
1079				}
1080				name = xid + "." + format
1081				xid = name
1082			} else {
1083				maxsize := 100000
1084				if len(data) > maxsize {
1085					log.Printf("bad image: %s too much text: %d", err, len(data))
1086					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1087					return
1088				}
1089				for i := 0; i < len(data); i++ {
1090					if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1091						log.Printf("bad image: %s not text: %d", err, data[i])
1092						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1093						return
1094					}
1095				}
1096				media = "text/plain"
1097				name = filehdr.Filename
1098				if name == "" {
1099					name = xid + ".txt"
1100				}
1101				xid += ".txt"
1102			}
1103			desc := strings.TrimSpace(r.FormValue("donkdesc"))
1104			if desc == "" {
1105				desc = name
1106			}
1107			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1108			fileid, err := savefile(xid, name, desc, url, media, true, data)
1109			if err != nil {
1110				log.Printf("unable to save image: %s", err)
1111				return
1112			}
1113			var d Donk
1114			d.FileID = fileid
1115			d.XID = xid
1116			d.Desc = desc
1117			d.URL = url
1118			d.Local = true
1119			honk.Donks = append(honk.Donks, &d)
1120			donkxid = xid
1121		}
1122	} else {
1123		xid := donkxid
1124		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1125		donk := finddonk(url)
1126		if donk != nil {
1127			honk.Donks = append(honk.Donks, donk)
1128		} else {
1129			log.Printf("can't find file: %s", xid)
1130		}
1131	}
1132	herd := herdofemus(honk.Noise)
1133	for _, e := range herd {
1134		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1135		if donk != nil {
1136			donk.Name = e.Name
1137			honk.Donks = append(honk.Donks, donk)
1138		}
1139	}
1140	memetize(honk)
1141
1142	placename := strings.TrimSpace(r.FormValue("placename"))
1143	placelat := strings.TrimSpace(r.FormValue("placelat"))
1144	placelong := strings.TrimSpace(r.FormValue("placelong"))
1145	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1146	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1147		p := new(Place)
1148		p.Name = placename
1149		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1150		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1151		p.Url = placeurl
1152		honk.Place = p
1153	}
1154	timestart := strings.TrimSpace(r.FormValue("timestart"))
1155	if timestart != "" {
1156		t := new(Time)
1157		now := time.Now().Local()
1158		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1159			start, err := time.ParseInLocation(layout, timestart, now.Location())
1160			if err == nil {
1161				if start.Year() == 0 {
1162					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1163				}
1164				t.StartTime = start
1165				break
1166			}
1167		}
1168		timeend := r.FormValue("timeend")
1169		dur, err := time.ParseDuration(timeend)
1170		if err == nil {
1171			t.Duration = Duration(dur)
1172		}
1173		if !t.StartTime.IsZero() {
1174			honk.What = "event"
1175			honk.Time = t
1176		}
1177	}
1178
1179	if honk.Public {
1180		honk.Whofore = 2
1181	} else {
1182		honk.Whofore = 3
1183	}
1184
1185	// back to markdown
1186	honk.Noise = noise
1187
1188	if r.FormValue("preview") == "preview" {
1189		honks := []*Honk{honk}
1190		reverbolate(userinfo.UserID, honks)
1191		templinfo := getInfo(r)
1192		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1193		templinfo["Honks"] = honks
1194		templinfo["InReplyTo"] = r.FormValue("rid")
1195		templinfo["Noise"] = r.FormValue("noise")
1196		templinfo["SavedFile"] = donkxid
1197		templinfo["IsPreview"] = true
1198		templinfo["ServerMessage"] = "honk preview"
1199		err := readviews.Execute(w, "honkpage.html", templinfo)
1200		if err != nil {
1201			log.Print(err)
1202		}
1203		return
1204	}
1205
1206	if updatexid != "" {
1207		updatehonk(honk)
1208		oldjonks.Clear(honk.XID)
1209	} else {
1210		err := savehonk(honk)
1211		if err != nil {
1212			log.Printf("uh oh")
1213			return
1214		}
1215	}
1216
1217	// reload for consistency
1218	honk.Donks = nil
1219	donksforhonks([]*Honk{honk})
1220
1221	go honkworldwide(user, honk)
1222
1223	http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1224}
1225
1226func showhonkers(w http.ResponseWriter, r *http.Request) {
1227	userinfo := login.GetUserInfo(r)
1228	templinfo := getInfo(r)
1229	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1230	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1231	err := readviews.Execute(w, "honkers.html", templinfo)
1232	if err != nil {
1233		log.Print(err)
1234	}
1235}
1236
1237var combocache = cacheNew(cacheOptions{Filler: func(userid int64) ([]string, bool) {
1238	honkers := gethonkers(userid)
1239	var combos []string
1240	for _, h := range honkers {
1241		combos = append(combos, h.Combos...)
1242	}
1243	for i, c := range combos {
1244		if c == "-" {
1245			combos[i] = ""
1246		}
1247	}
1248	combos = oneofakind(combos)
1249	sort.Strings(combos)
1250	return combos, true
1251}})
1252
1253func showcombos(w http.ResponseWriter, r *http.Request) {
1254	userinfo := login.GetUserInfo(r)
1255	var combos []string
1256	combocache.Get(userinfo.UserID, &combos)
1257	templinfo := getInfo(r)
1258	err := readviews.Execute(w, "combos.html", templinfo)
1259	if err != nil {
1260		log.Print(err)
1261	}
1262}
1263
1264func submithonker(w http.ResponseWriter, r *http.Request) {
1265	u := login.GetUserInfo(r)
1266	name := strings.TrimSpace(r.FormValue("name"))
1267	url := strings.TrimSpace(r.FormValue("url"))
1268	peep := r.FormValue("peep")
1269	combos := strings.TrimSpace(r.FormValue("combos"))
1270	combos = " " + combos + " "
1271	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1272
1273	defer combocache.Clear(u.UserID)
1274	defer shortnames.Clear(u.UserID)
1275
1276	if honkerid > 0 {
1277		goodbye := r.FormValue("goodbye")
1278		if goodbye == "F" {
1279			db := opendatabase()
1280			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1281				honkerid, u.UserID)
1282			err := row.Scan(&url)
1283			if err != nil {
1284				log.Printf("can't get honker xid: %s", err)
1285				return
1286			}
1287			log.Printf("unsubscribing from %s", url)
1288			user, _ := butwhatabout(u.Username)
1289			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, "sub")
1290			if err != nil {
1291				log.Printf("error updating honker: %s", err)
1292				return
1293			}
1294			go itakeitallback(user, url)
1295
1296			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1297			return
1298		}
1299		if goodbye == "X" {
1300			db := opendatabase()
1301			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1302				honkerid, u.UserID)
1303			err := row.Scan(&url)
1304			if err != nil {
1305				log.Printf("can't get honker xid: %s", err)
1306				return
1307			}
1308			log.Printf("resubscribing to %s", url)
1309			user, _ := butwhatabout(u.Username)
1310			_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "unsub")
1311			if err == nil {
1312				_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "peep")
1313			}
1314			if err != nil {
1315				log.Printf("error updating honker: %s", err)
1316				return
1317			}
1318			go subsub(user, url)
1319
1320			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1321			return
1322		}
1323		_, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1324		if err != nil {
1325			log.Printf("update honker err: %s", err)
1326			return
1327		}
1328		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1329		return
1330	}
1331
1332	flavor := "presub"
1333	if peep == "peep" {
1334		flavor = "peep"
1335	}
1336	p, err := investigate(url)
1337	if err != nil {
1338		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1339		log.Printf("failed to investigate honker: %s", err)
1340		return
1341	}
1342	url = p.XID
1343
1344	db := opendatabase()
1345	row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1346	var x string
1347	err = row.Scan(&x)
1348	if err != sql.ErrNoRows {
1349		http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1350		if err != nil {
1351			log.Printf("honker scan err: %s", err)
1352		}
1353		return
1354	}
1355
1356	if name == "" {
1357		name = p.Handle
1358	}
1359	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1360	if err != nil {
1361		log.Print(err)
1362		return
1363	}
1364	if flavor == "presub" {
1365		user, _ := butwhatabout(u.Username)
1366		go subsub(user, url)
1367	}
1368	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1369}
1370
1371func hfcspage(w http.ResponseWriter, r *http.Request) {
1372	userinfo := login.GetUserInfo(r)
1373
1374	filters := getfilters(userinfo.UserID, filtAny)
1375
1376	templinfo := getInfo(r)
1377	templinfo["Filters"] = filters
1378	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1379	err := readviews.Execute(w, "hfcs.html", templinfo)
1380	if err != nil {
1381		log.Print(err)
1382	}
1383}
1384
1385func savehfcs(w http.ResponseWriter, r *http.Request) {
1386	userinfo := login.GetUserInfo(r)
1387	itsok := r.FormValue("itsok")
1388	if itsok == "iforgiveyou" {
1389		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1390		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1391		if err != nil {
1392			log.Printf("error deleting filter: %s", err)
1393		}
1394		filtcache.Clear(userinfo.UserID)
1395		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1396		return
1397	}
1398
1399	filt := new(Filter)
1400	filt.Name = strings.TrimSpace(r.FormValue("name"))
1401	filt.Date = time.Now().UTC()
1402	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1403	filt.IncludeAudience = r.FormValue("incaud") == "yes"
1404	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1405	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1406	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1407	filt.Reject = r.FormValue("doreject") == "yes"
1408	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1409	filt.Hide = r.FormValue("dohide") == "yes"
1410	filt.Collapse = r.FormValue("docollapse") == "yes"
1411	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1412	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1413
1414	if filt.Actor == "" && filt.Text == "" {
1415		log.Printf("blank filter")
1416		return
1417	}
1418
1419	j, err := jsonify(filt)
1420	if err == nil {
1421		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1422	}
1423	if err != nil {
1424		log.Printf("error saving filter: %s", err)
1425	}
1426
1427	filtcache.Clear(userinfo.UserID)
1428	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1429}
1430
1431func accountpage(w http.ResponseWriter, r *http.Request) {
1432	u := login.GetUserInfo(r)
1433	user, _ := butwhatabout(u.Username)
1434	templinfo := getInfo(r)
1435	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1436	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1437	templinfo["User"] = user
1438	err := readviews.Execute(w, "account.html", templinfo)
1439	if err != nil {
1440		log.Print(err)
1441	}
1442}
1443
1444func dochpass(w http.ResponseWriter, r *http.Request) {
1445	err := login.ChangePassword(w, r)
1446	if err != nil {
1447		log.Printf("error changing password: %s", err)
1448	}
1449	http.Redirect(w, r, "/account", http.StatusSeeOther)
1450}
1451
1452func fingerlicker(w http.ResponseWriter, r *http.Request) {
1453	orig := r.FormValue("resource")
1454
1455	log.Printf("finger lick: %s", orig)
1456
1457	if strings.HasPrefix(orig, "acct:") {
1458		orig = orig[5:]
1459	}
1460
1461	name := orig
1462	idx := strings.LastIndexByte(name, '/')
1463	if idx != -1 {
1464		name = name[idx+1:]
1465		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1466			log.Printf("foreign request rejected")
1467			name = ""
1468		}
1469	} else {
1470		idx = strings.IndexByte(name, '@')
1471		if idx != -1 {
1472			name = name[:idx]
1473			if name+"@"+serverName != orig {
1474				log.Printf("foreign request rejected")
1475				name = ""
1476			}
1477		}
1478	}
1479	user, err := butwhatabout(name)
1480	if err != nil {
1481		http.NotFound(w, r)
1482		return
1483	}
1484	if stealthmode(user.ID, r) {
1485		http.NotFound(w, r)
1486		return
1487	}
1488
1489	j := junk.New()
1490	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1491	j["aliases"] = []string{user.URL}
1492	var links []junk.Junk
1493	l := junk.New()
1494	l["rel"] = "self"
1495	l["type"] = `application/activity+json`
1496	l["href"] = user.URL
1497	links = append(links, l)
1498	j["links"] = links
1499
1500	w.Header().Set("Cache-Control", "max-age=3600")
1501	w.Header().Set("Content-Type", "application/jrd+json")
1502	j.Write(w)
1503}
1504
1505func somedays() string {
1506	secs := 432000 + notrand.Int63n(432000)
1507	return fmt.Sprintf("%d", secs)
1508}
1509
1510func avatate(w http.ResponseWriter, r *http.Request) {
1511	n := r.FormValue("a")
1512	a := avatar(n)
1513	w.Header().Set("Cache-Control", "max-age="+somedays())
1514	w.Write(a)
1515}
1516
1517func servecss(w http.ResponseWriter, r *http.Request) {
1518	fd, err := os.Open("views" + r.URL.Path)
1519	if err != nil {
1520		http.NotFound(w, r)
1521		return
1522	}
1523	w.Header().Set("Cache-Control", "max-age=0")
1524	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1525	err = css.Filter(fd, w)
1526	if err != nil {
1527		log.Printf("error filtering css: %s", err)
1528	}
1529}
1530func serveasset(w http.ResponseWriter, r *http.Request) {
1531	w.Header().Set("Cache-Control", "max-age=7776000")
1532	http.ServeFile(w, r, "views"+r.URL.Path)
1533}
1534func servehelp(w http.ResponseWriter, r *http.Request) {
1535	name := mux.Vars(r)["name"]
1536	w.Header().Set("Cache-Control", "max-age=600")
1537	http.ServeFile(w, r, "docs/"+name)
1538}
1539func servehtml(w http.ResponseWriter, r *http.Request) {
1540	templinfo := getInfo(r)
1541	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1542	if err != nil {
1543		log.Print(err)
1544	}
1545}
1546func serveemu(w http.ResponseWriter, r *http.Request) {
1547	xid := mux.Vars(r)["xid"]
1548	w.Header().Set("Cache-Control", "max-age="+somedays())
1549	http.ServeFile(w, r, "emus/"+xid)
1550}
1551func servememe(w http.ResponseWriter, r *http.Request) {
1552	xid := mux.Vars(r)["xid"]
1553	w.Header().Set("Cache-Control", "max-age="+somedays())
1554	http.ServeFile(w, r, "memes/"+xid)
1555}
1556
1557func servefile(w http.ResponseWriter, r *http.Request) {
1558	xid := mux.Vars(r)["xid"]
1559	row := stmtGetFileData.QueryRow(xid)
1560	var media string
1561	var data []byte
1562	err := row.Scan(&media, &data)
1563	if err != nil {
1564		log.Printf("error loading file: %s", err)
1565		http.NotFound(w, r)
1566		return
1567	}
1568	w.Header().Set("Content-Type", media)
1569	w.Header().Set("X-Content-Type-Options", "nosniff")
1570	w.Header().Set("Cache-Control", "max-age="+somedays())
1571	w.Write(data)
1572}
1573
1574func nomoroboto(w http.ResponseWriter, r *http.Request) {
1575	io.WriteString(w, "User-agent: *\n")
1576	io.WriteString(w, "Disallow: /a\n")
1577	io.WriteString(w, "Disallow: /d\n")
1578	io.WriteString(w, "Disallow: /meme\n")
1579	for _, u := range allusers() {
1580		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1581	}
1582}
1583
1584func webhydra(w http.ResponseWriter, r *http.Request) {
1585	u := login.GetUserInfo(r)
1586	userid := u.UserID
1587	templinfo := getInfo(r)
1588	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1589	page := r.FormValue("page")
1590	var honks []*Honk
1591	switch page {
1592	case "atme":
1593		honks = gethonksforme(userid)
1594		templinfo["ServerMessage"] = "at me!"
1595	case "home":
1596		honks = gethonksforuser(userid)
1597		honks = osmosis(honks, userid)
1598		templinfo["ServerMessage"] = serverMsg
1599	case "first":
1600		honks = gethonksforuserfirstclass(userid)
1601		honks = osmosis(honks, userid)
1602		templinfo["ServerMessage"] = "first class only"
1603	case "saved":
1604		honks = getsavedhonks(userid)
1605		templinfo["PageName"] = "saved"
1606		templinfo["ServerMessage"] = "saved honks"
1607	case "combo":
1608		c := r.FormValue("c")
1609		honks = gethonksbycombo(userid, c)
1610		honks = osmosis(honks, userid)
1611		templinfo["ServerMessage"] = "honks by combo: " + c
1612	case "convoy":
1613		c := r.FormValue("c")
1614		honks = gethonksbyconvoy(userid, c)
1615		templinfo["ServerMessage"] = "honks in convoy: " + c
1616	case "honker":
1617		xid := r.FormValue("xid")
1618		if strings.IndexByte(xid, '@') != -1 {
1619			xid = gofish(xid)
1620		}
1621		honks = gethonksbyxonker(userid, xid)
1622		xid = html.EscapeString(xid)
1623		msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
1624		templinfo["ServerMessage"] = template.HTML(msg)
1625	default:
1626		http.NotFound(w, r)
1627	}
1628	if len(honks) > 0 {
1629		templinfo["TopXID"] = honks[0].XID
1630	}
1631	if topxid := r.FormValue("topxid"); topxid != "" {
1632		for i, h := range honks {
1633			if h.XID == topxid {
1634				honks = honks[0:i]
1635				break
1636			}
1637		}
1638		log.Printf("topxid %d frags", len(honks))
1639	}
1640	reverbolate(userid, honks)
1641	templinfo["Honks"] = honks
1642	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1643	err := readviews.Execute(w, "honkfrags.html", templinfo)
1644	if err != nil {
1645		log.Printf("frag error: %s", err)
1646	}
1647}
1648
1649func serve() {
1650	db := opendatabase()
1651	login.Init(db)
1652
1653	listener, err := openListener()
1654	if err != nil {
1655		log.Fatal(err)
1656	}
1657	go redeliverator()
1658
1659	debug := false
1660	getconfig("debug", &debug)
1661	readviews = templates.Load(debug,
1662		"views/honkpage.html",
1663		"views/honkfrags.html",
1664		"views/honkers.html",
1665		"views/hfcs.html",
1666		"views/combos.html",
1667		"views/honkform.html",
1668		"views/honk.html",
1669		"views/account.html",
1670		"views/about.html",
1671		"views/funzone.html",
1672		"views/login.html",
1673		"views/xzone.html",
1674		"views/header.html",
1675		"views/onts.html",
1676		"views/honkpage.js",
1677	)
1678	if !debug {
1679		assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1680		for _, s := range assets {
1681			savedassetparams[s] = getassetparam(s)
1682		}
1683	}
1684
1685	mux := mux.NewRouter()
1686	mux.Use(login.Checker)
1687
1688	posters := mux.Methods("POST").Subrouter()
1689	getters := mux.Methods("GET").Subrouter()
1690
1691	getters.HandleFunc("/", homepage)
1692	getters.HandleFunc("/home", homepage)
1693	getters.HandleFunc("/front", homepage)
1694	getters.HandleFunc("/events", homepage)
1695	getters.HandleFunc("/robots.txt", nomoroboto)
1696	getters.HandleFunc("/rss", showrss)
1697	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1698	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1699	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1700	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1701	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1702	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1703	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1704	getters.HandleFunc("/a", avatate)
1705	getters.HandleFunc("/o", thelistingoftheontologies)
1706	getters.HandleFunc("/o/{name:.+}", showontology)
1707	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1708	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1709	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1710	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1711
1712	getters.HandleFunc("/style.css", servecss)
1713	getters.HandleFunc("/local.css", servecss)
1714	getters.HandleFunc("/honkpage.js", serveasset)
1715	getters.HandleFunc("/about", servehtml)
1716	getters.HandleFunc("/login", servehtml)
1717	posters.HandleFunc("/dologin", login.LoginFunc)
1718	getters.HandleFunc("/logout", login.LogoutFunc)
1719	getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
1720
1721	loggedin := mux.NewRoute().Subrouter()
1722	loggedin.Use(login.Required)
1723	loggedin.HandleFunc("/first", homepage)
1724	loggedin.HandleFunc("/saved", homepage)
1725	loggedin.HandleFunc("/account", accountpage)
1726	loggedin.HandleFunc("/funzone", showfunzone)
1727	loggedin.HandleFunc("/chpass", dochpass)
1728	loggedin.HandleFunc("/atme", homepage)
1729	loggedin.HandleFunc("/hfcs", hfcspage)
1730	loggedin.HandleFunc("/xzone", xzone)
1731	loggedin.HandleFunc("/edit", edithonkpage)
1732	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1733	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1734	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1735	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
1736	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1737	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1738	loggedin.HandleFunc("/honkers", showhonkers)
1739	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1740	loggedin.HandleFunc("/h", showhonker)
1741	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1742	loggedin.HandleFunc("/c", showcombos)
1743	loggedin.HandleFunc("/t", showconvoy)
1744	loggedin.HandleFunc("/q", showsearch)
1745	loggedin.HandleFunc("/hydra", webhydra)
1746	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1747
1748	err = http.Serve(listener, mux)
1749	if err != nil {
1750		log.Fatal(err)
1751	}
1752}