all repos — honk @ a0b721897cb67ad05c730f2440e180998f9d8dec

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	"os/signal"
  30	"regexp"
  31	"sort"
  32	"strconv"
  33	"strings"
  34	"syscall"
  35	"time"
  36
  37	"github.com/gorilla/mux"
  38	"humungus.tedunangst.com/r/webs/cache"
  39	"humungus.tedunangst.com/r/webs/httpsig"
  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.Options.SkinnyCSS {
  57		return "main { max-width: 700px; }"
  58	}
  59	return ""
  60}
  61
  62func getmaplink(u *login.UserInfo) string {
  63	if u == nil {
  64		return "osm"
  65	}
  66	user, _ := butwhatabout(u.Username)
  67	ml := user.Options.MapLink
  68	if ml == "" {
  69		ml = "osm"
  70	}
  71	return ml
  72}
  73
  74func getInfo(r *http.Request) map[string]interface{} {
  75	u := login.GetUserInfo(r)
  76	templinfo := make(map[string]interface{})
  77	templinfo["StyleParam"] = getassetparam(viewDir + "/views/style.css")
  78	templinfo["LocalStyleParam"] = getassetparam(viewDir + "/views/local.css")
  79	templinfo["JSParam"] = getassetparam(viewDir + "/views/honkpage.js")
  80	templinfo["UserStyle"] = getuserstyle(u)
  81	templinfo["ServerName"] = serverName
  82	templinfo["IconName"] = iconName
  83	templinfo["UserInfo"] = u
  84	templinfo["UserSep"] = userSep
  85	if u != nil {
  86		var combos []string
  87		combocache.Get(u.UserID, &combos)
  88		templinfo["Combos"] = combos
  89	}
  90	return templinfo
  91}
  92
  93func homepage(w http.ResponseWriter, r *http.Request) {
  94	templinfo := getInfo(r)
  95	u := login.GetUserInfo(r)
  96	var honks []*Honk
  97	var userid int64 = -1
  98
  99	templinfo["ServerMessage"] = serverMsg
 100	if u == nil || r.URL.Path == "/front" {
 101		switch r.URL.Path {
 102		case "/events":
 103			honks = geteventhonks(userid)
 104			templinfo["ServerMessage"] = "some recent and upcoming events"
 105		default:
 106			templinfo["ShowRSS"] = true
 107			honks = getpublichonks()
 108		}
 109	} else {
 110		userid = u.UserID
 111		switch r.URL.Path {
 112		case "/atme":
 113			templinfo["ServerMessage"] = "at me!"
 114			templinfo["PageName"] = "atme"
 115			honks = gethonksforme(userid, 0)
 116			honks = osmosis(honks, userid, false)
 117		case "/events":
 118			templinfo["ServerMessage"] = "some recent and upcoming events"
 119			templinfo["PageName"] = "events"
 120			honks = geteventhonks(userid)
 121			honks = osmosis(honks, userid, true)
 122		case "/first":
 123			templinfo["PageName"] = "first"
 124			honks = gethonksforuserfirstclass(userid, 0)
 125			honks = osmosis(honks, userid, true)
 126		case "/saved":
 127			templinfo["ServerMessage"] = "saved honks"
 128			templinfo["PageName"] = "saved"
 129			honks = getsavedhonks(userid, 0)
 130		default:
 131			templinfo["PageName"] = "home"
 132			honks = gethonksforuser(userid, 0)
 133			honks = osmosis(honks, userid, true)
 134		}
 135		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 136	}
 137
 138	honkpage(w, u, honks, templinfo)
 139}
 140
 141func showfunzone(w http.ResponseWriter, r *http.Request) {
 142	var emunames, memenames []string
 143	dir, err := os.Open(dataDir + "/emus")
 144	if err == nil {
 145		emunames, _ = dir.Readdirnames(0)
 146		dir.Close()
 147	}
 148	for i, e := range emunames {
 149		if len(e) > 4 {
 150			emunames[i] = e[:len(e)-4]
 151		}
 152	}
 153	dir, err = os.Open(dataDir + "/memes")
 154	if err == nil {
 155		memenames, _ = dir.Readdirnames(0)
 156		dir.Close()
 157	}
 158	templinfo := getInfo(r)
 159	templinfo["Emus"] = emunames
 160	templinfo["Memes"] = memenames
 161	err = readviews.Execute(w, "funzone.html", templinfo)
 162	if err != nil {
 163		log.Print(err)
 164	}
 165}
 166
 167func showrss(w http.ResponseWriter, r *http.Request) {
 168	name := mux.Vars(r)["name"]
 169
 170	var honks []*Honk
 171	if name != "" {
 172		honks = gethonksbyuser(name, false, 0)
 173	} else {
 174		honks = getpublichonks()
 175	}
 176	reverbolate(-1, honks)
 177
 178	home := fmt.Sprintf("https://%s/", serverName)
 179	base := home
 180	if name != "" {
 181		home += "u/" + name
 182		name += " "
 183	}
 184	feed := rss.Feed{
 185		Title:       name + "honk",
 186		Link:        home,
 187		Description: name + "honk rss",
 188		Image: &rss.Image{
 189			URL:   base + "icon.png",
 190			Title: name + "honk rss",
 191			Link:  home,
 192		},
 193	}
 194	var modtime time.Time
 195	for _, honk := range honks {
 196		if !firstclass(honk) {
 197			continue
 198		}
 199		desc := string(honk.HTML)
 200		if t := honk.Time; t != nil {
 201			desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM EDT Mon Jan 02"))
 202			if t.Duration != 0 {
 203				desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
 204			}
 205		}
 206		if p := honk.Place; p != nil {
 207			desc += string(templates.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
 208				p.Url, p.Name, p.Latitude, p.Longitude))
 209		}
 210		for _, d := range honk.Donks {
 211			desc += string(templates.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
 212				d.URL, d.Name))
 213		}
 214
 215		feed.Items = append(feed.Items, &rss.Item{
 216			Title:       fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
 217			Description: rss.CData{Data: desc},
 218			Link:        honk.URL,
 219			PubDate:     honk.Date.Format(time.RFC1123),
 220			Guid:        &rss.Guid{IsPermaLink: true, Value: honk.URL},
 221		})
 222		if honk.Date.After(modtime) {
 223			modtime = honk.Date
 224		}
 225	}
 226	w.Header().Set("Cache-Control", "max-age=300")
 227	w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
 228
 229	err := feed.Write(w)
 230	if err != nil {
 231		log.Printf("error writing rss: %s", err)
 232	}
 233}
 234
 235func crappola(j junk.Junk) bool {
 236	t, _ := j.GetString("type")
 237	a, _ := j.GetString("actor")
 238	o, _ := j.GetString("object")
 239	if t == "Delete" && a == o {
 240		log.Printf("crappola from %s", a)
 241		return true
 242	}
 243	return false
 244}
 245
 246func ping(user *WhatAbout, who string) {
 247	var box *Box
 248	ok := boxofboxes.Get(who, &box)
 249	if !ok {
 250		log.Printf("no inbox to ping %s", who)
 251		return
 252	}
 253	j := junk.New()
 254	j["@context"] = itiswhatitis
 255	j["type"] = "Ping"
 256	j["id"] = user.URL + "/ping/" + xfiltrate()
 257	j["actor"] = user.URL
 258	j["to"] = who
 259	ki := ziggy(user.ID)
 260	if ki == nil {
 261		return
 262	}
 263	err := PostJunk(ki.keyname, ki.seckey, box.In, j)
 264	if err != nil {
 265		log.Printf("can't send ping: %s", err)
 266		return
 267	}
 268	log.Printf("sent ping to %s: %s", who, j["id"])
 269}
 270
 271func pong(user *WhatAbout, who string, obj string) {
 272	var box *Box
 273	ok := boxofboxes.Get(who, &box)
 274	if !ok {
 275		log.Printf("no inbox to pong %s", who)
 276		return
 277	}
 278	j := junk.New()
 279	j["@context"] = itiswhatitis
 280	j["type"] = "Pong"
 281	j["id"] = user.URL + "/pong/" + xfiltrate()
 282	j["actor"] = user.URL
 283	j["to"] = who
 284	j["object"] = obj
 285	ki := ziggy(user.ID)
 286	if ki == nil {
 287		return
 288	}
 289	err := PostJunk(ki.keyname, ki.seckey, box.In, j)
 290	if err != nil {
 291		log.Printf("can't send pong: %s", err)
 292		return
 293	}
 294}
 295
 296func inbox(w http.ResponseWriter, r *http.Request) {
 297	name := mux.Vars(r)["name"]
 298	user, err := butwhatabout(name)
 299	if err != nil {
 300		http.NotFound(w, r)
 301		return
 302	}
 303	if stealthmode(user.ID, r) {
 304		http.NotFound(w, r)
 305		return
 306	}
 307	var buf bytes.Buffer
 308	limiter := io.LimitReader(r.Body, 1*1024*1024)
 309	io.Copy(&buf, limiter)
 310	payload := buf.Bytes()
 311	j, err := junk.FromBytes(payload)
 312	if err != nil {
 313		log.Printf("bad payload: %s", err)
 314		io.WriteString(os.Stdout, "bad payload\n")
 315		os.Stdout.Write(payload)
 316		io.WriteString(os.Stdout, "\n")
 317		return
 318	}
 319
 320	if crappola(j) {
 321		return
 322	}
 323	what, _ := j.GetString("type")
 324	if what == "Like" {
 325		return
 326	}
 327	who, _ := j.GetString("actor")
 328	if rejectactor(user.ID, who) {
 329		return
 330	}
 331
 332	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 333	if err != nil && keyname != "" {
 334		savingthrow(keyname)
 335		keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
 336	}
 337	if err != nil {
 338		log.Printf("inbox message failed signature for %s from %s", keyname, r.Header.Get("X-Forwarded-For"))
 339		if keyname != "" {
 340			log.Printf("bad signature from %s", keyname)
 341			io.WriteString(os.Stdout, "bad payload\n")
 342			os.Stdout.Write(payload)
 343			io.WriteString(os.Stdout, "\n")
 344		}
 345		http.Error(w, "what did you call me?", http.StatusTeapot)
 346		return
 347	}
 348	origin := keymatch(keyname, who)
 349	if origin == "" {
 350		log.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 351		return
 352	}
 353
 354	switch what {
 355	case "Ping":
 356		obj, _ := j.GetString("id")
 357		log.Printf("ping from %s: %s", who, obj)
 358		pong(user, who, obj)
 359	case "Pong":
 360		obj, _ := j.GetString("object")
 361		log.Printf("pong from %s: %s", who, obj)
 362	case "Follow":
 363		obj, _ := j.GetString("object")
 364		if obj != user.URL {
 365			log.Printf("can't follow %s", obj)
 366			return
 367		}
 368		log.Printf("updating honker follow: %s", who)
 369
 370		var x string
 371		db := opendatabase()
 372		row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('dub', 'undub')", who, user.ID)
 373		err = row.Scan(&x)
 374		if err != sql.ErrNoRows {
 375			log.Printf("duplicate follow request: %s", who)
 376			_, err = stmtUpdateFlavor.Exec("dub", user.ID, who, who, "undub")
 377			if err != nil {
 378				log.Printf("error updating honker: %s", err)
 379			}
 380		} else {
 381			stmtSaveDub.Exec(user.ID, who, who, "dub")
 382		}
 383		go rubadubdub(user, j)
 384	case "Accept":
 385		log.Printf("updating honker accept: %s", who)
 386		var name string
 387		db := opendatabase()
 388		row := db.QueryRow("select name from honkers where userid = ? and xid = ? and flavor in ('presub')",
 389			user.ID, who)
 390		err := row.Scan(&name)
 391		if err != nil {
 392			log.Printf("can't get honker name: %s", err)
 393			return
 394		}
 395		_, err = stmtUpdateFlavor.Exec("sub", user.ID, who, name, "presub")
 396		if err != nil {
 397			log.Printf("error updating honker: %s", err)
 398			return
 399		}
 400	case "Update":
 401		obj, ok := j.GetMap("object")
 402		if ok {
 403			what, _ := obj.GetString("type")
 404			switch what {
 405			case "Person":
 406				return
 407			case "Question":
 408				return
 409			case "Note":
 410				go xonksaver(user, j, origin)
 411				return
 412			}
 413		}
 414		log.Printf("unknown Update activity")
 415		fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 416		j.Write(fd)
 417		io.WriteString(fd, "\n")
 418		fd.Close()
 419
 420	case "Undo":
 421		obj, ok := j.GetMap("object")
 422		if !ok {
 423			log.Printf("unknown undo no object")
 424			return
 425		}
 426		what, _ := obj.GetString("type")
 427		switch what {
 428		case "Follow":
 429			log.Printf("updating honker undo: %s", who)
 430			_, err = stmtUpdateFlavor.Exec("undub", user.ID, who, who, "dub")
 431			if err != nil {
 432				log.Printf("error updating honker: %s", err)
 433				return
 434			}
 435		case "Announce":
 436			xid, _ := obj.GetString("object")
 437			log.Printf("undo announce: %s", xid)
 438		case "Like":
 439		default:
 440			log.Printf("unknown undo: %s", what)
 441		}
 442	default:
 443		go xonksaver(user, j, origin)
 444	}
 445}
 446
 447func serverinbox(w http.ResponseWriter, r *http.Request) {
 448	if stealthmode(serverUID, r) {
 449		http.NotFound(w, r)
 450		return
 451	}
 452	var buf bytes.Buffer
 453	io.Copy(&buf, r.Body)
 454	payload := buf.Bytes()
 455	j, err := junk.FromBytes(payload)
 456	if err != nil {
 457		log.Printf("bad payload: %s", err)
 458		io.WriteString(os.Stdout, "bad payload\n")
 459		os.Stdout.Write(payload)
 460		io.WriteString(os.Stdout, "\n")
 461		return
 462	}
 463	if crappola(j) {
 464		return
 465	}
 466	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 467	if err != nil && keyname != "" {
 468		savingthrow(keyname)
 469		keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
 470	}
 471	if err != nil {
 472		log.Printf("inbox message failed signature for %s from %s", keyname, r.Header.Get("X-Forwarded-For"))
 473		if keyname != "" {
 474			log.Printf("bad signature from %s", keyname)
 475			io.WriteString(os.Stdout, "bad payload\n")
 476			os.Stdout.Write(payload)
 477			io.WriteString(os.Stdout, "\n")
 478		}
 479		http.Error(w, "what did you call me?", http.StatusTeapot)
 480		return
 481	}
 482	user := getserveruser()
 483	who, _ := j.GetString("actor")
 484	origin := keymatch(keyname, who)
 485	if origin == "" {
 486		log.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 487		return
 488	}
 489	if rejectactor(user.ID, who) {
 490		return
 491	}
 492	re_ont := regexp.MustCompile("https://" + serverName + "/o/([[:alnum:]]+)")
 493	what, _ := j.GetString("type")
 494	log.Printf("server got a %s", what)
 495	switch what {
 496	case "Follow":
 497		obj, _ := j.GetString("object")
 498		if obj == user.URL {
 499			log.Printf("can't follow the server!")
 500			return
 501		}
 502		m := re_ont.FindStringSubmatch(obj)
 503		if len(m) != 2 {
 504			log.Printf("not sure how to handle this")
 505			return
 506		}
 507		ont := "#" + m[1]
 508		log.Printf("%s wants to follow %s", who, ont)
 509		var x string
 510		db := opendatabase()
 511		row := db.QueryRow("select xid from honkers where name = ? and xid = ? and userid = ? and flavor in ('dub', 'undub')", ont, who, user.ID)
 512		err = row.Scan(&x)
 513		if err != sql.ErrNoRows {
 514			log.Printf("duplicate follow request: %s", who)
 515			_, err = stmtUpdateFlavor.Exec("dub", user.ID, who, ont, "undub")
 516			if err != nil {
 517				log.Printf("error updating honker: %s", err)
 518			}
 519		} else {
 520			stmtSaveDub.Exec(user.ID, ont, who, "dub")
 521		}
 522		go rubadubdub(user, j)
 523	case "Undo":
 524		obj, ok := j.GetMap("object")
 525		if !ok {
 526			log.Printf("unknown undo no object")
 527			return
 528		}
 529		what, _ := obj.GetString("type")
 530		if what != "Follow" {
 531			log.Printf("unknown undo: %s", what)
 532		}
 533		targ, _ := obj.GetString("object")
 534		m := re_ont.FindStringSubmatch(targ)
 535		if len(m) != 2 {
 536			log.Printf("not sure how to handle this")
 537			return
 538		}
 539		ont := "#" + m[1]
 540		log.Printf("updating honker undo: %s %s", who, ont)
 541		_, err = stmtUpdateFlavor.Exec("undub", user.ID, who, ont, "dub")
 542		if err != nil {
 543			log.Printf("error updating honker: %s", err)
 544			return
 545		}
 546	}
 547}
 548
 549func serveractor(w http.ResponseWriter, r *http.Request) {
 550	if stealthmode(serverUID, r) {
 551		http.NotFound(w, r)
 552		return
 553	}
 554	user := getserveruser()
 555	j := junkuser(user)
 556	w.Write(j)
 557}
 558
 559func ximport(w http.ResponseWriter, r *http.Request) {
 560	u := login.GetUserInfo(r)
 561	xid := strings.TrimSpace(r.FormValue("xid"))
 562	xonk := getxonk(u.UserID, xid)
 563	if xonk == nil {
 564		p, _ := investigate(xid)
 565		if p != nil {
 566			xid = p.XID
 567		}
 568		j, err := GetJunk(xid)
 569		if err != nil {
 570			http.Error(w, "error getting external object", http.StatusInternalServerError)
 571			log.Printf("error getting external object: %s", err)
 572			return
 573		}
 574		allinjest(originate(xid), j)
 575		log.Printf("importing %s", xid)
 576		user, _ := butwhatabout(u.Username)
 577
 578		info, _ := somethingabout(j)
 579		if info == nil {
 580			xonk = xonksaver(user, j, originate(xid))
 581		} else if info.What == SomeActor {
 582			outbox, _ := j.GetString("outbox")
 583			gimmexonks(user, outbox)
 584			http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
 585			return
 586		} else if info.What == SomeCollection {
 587			gimmexonks(user, xid)
 588			http.Redirect(w, r, "/xzone", http.StatusSeeOther)
 589			return
 590		}
 591	}
 592	convoy := ""
 593	if xonk != nil {
 594		convoy = xonk.Convoy
 595	}
 596	http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
 597}
 598
 599func xzone(w http.ResponseWriter, r *http.Request) {
 600	u := login.GetUserInfo(r)
 601	rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
 602	if err != nil {
 603		log.Printf("query err: %s", err)
 604		return
 605	}
 606	defer rows.Close()
 607	var honkers []Honker
 608	for rows.Next() {
 609		var xid string
 610		rows.Scan(&xid)
 611		honkers = append(honkers, Honker{XID: xid})
 612	}
 613	rows.Close()
 614	for i, _ := range honkers {
 615		_, honkers[i].Handle = handles(honkers[i].XID)
 616	}
 617	templinfo := getInfo(r)
 618	templinfo["XCSRF"] = login.GetCSRF("ximport", r)
 619	templinfo["Honkers"] = honkers
 620	err = readviews.Execute(w, "xzone.html", templinfo)
 621	if err != nil {
 622		log.Print(err)
 623	}
 624}
 625
 626var oldoutbox = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
 627	user, err := butwhatabout(name)
 628	if err != nil {
 629		return nil, false
 630	}
 631	honks := gethonksbyuser(name, false, 0)
 632	if len(honks) > 20 {
 633		honks = honks[0:20]
 634	}
 635
 636	var jonks []junk.Junk
 637	for _, h := range honks {
 638		j, _ := jonkjonk(user, h)
 639		jonks = append(jonks, j)
 640	}
 641
 642	j := junk.New()
 643	j["@context"] = itiswhatitis
 644	j["id"] = user.URL + "/outbox"
 645	j["attributedTo"] = user.URL
 646	j["type"] = "OrderedCollection"
 647	j["totalItems"] = len(jonks)
 648	j["orderedItems"] = jonks
 649
 650	return j.ToBytes(), true
 651}, Duration: 1 * time.Minute})
 652
 653func outbox(w http.ResponseWriter, r *http.Request) {
 654	name := mux.Vars(r)["name"]
 655	user, err := butwhatabout(name)
 656	if err != nil {
 657		http.NotFound(w, r)
 658		return
 659	}
 660	if stealthmode(user.ID, r) {
 661		http.NotFound(w, r)
 662		return
 663	}
 664	var j []byte
 665	ok := oldoutbox.Get(name, &j)
 666	if ok {
 667		w.Header().Set("Content-Type", theonetruename)
 668		w.Write(j)
 669	} else {
 670		http.NotFound(w, r)
 671	}
 672}
 673
 674var oldempties = cache.New(cache.Options{Filler: func(url string) ([]byte, bool) {
 675	colname := "/followers"
 676	if strings.HasSuffix(url, "/following") {
 677		colname = "/following"
 678	}
 679	user := fmt.Sprintf("https://%s%s", serverName, url[:len(url)-10])
 680	j := junk.New()
 681	j["@context"] = itiswhatitis
 682	j["id"] = user + colname
 683	j["attributedTo"] = user
 684	j["type"] = "OrderedCollection"
 685	j["totalItems"] = 0
 686	j["orderedItems"] = []junk.Junk{}
 687
 688	return j.ToBytes(), true
 689}})
 690
 691func emptiness(w http.ResponseWriter, r *http.Request) {
 692	name := mux.Vars(r)["name"]
 693	user, err := butwhatabout(name)
 694	if err != nil {
 695		http.NotFound(w, r)
 696		return
 697	}
 698	if stealthmode(user.ID, r) {
 699		http.NotFound(w, r)
 700		return
 701	}
 702	var j []byte
 703	ok := oldempties.Get(r.URL.Path, &j)
 704	if ok {
 705		w.Header().Set("Content-Type", theonetruename)
 706		w.Write(j)
 707	} else {
 708		http.NotFound(w, r)
 709	}
 710}
 711
 712func showuser(w http.ResponseWriter, r *http.Request) {
 713	name := mux.Vars(r)["name"]
 714	user, err := butwhatabout(name)
 715	if err != nil {
 716		log.Printf("user not found %s: %s", name, err)
 717		http.NotFound(w, r)
 718		return
 719	}
 720	if stealthmode(user.ID, r) {
 721		http.NotFound(w, r)
 722		return
 723	}
 724	if friendorfoe(r.Header.Get("Accept")) {
 725		j, ok := asjonker(name)
 726		if ok {
 727			w.Header().Set("Content-Type", theonetruename)
 728			w.Write(j)
 729		} else {
 730			http.NotFound(w, r)
 731		}
 732		return
 733	}
 734	u := login.GetUserInfo(r)
 735	honks := gethonksbyuser(name, u != nil && u.Username == name, 0)
 736	templinfo := getInfo(r)
 737	templinfo["Name"] = user.Name
 738	whatabout := user.About
 739	whatabout = markitzero(user.About)
 740	templinfo["WhatAbout"] = template.HTML(whatabout)
 741	templinfo["ServerMessage"] = ""
 742	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 743	honkpage(w, u, honks, templinfo)
 744}
 745
 746func showhonker(w http.ResponseWriter, r *http.Request) {
 747	u := login.GetUserInfo(r)
 748	name := mux.Vars(r)["name"]
 749	var honks []*Honk
 750	if name == "" {
 751		name = r.FormValue("xid")
 752		honks = gethonksbyxonker(u.UserID, name, 0)
 753	} else {
 754		honks = gethonksbyhonker(u.UserID, name, 0)
 755	}
 756	msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, name, name)
 757	templinfo := getInfo(r)
 758	templinfo["PageName"] = "honker"
 759	templinfo["PageArg"] = name
 760	templinfo["ServerMessage"] = msg
 761	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 762	honkpage(w, u, honks, templinfo)
 763}
 764
 765func showcombo(w http.ResponseWriter, r *http.Request) {
 766	name := mux.Vars(r)["name"]
 767	u := login.GetUserInfo(r)
 768	honks := gethonksbycombo(u.UserID, name, 0)
 769	honks = osmosis(honks, u.UserID, true)
 770	templinfo := getInfo(r)
 771	templinfo["PageName"] = "combo"
 772	templinfo["PageArg"] = name
 773	templinfo["ServerMessage"] = "honks by combo: " + name
 774	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 775	honkpage(w, u, honks, templinfo)
 776}
 777func showconvoy(w http.ResponseWriter, r *http.Request) {
 778	c := r.FormValue("c")
 779	u := login.GetUserInfo(r)
 780	honks := gethonksbyconvoy(u.UserID, c, 0)
 781	templinfo := getInfo(r)
 782	if len(honks) > 0 {
 783		templinfo["TopHID"] = honks[0].ID
 784	}
 785	honks = osmosis(honks, u.UserID, false)
 786	reversehonks(honks)
 787	templinfo["PageName"] = "convoy"
 788	templinfo["PageArg"] = c
 789	templinfo["ServerMessage"] = "honks in convoy: " + c
 790	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 791	honkpage(w, u, honks, templinfo)
 792}
 793func showsearch(w http.ResponseWriter, r *http.Request) {
 794	q := r.FormValue("q")
 795	u := login.GetUserInfo(r)
 796	honks := gethonksbysearch(u.UserID, q, 0)
 797	templinfo := getInfo(r)
 798	templinfo["PageName"] = "search"
 799	templinfo["PageArg"] = q
 800	templinfo["ServerMessage"] = "honks for search: " + q
 801	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 802	honkpage(w, u, honks, templinfo)
 803}
 804func showontology(w http.ResponseWriter, r *http.Request) {
 805	name := mux.Vars(r)["name"]
 806	u := login.GetUserInfo(r)
 807	var userid int64 = -1
 808	if u != nil {
 809		userid = u.UserID
 810	}
 811	honks := gethonksbyontology(userid, "#"+name, 0)
 812	if friendorfoe(r.Header.Get("Accept")) {
 813		if len(honks) > 40 {
 814			honks = honks[0:40]
 815		}
 816
 817		var xids []string
 818		for _, h := range honks {
 819			xids = append(xids, h.XID)
 820		}
 821
 822		user := getserveruser()
 823
 824		j := junk.New()
 825		j["@context"] = itiswhatitis
 826		j["id"] = fmt.Sprintf("https://%s/o/%s", serverName, name)
 827		j["name"] = "#" + name
 828		j["attributedTo"] = user.URL
 829		j["type"] = "OrderedCollection"
 830		j["totalItems"] = len(xids)
 831		j["orderedItems"] = xids
 832
 833		j.Write(w)
 834		return
 835	}
 836
 837	templinfo := getInfo(r)
 838	templinfo["ServerMessage"] = "honks by ontology: " + name
 839	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 840	honkpage(w, u, honks, templinfo)
 841}
 842
 843type Ont struct {
 844	Name  string
 845	Count int64
 846}
 847
 848func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 849	u := login.GetUserInfo(r)
 850	var userid int64 = -1
 851	if u != nil {
 852		userid = u.UserID
 853	}
 854	rows, err := stmtAllOnts.Query(userid)
 855	if err != nil {
 856		log.Printf("selection error: %s", err)
 857		return
 858	}
 859	defer rows.Close()
 860	var onts []Ont
 861	for rows.Next() {
 862		var o Ont
 863		err := rows.Scan(&o.Name, &o.Count)
 864		if err != nil {
 865			log.Printf("error scanning ont: %s", err)
 866			continue
 867		}
 868		if len(o.Name) > 24 {
 869			continue
 870		}
 871		o.Name = o.Name[1:]
 872		onts = append(onts, o)
 873	}
 874	sort.Slice(onts, func(i, j int) bool {
 875		return onts[i].Name < onts[j].Name
 876	})
 877	if u == nil {
 878		w.Header().Set("Cache-Control", "max-age=300")
 879	}
 880	templinfo := getInfo(r)
 881	templinfo["Onts"] = onts
 882	err = readviews.Execute(w, "onts.html", templinfo)
 883	if err != nil {
 884		log.Print(err)
 885	}
 886}
 887
 888type Track struct {
 889	xid string
 890	who string
 891}
 892
 893func savetracks(tracks map[string][]string) {
 894	db := opendatabase()
 895	tx, err := db.Begin()
 896	if err != nil {
 897		log.Printf("savetracks begin error: %s", err)
 898		return
 899	}
 900	defer func() {
 901		err := tx.Commit()
 902		if err != nil {
 903			log.Printf("savetracks commit error: %s", err)
 904		}
 905
 906	}()
 907	stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
 908	if err != nil {
 909		log.Printf("savetracks error: %s", err)
 910		return
 911	}
 912	stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
 913	if err != nil {
 914		log.Printf("savetracks error: %s", err)
 915		return
 916	}
 917	stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
 918	if err != nil {
 919		log.Printf("savetracks error: %s", err)
 920		return
 921	}
 922	count := 0
 923	for xid, f := range tracks {
 924		count += len(f)
 925		var prev string
 926		row := stmtGetTracks.QueryRow(xid)
 927		err := row.Scan(&prev)
 928		if err == sql.ErrNoRows {
 929			f = oneofakind(f)
 930			stmtNewTracks.Exec(xid, strings.Join(f, " "))
 931		} else if err == nil {
 932			all := append(strings.Split(prev, " "), f...)
 933			all = oneofakind(all)
 934			stmtUpdateTracks.Exec(strings.Join(all, " "))
 935		} else {
 936			log.Printf("savetracks error: %s", err)
 937		}
 938	}
 939	log.Printf("saved %d new fetches", count)
 940}
 941
 942var trackchan = make(chan Track)
 943
 944func tracker() {
 945	timeout := 4 * time.Minute
 946	sleeper := time.NewTimer(timeout)
 947	tracks := make(map[string][]string)
 948	for {
 949		select {
 950		case track := <-trackchan:
 951			tracks[track.xid] = append(tracks[track.xid], track.who)
 952		case <-sleeper.C:
 953			if len(tracks) > 0 {
 954				go savetracks(tracks)
 955				tracks = make(map[string][]string)
 956			}
 957			sleeper.Reset(timeout)
 958		case <-endoftheworld:
 959			if len(tracks) > 0 {
 960				savetracks(tracks)
 961			}
 962			readyalready <- true
 963			return
 964		}
 965	}
 966}
 967
 968var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
 969
 970func trackback(xid string, r *http.Request) {
 971	agent := r.UserAgent()
 972	who := originate(agent)
 973	sig := r.Header.Get("Signature")
 974	if sig != "" {
 975		m := re_keyholder.FindStringSubmatch(sig)
 976		if len(m) == 2 {
 977			who = m[1]
 978		}
 979	}
 980	if who != "" {
 981		trackchan <- Track{xid: xid, who: who}
 982	}
 983}
 984
 985func showonehonk(w http.ResponseWriter, r *http.Request) {
 986	name := mux.Vars(r)["name"]
 987	user, err := butwhatabout(name)
 988	if err != nil {
 989		http.NotFound(w, r)
 990		return
 991	}
 992	if stealthmode(user.ID, r) {
 993		http.NotFound(w, r)
 994		return
 995	}
 996	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
 997
 998	if friendorfoe(r.Header.Get("Accept")) {
 999		j, ok := gimmejonk(xid)
1000		if ok {
1001			trackback(xid, r)
1002			w.Header().Set("Content-Type", theonetruename)
1003			w.Write(j)
1004		} else {
1005			http.NotFound(w, r)
1006		}
1007		return
1008	}
1009	honk := getxonk(user.ID, xid)
1010	if honk == nil {
1011		http.NotFound(w, r)
1012		return
1013	}
1014	u := login.GetUserInfo(r)
1015	if u != nil && u.UserID != user.ID {
1016		u = nil
1017	}
1018	if !honk.Public {
1019		if u == nil {
1020			http.NotFound(w, r)
1021			return
1022
1023		}
1024		templinfo := getInfo(r)
1025		templinfo["ServerMessage"] = "one honk maybe more"
1026		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1027		honkpage(w, u, []*Honk{honk}, templinfo)
1028		return
1029	}
1030	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1031	reversehonks(rawhonks)
1032	var honks []*Honk
1033	for _, h := range rawhonks {
1034		if h.XID == xid && len(honks) != 0 {
1035			h.Style += " glow"
1036		}
1037		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1038			honks = append(honks, h)
1039		}
1040	}
1041
1042	templinfo := getInfo(r)
1043	templinfo["ServerMessage"] = "one honk maybe more"
1044	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1045	honkpage(w, u, honks, templinfo)
1046}
1047
1048func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1049	var userid int64 = -1
1050	if u != nil {
1051		userid = u.UserID
1052	}
1053	reverbolate(userid, honks)
1054	templinfo["Honks"] = honks
1055	templinfo["MapLink"] = getmaplink(u)
1056	if templinfo["TopHID"] == nil {
1057		if len(honks) > 0 {
1058			templinfo["TopHID"] = honks[0].ID
1059		} else {
1060			templinfo["TopHID"] = 0
1061		}
1062	}
1063	if u == nil {
1064		w.Header().Set("Cache-Control", "max-age=60")
1065	}
1066	err := readviews.Execute(w, "honkpage.html", templinfo)
1067	if err != nil {
1068		log.Print(err)
1069	}
1070}
1071
1072func saveuser(w http.ResponseWriter, r *http.Request) {
1073	whatabout := r.FormValue("whatabout")
1074	u := login.GetUserInfo(r)
1075	user, _ := butwhatabout(u.Username)
1076	db := opendatabase()
1077	options := user.Options
1078	if r.FormValue("skinny") == "skinny" {
1079		options.SkinnyCSS = true
1080	} else {
1081		options.SkinnyCSS = false
1082	}
1083	if r.FormValue("maps") == "apple" {
1084		options.MapLink = "apple"
1085	} else {
1086		options.MapLink = ""
1087	}
1088	j, err := jsonify(options)
1089	if err == nil {
1090		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1091	}
1092	if err != nil {
1093		log.Printf("error bouting what: %s", err)
1094	}
1095	somenamedusers.Clear(u.Username)
1096	somenumberedusers.Clear(u.UserID)
1097
1098	http.Redirect(w, r, "/account", http.StatusSeeOther)
1099}
1100
1101func submitbonk(w http.ResponseWriter, r *http.Request) {
1102	xid := r.FormValue("xid")
1103	userinfo := login.GetUserInfo(r)
1104	user, _ := butwhatabout(userinfo.Username)
1105
1106	log.Printf("bonking %s", xid)
1107
1108	xonk := getxonk(userinfo.UserID, xid)
1109	if xonk == nil {
1110		return
1111	}
1112	if !xonk.Public {
1113		return
1114	}
1115	if xonk.IsBonked() {
1116		return
1117	}
1118	donksforhonks([]*Honk{xonk})
1119
1120	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1121	if err != nil {
1122		log.Printf("error acking bonk: %s", err)
1123	}
1124
1125	oonker := xonk.Oonker
1126	if oonker == "" {
1127		oonker = xonk.Honker
1128	}
1129	dt := time.Now().UTC()
1130	bonk := &Honk{
1131		UserID:   userinfo.UserID,
1132		Username: userinfo.Username,
1133		What:     "bonk",
1134		Honker:   user.URL,
1135		Oonker:   oonker,
1136		XID:      xonk.XID,
1137		RID:      xonk.RID,
1138		Noise:    xonk.Noise,
1139		Precis:   xonk.Precis,
1140		URL:      xonk.URL,
1141		Date:     dt,
1142		Donks:    xonk.Donks,
1143		Whofore:  2,
1144		Convoy:   xonk.Convoy,
1145		Audience: []string{thewholeworld, oonker},
1146		Public:   true,
1147		Format:   "html",
1148		Place:    xonk.Place,
1149		Onts:     xonk.Onts,
1150		Time:     xonk.Time,
1151	}
1152
1153	err = savehonk(bonk)
1154	if err != nil {
1155		log.Printf("uh oh")
1156		return
1157	}
1158
1159	go honkworldwide(user, bonk)
1160
1161	if r.FormValue("js") != "1" {
1162		templinfo := getInfo(r)
1163		templinfo["ServerMessage"] = "Bonked!"
1164		err = readviews.Execute(w, "msg.html", templinfo)
1165		if err != nil {
1166			log.Print(err)
1167		}
1168	}
1169}
1170
1171func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
1172	zonk := &Honk{
1173		What:     what,
1174		XID:      xonk.XID,
1175		Date:     time.Now().UTC(),
1176		Audience: oneofakind(xonk.Audience),
1177	}
1178	zonk.Public = loudandproud(zonk.Audience)
1179
1180	log.Printf("announcing %sed honk: %s", what, xonk.XID)
1181	go honkworldwide(user, zonk)
1182}
1183
1184func zonkit(w http.ResponseWriter, r *http.Request) {
1185	wherefore := r.FormValue("wherefore")
1186	what := r.FormValue("what")
1187	userinfo := login.GetUserInfo(r)
1188	user, _ := butwhatabout(userinfo.Username)
1189
1190	if wherefore == "save" {
1191		xonk := getxonk(userinfo.UserID, what)
1192		if xonk != nil {
1193			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1194			if err != nil {
1195				log.Printf("error saving: %s", err)
1196			}
1197		}
1198		return
1199	}
1200
1201	if wherefore == "unsave" {
1202		xonk := getxonk(userinfo.UserID, what)
1203		if xonk != nil {
1204			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1205			if err != nil {
1206				log.Printf("error unsaving: %s", err)
1207			}
1208		}
1209		return
1210	}
1211
1212	// my hammer is too big, oh well
1213	defer oldjonks.Flush()
1214
1215	if wherefore == "ack" {
1216		xonk := getxonk(userinfo.UserID, what)
1217		if xonk != nil && !xonk.IsAcked() {
1218			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1219			if err != nil {
1220				log.Printf("error acking: %s", err)
1221			}
1222			sendzonkofsorts(xonk, user, "ack")
1223		}
1224		return
1225	}
1226
1227	if wherefore == "deack" {
1228		xonk := getxonk(userinfo.UserID, what)
1229		if xonk != nil && xonk.IsAcked() {
1230			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1231			if err != nil {
1232				log.Printf("error deacking: %s", err)
1233			}
1234			sendzonkofsorts(xonk, user, "deack")
1235		}
1236		return
1237	}
1238
1239	if wherefore == "unbonk" {
1240		xonk := getbonk(userinfo.UserID, what)
1241		if xonk != nil {
1242			deletehonk(xonk.ID)
1243			xonk = getxonk(userinfo.UserID, what)
1244			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1245			if err != nil {
1246				log.Printf("error unbonking: %s", err)
1247			}
1248			sendzonkofsorts(xonk, user, "unbonk")
1249		}
1250		return
1251	}
1252
1253	if wherefore == "untag" {
1254		xonk := getxonk(userinfo.UserID, what)
1255		if xonk != nil {
1256			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1257			if err != nil {
1258				log.Printf("error untagging: %s", err)
1259			}
1260		}
1261		var badparents map[string]bool
1262		untagged.GetAndLock(userinfo.UserID, &badparents)
1263		badparents[what] = true
1264		untagged.Unlock()
1265		return
1266	}
1267
1268	log.Printf("zonking %s %s", wherefore, what)
1269	if wherefore == "zonk" {
1270		xonk := getxonk(userinfo.UserID, what)
1271		if xonk != nil {
1272			deletehonk(xonk.ID)
1273			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1274				sendzonkofsorts(xonk, user, "zonk")
1275			}
1276		}
1277	}
1278	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1279	if err != nil {
1280		log.Printf("error saving zonker: %s", err)
1281		return
1282	}
1283}
1284
1285func edithonkpage(w http.ResponseWriter, r *http.Request) {
1286	u := login.GetUserInfo(r)
1287	user, _ := butwhatabout(u.Username)
1288	xid := r.FormValue("xid")
1289	honk := getxonk(u.UserID, xid)
1290	if !canedithonk(user, honk) {
1291		http.Error(w, "no editing that please", http.StatusInternalServerError)
1292		return
1293	}
1294
1295	noise := honk.Noise
1296
1297	honks := []*Honk{honk}
1298	donksforhonks(honks)
1299	reverbolate(u.UserID, honks)
1300	templinfo := getInfo(r)
1301	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1302	templinfo["Honks"] = honks
1303	templinfo["MapLink"] = getmaplink(u)
1304	templinfo["Noise"] = noise
1305	templinfo["SavedPlace"] = honk.Place
1306	templinfo["ServerMessage"] = "honk edit"
1307	templinfo["IsPreview"] = true
1308	templinfo["UpdateXID"] = honk.XID
1309	if len(honk.Donks) > 0 {
1310		templinfo["SavedFile"] = honk.Donks[0].XID
1311	}
1312	err := readviews.Execute(w, "honkpage.html", templinfo)
1313	if err != nil {
1314		log.Print(err)
1315	}
1316}
1317
1318func newhonkpage(w http.ResponseWriter, r *http.Request) {
1319	u := login.GetUserInfo(r)
1320	rid := r.FormValue("rid")
1321	noise := ""
1322
1323	xonk := getxonk(u.UserID, rid)
1324	if xonk != nil {
1325		_, replto := handles(xonk.Honker)
1326		if replto != "" {
1327			noise = "@" + replto + " "
1328		}
1329	}
1330
1331	templinfo := getInfo(r)
1332	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1333	templinfo["InReplyTo"] = rid
1334	templinfo["Noise"] = noise
1335	templinfo["ServerMessage"] = "compose honk"
1336	templinfo["IsPreview"] = true
1337	err := readviews.Execute(w, "honkpage.html", templinfo)
1338	if err != nil {
1339		log.Print(err)
1340	}
1341}
1342
1343func canedithonk(user *WhatAbout, honk *Honk) bool {
1344	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1345		return false
1346	}
1347	return true
1348}
1349
1350func submitwebhonk(w http.ResponseWriter, r *http.Request) {
1351	submithonk(w, r, false)
1352}
1353
1354// what a hot mess this function is
1355func submithonk(w http.ResponseWriter, r *http.Request, isAPI bool) {
1356	rid := r.FormValue("rid")
1357	noise := r.FormValue("noise")
1358
1359	userinfo := login.GetUserInfo(r)
1360	user, _ := butwhatabout(userinfo.Username)
1361
1362	dt := time.Now().UTC()
1363	updatexid := r.FormValue("updatexid")
1364	var honk *Honk
1365	if updatexid != "" {
1366		honk = getxonk(userinfo.UserID, updatexid)
1367		if !canedithonk(user, honk) {
1368			http.Error(w, "no editing that please", http.StatusInternalServerError)
1369			return
1370		}
1371		honk.Date = dt
1372		honk.What = "update"
1373		honk.Format = "markdown"
1374	} else {
1375		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1376		what := "honk"
1377		if rid != "" {
1378			what = "tonk"
1379		}
1380		honk = &Honk{
1381			UserID:   userinfo.UserID,
1382			Username: userinfo.Username,
1383			What:     what,
1384			Honker:   user.URL,
1385			XID:      xid,
1386			Date:     dt,
1387			Format:   "markdown",
1388		}
1389	}
1390
1391	noise = strings.Replace(noise, "\r", "", -1)
1392	noise = quickrename(noise, userinfo.UserID)
1393	noise = hooterize(noise)
1394	honk.Noise = noise
1395	translate(honk, false)
1396
1397	var convoy string
1398	if rid != "" {
1399		xonk := getxonk(userinfo.UserID, rid)
1400		if xonk != nil {
1401			if xonk.Public {
1402				honk.Audience = append(honk.Audience, xonk.Audience...)
1403			}
1404			convoy = xonk.Convoy
1405		} else {
1406			xonkaud, c := whosthere(rid)
1407			honk.Audience = append(honk.Audience, xonkaud...)
1408			convoy = c
1409		}
1410		for i, a := range honk.Audience {
1411			if a == thewholeworld {
1412				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1413				break
1414			}
1415		}
1416		honk.RID = rid
1417	} else {
1418		honk.Audience = []string{thewholeworld}
1419	}
1420	if honk.Noise != "" && honk.Noise[0] == '@' {
1421		honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
1422	} else {
1423		honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
1424	}
1425
1426	if convoy == "" {
1427		convoy = "data:,electrichonkytonk-" + xfiltrate()
1428	}
1429	butnottooloud(honk.Audience)
1430	honk.Audience = oneofakind(honk.Audience)
1431	if len(honk.Audience) == 0 {
1432		log.Printf("honk to nowhere")
1433		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1434		return
1435	}
1436	honk.Public = loudandproud(honk.Audience)
1437	honk.Convoy = convoy
1438
1439	donkxid := r.FormValue("donkxid")
1440	if donkxid == "" {
1441		file, filehdr, err := r.FormFile("donk")
1442		if err == nil {
1443			var buf bytes.Buffer
1444			io.Copy(&buf, file)
1445			file.Close()
1446			data := buf.Bytes()
1447			xid := xfiltrate()
1448			var media, name string
1449			img, err := shrinkit(data)
1450			if err == nil {
1451				data = img.Data
1452				format := img.Format
1453				media = "image/" + format
1454				if format == "jpeg" {
1455					format = "jpg"
1456				}
1457				name = xid + "." + format
1458				xid = name
1459			} else {
1460				ct := http.DetectContentType(data)
1461				switch ct {
1462				case "application/pdf":
1463					maxsize := 1000000
1464					if len(data) > maxsize {
1465						log.Printf("bad image: %s too much pdf: %d", err, len(data))
1466						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1467						return
1468					}
1469					media = ct
1470					xid += ".pdf"
1471					name = filehdr.Filename
1472					if name == "" {
1473						name = xid
1474					}
1475				default:
1476					maxsize := 100000
1477					if len(data) > maxsize {
1478						log.Printf("bad image: %s too much text: %d", err, len(data))
1479						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1480						return
1481					}
1482					for i := 0; i < len(data); i++ {
1483						if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1484							log.Printf("bad image: %s not text: %d", err, data[i])
1485							http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1486							return
1487						}
1488					}
1489					media = "text/plain"
1490					xid += ".txt"
1491					name = filehdr.Filename
1492					if name == "" {
1493						name = xid
1494					}
1495				}
1496			}
1497			desc := strings.TrimSpace(r.FormValue("donkdesc"))
1498			if desc == "" {
1499				desc = name
1500			}
1501			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1502			fileid, err := savefile(xid, name, desc, url, media, true, data)
1503			if err != nil {
1504				log.Printf("unable to save image: %s", err)
1505				return
1506			}
1507			d := &Donk{
1508				FileID: fileid,
1509				XID:    xid,
1510				Desc:   desc,
1511				URL:    url,
1512				Local:  true,
1513			}
1514			honk.Donks = append(honk.Donks, d)
1515			donkxid = xid
1516		}
1517	} else {
1518		xid := donkxid
1519		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1520		donk := finddonk(url)
1521		if donk != nil {
1522			honk.Donks = append(honk.Donks, donk)
1523		} else {
1524			log.Printf("can't find file: %s", xid)
1525		}
1526	}
1527	herd := herdofemus(noise)
1528	for _, e := range herd {
1529		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1530		if donk != nil {
1531			donk.Name = e.Name
1532			honk.Donks = append(honk.Donks, donk)
1533		}
1534	}
1535	memetize(honk)
1536	imaginate(honk)
1537
1538	placename := strings.TrimSpace(r.FormValue("placename"))
1539	placelat := strings.TrimSpace(r.FormValue("placelat"))
1540	placelong := strings.TrimSpace(r.FormValue("placelong"))
1541	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1542	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1543		p := new(Place)
1544		p.Name = placename
1545		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1546		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1547		p.Url = placeurl
1548		honk.Place = p
1549	}
1550	timestart := strings.TrimSpace(r.FormValue("timestart"))
1551	if timestart != "" {
1552		t := new(Time)
1553		now := time.Now().Local()
1554		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1555			start, err := time.ParseInLocation(layout, timestart, now.Location())
1556			if err == nil {
1557				if start.Year() == 0 {
1558					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1559				}
1560				t.StartTime = start
1561				break
1562			}
1563		}
1564		timeend := r.FormValue("timeend")
1565		dur := parseDuration(timeend)
1566		if dur != 0 {
1567			t.Duration = Duration(dur)
1568		}
1569		if !t.StartTime.IsZero() {
1570			honk.What = "event"
1571			honk.Time = t
1572		}
1573	}
1574
1575	if honk.Public {
1576		honk.Whofore = 2
1577	} else {
1578		honk.Whofore = 3
1579	}
1580
1581	// back to markdown
1582	honk.Noise = noise
1583
1584	if r.FormValue("preview") == "preview" {
1585		honks := []*Honk{honk}
1586		reverbolate(userinfo.UserID, honks)
1587		templinfo := getInfo(r)
1588		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1589		templinfo["Honks"] = honks
1590		templinfo["MapLink"] = getmaplink(userinfo)
1591		templinfo["InReplyTo"] = r.FormValue("rid")
1592		templinfo["Noise"] = r.FormValue("noise")
1593		templinfo["SavedFile"] = donkxid
1594		templinfo["IsPreview"] = true
1595		templinfo["UpdateXID"] = updatexid
1596		templinfo["ServerMessage"] = "honk preview"
1597		err := readviews.Execute(w, "honkpage.html", templinfo)
1598		if err != nil {
1599			log.Print(err)
1600		}
1601		return
1602	}
1603
1604	if updatexid != "" {
1605		updatehonk(honk)
1606		oldjonks.Clear(honk.XID)
1607	} else {
1608		err := savehonk(honk)
1609		if err != nil {
1610			log.Printf("uh oh")
1611			return
1612		}
1613	}
1614
1615	// reload for consistency
1616	honk.Donks = nil
1617	donksforhonks([]*Honk{honk})
1618
1619	go honkworldwide(user, honk)
1620
1621	if isAPI {
1622		w.Write([]byte(honk.XID))
1623	} else {
1624		http.Redirect(w, r, honk.XID[len(serverName)+8:], http.StatusSeeOther)
1625	}
1626}
1627
1628func showhonkers(w http.ResponseWriter, r *http.Request) {
1629	userinfo := login.GetUserInfo(r)
1630	templinfo := getInfo(r)
1631	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1632	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1633	err := readviews.Execute(w, "honkers.html", templinfo)
1634	if err != nil {
1635		log.Print(err)
1636	}
1637}
1638
1639var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1640	honkers := gethonkers(userid)
1641	var combos []string
1642	for _, h := range honkers {
1643		combos = append(combos, h.Combos...)
1644	}
1645	for i, c := range combos {
1646		if c == "-" {
1647			combos[i] = ""
1648		}
1649	}
1650	combos = oneofakind(combos)
1651	sort.Strings(combos)
1652	return combos, true
1653}, Invalidator: &honkerinvalidator})
1654
1655func showcombos(w http.ResponseWriter, r *http.Request) {
1656	userinfo := login.GetUserInfo(r)
1657	var combos []string
1658	combocache.Get(userinfo.UserID, &combos)
1659	templinfo := getInfo(r)
1660	err := readviews.Execute(w, "combos.html", templinfo)
1661	if err != nil {
1662		log.Print(err)
1663	}
1664}
1665
1666func submithonker(w http.ResponseWriter, r *http.Request) {
1667	u := login.GetUserInfo(r)
1668	name := strings.TrimSpace(r.FormValue("name"))
1669	url := strings.TrimSpace(r.FormValue("url"))
1670	peep := r.FormValue("peep")
1671	combos := strings.TrimSpace(r.FormValue("combos"))
1672	combos = " " + combos + " "
1673	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1674
1675	defer honkerinvalidator.Clear(u.UserID)
1676
1677	if honkerid > 0 {
1678		goodbye := r.FormValue("goodbye")
1679		if goodbye == "F" {
1680			db := opendatabase()
1681			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1682				honkerid, u.UserID)
1683			err := row.Scan(&url)
1684			if err != nil {
1685				log.Printf("can't get honker xid: %s", err)
1686				return
1687			}
1688			log.Printf("unsubscribing from %s", url)
1689			user, _ := butwhatabout(u.Username)
1690			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, name, "sub")
1691			if err != nil {
1692				log.Printf("error updating honker: %s", err)
1693				return
1694			}
1695			go itakeitallback(user, url)
1696
1697			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1698			return
1699		}
1700		if goodbye == "X" {
1701			var owner string
1702			db := opendatabase()
1703			row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1704				honkerid, u.UserID)
1705			err := row.Scan(&url, &owner)
1706			if err != nil {
1707				log.Printf("can't get honker xid: %s", err)
1708				return
1709			}
1710			log.Printf("resubscribing to %s", url)
1711			user, _ := butwhatabout(u.Username)
1712			_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "unsub")
1713			if err == nil {
1714				_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "peep")
1715			}
1716			if err != nil {
1717				log.Printf("error updating honker: %s", err)
1718				return
1719			}
1720			go subsub(user, url, owner)
1721
1722			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1723			return
1724		}
1725		_, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1726		if err != nil {
1727			log.Printf("update honker err: %s", err)
1728			return
1729		}
1730		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1731		return
1732	}
1733
1734	if url == "" {
1735		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1736		return
1737	}
1738
1739	flavor := "presub"
1740	if peep == "peep" {
1741		flavor = "peep"
1742	}
1743
1744	if url[0] == '#' {
1745		flavor = "peep"
1746		if name == "" {
1747			name = url
1748		}
1749		_, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url)
1750		if err != nil {
1751			log.Print(err)
1752			return
1753		}
1754		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1755		return
1756	}
1757
1758	info, err := investigate(url)
1759	if err != nil {
1760		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1761		log.Printf("failed to investigate honker: %s", err)
1762		return
1763	}
1764	url = info.XID
1765
1766	var x string
1767	db := opendatabase()
1768	row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1769	err = row.Scan(&x)
1770	if err != sql.ErrNoRows {
1771		http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1772		if err != nil {
1773			log.Printf("honker scan err: %s", err)
1774		}
1775		return
1776	}
1777
1778	if name == "" {
1779		name = info.Name
1780	}
1781	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner)
1782	if err != nil {
1783		log.Print(err)
1784		return
1785	}
1786	if flavor == "presub" {
1787		user, _ := butwhatabout(u.Username)
1788		go subsub(user, url, info.Owner)
1789	}
1790	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1791}
1792
1793func hfcspage(w http.ResponseWriter, r *http.Request) {
1794	userinfo := login.GetUserInfo(r)
1795
1796	filters := getfilters(userinfo.UserID, filtAny)
1797
1798	templinfo := getInfo(r)
1799	templinfo["Filters"] = filters
1800	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1801	err := readviews.Execute(w, "hfcs.html", templinfo)
1802	if err != nil {
1803		log.Print(err)
1804	}
1805}
1806
1807func savehfcs(w http.ResponseWriter, r *http.Request) {
1808	userinfo := login.GetUserInfo(r)
1809	itsok := r.FormValue("itsok")
1810	if itsok == "iforgiveyou" {
1811		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1812		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1813		if err != nil {
1814			log.Printf("error deleting filter: %s", err)
1815		}
1816		filtcache.Clear(userinfo.UserID)
1817		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1818		return
1819	}
1820
1821	filt := new(Filter)
1822	filt.Name = strings.TrimSpace(r.FormValue("name"))
1823	filt.Date = time.Now().UTC()
1824	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1825	filt.IncludeAudience = r.FormValue("incaud") == "yes"
1826	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1827	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1828	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1829	filt.Reject = r.FormValue("doreject") == "yes"
1830	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1831	filt.Hide = r.FormValue("dohide") == "yes"
1832	filt.Collapse = r.FormValue("docollapse") == "yes"
1833	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1834	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1835	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
1836		filt.Expiration = time.Now().UTC().Add(dur)
1837	}
1838
1839	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
1840		log.Printf("blank filter")
1841		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
1842		return
1843	}
1844
1845	j, err := jsonify(filt)
1846	if err == nil {
1847		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1848	}
1849	if err != nil {
1850		log.Printf("error saving filter: %s", err)
1851	}
1852
1853	filtcache.Clear(userinfo.UserID)
1854	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1855}
1856
1857func accountpage(w http.ResponseWriter, r *http.Request) {
1858	u := login.GetUserInfo(r)
1859	user, _ := butwhatabout(u.Username)
1860	templinfo := getInfo(r)
1861	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1862	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1863	templinfo["User"] = user
1864	err := readviews.Execute(w, "account.html", templinfo)
1865	if err != nil {
1866		log.Print(err)
1867	}
1868}
1869
1870func dochpass(w http.ResponseWriter, r *http.Request) {
1871	err := login.ChangePassword(w, r)
1872	if err != nil {
1873		log.Printf("error changing password: %s", err)
1874	}
1875	http.Redirect(w, r, "/account", http.StatusSeeOther)
1876}
1877
1878func fingerlicker(w http.ResponseWriter, r *http.Request) {
1879	orig := r.FormValue("resource")
1880
1881	log.Printf("finger lick: %s", orig)
1882
1883	if strings.HasPrefix(orig, "acct:") {
1884		orig = orig[5:]
1885	}
1886
1887	name := orig
1888	idx := strings.LastIndexByte(name, '/')
1889	if idx != -1 {
1890		name = name[idx+1:]
1891		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1892			log.Printf("foreign request rejected")
1893			name = ""
1894		}
1895	} else {
1896		idx = strings.IndexByte(name, '@')
1897		if idx != -1 {
1898			name = name[:idx]
1899			if name+"@"+serverName != orig {
1900				log.Printf("foreign request rejected")
1901				name = ""
1902			}
1903		}
1904	}
1905	user, err := butwhatabout(name)
1906	if err != nil {
1907		http.NotFound(w, r)
1908		return
1909	}
1910	if stealthmode(user.ID, r) {
1911		http.NotFound(w, r)
1912		return
1913	}
1914
1915	j := junk.New()
1916	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1917	j["aliases"] = []string{user.URL}
1918	l := junk.New()
1919	l["rel"] = "self"
1920	l["type"] = `application/activity+json`
1921	l["href"] = user.URL
1922	j["links"] = []junk.Junk{l}
1923
1924	w.Header().Set("Content-Type", "application/jrd+json")
1925	j.Write(w)
1926}
1927
1928func somedays() string {
1929	secs := 432000 + notrand.Int63n(432000)
1930	return fmt.Sprintf("%d", secs)
1931}
1932
1933func avatate(w http.ResponseWriter, r *http.Request) {
1934	n := r.FormValue("a")
1935	a := avatar(n)
1936	w.Header().Set("Cache-Control", "max-age="+somedays())
1937	w.Write(a)
1938}
1939
1940func serveasset(w http.ResponseWriter, r *http.Request) {
1941	w.Header().Set("Cache-Control", "max-age=7776000")
1942	dir := viewDir
1943	if r.URL.Path == "/local.css" {
1944		dir = dataDir
1945	}
1946	http.ServeFile(w, r, dir+"/views"+r.URL.Path)
1947}
1948func servehelp(w http.ResponseWriter, r *http.Request) {
1949	name := mux.Vars(r)["name"]
1950	w.Header().Set("Cache-Control", "max-age=3600")
1951	http.ServeFile(w, r, viewDir+"/docs/"+name)
1952}
1953func servehtml(w http.ResponseWriter, r *http.Request) {
1954	u := login.GetUserInfo(r)
1955	templinfo := getInfo(r)
1956	templinfo["AboutMsg"] = aboutMsg
1957	templinfo["LoginMsg"] = loginMsg
1958	templinfo["HonkVersion"] = softwareVersion
1959	if r.URL.Path == "/about" {
1960		templinfo["Sensors"] = getSensors()
1961	}
1962	if u == nil {
1963		w.Header().Set("Cache-Control", "max-age=60")
1964	}
1965	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1966	if err != nil {
1967		log.Print(err)
1968	}
1969}
1970func serveemu(w http.ResponseWriter, r *http.Request) {
1971	xid := mux.Vars(r)["xid"]
1972	w.Header().Set("Cache-Control", "max-age="+somedays())
1973	http.ServeFile(w, r, dataDir+"/emus/"+xid)
1974}
1975func servememe(w http.ResponseWriter, r *http.Request) {
1976	xid := mux.Vars(r)["xid"]
1977	w.Header().Set("Cache-Control", "max-age="+somedays())
1978	http.ServeFile(w, r, dataDir+"/memes/"+xid)
1979}
1980
1981func servefile(w http.ResponseWriter, r *http.Request) {
1982	xid := mux.Vars(r)["xid"]
1983	var media string
1984	var data []byte
1985	row := stmtGetFileData.QueryRow(xid)
1986	err := row.Scan(&media, &data)
1987	if err != nil {
1988		log.Printf("error loading file: %s", err)
1989		http.NotFound(w, r)
1990		return
1991	}
1992	w.Header().Set("Content-Type", media)
1993	w.Header().Set("X-Content-Type-Options", "nosniff")
1994	w.Header().Set("Cache-Control", "max-age="+somedays())
1995	w.Write(data)
1996}
1997
1998func nomoroboto(w http.ResponseWriter, r *http.Request) {
1999	io.WriteString(w, "User-agent: *\n")
2000	io.WriteString(w, "Disallow: /a\n")
2001	io.WriteString(w, "Disallow: /d\n")
2002	io.WriteString(w, "Disallow: /meme\n")
2003	io.WriteString(w, "Disallow: /o\n")
2004	for _, u := range allusers() {
2005		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2006	}
2007}
2008
2009func webhydra(w http.ResponseWriter, r *http.Request) {
2010	u := login.GetUserInfo(r)
2011	userid := u.UserID
2012	templinfo := getInfo(r)
2013	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2014	page := r.FormValue("page")
2015
2016	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2017
2018	var honks []*Honk
2019	switch page {
2020	case "atme":
2021		honks = gethonksforme(userid, wanted)
2022		honks = osmosis(honks, userid, false)
2023		templinfo["ServerMessage"] = "at me!"
2024	case "home":
2025		honks = gethonksforuser(userid, wanted)
2026		honks = osmosis(honks, userid, true)
2027		templinfo["ServerMessage"] = serverMsg
2028	case "first":
2029		honks = gethonksforuserfirstclass(userid, wanted)
2030		honks = osmosis(honks, userid, true)
2031		templinfo["ServerMessage"] = "first class only"
2032	case "saved":
2033		honks = getsavedhonks(userid, wanted)
2034		templinfo["PageName"] = "saved"
2035		templinfo["ServerMessage"] = "saved honks"
2036	case "combo":
2037		c := r.FormValue("c")
2038		honks = gethonksbycombo(userid, c, wanted)
2039		honks = osmosis(honks, userid, false)
2040		templinfo["ServerMessage"] = "honks by combo: " + c
2041	case "convoy":
2042		c := r.FormValue("c")
2043		honks = gethonksbyconvoy(userid, c, wanted)
2044		honks = osmosis(honks, userid, false)
2045		templinfo["ServerMessage"] = "honks in convoy: " + c
2046	case "honker":
2047		xid := r.FormValue("xid")
2048		honks = gethonksbyxonker(userid, xid, wanted)
2049		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
2050		templinfo["ServerMessage"] = msg
2051	default:
2052		http.NotFound(w, r)
2053	}
2054	if len(honks) > 0 {
2055		templinfo["TopHID"] = honks[0].ID
2056	} else {
2057		templinfo["TopHID"] = wanted
2058	}
2059	reverbolate(userid, honks)
2060	templinfo["Honks"] = honks
2061	templinfo["MapLink"] = getmaplink(u)
2062	w.Header().Set("Content-Type", "text/html; charset=utf-8")
2063	err := readviews.Execute(w, "honkfrags.html", templinfo)
2064	if err != nil {
2065		log.Printf("frag error: %s", err)
2066	}
2067}
2068
2069var honkline = make(chan bool)
2070
2071func honkhonkline() {
2072	for {
2073		select {
2074		case honkline <- true:
2075		default:
2076			return
2077		}
2078	}
2079}
2080
2081func apihandler(w http.ResponseWriter, r *http.Request) {
2082	u := login.GetUserInfo(r)
2083	userid := u.UserID
2084	action := r.FormValue("action")
2085	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2086	log.Printf("api request '%s' on behalf of %s", action, u.Username)
2087	switch action {
2088	case "honk":
2089		submithonk(w, r, true)
2090	case "gethonks":
2091		var honks []*Honk
2092		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2093		page := r.FormValue("page")
2094		var waitchan <-chan time.Time
2095	requery:
2096		switch page {
2097		case "atme":
2098			honks = gethonksforme(userid, wanted)
2099			honks = osmosis(honks, userid, false)
2100		case "home":
2101			honks = gethonksforuser(userid, wanted)
2102			honks = osmosis(honks, userid, true)
2103		default:
2104			http.Error(w, "unknown page", http.StatusNotFound)
2105			return
2106		}
2107		if len(honks) == 0 && wait > 0 {
2108			if waitchan == nil {
2109				waitchan = time.After(time.Duration(wait) * time.Second)
2110			}
2111			select {
2112			case <-honkline:
2113				goto requery
2114			case <-waitchan:
2115			}
2116		}
2117		reverbolate(userid, honks)
2118		j := junk.New()
2119		j["honks"] = honks
2120		j.Write(w)
2121	default:
2122		http.Error(w, "unknown action", http.StatusNotFound)
2123		return
2124	}
2125}
2126
2127var endoftheworld = make(chan bool)
2128var readyalready = make(chan bool)
2129
2130func enditall() {
2131	sig := make(chan os.Signal)
2132	signal.Notify(sig, os.Interrupt)
2133	signal.Notify(sig, syscall.SIGTERM)
2134	<-sig
2135	count := 0
2136	log.Printf("stopping...")
2137sendloop:
2138	for {
2139		select {
2140		case endoftheworld <- true:
2141			count++
2142		default:
2143			break sendloop
2144		}
2145	}
2146	log.Printf("waiting...")
2147	for i := 0; i < count; i++ {
2148		<-readyalready
2149	}
2150	log.Printf("apocalypse")
2151	os.Exit(0)
2152}
2153
2154var preservehooks []func()
2155
2156func serve() {
2157	db := opendatabase()
2158	login.Init(db)
2159
2160	listener, err := openListener()
2161	if err != nil {
2162		log.Fatal(err)
2163	}
2164	startBackendServer()
2165	go enditall()
2166	go redeliverator()
2167	go tracker()
2168
2169	debug := false
2170	getconfig("debug", &debug)
2171	readviews = templates.Load(debug,
2172		viewDir+"/views/honkpage.html",
2173		viewDir+"/views/honkfrags.html",
2174		viewDir+"/views/honkers.html",
2175		viewDir+"/views/hfcs.html",
2176		viewDir+"/views/combos.html",
2177		viewDir+"/views/honkform.html",
2178		viewDir+"/views/honk.html",
2179		viewDir+"/views/account.html",
2180		viewDir+"/views/about.html",
2181		viewDir+"/views/funzone.html",
2182		viewDir+"/views/login.html",
2183		viewDir+"/views/xzone.html",
2184		viewDir+"/views/msg.html",
2185		viewDir+"/views/header.html",
2186		viewDir+"/views/onts.html",
2187		viewDir+"/views/honkpage.js",
2188	)
2189	if !debug {
2190		assets := []string{viewDir + "/views/style.css", dataDir + "/views/local.css", viewDir + "/views/honkpage.js"}
2191		for _, s := range assets {
2192			savedassetparams[s] = getassetparam(s)
2193		}
2194	}
2195
2196	for _, h := range preservehooks {
2197		h()
2198	}
2199
2200	mux := mux.NewRouter()
2201	mux.Use(login.Checker)
2202
2203	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2204
2205	posters := mux.Methods("POST").Subrouter()
2206	getters := mux.Methods("GET").Subrouter()
2207
2208	getters.HandleFunc("/", homepage)
2209	getters.HandleFunc("/home", homepage)
2210	getters.HandleFunc("/front", homepage)
2211	getters.HandleFunc("/events", homepage)
2212	getters.HandleFunc("/robots.txt", nomoroboto)
2213	getters.HandleFunc("/rss", showrss)
2214	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
2215	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showonehonk)
2216	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
2217	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
2218	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
2219	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
2220	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
2221	getters.HandleFunc("/a", avatate)
2222	getters.HandleFunc("/o", thelistingoftheontologies)
2223	getters.HandleFunc("/o/{name:.+}", showontology)
2224	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
2225	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
2226	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
2227	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2228
2229	getters.HandleFunc("/server", serveractor)
2230	posters.HandleFunc("/server/inbox", serverinbox)
2231
2232	getters.HandleFunc("/style.css", serveasset)
2233	getters.HandleFunc("/local.css", serveasset)
2234	getters.HandleFunc("/honkpage.js", serveasset)
2235	getters.HandleFunc("/about", servehtml)
2236	getters.HandleFunc("/login", servehtml)
2237	posters.HandleFunc("/dologin", login.LoginFunc)
2238	getters.HandleFunc("/logout", login.LogoutFunc)
2239	getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
2240
2241	loggedin := mux.NewRoute().Subrouter()
2242	loggedin.Use(login.Required)
2243	loggedin.HandleFunc("/first", homepage)
2244	loggedin.HandleFunc("/saved", homepage)
2245	loggedin.HandleFunc("/account", accountpage)
2246	loggedin.HandleFunc("/funzone", showfunzone)
2247	loggedin.HandleFunc("/chpass", dochpass)
2248	loggedin.HandleFunc("/atme", homepage)
2249	loggedin.HandleFunc("/hfcs", hfcspage)
2250	loggedin.HandleFunc("/xzone", xzone)
2251	loggedin.HandleFunc("/newhonk", newhonkpage)
2252	loggedin.HandleFunc("/edit", edithonkpage)
2253	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitwebhonk)))
2254	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2255	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2256	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2257	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2258	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2259	loggedin.HandleFunc("/honkers", showhonkers)
2260	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
2261	loggedin.HandleFunc("/h", showhonker)
2262	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
2263	loggedin.HandleFunc("/c", showcombos)
2264	loggedin.HandleFunc("/t", showconvoy)
2265	loggedin.HandleFunc("/q", showsearch)
2266	loggedin.HandleFunc("/hydra", webhydra)
2267	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
2268
2269	err = http.Serve(listener, mux)
2270	if err != nil {
2271		log.Fatal(err)
2272	}
2273}