all repos — honk @ 751ebfcd0c0e45720a40a5db9ca5ec1b43a5c282

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