all repos — honk @ 43d890847e104fb2f2083f4f9931287a9ac82633

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 getbacktracks(xid string) []string {
 894	c := make(chan bool)
 895	dumptracks <- c
 896	<-c
 897	row := stmtGetTracks.QueryRow(xid)
 898	var rawtracks string
 899	err := row.Scan(&rawtracks)
 900	if err != nil {
 901		if err != sql.ErrNoRows {
 902			log.Printf("error scanning tracks: %s", err)
 903		}
 904		return nil
 905	}
 906	var rcpts []string
 907	for _, f := range strings.Split(rawtracks, " ") {
 908		idx := strings.LastIndexByte(f, '#')
 909		if idx != -1 {
 910			f = f[:idx]
 911		}
 912		if !strings.HasPrefix(f, "https://") {
 913			f = fmt.Sprintf("%%https://%s/inbox", f)
 914		}
 915		rcpts = append(rcpts, f)
 916	}
 917	return rcpts
 918}
 919
 920func savetracks(tracks map[string][]string) {
 921	db := opendatabase()
 922	tx, err := db.Begin()
 923	if err != nil {
 924		log.Printf("savetracks begin error: %s", err)
 925		return
 926	}
 927	defer func() {
 928		err := tx.Commit()
 929		if err != nil {
 930			log.Printf("savetracks commit error: %s", err)
 931		}
 932
 933	}()
 934	stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
 935	if err != nil {
 936		log.Printf("savetracks error: %s", err)
 937		return
 938	}
 939	stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
 940	if err != nil {
 941		log.Printf("savetracks error: %s", err)
 942		return
 943	}
 944	stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
 945	if err != nil {
 946		log.Printf("savetracks error: %s", err)
 947		return
 948	}
 949	count := 0
 950	for xid, f := range tracks {
 951		count += len(f)
 952		var prev string
 953		row := stmtGetTracks.QueryRow(xid)
 954		err := row.Scan(&prev)
 955		if err == sql.ErrNoRows {
 956			f = oneofakind(f)
 957			stmtNewTracks.Exec(xid, strings.Join(f, " "))
 958		} else if err == nil {
 959			all := append(strings.Split(prev, " "), f...)
 960			all = oneofakind(all)
 961			stmtUpdateTracks.Exec(strings.Join(all, " "))
 962		} else {
 963			log.Printf("savetracks error: %s", err)
 964		}
 965	}
 966	log.Printf("saved %d new fetches", count)
 967}
 968
 969var trackchan = make(chan Track)
 970var dumptracks = make(chan chan bool)
 971
 972func tracker() {
 973	timeout := 4 * time.Minute
 974	sleeper := time.NewTimer(timeout)
 975	tracks := make(map[string][]string)
 976	for {
 977		select {
 978		case track := <-trackchan:
 979			tracks[track.xid] = append(tracks[track.xid], track.who)
 980		case <-sleeper.C:
 981			if len(tracks) > 0 {
 982				go savetracks(tracks)
 983				tracks = make(map[string][]string)
 984			}
 985			sleeper.Reset(timeout)
 986		case c := <-dumptracks:
 987			if len(tracks) > 0 {
 988				savetracks(tracks)
 989			}
 990			c <- true
 991		case <-endoftheworld:
 992			if len(tracks) > 0 {
 993				savetracks(tracks)
 994			}
 995			readyalready <- true
 996			return
 997		}
 998	}
 999}
