all repos — honk @ 8a01b26d77b4022a9d339d5fd2ae74a43b196d69

my fork of honk

web.go (view raw)

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