all repos — honk @ ddc61615a1aafa81de8da6e6c55697e11e134bd9

my fork of honk

web.go (view raw)

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