all repos — honk @ 2816bb2db70efac2361b547a426b4efec7c804ea

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