all repos — honk @ e7e14f758256cc3816706acd4dfbbbca7aec1fe3

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