all repos — honk @ e5e0a306fa1dfbcfb10c586cac46085ec94b02b3

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
1275	if honkerid > 0 {
1276		goodbye := r.FormValue("goodbye")
1277		if goodbye == "F" {
1278			db := opendatabase()
1279			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1280				honkerid, u.UserID)
1281			err := row.Scan(&url)
1282			if err != nil {
1283				log.Printf("can't get honker xid: %s", err)
1284				return
1285			}
1286			log.Printf("unsubscribing from %s", url)
1287			user, _ := butwhatabout(u.Username)
1288			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, "sub")
1289			if err != nil {
1290				log.Printf("error updating honker: %s", err)
1291				return
1292			}
1293			go itakeitallback(user, url)
1294
1295			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1296			return
1297		}
1298		if goodbye == "X" {
1299			db := opendatabase()
1300			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1301				honkerid, u.UserID)
1302			err := row.Scan(&url)
1303			if err != nil {
1304				log.Printf("can't get honker xid: %s", err)
1305				return
1306			}
1307			log.Printf("resubscribing to %s", url)
1308			user, _ := butwhatabout(u.Username)
1309			_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "unsub")
1310			if err == nil {
1311				_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "peep")
1312			}
1313			if err != nil {
1314				log.Printf("error updating honker: %s", err)
1315				return
1316			}
1317			go subsub(user, url)
1318
1319			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1320			return
1321		}
1322		_, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1323		if err != nil {
1324			log.Printf("update honker err: %s", err)
1325			return
1326		}
1327		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1328		return
1329	}
1330
1331	flavor := "presub"
1332	if peep == "peep" {
1333		flavor = "peep"
1334	}
1335	p, err := investigate(url)
1336	if err != nil {
1337		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1338		log.Printf("failed to investigate honker: %s", err)
1339		return
1340	}
1341	url = p.XID
1342
1343	db := opendatabase()
1344	row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1345	var x string
1346	err = row.Scan(&x)
1347	if err != sql.ErrNoRows {
1348		http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1349		if err != nil {
1350			log.Printf("honker scan err: %s", err)
1351		}
1352		return
1353	}
1354
1355	if name == "" {
1356		name = p.Handle
1357	}
1358	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1359	if err != nil {
1360		log.Print(err)
1361		return
1362	}
1363	if flavor == "presub" {
1364		user, _ := butwhatabout(u.Username)
1365		go subsub(user, url)
1366	}
1367	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1368}
1369
1370func hfcspage(w http.ResponseWriter, r *http.Request) {
1371	userinfo := login.GetUserInfo(r)
1372
1373	filters := getfilters(userinfo.UserID, filtAny)
1374
1375	templinfo := getInfo(r)
1376	templinfo["Filters"] = filters
1377	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1378	err := readviews.Execute(w, "hfcs.html", templinfo)
1379	if err != nil {
1380		log.Print(err)
1381	}
1382}
1383
1384func savehfcs(w http.ResponseWriter, r *http.Request) {
1385	userinfo := login.GetUserInfo(r)
1386	itsok := r.FormValue("itsok")
1387	if itsok == "iforgiveyou" {
1388		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1389		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1390		if err != nil {
1391			log.Printf("error deleting filter: %s", err)
1392		}
1393		filtcache.Clear(userinfo.UserID)
1394		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1395		return
1396	}
1397
1398	filt := new(Filter)
1399	filt.Name = strings.TrimSpace(r.FormValue("name"))
1400	filt.Date = time.Now().UTC()
1401	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1402	filt.IncludeAudience = r.FormValue("incaud") == "yes"
1403	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1404	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1405	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1406	filt.Reject = r.FormValue("doreject") == "yes"
1407	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1408	filt.Hide = r.FormValue("dohide") == "yes"
1409	filt.Collapse = r.FormValue("docollapse") == "yes"
1410	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1411	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1412
1413	if filt.Actor == "" && filt.Text == "" {
1414		log.Printf("blank filter")
1415		return
1416	}
1417
1418	j, err := jsonify(filt)
1419	if err == nil {
1420		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1421	}
1422	if err != nil {
1423		log.Printf("error saving filter: %s", err)
1424	}
1425
1426	filtcache.Clear(userinfo.UserID)
1427	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1428}
1429
1430func accountpage(w http.ResponseWriter, r *http.Request) {
1431	u := login.GetUserInfo(r)
1432	user, _ := butwhatabout(u.Username)
1433	templinfo := getInfo(r)
1434	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1435	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1436	templinfo["User"] = user
1437	err := readviews.Execute(w, "account.html", templinfo)
1438	if err != nil {
1439		log.Print(err)
1440	}
1441}
1442
1443func dochpass(w http.ResponseWriter, r *http.Request) {
1444	err := login.ChangePassword(w, r)
1445	if err != nil {
1446		log.Printf("error changing password: %s", err)
1447	}
1448	http.Redirect(w, r, "/account", http.StatusSeeOther)
1449}
1450
1451func fingerlicker(w http.ResponseWriter, r *http.Request) {
1452	orig := r.FormValue("resource")
1453
1454	log.Printf("finger lick: %s", orig)
1455
1456	if strings.HasPrefix(orig, "acct:") {
1457		orig = orig[5:]
1458	}
1459
1460	name := orig
1461	idx := strings.LastIndexByte(name, '/')
1462	if idx != -1 {
1463		name = name[idx+1:]
1464		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1465			log.Printf("foreign request rejected")
1466			name = ""
1467		}
1468	} else {
1469		idx = strings.IndexByte(name, '@')
1470		if idx != -1 {
1471			name = name[:idx]
1472			if name+"@"+serverName != orig {
1473				log.Printf("foreign request rejected")
1474				name = ""
1475			}
1476		}
1477	}
1478	user, err := butwhatabout(name)
1479	if err != nil {
1480		http.NotFound(w, r)
1481		return
1482	}
1483	if stealthmode(user.ID, r) {
1484		http.NotFound(w, r)
1485		return
1486	}
1487
1488	j := junk.New()
1489	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1490	j["aliases"] = []string{user.URL}
1491	var links []junk.Junk
1492	l := junk.New()
1493	l["rel"] = "self"
1494	l["type"] = `application/activity+json`
1495	l["href"] = user.URL
1496	links = append(links, l)
1497	j["links"] = links
1498
1499	w.Header().Set("Cache-Control", "max-age=3600")
1500	w.Header().Set("Content-Type", "application/jrd+json")
1501	j.Write(w)
1502}
1503
1504func somedays() string {
1505	secs := 432000 + notrand.Int63n(432000)
1506	return fmt.Sprintf("%d", secs)
1507}
1508
1509func avatate(w http.ResponseWriter, r *http.Request) {
1510	n := r.FormValue("a")
1511	a := avatar(n)
1512	w.Header().Set("Cache-Control", "max-age="+somedays())
1513	w.Write(a)
1514}
1515
1516func servecss(w http.ResponseWriter, r *http.Request) {
1517	fd, err := os.Open("views" + r.URL.Path)
1518	if err != nil {
1519		http.NotFound(w, r)
1520		return
1521	}
1522	w.Header().Set("Cache-Control", "max-age=0")
1523	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1524	err = css.Filter(fd, w)
1525	if err != nil {
1526		log.Printf("error filtering css: %s", err)
1527	}
1528}
1529func serveasset(w http.ResponseWriter, r *http.Request) {
1530	w.Header().Set("Cache-Control", "max-age=7776000")
1531	http.ServeFile(w, r, "views"+r.URL.Path)
1532}
1533func servehelp(w http.ResponseWriter, r *http.Request) {
1534	name := mux.Vars(r)["name"]
1535	w.Header().Set("Cache-Control", "max-age=600")
1536	http.ServeFile(w, r, "docs/"+name)
1537}
1538func servehtml(w http.ResponseWriter, r *http.Request) {
1539	templinfo := getInfo(r)
1540	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1541	if err != nil {
1542		log.Print(err)
1543	}
1544}
1545func serveemu(w http.ResponseWriter, r *http.Request) {
1546	xid := mux.Vars(r)["xid"]
1547	w.Header().Set("Cache-Control", "max-age="+somedays())
1548	http.ServeFile(w, r, "emus/"+xid)
1549}
1550func servememe(w http.ResponseWriter, r *http.Request) {
1551	xid := mux.Vars(r)["xid"]
1552	w.Header().Set("Cache-Control", "max-age="+somedays())
1553	http.ServeFile(w, r, "memes/"+xid)
1554}
1555
1556func servefile(w http.ResponseWriter, r *http.Request) {
1557	xid := mux.Vars(r)["xid"]
1558	row := stmtGetFileData.QueryRow(xid)
1559	var media string
1560	var data []byte
1561	err := row.Scan(&media, &data)
1562	if err != nil {
1563		log.Printf("error loading file: %s", err)
1564		http.NotFound(w, r)
1565		return
1566	}
1567	w.Header().Set("Content-Type", media)
1568	w.Header().Set("X-Content-Type-Options", "nosniff")
1569	w.Header().Set("Cache-Control", "max-age="+somedays())
1570	w.Write(data)
1571}
1572
1573func nomoroboto(w http.ResponseWriter, r *http.Request) {
1574	io.WriteString(w, "User-agent: *\n")
1575	io.WriteString(w, "Disallow: /a\n")
1576	io.WriteString(w, "Disallow: /d\n")
1577	io.WriteString(w, "Disallow: /meme\n")
1578	for _, u := range allusers() {
1579		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1580	}
1581}
1582
1583func webhydra(w http.ResponseWriter, r *http.Request) {
1584	u := login.GetUserInfo(r)
1585	userid := u.UserID
1586	templinfo := getInfo(r)
1587	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1588	page := r.FormValue("page")
1589	var honks []*Honk
1590	switch page {
1591	case "atme":
1592		honks = gethonksforme(userid)
1593		templinfo["ServerMessage"] = "at me!"
1594	case "home":
1595		honks = gethonksforuser(userid)
1596		honks = osmosis(honks, userid)
1597		templinfo["ServerMessage"] = serverMsg
1598	case "first":
1599		honks = gethonksforuserfirstclass(userid)
1600		honks = osmosis(honks, userid)
1601		templinfo["ServerMessage"] = "first class only"
1602	case "saved":
1603		honks = getsavedhonks(userid)
1604		templinfo["PageName"] = "saved"
1605		templinfo["ServerMessage"] = "saved honks"
1606	case "combo":
1607		c := r.FormValue("c")
1608		honks = gethonksbycombo(userid, c)
1609		honks = osmosis(honks, userid)
1610		templinfo["ServerMessage"] = "honks by combo: " + c
1611	case "convoy":
1612		c := r.FormValue("c")
1613		honks = gethonksbyconvoy(userid, c)
1614		templinfo["ServerMessage"] = "honks in convoy: " + c
1615	case "honker":
1616		xid := r.FormValue("xid")
1617		if strings.IndexByte(xid, '@') != -1 {
1618			xid = gofish(xid)
1619		}
1620		honks = gethonksbyxonker(userid, xid)
1621		xid = html.EscapeString(xid)
1622		msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
1623		templinfo["ServerMessage"] = template.HTML(msg)
1624	default:
1625		http.NotFound(w, r)
1626	}
1627	if len(honks) > 0 {
1628		templinfo["TopXID"] = honks[0].XID
1629	}
1630	if topxid := r.FormValue("topxid"); topxid != "" {
1631		for i, h := range honks {
1632			if h.XID == topxid {
1633				honks = honks[0:i]
1634				break
1635			}
1636		}
1637		log.Printf("topxid %d frags", len(honks))
1638	}
1639	reverbolate(userid, honks)
1640	templinfo["Honks"] = honks
1641	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1642	err := readviews.Execute(w, "honkfrags.html", templinfo)
1643	if err != nil {
1644		log.Printf("frag error: %s", err)
1645	}
1646}
1647
1648func serve() {
1649	db := opendatabase()
1650	login.Init(db)
1651
1652	listener, err := openListener()
1653	if err != nil {
1654		log.Fatal(err)
1655	}
1656	go redeliverator()
1657
1658	debug := false
1659	getconfig("debug", &debug)
1660	readviews = templates.Load(debug,
1661		"views/honkpage.html",
1662		"views/honkfrags.html",
1663		"views/honkers.html",
1664		"views/hfcs.html",
1665		"views/combos.html",
1666		"views/honkform.html",
1667		"views/honk.html",
1668		"views/account.html",
1669		"views/about.html",
1670		"views/funzone.html",
1671		"views/login.html",
1672		"views/xzone.html",
1673		"views/header.html",
1674		"views/onts.html",
1675		"views/honkpage.js",
1676	)
1677	if !debug {
1678		assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1679		for _, s := range assets {
1680			savedassetparams[s] = getassetparam(s)
1681		}
1682	}
1683
1684	mux := mux.NewRouter()
1685	mux.Use(login.Checker)
1686
1687	posters := mux.Methods("POST").Subrouter()
1688	getters := mux.Methods("GET").Subrouter()
1689
1690	getters.HandleFunc("/", homepage)
1691	getters.HandleFunc("/home", homepage)
1692	getters.HandleFunc("/front", homepage)
1693	getters.HandleFunc("/events", homepage)
1694	getters.HandleFunc("/robots.txt", nomoroboto)
1695	getters.HandleFunc("/rss", showrss)
1696	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1697	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1698	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1699	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1700	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1701	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1702	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1703	getters.HandleFunc("/a", avatate)
1704	getters.HandleFunc("/o", thelistingoftheontologies)
1705	getters.HandleFunc("/o/{name:.+}", showontology)
1706	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1707	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1708	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1709	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1710
1711	getters.HandleFunc("/style.css", servecss)
1712	getters.HandleFunc("/local.css", servecss)
1713	getters.HandleFunc("/honkpage.js", serveasset)
1714	getters.HandleFunc("/about", servehtml)
1715	getters.HandleFunc("/login", servehtml)
1716	posters.HandleFunc("/dologin", login.LoginFunc)
1717	getters.HandleFunc("/logout", login.LogoutFunc)
1718	getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
1719
1720	loggedin := mux.NewRoute().Subrouter()
1721	loggedin.Use(login.Required)
1722	loggedin.HandleFunc("/first", homepage)
1723	loggedin.HandleFunc("/saved", homepage)
1724	loggedin.HandleFunc("/account", accountpage)
1725	loggedin.HandleFunc("/funzone", showfunzone)
1726	loggedin.HandleFunc("/chpass", dochpass)
1727	loggedin.HandleFunc("/atme", homepage)
1728	loggedin.HandleFunc("/hfcs", hfcspage)
1729	loggedin.HandleFunc("/xzone", xzone)
1730	loggedin.HandleFunc("/edit", edithonkpage)
1731	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1732	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1733	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1734	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
1735	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1736	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1737	loggedin.HandleFunc("/honkers", showhonkers)
1738	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1739	loggedin.HandleFunc("/h", showhonker)
1740	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1741	loggedin.HandleFunc("/c", showcombos)
1742	loggedin.HandleFunc("/t", showconvoy)
1743	loggedin.HandleFunc("/q", showsearch)
1744	loggedin.HandleFunc("/hydra", webhydra)
1745	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1746
1747	err = http.Serve(listener, mux)
1748	if err != nil {
1749		log.Fatal(err)
1750	}
1751}