1000
1001var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
1002
1003func trackback(xid string, r *http.Request) {
1004	agent := r.UserAgent()
1005	who := originate(agent)
1006	sig := r.Header.Get("Signature")
1007	if sig != "" {
1008		m := re_keyholder.FindStringSubmatch(sig)
1009		if len(m) == 2 {
1010			who = m[1]
1011		}
1012	}
1013	if who != "" {
1014		trackchan <- Track{xid: xid, who: who}
1015	}
1016}
1017
1018func showonehonk(w http.ResponseWriter, r *http.Request) {
1019	name := mux.Vars(r)["name"]
1020	user, err := butwhatabout(name)
1021	if err != nil {
1022		http.NotFound(w, r)
1023		return
1024	}
1025	if stealthmode(user.ID, r) {
1026		http.NotFound(w, r)
1027		return
1028	}
1029	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1030
1031	if friendorfoe(r.Header.Get("Accept")) {
1032		j, ok := gimmejonk(xid)
1033		if ok {
1034			trackback(xid, r)
1035			w.Header().Set("Content-Type", theonetruename)
1036			w.Write(j)
1037		} else {
1038			http.NotFound(w, r)
1039		}
1040		return
1041	}
1042	honk := getxonk(user.ID, xid)
1043	if honk == nil {
1044		http.NotFound(w, r)
1045		return
1046	}
1047	u := login.GetUserInfo(r)
1048	if u != nil && u.UserID != user.ID {
1049		u = nil
1050	}
1051	if !honk.Public {
1052		if u == nil {
1053			http.NotFound(w, r)
1054			return
1055
1056		}
1057		templinfo := getInfo(r)
1058		templinfo["ServerMessage"] = "one honk maybe more"
1059		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1060		honkpage(w, u, []*Honk{honk}, templinfo)
1061		return
1062	}
1063	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1064	reversehonks(rawhonks)
1065	var honks []*Honk
1066	for _, h := range rawhonks {
1067		if h.XID == xid && len(honks) != 0 {
1068			h.Style += " glow"
1069		}
1070		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1071			honks = append(honks, h)
1072		}
1073	}
1074
1075	templinfo := getInfo(r)
1076	templinfo["ServerMessage"] = "one honk maybe more"
1077	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1078	honkpage(w, u, honks, templinfo)
1079}
1080
1081func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1082	var userid int64 = -1
1083	if u != nil {
1084		userid = u.UserID
1085	}
1086	reverbolate(userid, honks)
1087	templinfo["Honks"] = honks
1088	templinfo["MapLink"] = getmaplink(u)
1089	if templinfo["TopHID"] == nil {
1090		if len(honks) > 0 {
1091			templinfo["TopHID"] = honks[0].ID
1092		} else {
1093			templinfo["TopHID"] = 0
1094		}
1095	}
1096	if u == nil {
1097		w.Header().Set("Cache-Control", "max-age=60")
1098	}
1099	err := readviews.Execute(w, "honkpage.html", templinfo)
1100	if err != nil {
1101		log.Print(err)
1102	}
1103}
1104
1105func saveuser(w http.ResponseWriter, r *http.Request) {
1106	whatabout := r.FormValue("whatabout")
1107	u := login.GetUserInfo(r)
1108	user, _ := butwhatabout(u.Username)
1109	db := opendatabase()
1110	options := user.Options
1111	if r.FormValue("skinny") == "skinny" {
1112		options.SkinnyCSS = true
1113	} else {
1114		options.SkinnyCSS = false
1115	}
1116	if r.FormValue("maps") == "apple" {
1117		options.MapLink = "apple"
1118	} else {
1119		options.MapLink = ""
1120	}
1121	if ava := re_avatar.FindString(whatabout); ava != "" {
1122		whatabout = re_avatar.ReplaceAllString(whatabout, "")
1123		ava = ava[7:]
1124		if ava[0] == ' ' {
1125			ava = ava[1:]
1126		}
1127		options.Avatar = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1128	} else {
1129		options.Avatar = ""
1130	}
1131	whatabout = strings.TrimSpace(whatabout)
1132	j, err := jsonify(options)
1133	if err == nil {
1134		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1135	}
1136	if err != nil {
1137		log.Printf("error bouting what: %s", err)
1138	}
1139	somenamedusers.Clear(u.Username)
1140	somenumberedusers.Clear(u.UserID)
1141
1142	http.Redirect(w, r, "/account", http.StatusSeeOther)
1143}
1144
1145func submitbonk(w http.ResponseWriter, r *http.Request) {
1146	xid := r.FormValue("xid")
1147	userinfo := login.GetUserInfo(r)
1148	user, _ := butwhatabout(userinfo.Username)
1149
1150	log.Printf("bonking %s", xid)
1151
1152	xonk := getxonk(userinfo.UserID, xid)
1153	if xonk == nil {
1154		return
1155	}
1156	if !xonk.Public {
1157		return
1158	}
1159	if xonk.IsBonked() {
1160		return
1161	}
1162	donksforhonks([]*Honk{xonk})
1163
1164	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1165	if err != nil {
1166		log.Printf("error acking bonk: %s", err)
1167	}
1168
1169	oonker := xonk.Oonker
1170	if oonker == "" {
1171		oonker = xonk.Honker
1172	}
1173	dt := time.Now().UTC()
1174	bonk := &Honk{
1175		UserID:   userinfo.UserID,
1176		Username: userinfo.Username,
1177		What:     "bonk",
1178		Honker:   user.URL,
1179		Oonker:   oonker,
1180		XID:      xonk.XID,
1181		RID:      xonk.RID,
1182		Noise:    xonk.Noise,
1183		Precis:   xonk.Precis,
1184		URL:      xonk.URL,
1185		Date:     dt,
1186		Donks:    xonk.Donks,
1187		Whofore:  2,
1188		Convoy:   xonk.Convoy,
1189		Audience: []string{thewholeworld, oonker},
1190		Public:   true,
1191		Format:   "html",
1192		Place:    xonk.Place,
1193		Onts:     xonk.Onts,
1194		Time:     xonk.Time,
1195	}
1196
1197	err = savehonk(bonk)
1198	if err != nil {
1199		log.Printf("uh oh")
1200		return
1201	}
1202
1203	go honkworldwide(user, bonk)
1204
1205	if r.FormValue("js") != "1" {
1206		templinfo := getInfo(r)
1207		templinfo["ServerMessage"] = "Bonked!"
1208		err = readviews.Execute(w, "msg.html", templinfo)
1209		if err != nil {
1210			log.Print(err)
1211		}
1212	}
1213}
1214
1215func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
1216	zonk := &Honk{
1217		What:     what,
1218		XID:      xonk.XID,
1219		Date:     time.Now().UTC(),
1220		Audience: oneofakind(xonk.Audience),
1221	}
1222	zonk.Public = loudandproud(zonk.Audience)
1223
1224	log.Printf("announcing %sed honk: %s", what, xonk.XID)
1225	go honkworldwide(user, zonk)
1226}
1227
1228func zonkit(w http.ResponseWriter, r *http.Request) {
1229	wherefore := r.FormValue("wherefore")
1230	what := r.FormValue("what")
1231	userinfo := login.GetUserInfo(r)
1232	user, _ := butwhatabout(userinfo.Username)
1233
1234	if wherefore == "save" {
1235		xonk := getxonk(userinfo.UserID, what)
1236		if xonk != nil {
1237			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1238			if err != nil {
1239				log.Printf("error saving: %s", err)
1240			}
1241		}
1242		return
1243	}
1244
1245	if wherefore == "unsave" {
1246		xonk := getxonk(userinfo.UserID, what)
1247		if xonk != nil {
1248			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1249			if err != nil {
1250				log.Printf("error unsaving: %s", err)
1251			}
1252		}
1253		return
1254	}
1255
1256	// my hammer is too big, oh well
1257	defer oldjonks.Flush()
1258
1259	if wherefore == "ack" {
1260		xonk := getxonk(userinfo.UserID, what)
1261		if xonk != nil && !xonk.IsAcked() {
1262			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1263			if err != nil {
1264				log.Printf("error acking: %s", err)
1265			}
1266			sendzonkofsorts(xonk, user, "ack")
1267		}
1268		return
1269	}
1270
1271	if wherefore == "deack" {
1272		xonk := getxonk(userinfo.UserID, what)
1273		if xonk != nil && xonk.IsAcked() {
1274			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1275			if err != nil {
1276				log.Printf("error deacking: %s", err)
1277			}
1278			sendzonkofsorts(xonk, user, "deack")
1279		}
1280		return
1281	}
1282
1283	if wherefore == "unbonk" {
1284		xonk := getbonk(userinfo.UserID, what)
1285		if xonk != nil {
1286			deletehonk(xonk.ID)
1287			xonk = getxonk(userinfo.UserID, what)
1288			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1289			if err != nil {
1290				log.Printf("error unbonking: %s", err)
1291			}
1292			sendzonkofsorts(xonk, user, "unbonk")
1293		}
1294		return
1295	}
1296
1297	if wherefore == "untag" {
1298		xonk := getxonk(userinfo.UserID, what)
1299		if xonk != nil {
1300			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1301			if err != nil {
1302				log.Printf("error untagging: %s", err)
1303			}
1304		}
1305		var badparents map[string]bool
1306		untagged.GetAndLock(userinfo.UserID, &badparents)
1307		badparents[what] = true
1308		untagged.Unlock()
1309		return
1310	}
1311
1312	log.Printf("zonking %s %s", wherefore, what)
1313	if wherefore == "zonk" {
1314		xonk := getxonk(userinfo.UserID, what)
1315		if xonk != nil {
1316			deletehonk(xonk.ID)
1317			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1318				sendzonkofsorts(xonk, user, "zonk")
1319			}
1320		}
1321	}
1322	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1323	if err != nil {
1324		log.Printf("error saving zonker: %s", err)
1325		return
1326	}
1327}
1328
1329func edithonkpage(w http.ResponseWriter, r *http.Request) {
1330	u := login.GetUserInfo(r)
1331	user, _ := butwhatabout(u.Username)
1332	xid := r.FormValue("xid")
1333	honk := getxonk(u.UserID, xid)
1334	if !canedithonk(user, honk) {
1335		http.Error(w, "no editing that please", http.StatusInternalServerError)
1336		return
1337	}
1338
1339	noise := honk.Noise
1340
1341	honks := []*Honk{honk}
1342	donksforhonks(honks)
1343	reverbolate(u.UserID, honks)
1344	templinfo := getInfo(r)
1345	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1346	templinfo["Honks"] = honks
1347	templinfo["MapLink"] = getmaplink(u)
1348	templinfo["Noise"] = noise
1349	templinfo["SavedPlace"] = honk.Place
1350	templinfo["ServerMessage"] = "honk edit"
1351	templinfo["IsPreview"] = true
1352	templinfo["UpdateXID"] = honk.XID
1353	if len(honk.Donks) > 0 {
1354		templinfo["SavedFile"] = honk.Donks[0].XID
1355	}
1356	err := readviews.Execute(w, "honkpage.html", templinfo)
1357	if err != nil {
1358		log.Print(err)
1359	}
1360}
1361
1362func newhonkpage(w http.ResponseWriter, r *http.Request) {
1363	u := login.GetUserInfo(r)
1364	rid := r.FormValue("rid")
1365	noise := ""
1366
1367	xonk := getxonk(u.UserID, rid)
1368	if xonk != nil {
1369		_, replto := handles(xonk.Honker)
1370		if replto != "" {
1371			noise = "@" + replto + " "
1372		}
1373	}
1374
1375	templinfo := getInfo(r)
1376	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1377	templinfo["InReplyTo"] = rid
1378	templinfo["Noise"] = noise
1379	templinfo["ServerMessage"] = "compose honk"
1380	templinfo["IsPreview"] = true
1381	err := readviews.Execute(w, "honkpage.html", templinfo)
1382	if err != nil {
1383		log.Print(err)
1384	}
1385}
1386
1387func canedithonk(user *WhatAbout, honk *Honk) bool {
1388	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1389		return false
1390	}
1391	return true
1392}
1393
1394func submitwebhonk(w http.ResponseWriter, r *http.Request) {
1395	submithonk(w, r, false)
1396}
1397
1398// what a hot mess this function is
1399func submithonk(w http.ResponseWriter, r *http.Request, isAPI bool) {
1400	rid := r.FormValue("rid")
1401	noise := r.FormValue("noise")
1402
1403	userinfo := login.GetUserInfo(r)
1404	user, _ := butwhatabout(userinfo.Username)
1405
1406	dt := time.Now().UTC()
1407	updatexid := r.FormValue("updatexid")
1408	var honk *Honk
1409	if updatexid != "" {
1410		honk = getxonk(userinfo.UserID, updatexid)
1411		if !canedithonk(user, honk) {
1412			http.Error(w, "no editing that please", http.StatusInternalServerError)
1413			return
1414		}
1415		honk.Date = dt
1416		honk.What = "update"
1417		honk.Format = "markdown"
1418	} else {
1419		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1420		what := "honk"
1421		if rid != "" {
1422			what = "tonk"
1423		}
1424		honk = &Honk{
1425			UserID:   userinfo.UserID,
1426			Username: userinfo.Username,
1427			What:     what,
1428			Honker:   user.URL,
1429			XID:      xid,
1430			Date:     dt,
1431			Format:   "markdown",
1432		}
1433	}
1434
1435	noise = strings.Replace(noise, "\r", "", -1)
1436	noise = quickrename(noise, userinfo.UserID)
1437	noise = hooterize(noise)
1438	honk.Noise = noise
1439	translate(honk, false)
1440
1441	var convoy string
1442	if rid != "" {
1443		xonk := getxonk(userinfo.UserID, rid)
1444		if xonk != nil {
1445			if xonk.Public {
1446				honk.Audience = append(honk.Audience, xonk.Audience...)
1447			}
1448			convoy = xonk.Convoy
1449		} else {
1450			xonkaud, c := whosthere(rid)
1451			honk.Audience = append(honk.Audience, xonkaud...)
1452			convoy = c
1453		}
1454		for i, a := range honk.Audience {
1455			if a == thewholeworld {
1456				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1457				break
1458			}
1459		}
1460		honk.RID = rid
1461		if xonk.Precis != "" && honk.Precis == "" {
1462			honk.Precis = xonk.Precis
1463			if !(strings.HasPrefix(honk.Precis, "DZ:") || strings.HasPrefix(honk.Precis, "re: re: re: ")) {
1464				honk.Precis = "re: " + honk.Precis
1465			}
1466		}
1467	} else {
1468		honk.Audience = []string{thewholeworld}
1469	}
1470	if honk.Noise != "" && honk.Noise[0] == '@' {
1471		honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
1472	} else {
1473		honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
1474	}
1475
1476	if convoy == "" {
1477		convoy = "data:,electrichonkytonk-" + xfiltrate()
1478	}
1479	butnottooloud(honk.Audience)
1480	honk.Audience = oneofakind(honk.Audience)
1481	if len(honk.Audience) == 0 {
1482		log.Printf("honk to nowhere")
1483		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1484		return
1485	}
1486	honk.Public = loudandproud(honk.Audience)
1487	honk.Convoy = convoy
1488
1489	donkxid := r.FormValue("donkxid")
1490	if donkxid == "" {
1491		file, filehdr, err := r.FormFile("donk")
1492		if err == nil {
1493			var buf bytes.Buffer
1494			io.Copy(&buf, file)
1495			file.Close()
1496			data := buf.Bytes()
1497			xid := xfiltrate()
1498			var media, name string
1499			img, err := shrinkit(data)
1500			if err == nil {
1501				data = img.Data
1502				format := img.Format
1503				media = "image/" + format
1504				if format == "jpeg" {
1505					format = "jpg"
1506				}
1507				name = xid + "." + format
1508				xid = name
1509			} else {
1510				ct := http.DetectContentType(data)
1511				switch ct {
1512				case "application/pdf":
1513					maxsize := 1000000
1514					if len(data) > maxsize {
1515						log.Printf("bad image: %s too much pdf: %d", err, len(data))
1516						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1517						return
1518					}
1519					media = ct
1520					xid += ".pdf"
1521					name = filehdr.Filename
1522					if name == "" {
1523						name = xid
1524					}
1525				default:
1526					maxsize := 100000
1527					if len(data) > maxsize {
1528						log.Printf("bad image: %s too much text: %d", err, len(data))
1529						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1530						return
1531					}
1532					for i := 0; i < len(data); i++ {
1533						if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1534							log.Printf("bad image: %s not text: %d", err, data[i])
1535							http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1536							return
1537						}
1538					}
1539					media = "text/plain"
1540					xid += ".txt"
1541					name = filehdr.Filename
1542					if name == "" {
1543						name = xid
1544					}
1545				}
1546			}
1547			desc := strings.TrimSpace(r.FormValue("donkdesc"))
1548			if desc == "" {
1549				desc = name
1550			}
1551			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1552			fileid, err := savefile(xid, name, desc, url, media, true, data)
1553			if err != nil {
1554				log.Printf("unable to save image: %s", err)
1555				return
1556			}
1557			d := &Donk{
1558				FileID: fileid,
1559				XID:    xid,
1560				Desc:   desc,
1561				URL:    url,
1562				Local:  true,
1563			}
1564			honk.Donks = append(honk.Donks, d)
1565			donkxid = xid
1566		}
1567	} else {
1568		xid := donkxid
1569		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1570		donk := finddonk(url)
1571		if donk != nil {
1572			honk.Donks = append(honk.Donks, donk)
1573		} else {
1574			log.Printf("can't find file: %s", xid)
1575		}
1576	}
1577	herd := herdofemus(noise)
1578	for _, e := range herd {
1579		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1580		if donk != nil {
1581			donk.Name = e.Name
1582			honk.Donks = append(honk.Donks, donk)
1583		}
1584	}
1585	memetize(honk)
1586	imaginate(honk)
1587
1588	placename := strings.TrimSpace(r.FormValue("placename"))
1589	placelat := strings.TrimSpace(r.FormValue("placelat"))
1590	placelong := strings.TrimSpace(r.FormValue("placelong"))
1591	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1592	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1593		p := new(Place)
1594		p.Name = placename
1595		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1596		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1597		p.Url = placeurl
1598		honk.Place = p
1599	}
1600	timestart := strings.TrimSpace(r.FormValue("timestart"))
1601	if timestart != "" {
1602		t := new(Time)
1603		now := time.Now().Local()
1604		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1605			start, err := time.ParseInLocation(layout, timestart, now.Location())
1606			if err == nil {
1607				if start.Year() == 0 {
1608					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1609				}
1610				t.StartTime = start
1611				break
1612			}
1613		}
1614		timeend := r.FormValue("timeend")
1615		dur := parseDuration(timeend)
1616		if dur != 0 {
1617			t.Duration = Duration(dur)
1618		}
1619		if !t.StartTime.IsZero() {
1620			honk.What = "event"
1621			honk.Time = t
1622		}
1623	}
1624
1625	if honk.Public {
1626		honk.Whofore = 2
1627	} else {
1628		honk.Whofore = 3
1629	}
1630
1631	// back to markdown
1632	honk.Noise = noise
1633
1634	if r.FormValue("preview") == "preview" {
1635		honks := []*Honk{honk}
1636		reverbolate(userinfo.UserID, honks)
1637		templinfo := getInfo(r)
1638		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1639		templinfo["Honks"] = honks
1640		templinfo["MapLink"] = getmaplink(userinfo)
1641		templinfo["InReplyTo"] = r.FormValue("rid")
1642		templinfo["Noise"] = r.FormValue("noise")
1643		templinfo["SavedFile"] = donkxid
1644		templinfo["IsPreview"] = true
1645		templinfo["UpdateXID"] = updatexid
1646		templinfo["ServerMessage"] = "honk preview"
1647		err := readviews.Execute(w, "honkpage.html", templinfo)
1648		if err != nil {
1649			log.Print(err)
1650		}
1651		return
1652	}
1653
1654	if updatexid != "" {
1655		updatehonk(honk)
1656		oldjonks.Clear(honk.XID)
1657	} else {
1658		err := savehonk(honk)
1659		if err != nil {
1660			log.Printf("uh oh")
1661			return
1662		}
1663	}
1664
1665	// reload for consistency
1666	honk.Donks = nil
1667	donksforhonks([]*Honk{honk})
1668
1669	go honkworldwide(user, honk)
1670
1671	if isAPI {
1672		w.Write([]byte(honk.XID))
1673	} else {
1674		http.Redirect(w, r, honk.XID[len(serverName)+8:], http.StatusSeeOther)
1675	}
1676}
1677
1678func showhonkers(w http.ResponseWriter, r *http.Request) {
1679	userinfo := login.GetUserInfo(r)
1680	templinfo := getInfo(r)
1681	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1682	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1683	err := readviews.Execute(w, "honkers.html", templinfo)
1684	if err != nil {
1685		log.Print(err)
1686	}
1687}
1688
1689var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1690	honkers := gethonkers(userid)
1691	var combos []string
1692	for _, h := range honkers {
1693		combos = append(combos, h.Combos...)
1694	}
1695	for i, c := range combos {
1696		if c == "-" {
1697			combos[i] = ""
1698		}
1699	}
1700	combos = oneofakind(combos)
1701	sort.Strings(combos)
1702	return combos, true
1703}, Invalidator: &honkerinvalidator})
1704
1705func showcombos(w http.ResponseWriter, r *http.Request) {
1706	userinfo := login.GetUserInfo(r)
1707	var combos []string
1708	combocache.Get(userinfo.UserID, &combos)
1709	templinfo := getInfo(r)
1710	err := readviews.Execute(w, "combos.html", templinfo)
1711	if err != nil {
1712		log.Print(err)
1713	}
1714}
1715
1716func submithonker(w http.ResponseWriter, r *http.Request) {
1717	u := login.GetUserInfo(r)
1718	name := strings.TrimSpace(r.FormValue("name"))
1719	url := strings.TrimSpace(r.FormValue("url"))
1720	peep := r.FormValue("peep")
1721	combos := strings.TrimSpace(r.FormValue("combos"))
1722	combos = " " + combos + " "
1723	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1724
1725	defer honkerinvalidator.Clear(u.UserID)
1726
1727	if honkerid > 0 {
1728		goodbye := r.FormValue("goodbye")
1729		if goodbye == "F" {
1730			db := opendatabase()
1731			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1732				honkerid, u.UserID)
1733			err := row.Scan(&url)
1734			if err != nil {
1735				log.Printf("can't get honker xid: %s", err)
1736				return
1737			}
1738			log.Printf("unsubscribing from %s", url)
1739			user, _ := butwhatabout(u.Username)
1740			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, name, "sub")
1741			if err != nil {
1742				log.Printf("error updating honker: %s", err)
1743				return
1744			}
1745			go itakeitallback(user, url)
1746
1747			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1748			return
1749		}
1750		if goodbye == "X" {
1751			var owner string
1752			db := opendatabase()
1753			row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1754				honkerid, u.UserID)
1755			err := row.Scan(&url, &owner)
1756			if err != nil {
1757				log.Printf("can't get honker xid: %s", err)
1758				return
1759			}
1760			log.Printf("resubscribing to %s", url)
1761			user, _ := butwhatabout(u.Username)
1762			_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "unsub")
1763			if err == nil {
1764				_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, name, "peep")
1765			}
1766			if err != nil {
1767				log.Printf("error updating honker: %s", err)
1768				return
1769			}
1770			go subsub(user, url, owner)
1771
1772			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1773			return
1774		}
1775		_, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1776		if err != nil {
1777			log.Printf("update honker err: %s", err)
1778			return
1779		}
1780		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1781		return
1782	}
1783
1784	if url == "" {
1785		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1786		return
1787	}
1788
1789	flavor := "presub"
1790	if peep == "peep" {
1791		flavor = "peep"
1792	}
1793
1794	if url[0] == '#' {
1795		flavor = "peep"
1796		if name == "" {
1797			name = url
1798		}
1799		_, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url)
1800		if err != nil {
1801			log.Print(err)
1802			return
1803		}
1804		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1805		return
1806	}
1807
1808	info, err := investigate(url)
1809	if err != nil {
1810		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1811		log.Printf("failed to investigate honker: %s", err)
1812		return
1813	}
1814	url = info.XID
1815
1816	var x string
1817	db := opendatabase()
1818	row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1819	err = row.Scan(&x)
1820	if err != sql.ErrNoRows {
1821		http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1822		if err != nil {
1823			log.Printf("honker scan err: %s", err)
1824		}
1825		return
1826	}
1827
1828	if name == "" {
1829		name = info.Name
1830	}
1831	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner)
1832	if err != nil {
1833		log.Print(err)
1834		return
1835	}
1836	if flavor == "presub" {
1837		user, _ := butwhatabout(u.Username)
1838		go subsub(user, url, info.Owner)
1839	}
1840	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1841}
1842
1843func hfcspage(w http.ResponseWriter, r *http.Request) {
1844	userinfo := login.GetUserInfo(r)
1845
1846	filters := getfilters(userinfo.UserID, filtAny)
1847
1848	templinfo := getInfo(r)
1849	templinfo["Filters"] = filters
1850	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1851	err := readviews.Execute(w, "hfcs.html", templinfo)
1852	if err != nil {
1853		log.Print(err)
1854	}
1855}
1856
1857func savehfcs(w http.ResponseWriter, r *http.Request) {
1858	userinfo := login.GetUserInfo(r)
1859	itsok := r.FormValue("itsok")
1860	if itsok == "iforgiveyou" {
1861		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1862		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1863		if err != nil {
1864			log.Printf("error deleting filter: %s", err)
1865		}
1866		filtcache.Clear(userinfo.UserID)
1867		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1868		return
1869	}
1870
1871	filt := new(Filter)
1872	filt.Name = strings.TrimSpace(r.FormValue("name"))
1873	filt.Date = time.Now().UTC()
1874	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
1875	filt.IncludeAudience = r.FormValue("incaud") == "yes"
1876	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
1877	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1878	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
1879	filt.Reject = r.FormValue("doreject") == "yes"
1880	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1881	filt.Hide = r.FormValue("dohide") == "yes"
1882	filt.Collapse = r.FormValue("docollapse") == "yes"
1883	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
1884	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
1885	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
1886		filt.Expiration = time.Now().UTC().Add(dur)
1887	}
1888
1889	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
1890		log.Printf("blank filter")
1891		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
1892		return
1893	}
1894
1895	j, err := jsonify(filt)
1896	if err == nil {
1897		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1898	}
1899	if err != nil {
1900		log.Printf("error saving filter: %s", err)
1901	}
1902
1903	filtcache.Clear(userinfo.UserID)
1904	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1905}
1906
1907func accountpage(w http.ResponseWriter, r *http.Request) {
1908	u := login.GetUserInfo(r)
1909	user, _ := butwhatabout(u.Username)
1910	templinfo := getInfo(r)
1911	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1912	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1913	templinfo["User"] = user
1914	about := user.About
1915	if ava := user.Options.Avatar; ava != "" {
1916		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
1917	}
1918	templinfo["WhatAbout"] = about
1919	err := readviews.Execute(w, "account.html", templinfo)
1920	if err != nil {
1921		log.Print(err)
1922	}
1923}
1924
1925func dochpass(w http.ResponseWriter, r *http.Request) {
1926	err := login.ChangePassword(w, r)
1927	if err != nil {
1928		log.Printf("error changing password: %s", err)
1929	}
1930	http.Redirect(w, r, "/account", http.StatusSeeOther)
1931}
1932
1933func fingerlicker(w http.ResponseWriter, r *http.Request) {
1934	orig := r.FormValue("resource")
1935
1936	log.Printf("finger lick: %s", orig)
1937
1938	if strings.HasPrefix(orig, "acct:") {
1939		orig = orig[5:]
1940	}
1941
1942	name := orig
1943	idx := strings.LastIndexByte(name, '/')
1944	if idx != -1 {
1945		name = name[idx+1:]
1946		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1947			log.Printf("foreign request rejected")
1948			name = ""
1949		}
1950	} else {
1951		idx = strings.IndexByte(name, '@')
1952		if idx != -1 {
1953			name = name[:idx]
1954			if name+"@"+serverName != orig {
1955				log.Printf("foreign request rejected")
1956				name = ""
1957			}
1958		}
1959	}
1960	user, err := butwhatabout(name)
1961	if err != nil {
1962		http.NotFound(w, r)
1963		return
1964	}
1965	if stealthmode(user.ID, r) {
1966		http.NotFound(w, r)
1967		return
1968	}
1969
1970	j := junk.New()
1971	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1972	j["aliases"] = []string{user.URL}
1973	l := junk.New()
1974	l["rel"] = "self"
1975	l["type"] = `application/activity+json`
1976	l["href"] = user.URL
1977	j["links"] = []junk.Junk{l}
1978
1979	w.Header().Set("Content-Type", "application/jrd+json")
1980	j.Write(w)
1981}
1982
1983func somedays() string {
1984	secs := 432000 + notrand.Int63n(432000)
1985	return fmt.Sprintf("%d", secs)
1986}
1987
1988func avatate(w http.ResponseWriter, r *http.Request) {
1989	n := r.FormValue("a")
1990	a := avatar(n)
1991	w.Header().Set("Cache-Control", "max-age="+somedays())
1992	w.Write(a)
1993}
1994
1995func serveasset(w http.ResponseWriter, r *http.Request) {
1996	w.Header().Set("Cache-Control", "max-age=7776000")
1997	dir := viewDir
1998	if r.URL.Path == "/local.css" {
1999		dir = dataDir
2000	}
2001	http.ServeFile(w, r, dir+"/views"+r.URL.Path)
2002}
2003func servehelp(w http.ResponseWriter, r *http.Request) {
2004	name := mux.Vars(r)["name"]
2005	w.Header().Set("Cache-Control", "max-age=3600")
2006	http.ServeFile(w, r, viewDir+"/docs/"+name)
2007}
2008func servehtml(w http.ResponseWriter, r *http.Request) {
2009	u := login.GetUserInfo(r)
2010	templinfo := getInfo(r)
2011	templinfo["AboutMsg"] = aboutMsg
2012	templinfo["LoginMsg"] = loginMsg
2013	templinfo["HonkVersion"] = softwareVersion
2014	if r.URL.Path == "/about" {
2015		templinfo["Sensors"] = getSensors()
2016	}
2017	if u == nil {
2018		w.Header().Set("Cache-Control", "max-age=60")
2019	}
2020	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2021	if err != nil {
2022		log.Print(err)
2023	}
2024}
2025func serveemu(w http.ResponseWriter, r *http.Request) {
2026	emu := mux.Vars(r)["emu"]
2027
2028	w.Header().Set("Cache-Control", "max-age="+somedays())
2029	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2030}
2031func servememe(w http.ResponseWriter, r *http.Request) {
2032	meme := mux.Vars(r)["meme"]
2033
2034	w.Header().Set("Cache-Control", "max-age="+somedays())
2035	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2036}
2037
2038func servefile(w http.ResponseWriter, r *http.Request) {
2039	xid := mux.Vars(r)["xid"]
2040	var media string
2041	var data []byte
2042	row := stmtGetFileData.QueryRow(xid)
2043	err := row.Scan(&media, &data)
2044	if err != nil {
2045		log.Printf("error loading file: %s", err)
2046		http.NotFound(w, r)
2047		return
2048	}
2049	w.Header().Set("Content-Type", media)
2050	w.Header().Set("X-Content-Type-Options", "nosniff")
2051	w.Header().Set("Cache-Control", "max-age="+somedays())
2052	w.Write(data)
2053}
2054
2055func nomoroboto(w http.ResponseWriter, r *http.Request) {
2056	io.WriteString(w, "User-agent: *\n")
2057	io.WriteString(w, "Disallow: /a\n")
2058	io.WriteString(w, "Disallow: /d\n")
2059	io.WriteString(w, "Disallow: /meme\n")
2060	io.WriteString(w, "Disallow: /o\n")
2061	for _, u := range allusers() {
2062		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2063	}
2064}
2065
2066func webhydra(w http.ResponseWriter, r *http.Request) {
2067	u := login.GetUserInfo(r)
2068	userid := u.UserID
2069	templinfo := getInfo(r)
2070	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2071	page := r.FormValue("page")
2072
2073	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2074
2075	var honks []*Honk
2076	switch page {
2077	case "atme":
2078		honks = gethonksforme(userid, wanted)
2079		honks = osmosis(honks, userid, false)
2080		templinfo["ServerMessage"] = "at me!"
2081	case "home":
2082		honks = gethonksforuser(userid, wanted)
2083		honks = osmosis(honks, userid, true)
2084		templinfo["ServerMessage"] = serverMsg
2085	case "first":
2086		honks = gethonksforuserfirstclass(userid, wanted)
2087		honks = osmosis(honks, userid, true)
2088		templinfo["ServerMessage"] = "first class only"
2089	case "saved":
2090		honks = getsavedhonks(userid, wanted)
2091		templinfo["PageName"] = "saved"
2092		templinfo["ServerMessage"] = "saved honks"
2093	case "combo":
2094		c := r.FormValue("c")
2095		honks = gethonksbycombo(userid, c, wanted)
2096		honks = osmosis(honks, userid, false)
2097		templinfo["ServerMessage"] = "honks by combo: " + c
2098	case "convoy":
2099		c := r.FormValue("c")
2100		honks = gethonksbyconvoy(userid, c, wanted)
2101		honks = osmosis(honks, userid, false)
2102		templinfo["ServerMessage"] = "honks in convoy: " + c
2103	case "honker":
2104		xid := r.FormValue("xid")
2105		honks = gethonksbyxonker(userid, xid, wanted)
2106		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
2107		templinfo["ServerMessage"] = msg
2108	default:
2109		http.NotFound(w, r)
2110	}
2111	if len(honks) > 0 {
2112		templinfo["TopHID"] = honks[0].ID
2113	} else {
2114		templinfo["TopHID"] = wanted
2115	}
2116	reverbolate(userid, honks)
2117	templinfo["Honks"] = honks
2118	templinfo["MapLink"] = getmaplink(u)
2119	w.Header().Set("Content-Type", "text/html; charset=utf-8")
2120	err := readviews.Execute(w, "honkfrags.html", templinfo)
2121	if err != nil {
2122		log.Printf("frag error: %s", err)
2123	}
2124}
2125
2126var honkline = make(chan bool)
2127
2128func honkhonkline() {
2129	for {
2130		select {
2131		case honkline <- true:
2132		default:
2133			return
2134		}
2135	}
2136}
2137
2138func apihandler(w http.ResponseWriter, r *http.Request) {
2139	u := login.GetUserInfo(r)
2140	userid := u.UserID
2141	action := r.FormValue("action")
2142	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2143	log.Printf("api request '%s' on behalf of %s", action, u.Username)
2144	switch action {
2145	case "honk":
2146		submithonk(w, r, true)
2147	case "gethonks":
2148		var honks []*Honk
2149		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2150		page := r.FormValue("page")
2151		var waitchan <-chan time.Time
2152	requery:
2153		switch page {
2154		case "atme":
2155			honks = gethonksforme(userid, wanted)
2156			honks = osmosis(honks, userid, false)
2157		case "home":
2158			honks = gethonksforuser(userid, wanted)
2159			honks = osmosis(honks, userid, true)
2160		default:
2161			http.Error(w, "unknown page", http.StatusNotFound)
2162			return
2163		}
2164		if len(honks) == 0 && wait > 0 {
2165			if waitchan == nil {
2166				waitchan = time.After(time.Duration(wait) * time.Second)
2167			}
2168			select {
2169			case <-honkline:
2170				goto requery
2171			case <-waitchan:
2172			}
2173		}
2174		reverbolate(userid, honks)
2175		j := junk.New()
2176		j["honks"] = honks
2177		j.Write(w)
2178	default:
2179		http.Error(w, "unknown action", http.StatusNotFound)
2180		return
2181	}
2182}
2183
2184var endoftheworld = make(chan bool)
2185var readyalready = make(chan bool)
2186
2187func enditall() {
2188	sig := make(chan os.Signal)
2189	signal.Notify(sig, os.Interrupt)
2190	signal.Notify(sig, syscall.SIGTERM)
2191	<-sig
2192	count := 0
2193	log.Printf("stopping...")
2194sendloop:
2195	for {
2196		select {
2197		case endoftheworld <- true:
2198			count++
2199		default:
2200			break sendloop
2201		}
2202	}
2203	log.Printf("waiting...")
2204	for i := 0; i < count; i++ {
2205		<-readyalready
2206	}
2207	log.Printf("apocalypse")
2208	os.Exit(0)
2209}
2210
2211var preservehooks []func()
2212
2213func serve() {
2214	db := opendatabase()
2215	login.Init(db)
2216
2217	listener, err := openListener()
2218	if err != nil {
2219		log.Fatal(err)
2220	}
2221	startBackendServer()
2222	go enditall()
2223	go redeliverator()
2224	go tracker()
2225
2226	debug := false
2227	getconfig("debug", &debug)
2228	readviews = templates.Load(debug,
2229		viewDir+"/views/honkpage.html",
2230		viewDir+"/views/honkfrags.html",
2231		viewDir+"/views/honkers.html",
2232		viewDir+"/views/hfcs.html",
2233		viewDir+"/views/combos.html",
2234		viewDir+"/views/honkform.html",
2235		viewDir+"/views/honk.html",
2236		viewDir+"/views/account.html",
2237		viewDir+"/views/about.html",
2238		viewDir+"/views/funzone.html",
2239		viewDir+"/views/login.html",
2240		viewDir+"/views/xzone.html",
2241		viewDir+"/views/msg.html",
2242		viewDir+"/views/header.html",
2243		viewDir+"/views/onts.html",
2244		viewDir+"/views/honkpage.js",
2245	)
2246	if !debug {
2247		assets := []string{viewDir + "/views/style.css", dataDir + "/views/local.css", viewDir + "/views/honkpage.js"}
2248		for _, s := range assets {
2249			savedassetparams[s] = getassetparam(s)
2250		}
2251	}
2252
2253	for _, h := range preservehooks {
2254		h()
2255	}
2256
2257	mux := mux.NewRouter()
2258	mux.Use(login.Checker)
2259
2260	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2261
2262	posters := mux.Methods("POST").Subrouter()
2263	getters := mux.Methods("GET").Subrouter()
2264
2265	getters.HandleFunc("/", homepage)
2266	getters.HandleFunc("/home", homepage)
2267	getters.HandleFunc("/front", homepage)
2268	getters.HandleFunc("/events", homepage)
2269	getters.HandleFunc("/robots.txt", nomoroboto)
2270	getters.HandleFunc("/rss", showrss)
2271	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
2272	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showonehonk)
2273	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
2274	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
2275	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
2276	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
2277	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
2278	getters.HandleFunc("/a", avatate)
2279	getters.HandleFunc("/o", thelistingoftheontologies)
2280	getters.HandleFunc("/o/{name:.+}", showontology)
2281	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
2282	getters.HandleFunc("/emu/{emu:[^/]+}", serveemu)
2283	getters.HandleFunc("/meme/{meme:[^/]+}", servememe)
2284	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2285
2286	getters.HandleFunc("/server", serveractor)
2287	posters.HandleFunc("/server/inbox", serverinbox)
2288
2289	getters.HandleFunc("/style.css", serveasset)
2290	getters.HandleFunc("/local.css", serveasset)
2291	getters.HandleFunc("/honkpage.js", serveasset)
2292	getters.HandleFunc("/about", servehtml)
2293	getters.HandleFunc("/login", servehtml)
2294	posters.HandleFunc("/dologin", login.LoginFunc)
2295	getters.HandleFunc("/logout", login.LogoutFunc)
2296	getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
2297
2298	loggedin := mux.NewRoute().Subrouter()
2299	loggedin.Use(login.Required)
2300	loggedin.HandleFunc("/first", homepage)
2301	loggedin.HandleFunc("/saved", homepage)
2302	loggedin.HandleFunc("/account", accountpage)
2303	loggedin.HandleFunc("/funzone", showfunzone)
2304	loggedin.HandleFunc("/chpass", dochpass)
2305	loggedin.HandleFunc("/atme", homepage)
2306	loggedin.HandleFunc("/hfcs", hfcspage)
2307	loggedin.HandleFunc("/xzone", xzone)
2308	loggedin.HandleFunc("/newhonk", newhonkpage)
2309	loggedin.HandleFunc("/edit", edithonkpage)
2310	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitwebhonk)))
2311	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2312	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2313	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2314	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2315	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2316	loggedin.HandleFunc("/honkers", showhonkers)
2317	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
2318	loggedin.HandleFunc("/h", showhonker)
2319	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
2320	loggedin.HandleFunc("/c", showcombos)
2321	loggedin.HandleFunc("/t", showconvoy)
2322	loggedin.HandleFunc("/q", showsearch)
2323	loggedin.HandleFunc("/hydra", webhydra)
2324	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
2325
2326	err = http.Serve(listener, mux)
2327	if err != nil {
2328		log.Fatal(err)
2329	}
2330}