all repos — honk @ ef186cbebeb6525a27f43d29be14abf2ebf2c1af

my fork of honk

web.go (view raw)

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