all repos — honk @ 53d3bb8d953376a0725dc094eb578654df4131cb

my fork of honk

web.go (view raw)

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