all repos — honk @ 1d3a86682b0bd742c02da7dbbdb6c39cac3a1ecb

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