all repos — honk @ 4486057adcd0805c66e1e1a29f06c466508be110

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