all repos — honk @ 535dc746d1a918b8dfbb5fe3c162915239c646a1

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