all repos — honk @ 5a0da852e400bba1e3520961b4717860c7f0c9db

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["Name"] = user.Name
 716	templinfo["WhatAbout"] = user.HTAbout
 717	templinfo["ServerMessage"] = ""
 718	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 719	honkpage(w, u, honks, templinfo)
 720}
 721
 722func showhonker(w http.ResponseWriter, r *http.Request) {
 723	u := login.GetUserInfo(r)
 724	name := mux.Vars(r)["name"]
 725	var honks []*Honk
 726	if name == "" {
 727		name = r.FormValue("xid")
 728		honks = gethonksbyxonker(u.UserID, name, 0)
 729	} else {
 730		honks = gethonksbyhonker(u.UserID, name, 0)
 731	}
 732	miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
 733<input type="hidden" name="CSRF" value="%s">
 734<input type="hidden" name="url" value="%s">
 735<button tabindex=1 name="add honker" value="add honker">add honker</button>
 736</form>`, login.GetCSRF("submithonker", r), name)
 737	msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, name, name, miniform)
 738	templinfo := getInfo(r)
 739	templinfo["PageName"] = "honker"
 740	templinfo["PageArg"] = name
 741	templinfo["ServerMessage"] = msg
 742	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 743	honkpage(w, u, honks, templinfo)
 744}
 745
 746func showcombo(w http.ResponseWriter, r *http.Request) {
 747	name := mux.Vars(r)["name"]
 748	u := login.GetUserInfo(r)
 749	honks := gethonksbycombo(u.UserID, name, 0)
 750	honks = osmosis(honks, u.UserID, true)
 751	templinfo := getInfo(r)
 752	templinfo["PageName"] = "combo"
 753	templinfo["PageArg"] = name
 754	templinfo["ServerMessage"] = "honks by combo: " + name
 755	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 756	honkpage(w, u, honks, templinfo)
 757}
 758func showconvoy(w http.ResponseWriter, r *http.Request) {
 759	c := r.FormValue("c")
 760	u := login.GetUserInfo(r)
 761	honks := gethonksbyconvoy(u.UserID, c, 0)
 762	templinfo := getInfo(r)
 763	if len(honks) > 0 {
 764		templinfo["TopHID"] = honks[0].ID
 765	}
 766	honks = osmosis(honks, u.UserID, false)
 767	reversehonks(honks)
 768	templinfo["PageName"] = "convoy"
 769	templinfo["PageArg"] = c
 770	templinfo["ServerMessage"] = "honks in convoy: " + c
 771	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 772	honkpage(w, u, honks, templinfo)
 773}
 774func showsearch(w http.ResponseWriter, r *http.Request) {
 775	q := r.FormValue("q")
 776	u := login.GetUserInfo(r)
 777	honks := gethonksbysearch(u.UserID, q, 0)
 778	templinfo := getInfo(r)
 779	templinfo["PageName"] = "search"
 780	templinfo["PageArg"] = q
 781	templinfo["ServerMessage"] = "honks for search: " + q
 782	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 783	honkpage(w, u, honks, templinfo)
 784}
 785func showontology(w http.ResponseWriter, r *http.Request) {
 786	name := mux.Vars(r)["name"]
 787	u := login.GetUserInfo(r)
 788	var userid int64 = -1
 789	if u != nil {
 790		userid = u.UserID
 791	}
 792	honks := gethonksbyontology(userid, "#"+name, 0)
 793	if friendorfoe(r.Header.Get("Accept")) {
 794		if len(honks) > 40 {
 795			honks = honks[0:40]
 796		}
 797
 798		var xids []string
 799		for _, h := range honks {
 800			xids = append(xids, h.XID)
 801		}
 802
 803		user := getserveruser()
 804
 805		j := junk.New()
 806		j["@context"] = itiswhatitis
 807		j["id"] = fmt.Sprintf("https://%s/o/%s", serverName, name)
 808		j["name"] = "#" + name
 809		j["attributedTo"] = user.URL
 810		j["type"] = "OrderedCollection"
 811		j["totalItems"] = len(xids)
 812		j["orderedItems"] = xids
 813
 814		j.Write(w)
 815		return
 816	}
 817
 818	templinfo := getInfo(r)
 819	templinfo["ServerMessage"] = "honks by ontology: " + name
 820	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 821	honkpage(w, u, honks, templinfo)
 822}
 823
 824type Ont struct {
 825	Name  string
 826	Count int64
 827}
 828
 829func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 830	u := login.GetUserInfo(r)
 831	var userid int64 = -1
 832	if u != nil {
 833		userid = u.UserID
 834	}
 835	rows, err := stmtAllOnts.Query(userid)
 836	if err != nil {
 837		elog.Printf("selection error: %s", err)
 838		return
 839	}
 840	defer rows.Close()
 841	var onts []Ont
 842	for rows.Next() {
 843		var o Ont
 844		err := rows.Scan(&o.Name, &o.Count)
 845		if err != nil {
 846			elog.Printf("error scanning ont: %s", err)
 847			continue
 848		}
 849		if len(o.Name) > 24 {
 850			continue
 851		}
 852		o.Name = o.Name[1:]
 853		onts = append(onts, o)
 854	}
 855	sort.Slice(onts, func(i, j int) bool {
 856		return onts[i].Name < onts[j].Name
 857	})
 858	if u == nil && !develMode {
 859		w.Header().Set("Cache-Control", "max-age=300")
 860	}
 861	templinfo := getInfo(r)
 862	templinfo["Onts"] = onts
 863	err = readviews.Execute(w, "onts.html", templinfo)
 864	if err != nil {
 865		elog.Print(err)
 866	}
 867}
 868
 869type Track struct {
 870	xid string
 871	who string
 872}
 873
 874func getbacktracks(xid string) []string {
 875	c := make(chan bool)
 876	dumptracks <- c
 877	<-c
 878	row := stmtGetTracks.QueryRow(xid)
 879	var rawtracks string
 880	err := row.Scan(&rawtracks)
 881	if err != nil {
 882		if err != sql.ErrNoRows {
 883			elog.Printf("error scanning tracks: %s", err)
 884		}
 885		return nil
 886	}
 887	var rcpts []string
 888	for _, f := range strings.Split(rawtracks, " ") {
 889		idx := strings.LastIndexByte(f, '#')
 890		if idx != -1 {
 891			f = f[:idx]
 892		}
 893		if !strings.HasPrefix(f, "https://") {
 894			f = fmt.Sprintf("%%https://%s/inbox", f)
 895		}
 896		rcpts = append(rcpts, f)
 897	}
 898	return rcpts
 899}
 900
 901func savetracks(tracks map[string][]string) {
 902	db := opendatabase()
 903	tx, err := db.Begin()
 904	if err != nil {
 905		elog.Printf("savetracks begin error: %s", err)
 906		return
 907	}
 908	defer func() {
 909		err := tx.Commit()
 910		if err != nil {
 911			elog.Printf("savetracks commit error: %s", err)
 912		}
 913
 914	}()
 915	stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
 916	if err != nil {
 917		elog.Printf("savetracks error: %s", err)
 918		return
 919	}
 920	stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
 921	if err != nil {
 922		elog.Printf("savetracks error: %s", err)
 923		return
 924	}
 925	stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
 926	if err != nil {
 927		elog.Printf("savetracks error: %s", err)
 928		return
 929	}
 930	count := 0
 931	for xid, f := range tracks {
 932		count += len(f)
 933		var prev string
 934		row := stmtGetTracks.QueryRow(xid)
 935		err := row.Scan(&prev)
 936		if err == sql.ErrNoRows {
 937			f = oneofakind(f)
 938			stmtNewTracks.Exec(xid, strings.Join(f, " "))
 939		} else if err == nil {
 940			all := append(strings.Split(prev, " "), f...)
 941			all = oneofakind(all)
 942			stmtUpdateTracks.Exec(strings.Join(all, " "))
 943		} else {
 944			elog.Printf("savetracks error: %s", err)
 945		}
 946	}
 947	dlog.Printf("saved %d new fetches", count)
 948}
 949
 950var trackchan = make(chan Track)
 951var dumptracks = make(chan chan bool)
 952
 953func tracker() {
 954	timeout := 4 * time.Minute
 955	sleeper := time.NewTimer(timeout)
 956	tracks := make(map[string][]string)
 957	workinprogress++
 958	for {
 959		select {
 960		case track := <-trackchan:
 961			tracks[track.xid] = append(tracks[track.xid], track.who)
 962		case <-sleeper.C:
 963			if len(tracks) > 0 {
 964				go savetracks(tracks)
 965				tracks = make(map[string][]string)
 966			}
 967			sleeper.Reset(timeout)
 968		case c := <-dumptracks:
 969			if len(tracks) > 0 {
 970				savetracks(tracks)
 971			}
 972			c <- true
 973		case <-endoftheworld:
 974			if len(tracks) > 0 {
 975				savetracks(tracks)
 976			}
 977			readyalready <- true
 978			return
 979		}
 980	}
 981}
 982
 983var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
 984
 985func trackback(xid string, r *http.Request) {
 986	agent := r.UserAgent()
 987	who := originate(agent)
 988	sig := r.Header.Get("Signature")
 989	if sig != "" {
 990		m := re_keyholder.FindStringSubmatch(sig)
 991		if len(m) == 2 {
 992			who = m[1]
 993		}
 994	}
 995	if who != "" {
 996		trackchan <- Track{xid: xid, who: who}
 997	}
 998}
 999
1000func showonehonk(w http.ResponseWriter, r *http.Request) {
1001	name := mux.Vars(r)["name"]
1002	user, err := butwhatabout(name)
1003	if err != nil {
1004		http.NotFound(w, r)
1005		return
1006	}
1007	if stealthmode(user.ID, r) {
1008		http.NotFound(w, r)
1009		return
1010	}
1011	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
1012
1013	if friendorfoe(r.Header.Get("Accept")) {
1014		j, ok := gimmejonk(xid)
1015		if ok {
1016			trackback(xid, r)
1017			w.Header().Set("Content-Type", theonetruename)
1018			w.Write(j)
1019		} else {
1020			http.NotFound(w, r)
1021		}
1022		return
1023	}
1024	honk := getxonk(user.ID, xid)
1025	if honk == nil {
1026		http.NotFound(w, r)
1027		return
1028	}
1029	u := login.GetUserInfo(r)
1030	if u != nil && u.UserID != user.ID {
1031		u = nil
1032	}
1033	if !honk.Public {
1034		if u == nil {
1035			http.NotFound(w, r)
1036			return
1037
1038		}
1039		honks := []*Honk{honk}
1040		donksforhonks(honks)
1041		templinfo := getInfo(r)
1042		templinfo["ServerMessage"] = "one honk maybe more"
1043		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1044		honkpage(w, u, honks, templinfo)
1045		return
1046	}
1047	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1048	reversehonks(rawhonks)
1049	var honks []*Honk
1050	for _, h := range rawhonks {
1051		if h.XID == xid && len(honks) != 0 {
1052			h.Style += " glow"
1053		}
1054		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1055			honks = append(honks, h)
1056		}
1057	}
1058
1059	templinfo := getInfo(r)
1060	templinfo["ServerMessage"] = "one honk maybe more"
1061	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1062	honkpage(w, u, honks, templinfo)
1063}
1064
1065func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1066	var userid int64 = -1
1067	if u != nil {
1068		userid = u.UserID
1069		templinfo["User"], _ = butwhatabout(u.Username)
1070	}
1071	reverbolate(userid, honks)
1072	templinfo["Honks"] = honks
1073	templinfo["MapLink"] = getmaplink(u)
1074	if templinfo["TopHID"] == nil {
1075		if len(honks) > 0 {
1076			templinfo["TopHID"] = honks[0].ID
1077		} else {
1078			templinfo["TopHID"] = 0
1079		}
1080	}
1081	if u == nil && !develMode {
1082		w.Header().Set("Cache-Control", "max-age=60")
1083	}
1084	err := readviews.Execute(w, "honkpage.html", templinfo)
1085	if err != nil {
1086		elog.Print(err)
1087	}
1088}
1089
1090func saveuser(w http.ResponseWriter, r *http.Request) {
1091	whatabout := r.FormValue("whatabout")
1092	whatabout = strings.Replace(whatabout, "\r", "", -1)
1093	u := login.GetUserInfo(r)
1094	user, _ := butwhatabout(u.Username)
1095	db := opendatabase()
1096
1097	options := user.Options
1098	if r.FormValue("skinny") == "skinny" {
1099		options.SkinnyCSS = true
1100	} else {
1101		options.SkinnyCSS = false
1102	}
1103	if r.FormValue("avahex") == "avahex" {
1104		options.Avahex = true
1105	} else {
1106		options.Avahex = false
1107	}
1108	if r.FormValue("omitimages") == "omitimages" {
1109		options.OmitImages = true
1110	} else {
1111		options.OmitImages = false
1112	}
1113	if r.FormValue("mentionall") == "mentionall" {
1114		options.MentionAll = true
1115	} else {
1116		options.MentionAll = false
1117	}
1118	if r.FormValue("maps") == "apple" {
1119		options.MapLink = "apple"
1120	} else {
1121		options.MapLink = ""
1122	}
1123	options.Reaction = r.FormValue("reaction")
1124
1125	sendupdate := false
1126	ava := re_avatar.FindString(whatabout)
1127	if ava != "" {
1128		whatabout = re_avatar.ReplaceAllString(whatabout, "")
1129		ava = ava[7:]
1130		if ava[0] == ' ' {
1131			ava = ava[1:]
1132		}
1133		ava = fmt.Sprintf("https://%s/meme/%s", serverName, ava)
1134	}
1135	if ava != options.Avatar {
1136		options.Avatar = ava
1137		sendupdate = true
1138	}
1139	whatabout = strings.TrimSpace(whatabout)
1140	if whatabout != user.About {
1141		sendupdate = true
1142	}
1143	j, err := jsonify(options)
1144	if err == nil {
1145		_, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1146	}
1147	if err != nil {
1148		elog.Printf("error bouting what: %s", err)
1149	}
1150	somenamedusers.Clear(u.Username)
1151	somenumberedusers.Clear(u.UserID)
1152	oldjonkers.Clear(u.Username)
1153
1154	if sendupdate {
1155		updateMe(u.Username)
1156	}
1157
1158	http.Redirect(w, r, "/account", http.StatusSeeOther)
1159}
1160
1161func bonkit(xid string, user *WhatAbout) {
1162	dlog.Printf("bonking %s", xid)
1163
1164	xonk := getxonk(user.ID, xid)
1165	if xonk == nil {
1166		return
1167	}
1168	if !xonk.Public {
1169		return
1170	}
1171	if xonk.IsBonked() {
1172		return
1173	}
1174	donksforhonks([]*Honk{xonk})
1175
1176	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1177	if err != nil {
1178		elog.Printf("error acking bonk: %s", err)
1179	}
1180
1181	oonker := xonk.Oonker
1182	if oonker == "" {
1183		oonker = xonk.Honker
1184	}
1185	dt := time.Now().UTC()
1186	bonk := &Honk{
1187		UserID:   user.ID,
1188		Username: user.Name,
1189		What:     "bonk",
1190		Honker:   user.URL,
1191		Oonker:   oonker,
1192		XID:      xonk.XID,
1193		RID:      xonk.RID,
1194		Noise:    xonk.Noise,
1195		Precis:   xonk.Precis,
1196		URL:      xonk.URL,
1197		Date:     dt,
1198		Donks:    xonk.Donks,
1199		Whofore:  2,
1200		Convoy:   xonk.Convoy,
1201		Audience: []string{thewholeworld, oonker},
1202		Public:   true,
1203		Format:   "html",
1204		Place:    xonk.Place,
1205		Onts:     xonk.Onts,
1206		Time:     xonk.Time,
1207	}
1208
1209	err = savehonk(bonk)
1210	if err != nil {
1211		elog.Printf("uh oh")
1212		return
1213	}
1214
1215	go honkworldwide(user, bonk)
1216}
1217
1218func submitbonk(w http.ResponseWriter, r *http.Request) {
1219	xid := r.FormValue("xid")
1220	userinfo := login.GetUserInfo(r)
1221	user, _ := butwhatabout(userinfo.Username)
1222
1223	bonkit(xid, user)
1224
1225	if r.FormValue("js") != "1" {
1226		templinfo := getInfo(r)
1227		templinfo["ServerMessage"] = "Bonked!"
1228		err := readviews.Execute(w, "msg.html", templinfo)
1229		if err != nil {
1230			elog.Print(err)
1231		}
1232	}
1233}
1234
1235func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1236	zonk := &Honk{
1237		What:     what,
1238		XID:      xonk.XID,
1239		Date:     time.Now().UTC(),
1240		Audience: oneofakind(xonk.Audience),
1241		Noise:    aux,
1242	}
1243	zonk.Public = loudandproud(zonk.Audience)
1244
1245	dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1246	go honkworldwide(user, zonk)
1247}
1248
1249func zonkit(w http.ResponseWriter, r *http.Request) {
1250	wherefore := r.FormValue("wherefore")
1251	what := r.FormValue("what")
1252	userinfo := login.GetUserInfo(r)
1253	user, _ := butwhatabout(userinfo.Username)
1254
1255	if wherefore == "save" {
1256		xonk := getxonk(userinfo.UserID, what)
1257		if xonk != nil {
1258			_, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1259			if err != nil {
1260				elog.Printf("error saving: %s", err)
1261			}
1262		}
1263		return
1264	}
1265
1266	if wherefore == "unsave" {
1267		xonk := getxonk(userinfo.UserID, what)
1268		if xonk != nil {
1269			_, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1270			if err != nil {
1271				elog.Printf("error unsaving: %s", err)
1272			}
1273		}
1274		return
1275	}
1276
1277	if wherefore == "react" {
1278		reaction := user.Options.Reaction
1279		if r2 := r.FormValue("reaction"); r2 != "" {
1280			reaction = r2
1281		}
1282		if reaction == "none" {
1283			return
1284		}
1285		xonk := getxonk(userinfo.UserID, what)
1286		if xonk != nil {
1287			_, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1288			if err != nil {
1289				elog.Printf("error saving: %s", err)
1290			}
1291			sendzonkofsorts(xonk, user, "react", reaction)
1292		}
1293		return
1294	}
1295
1296	if wherefore == "wonk" {
1297		xonk := getxonk(userinfo.UserID, what)
1298		if xonk != nil {
1299			_, err := stmtUpdateFlags.Exec(flagIsWonked, xonk.ID)
1300			if err == nil {
1301				guesses := r.FormValue("guesses")
1302				_, err = stmtSaveMeta.Exec(xonk.ID, "guesses", guesses)
1303			}
1304			if err != nil {
1305				elog.Printf("error saving: %s", err)
1306			}
1307		}
1308		return
1309	}
1310
1311	// my hammer is too big, oh well
1312	defer oldjonks.Flush()
1313
1314	if wherefore == "ack" {
1315		xonk := getxonk(userinfo.UserID, what)
1316		if xonk != nil && !xonk.IsAcked() {
1317			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1318			if err != nil {
1319				elog.Printf("error acking: %s", err)
1320			}
1321			sendzonkofsorts(xonk, user, "ack", "")
1322		}
1323		return
1324	}
1325
1326	if wherefore == "deack" {
1327		xonk := getxonk(userinfo.UserID, what)
1328		if xonk != nil && xonk.IsAcked() {
1329			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1330			if err != nil {
1331				elog.Printf("error deacking: %s", err)
1332			}
1333			sendzonkofsorts(xonk, user, "deack", "")
1334		}
1335		return
1336	}
1337
1338	if wherefore == "bonk" {
1339		user, _ := butwhatabout(userinfo.Username)
1340		bonkit(what, user)
1341		return
1342	}
1343
1344	if wherefore == "unbonk" {
1345		xonk := getbonk(userinfo.UserID, what)
1346		if xonk != nil {
1347			deletehonk(xonk.ID)
1348			xonk = getxonk(userinfo.UserID, what)
1349			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1350			if err != nil {
1351				elog.Printf("error unbonking: %s", err)
1352			}
1353			sendzonkofsorts(xonk, user, "unbonk", "")
1354		}
1355		return
1356	}
1357
1358	if wherefore == "untag" {
1359		xonk := getxonk(userinfo.UserID, what)
1360		if xonk != nil {
1361			_, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1362			if err != nil {
1363				elog.Printf("error untagging: %s", err)
1364			}
1365		}
1366		var badparents map[string]bool
1367		untagged.GetAndLock(userinfo.UserID, &badparents)
1368		badparents[what] = true
1369		untagged.Unlock()
1370		return
1371	}
1372
1373	ilog.Printf("zonking %s %s", wherefore, what)
1374	if wherefore == "zonk" {
1375		xonk := getxonk(userinfo.UserID, what)
1376		if xonk != nil {
1377			deletehonk(xonk.ID)
1378			if xonk.Whofore == 2 || xonk.Whofore == 3 {
1379				sendzonkofsorts(xonk, user, "zonk", "")
1380			}
1381		}
1382	}
1383	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
1384	if err != nil {
1385		elog.Printf("error saving zonker: %s", err)
1386		return
1387	}
1388}
1389
1390func edithonkpage(w http.ResponseWriter, r *http.Request) {
1391	u := login.GetUserInfo(r)
1392	user, _ := butwhatabout(u.Username)
1393	xid := r.FormValue("xid")
1394	honk := getxonk(u.UserID, xid)
1395	if !canedithonk(user, honk) {
1396		http.Error(w, "no editing that please", http.StatusInternalServerError)
1397		return
1398	}
1399
1400	noise := honk.Noise
1401
1402	honks := []*Honk{honk}
1403	donksforhonks(honks)
1404	reverbolate(u.UserID, honks)
1405	templinfo := getInfo(r)
1406	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1407	templinfo["Honks"] = honks
1408	templinfo["MapLink"] = getmaplink(u)
1409	templinfo["Noise"] = noise
1410	templinfo["SavedPlace"] = honk.Place
1411	if tm := honk.Time; tm != nil {
1412		templinfo["ShowTime"] = ";"
1413		templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1414		if tm.Duration != 0 {
1415			templinfo["Duration"] = tm.Duration
1416		}
1417	}
1418	templinfo["ServerMessage"] = "honk edit 2"
1419	templinfo["IsPreview"] = true
1420	templinfo["UpdateXID"] = honk.XID
1421	if len(honk.Donks) > 0 {
1422		templinfo["SavedFile"] = honk.Donks[0].XID
1423	}
1424	err := readviews.Execute(w, "honkpage.html", templinfo)
1425	if err != nil {
1426		elog.Print(err)
1427	}
1428}
1429
1430func newhonkpage(w http.ResponseWriter, r *http.Request) {
1431	u := login.GetUserInfo(r)
1432	rid := r.FormValue("rid")
1433	noise := ""
1434
1435	xonk := getxonk(u.UserID, rid)
1436	if xonk != nil {
1437		_, replto := handles(xonk.Honker)
1438		if replto != "" {
1439			noise = "@" + replto + " "
1440		}
1441	}
1442
1443	templinfo := getInfo(r)
1444	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1445	templinfo["InReplyTo"] = rid
1446	templinfo["Noise"] = noise
1447	templinfo["ServerMessage"] = "compose honk"
1448	templinfo["IsPreview"] = true
1449	err := readviews.Execute(w, "honkpage.html", templinfo)
1450	if err != nil {
1451		elog.Print(err)
1452	}
1453}
1454
1455func canedithonk(user *WhatAbout, honk *Honk) bool {
1456	if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1457		return false
1458	}
1459	return true
1460}
1461
1462func submitdonk(w http.ResponseWriter, r *http.Request) (*Donk, error) {
1463	if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1464		return nil, nil
1465	}
1466	file, filehdr, err := r.FormFile("donk")
1467	if err != nil {
1468		if err == http.ErrMissingFile {
1469			return nil, nil
1470		}
1471		elog.Printf("error reading donk: %s", err)
1472		http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1473		return nil, err
1474	}
1475	var buf bytes.Buffer
1476	io.Copy(&buf, file)
1477	file.Close()
1478	data := buf.Bytes()
1479	var media, name string
1480	img, err := shrinkit(data)
1481	if err == nil {
1482		data = img.Data
1483		format := img.Format
1484		media = "image/" + format
1485		if format == "jpeg" {
1486			format = "jpg"
1487		}
1488		name = xfiltrate() + "." + format
1489	} else {
1490		ct := http.DetectContentType(data)
1491		switch ct {
1492		case "application/pdf":
1493			maxsize := 10000000
1494			if len(data) > maxsize {
1495				ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1496				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1497				return nil, err
1498			}
1499			media = ct
1500			name = filehdr.Filename
1501			if name == "" {
1502				name = xfiltrate() + ".pdf"
1503			}
1504		default:
1505			maxsize := 100000
1506			if len(data) > maxsize {
1507				ilog.Printf("bad image: %s too much text: %d", err, len(data))
1508				http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1509				return nil, err
1510			}
1511			for i := 0; i < len(data); i++ {
1512				if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1513					ilog.Printf("bad image: %s not text: %d", err, data[i])
1514					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1515					return nil, err
1516				}
1517			}
1518			media = "text/plain"
1519			name = filehdr.Filename
1520			if name == "" {
1521				name = xfiltrate() + ".txt"
1522			}
1523		}
1524	}
1525	desc := strings.TrimSpace(r.FormValue("donkdesc"))
1526	if desc == "" {
1527		desc = name
1528	}
1529	fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1530	if err != nil {
1531		elog.Printf("unable to save image: %s", err)
1532		http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1533		return nil, err
1534	}
1535	d := &Donk{
1536		FileID: fileid,
1537		XID:    xid,
1538		Desc:   desc,
1539		Local:  true,
1540	}
1541	return d, nil
1542}
1543
1544func submitwebhonk(w http.ResponseWriter, r *http.Request) {
1545	h := submithonk(w, r)
1546	if h == nil {
1547		return
1548	}
1549	http.Redirect(w, r, h.XID[len(serverName)+8:], http.StatusSeeOther)
1550}
1551
1552// what a hot mess this function is
1553func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1554	rid := r.FormValue("rid")
1555	noise := r.FormValue("noise")
1556	format := r.FormValue("format")
1557	if format == "" {
1558		format = "markdown"
1559	}
1560	if !(format == "markdown" || format == "html") {
1561		http.Error(w, "unknown format", 500)
1562		return nil
1563	}
1564
1565	userinfo := login.GetUserInfo(r)
1566	user, _ := butwhatabout(userinfo.Username)
1567
1568	dt := time.Now().UTC()
1569	updatexid := r.FormValue("updatexid")
1570	var honk *Honk
1571	if updatexid != "" {
1572		honk = getxonk(userinfo.UserID, updatexid)
1573		if !canedithonk(user, honk) {
1574			http.Error(w, "no editing that please", http.StatusInternalServerError)
1575			return nil
1576		}
1577		honk.Date = dt
1578		honk.What = "update"
1579		honk.Format = format
1580	} else {
1581		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1582		what := "honk"
1583		if rid != "" {
1584			what = "tonk"
1585		}
1586		wonkles := r.FormValue("wonkles")
1587		if wonkles != "" {
1588			what = "wonk"
1589		}
1590		honk = &Honk{
1591			UserID:   userinfo.UserID,
1592			Username: userinfo.Username,
1593			What:     what,
1594			Honker:   user.URL,
1595			XID:      xid,
1596			Date:     dt,
1597			Format:   format,
1598			Wonkles:  wonkles,
1599		}
1600	}
1601
1602	noise = strings.Replace(noise, "\r", "", -1)
1603	noise = quickrename(noise, userinfo.UserID)
1604	noise = hooterize(noise)
1605	honk.Noise = noise
1606	translate(honk)
1607
1608	var convoy string
1609	if rid != "" {
1610		xonk := getxonk(userinfo.UserID, rid)
1611		if xonk == nil {
1612			http.Error(w, "replyto disappeared", http.StatusNotFound)
1613			return nil
1614		}
1615		if xonk.Public {
1616			honk.Audience = append(honk.Audience, xonk.Audience...)
1617		}
1618		convoy = xonk.Convoy
1619		for i, a := range honk.Audience {
1620			if a == thewholeworld {
1621				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1622				break
1623			}
1624		}
1625		honk.RID = rid
1626		if xonk.Precis != "" && honk.Precis == "" {
1627			honk.Precis = xonk.Precis
1628			if !(strings.HasPrefix(honk.Precis, "DZ:") || strings.HasPrefix(honk.Precis, "re: re: re: ")) {
1629				honk.Precis = "re: " + honk.Precis
1630			}
1631		}
1632	} else {
1633		honk.Audience = []string{thewholeworld}
1634	}
1635	if honk.Noise != "" && honk.Noise[0] == '@' {
1636		honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1637	} else {
1638		honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1639	}
1640
1641	if convoy == "" {
1642		convoy = "data:,electrichonkytonk-" + xfiltrate()
1643	}
1644	butnottooloud(honk.Audience)
1645	honk.Audience = oneofakind(honk.Audience)
1646	if len(honk.Audience) == 0 {
1647		ilog.Printf("honk to nowhere")
1648		http.Error(w, "honk to nowhere...", http.StatusNotFound)
1649		return nil
1650	}
1651	honk.Public = loudandproud(honk.Audience)
1652	honk.Convoy = convoy
1653
1654	donkxid := r.FormValue("donkxid")
1655	if donkxid == "" {
1656		d, err := submitdonk(w, r)
1657		if err != nil && err != http.ErrMissingFile {
1658			return nil
1659		}
1660		if d != nil {
1661			honk.Donks = append(honk.Donks, d)
1662			donkxid = d.XID
1663		}
1664	} else {
1665		xid := donkxid
1666		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1667		donk := finddonk(url)
1668		if donk != nil {
1669			honk.Donks = append(honk.Donks, donk)
1670		} else {
1671			ilog.Printf("can't find file: %s", xid)
1672		}
1673	}
1674	memetize(honk)
1675	imaginate(honk)
1676
1677	placename := strings.TrimSpace(r.FormValue("placename"))
1678	placelat := strings.TrimSpace(r.FormValue("placelat"))
1679	placelong := strings.TrimSpace(r.FormValue("placelong"))
1680	placeurl := strings.TrimSpace(r.FormValue("placeurl"))
1681	if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
1682		p := new(Place)
1683		p.Name = placename
1684		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1685		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1686		p.Url = placeurl
1687		honk.Place = p
1688	}
1689	timestart := strings.TrimSpace(r.FormValue("timestart"))
1690	if timestart != "" {
1691		t := new(Time)
1692		now := time.Now().Local()
1693		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1694			start, err := time.ParseInLocation(layout, timestart, now.Location())
1695			if err == nil {
1696				if start.Year() == 0 {
1697					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1698				}
1699				t.StartTime = start
1700				break
1701			}
1702		}
1703		timeend := r.FormValue("timeend")
1704		dur := parseDuration(timeend)
1705		if dur != 0 {
1706			t.Duration = Duration(dur)
1707		}
1708		if !t.StartTime.IsZero() {
1709			honk.What = "event"
1710			honk.Time = t
1711		}
1712	}
1713
1714	if honk.Public {
1715		honk.Whofore = 2
1716	} else {
1717		honk.Whofore = 3
1718	}
1719
1720	// back to markdown
1721	honk.Noise = noise
1722
1723	if r.FormValue("preview") == "preview" {
1724		honks := []*Honk{honk}
1725		reverbolate(userinfo.UserID, honks)
1726		templinfo := getInfo(r)
1727		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1728		templinfo["Honks"] = honks
1729		templinfo["MapLink"] = getmaplink(userinfo)
1730		templinfo["InReplyTo"] = r.FormValue("rid")
1731		templinfo["Noise"] = r.FormValue("noise")
1732		templinfo["SavedFile"] = donkxid
1733		if tm := honk.Time; tm != nil {
1734			templinfo["ShowTime"] = ";"
1735			templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1736			if tm.Duration != 0 {
1737				templinfo["Duration"] = tm.Duration
1738			}
1739		}
1740		templinfo["IsPreview"] = true
1741		templinfo["UpdateXID"] = updatexid
1742		templinfo["ServerMessage"] = "honk preview"
1743		err := readviews.Execute(w, "honkpage.html", templinfo)
1744		if err != nil {
1745			elog.Print(err)
1746		}
1747		return nil
1748	}
1749
1750	if updatexid != "" {
1751		updatehonk(honk)
1752		oldjonks.Clear(honk.XID)
1753	} else {
1754		err := savehonk(honk)
1755		if err != nil {
1756			elog.Printf("uh oh")
1757			return nil
1758		}
1759	}
1760
1761	// reload for consistency
1762	honk.Donks = nil
1763	donksforhonks([]*Honk{honk})
1764
1765	go honkworldwide(user, honk)
1766
1767	return honk
1768}
1769
1770func showhonkers(w http.ResponseWriter, r *http.Request) {
1771	userinfo := login.GetUserInfo(r)
1772	templinfo := getInfo(r)
1773	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1774	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1775	err := readviews.Execute(w, "honkers.html", templinfo)
1776	if err != nil {
1777		elog.Print(err)
1778	}
1779}
1780
1781func showchatter(w http.ResponseWriter, r *http.Request) {
1782	u := login.GetUserInfo(r)
1783	chatnewnone(u.UserID)
1784	chatter := loadchatter(u.UserID)
1785	for _, chat := range chatter {
1786		for _, ch := range chat.Chonks {
1787			filterchonk(ch)
1788		}
1789	}
1790
1791	templinfo := getInfo(r)
1792	templinfo["Chatter"] = chatter
1793	templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
1794	err := readviews.Execute(w, "chatter.html", templinfo)
1795	if err != nil {
1796		elog.Print(err)
1797	}
1798}
1799
1800func submitchonk(w http.ResponseWriter, r *http.Request) {
1801	u := login.GetUserInfo(r)
1802	user, _ := butwhatabout(u.Username)
1803	noise := r.FormValue("noise")
1804	target := r.FormValue("target")
1805	format := "markdown"
1806	dt := time.Now().UTC()
1807	xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
1808
1809	if !strings.HasPrefix(target, "https://") {
1810		target = fullname(target, u.UserID)
1811	}
1812	if target == "" {
1813		http.Error(w, "who is that?", http.StatusInternalServerError)
1814		return
1815	}
1816	ch := Chonk{
1817		UserID: u.UserID,
1818		XID:    xid,
1819		Who:    user.URL,
1820		Target: target,
1821		Date:   dt,
1822		Noise:  noise,
1823		Format: format,
1824	}
1825	d, err := submitdonk(w, r)
1826	if err != nil && err != http.ErrMissingFile {
1827		return
1828	}
1829	if d != nil {
1830		ch.Donks = append(ch.Donks, d)
1831	}
1832
1833	translatechonk(&ch)
1834	savechonk(&ch)
1835	// reload for consistency
1836	ch.Donks = nil
1837	donksforchonks([]*Chonk{&ch})
1838	go sendchonk(user, &ch)
1839
1840	http.Redirect(w, r, "/chatter", http.StatusSeeOther)
1841}
1842
1843var combocache = cache.New(cache.Options{Filler: func(userid int64) ([]string, bool) {
1844	honkers := gethonkers(userid)
1845	var combos []string
1846	for _, h := range honkers {
1847		combos = append(combos, h.Combos...)
1848	}
1849	for i, c := range combos {
1850		if c == "-" {
1851			combos[i] = ""
1852		}
1853	}
1854	combos = oneofakind(combos)
1855	sort.Strings(combos)
1856	return combos, true
1857}, Invalidator: &honkerinvalidator})
1858
1859func showcombos(w http.ResponseWriter, r *http.Request) {
1860	userinfo := login.GetUserInfo(r)
1861	var combos []string
1862	combocache.Get(userinfo.UserID, &combos)
1863	templinfo := getInfo(r)
1864	err := readviews.Execute(w, "combos.html", templinfo)
1865	if err != nil {
1866		elog.Print(err)
1867	}
1868}
1869
1870func submithonker(w http.ResponseWriter, r *http.Request) {
1871	u := login.GetUserInfo(r)
1872	user, _ := butwhatabout(u.Username)
1873	name := strings.TrimSpace(r.FormValue("name"))
1874	url := strings.TrimSpace(r.FormValue("url"))
1875	peep := r.FormValue("peep")
1876	combos := strings.TrimSpace(r.FormValue("combos"))
1877	combos = " " + combos + " "
1878	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1879
1880	re_namecheck := regexp.MustCompile("[[:alnum:]_.-]+")
1881	if name != "" && !re_namecheck.MatchString(name) {
1882		http.Error(w, "please use a plainer name", http.StatusInternalServerError)
1883		return
1884	}
1885
1886	var meta HonkerMeta
1887	meta.Notes = strings.TrimSpace(r.FormValue("notes"))
1888	mj, _ := jsonify(&meta)
1889
1890	defer honkerinvalidator.Clear(u.UserID)
1891
1892	if honkerid > 0 {
1893		if r.FormValue("delete") == "delete" {
1894			unfollowyou(user, honkerid)
1895			stmtDeleteHonker.Exec(honkerid)
1896			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1897			return
1898		}
1899		if r.FormValue("unsub") == "unsub" {
1900			unfollowyou(user, honkerid)
1901		}
1902		if r.FormValue("sub") == "sub" {
1903			followyou(user, honkerid)
1904		}
1905		_, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, u.UserID)
1906		if err != nil {
1907			elog.Printf("update honker err: %s", err)
1908			return
1909		}
1910		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1911		return
1912	}
1913
1914	if url == "" {
1915		http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
1916		return
1917	}
1918
1919	flavor := "presub"
1920	if peep == "peep" {
1921		flavor = "peep"
1922	}
1923
1924	if url[0] == '#' {
1925		flavor = "peep"
1926		if name == "" {
1927			name = url[1:]
1928		}
1929		_, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, url, mj)
1930		if err != nil {
1931			elog.Print(err)
1932			return
1933		}
1934		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1935		return
1936	}
1937
1938	info, err := investigate(url)
1939	if err != nil {
1940		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1941		ilog.Printf("failed to investigate honker: %s", err)
1942		return
1943	}
1944	url = info.XID
1945
1946	if name == "" {
1947		name = info.Name
1948	}
1949
1950	var x string
1951	db := opendatabase()
1952	row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1953	err = row.Scan(&x)
1954	if err != sql.ErrNoRows {
1955		http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1956		if err != nil {
1957			elog.Printf("honker scan err: %s", err)
1958		}
1959		return
1960	}
1961
1962	res, err := stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos, info.Owner, mj)
1963	if err != nil {
1964		elog.Print(err)
1965		return
1966	}
1967	honkerid, _ = res.LastInsertId()
1968	if flavor == "presub" {
1969		followyou(user, honkerid)
1970	}
1971	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1972}
1973
1974func hfcspage(w http.ResponseWriter, r *http.Request) {
1975	userinfo := login.GetUserInfo(r)
1976
1977	filters := getfilters(userinfo.UserID, filtAny)
1978
1979	templinfo := getInfo(r)
1980	templinfo["Filters"] = filters
1981	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1982	err := readviews.Execute(w, "hfcs.html", templinfo)
1983	if err != nil {
1984		elog.Print(err)
1985	}
1986}
1987
1988func savehfcs(w http.ResponseWriter, r *http.Request) {
1989	userinfo := login.GetUserInfo(r)
1990	itsok := r.FormValue("itsok")
1991	if itsok == "iforgiveyou" {
1992		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1993		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1994		if err != nil {
1995			elog.Printf("error deleting filter: %s", err)
1996		}
1997		filtInvalidator.Clear(userinfo.UserID)
1998		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1999		return
2000	}
2001
2002	filt := new(Filter)
2003	filt.Name = strings.TrimSpace(r.FormValue("name"))
2004	filt.Date = time.Now().UTC()
2005	filt.Actor = strings.TrimSpace(r.FormValue("actor"))
2006	filt.IncludeAudience = r.FormValue("incaud") == "yes"
2007	filt.Text = strings.TrimSpace(r.FormValue("filttext"))
2008	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
2009	filt.AnnounceOf = strings.TrimSpace(r.FormValue("announceof"))
2010	filt.Reject = r.FormValue("doreject") == "yes"
2011	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
2012	filt.Hide = r.FormValue("dohide") == "yes"
2013	filt.Collapse = r.FormValue("docollapse") == "yes"
2014	filt.Rewrite = strings.TrimSpace(r.FormValue("filtrewrite"))
2015	filt.Replace = strings.TrimSpace(r.FormValue("filtreplace"))
2016	if dur := parseDuration(r.FormValue("filtduration")); dur > 0 {
2017		filt.Expiration = time.Now().UTC().Add(dur)
2018	}
2019	filt.Notes = strings.TrimSpace(r.FormValue("filtnotes"))
2020
2021	if filt.Actor == "" && filt.Text == "" && !filt.IsAnnounce {
2022		ilog.Printf("blank filter")
2023		http.Error(w, "can't save a blank filter", http.StatusInternalServerError)
2024		return
2025	}
2026
2027	j, err := jsonify(filt)
2028	if err == nil {
2029		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
2030	}
2031	if err != nil {
2032		elog.Printf("error saving filter: %s", err)
2033	}
2034
2035	filtInvalidator.Clear(userinfo.UserID)
2036	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
2037}
2038
2039func accountpage(w http.ResponseWriter, r *http.Request) {
2040	u := login.GetUserInfo(r)
2041	user, _ := butwhatabout(u.Username)
2042	templinfo := getInfo(r)
2043	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2044	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2045	templinfo["User"] = user
2046	about := user.About
2047	if ava := user.Options.Avatar; ava != "" {
2048		about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2049	}
2050	templinfo["WhatAbout"] = about
2051	err := readviews.Execute(w, "account.html", templinfo)
2052	if err != nil {
2053		elog.Print(err)
2054	}
2055}
2056
2057func dochpass(w http.ResponseWriter, r *http.Request) {
2058	err := login.ChangePassword(w, r)
2059	if err != nil {
2060		elog.Printf("error changing password: %s", err)
2061	}
2062	http.Redirect(w, r, "/account", http.StatusSeeOther)
2063}
2064
2065func fingerlicker(w http.ResponseWriter, r *http.Request) {
2066	orig := r.FormValue("resource")
2067
2068	dlog.Printf("finger lick: %s", orig)
2069
2070	if strings.HasPrefix(orig, "acct:") {
2071		orig = orig[5:]
2072	}
2073
2074	name := orig
2075	idx := strings.LastIndexByte(name, '/')
2076	if idx != -1 {
2077		name = name[idx+1:]
2078		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
2079			ilog.Printf("foreign request rejected")
2080			name = ""
2081		}
2082	} else {
2083		idx = strings.IndexByte(name, '@')
2084		if idx != -1 {
2085			name = name[:idx]
2086			if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2087				ilog.Printf("foreign request rejected")
2088				name = ""
2089			}
2090		}
2091	}
2092	user, err := butwhatabout(name)
2093	if err != nil {
2094		http.NotFound(w, r)
2095		return
2096	}
2097	if stealthmode(user.ID, r) {
2098		http.NotFound(w, r)
2099		return
2100	}
2101
2102	j := junk.New()
2103	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2104	j["aliases"] = []string{user.URL}
2105	l := junk.New()
2106	l["rel"] = "self"
2107	l["type"] = `application/activity+json`
2108	l["href"] = user.URL
2109	j["links"] = []junk.Junk{l}
2110
2111	w.Header().Set("Content-Type", "application/jrd+json")
2112	j.Write(w)
2113}
2114
2115func somedays() string {
2116	secs := 432000 + notrand.Int63n(432000)
2117	return fmt.Sprintf("%d", secs)
2118}
2119
2120func avatate(w http.ResponseWriter, r *http.Request) {
2121	if develMode {
2122		loadAvatarColors()
2123	}
2124	n := r.FormValue("a")
2125	hex := r.FormValue("hex") == "1"
2126	a := genAvatar(n, hex)
2127	if !develMode {
2128		w.Header().Set("Cache-Control", "max-age="+somedays())
2129	}
2130	w.Write(a)
2131}
2132
2133func serveviewasset(w http.ResponseWriter, r *http.Request) {
2134	serveasset(w, r, viewDir)
2135}
2136func servedataasset(w http.ResponseWriter, r *http.Request) {
2137	serveasset(w, r, dataDir)
2138}
2139
2140func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2141	if !develMode {
2142		w.Header().Set("Cache-Control", "max-age=7776000")
2143	}
2144	http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2145}
2146func servehelp(w http.ResponseWriter, r *http.Request) {
2147	name := mux.Vars(r)["name"]
2148	if !develMode {
2149		w.Header().Set("Cache-Control", "max-age=3600")
2150	}
2151	http.ServeFile(w, r, viewDir+"/docs/"+name)
2152}
2153func servehtml(w http.ResponseWriter, r *http.Request) {
2154	u := login.GetUserInfo(r)
2155	templinfo := getInfo(r)
2156	templinfo["AboutMsg"] = aboutMsg
2157	templinfo["LoginMsg"] = loginMsg
2158	templinfo["HonkVersion"] = softwareVersion
2159	if r.URL.Path == "/about" {
2160		templinfo["Sensors"] = getSensors()
2161	}
2162	if u == nil && !develMode {
2163		w.Header().Set("Cache-Control", "max-age=60")
2164	}
2165	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2166	if err != nil {
2167		elog.Print(err)
2168	}
2169}
2170func serveemu(w http.ResponseWriter, r *http.Request) {
2171	emu := mux.Vars(r)["emu"]
2172
2173	w.Header().Set("Cache-Control", "max-age="+somedays())
2174	http.ServeFile(w, r, dataDir+"/emus/"+emu)
2175}
2176func servememe(w http.ResponseWriter, r *http.Request) {
2177	meme := mux.Vars(r)["meme"]
2178
2179	w.Header().Set("Cache-Control", "max-age="+somedays())
2180	http.ServeFile(w, r, dataDir+"/memes/"+meme)
2181}
2182
2183func servefile(w http.ResponseWriter, r *http.Request) {
2184	xid := mux.Vars(r)["xid"]
2185	var media string
2186	var data []byte
2187	row := stmtGetFileData.QueryRow(xid)
2188	err := row.Scan(&media, &data)
2189	if err != nil {
2190		elog.Printf("error loading file: %s", err)
2191		http.NotFound(w, r)
2192		return
2193	}
2194	w.Header().Set("Content-Type", media)
2195	w.Header().Set("X-Content-Type-Options", "nosniff")
2196	w.Header().Set("Cache-Control", "max-age="+somedays())
2197	w.Write(data)
2198}
2199
2200func nomoroboto(w http.ResponseWriter, r *http.Request) {
2201	io.WriteString(w, "User-agent: *\n")
2202	io.WriteString(w, "Disallow: /a\n")
2203	io.WriteString(w, "Disallow: /d/\n")
2204	io.WriteString(w, "Disallow: /meme/\n")
2205	io.WriteString(w, "Disallow: /o\n")
2206	io.WriteString(w, "Disallow: /o/\n")
2207	io.WriteString(w, "Disallow: /help/\n")
2208	for _, u := range allusers() {
2209		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2210	}
2211}
2212
2213type Hydration struct {
2214	Tophid    int64
2215	Srvmsg    template.HTML
2216	Honks     string
2217	MeCount   int64
2218	ChatCount int64
2219}
2220
2221func webhydra(w http.ResponseWriter, r *http.Request) {
2222	u := login.GetUserInfo(r)
2223	userid := u.UserID
2224	templinfo := getInfo(r)
2225	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2226	page := r.FormValue("page")
2227
2228	wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2229
2230	var hydra Hydration
2231
2232	var honks []*Honk
2233	switch page {
2234	case "atme":
2235		honks = gethonksforme(userid, wanted)
2236		honks = osmosis(honks, userid, false)
2237		menewnone(userid)
2238		hydra.Srvmsg = "at me!"
2239	case "longago":
2240		honks = gethonksfromlongago(userid, wanted)
2241		honks = osmosis(honks, userid, false)
2242		hydra.Srvmsg = "from long ago"
2243	case "home":
2244		honks = gethonksforuser(userid, wanted)
2245		honks = osmosis(honks, userid, true)
2246		hydra.Srvmsg = serverMsg
2247	case "first":
2248		honks = gethonksforuserfirstclass(userid, wanted)
2249		honks = osmosis(honks, userid, true)
2250		hydra.Srvmsg = "first class only"
2251	case "saved":
2252		honks = getsavedhonks(userid, wanted)
2253		templinfo["PageName"] = "saved"
2254		hydra.Srvmsg = "saved honks"
2255	case "combo":
2256		c := r.FormValue("c")
2257		honks = gethonksbycombo(userid, c, wanted)
2258		honks = osmosis(honks, userid, false)
2259		hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2260	case "convoy":
2261		c := r.FormValue("c")
2262		honks = gethonksbyconvoy(userid, c, wanted)
2263		honks = osmosis(honks, userid, false)
2264		hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2265	case "honker":
2266		xid := r.FormValue("xid")
2267		honks = gethonksbyxonker(userid, xid, wanted)
2268		miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2269			<input type="hidden" name="CSRF" value="%s">
2270			<input type="hidden" name="url" value="%s">
2271			<button tabindex=1 name="add honker" value="add honker">add honker</button>
2272			</form>`, login.GetCSRF("submithonker", r), xid)
2273		msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2274		hydra.Srvmsg = msg
2275	default:
2276		http.NotFound(w, r)
2277	}
2278
2279	if len(honks) > 0 {
2280		hydra.Tophid = honks[0].ID
2281	} else {
2282		hydra.Tophid = wanted
2283	}
2284	reverbolate(userid, honks)
2285
2286	user, _ := butwhatabout(u.Username)
2287
2288	var buf strings.Builder
2289	templinfo["Honks"] = honks
2290	templinfo["MapLink"] = getmaplink(u)
2291	templinfo["User"], _ = butwhatabout(u.Username)
2292	err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2293	if err != nil {
2294		elog.Printf("frag error: %s", err)
2295		return
2296	}
2297	hydra.Honks = buf.String()
2298	hydra.MeCount = user.Options.MeCount
2299	hydra.ChatCount = user.Options.ChatCount
2300	w.Header().Set("Content-Type", "application/json")
2301	j, _ := jsonify(&hydra)
2302	io.WriteString(w, j)
2303}
2304
2305var honkline = make(chan bool)
2306
2307func honkhonkline() {
2308	for {
2309		select {
2310		case honkline <- true:
2311		default:
2312			return
2313		}
2314	}
2315}
2316
2317func apihandler(w http.ResponseWriter, r *http.Request) {
2318	u := login.GetUserInfo(r)
2319	userid := u.UserID
2320	action := r.FormValue("action")
2321	wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2322	dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2323	switch action {
2324	case "honk":
2325		h := submithonk(w, r)
2326		if h == nil {
2327			return
2328		}
2329		w.Write([]byte(h.XID))
2330	case "donk":
2331		d, err := submitdonk(w, r)
2332		if err != nil {
2333			http.Error(w, err.Error(), http.StatusBadRequest)
2334			return
2335		}
2336		if d == nil {
2337			http.Error(w, "missing donk", http.StatusBadRequest)
2338			return
2339		}
2340		w.Write([]byte(d.XID))
2341	case "zonkit":
2342		zonkit(w, r)
2343	case "gethonks":
2344		var honks []*Honk
2345		wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2346		page := r.FormValue("page")
2347		var waitchan <-chan time.Time
2348	requery:
2349		switch page {
2350		case "atme":
2351			honks = gethonksforme(userid, wanted)
2352			honks = osmosis(honks, userid, false)
2353			menewnone(userid)
2354		case "longago":
2355			honks = gethonksfromlongago(userid, wanted)
2356			honks = osmosis(honks, userid, false)
2357		case "home":
2358			honks = gethonksforuser(userid, wanted)
2359			honks = osmosis(honks, userid, true)
2360		default:
2361			http.Error(w, "unknown page", http.StatusNotFound)
2362			return
2363		}
2364		if len(honks) == 0 && wait > 0 {
2365			if waitchan == nil {
2366				waitchan = time.After(time.Duration(wait) * time.Second)
2367			}
2368			select {
2369			case <-honkline:
2370				goto requery
2371			case <-waitchan:
2372			}
2373		}
2374		reverbolate(userid, honks)
2375		j := junk.New()
2376		j["honks"] = honks
2377		j.Write(w)
2378	case "sendactivity":
2379		user, _ := butwhatabout(u.Username)
2380		public := r.FormValue("public") == "1"
2381		rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2382		msg := []byte(r.FormValue("msg"))
2383		for rcpt := range rcpts {
2384			go deliverate(0, userid, rcpt, msg, true)
2385		}
2386	default:
2387		http.Error(w, "unknown action", http.StatusNotFound)
2388		return
2389	}
2390}
2391
2392var endoftheworld = make(chan bool)
2393var readyalready = make(chan bool)
2394var workinprogress = 0
2395
2396func enditall() {
2397	sig := make(chan os.Signal)
2398	signal.Notify(sig, os.Interrupt)
2399	signal.Notify(sig, syscall.SIGTERM)
2400	<-sig
2401	ilog.Printf("stopping...")
2402	for i := 0; i < workinprogress; i++ {
2403		endoftheworld <- true
2404	}
2405	ilog.Printf("waiting...")
2406	for i := 0; i < workinprogress; i++ {
2407		<-readyalready
2408	}
2409	ilog.Printf("apocalypse")
2410	os.Exit(0)
2411}
2412
2413var preservehooks []func()
2414
2415func wait100ms() chan struct{} {
2416	c := make(chan struct{})
2417	go func() {
2418		time.Sleep(100 * time.Millisecond)
2419		close(c)
2420	}()
2421	return c
2422}
2423
2424func bgmonitor() {
2425	for {
2426		time.Sleep(50 * time.Minute)
2427	}
2428}
2429
2430func serve() {
2431	db := opendatabase()
2432	login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode})
2433
2434	listener, err := openListener()
2435	if err != nil {
2436		elog.Fatal(err)
2437	}
2438	go runBackendServer()
2439	go enditall()
2440	go redeliverator()
2441	go tracker()
2442	go bgmonitor()
2443	loadLingo()
2444	w100 := wait100ms()
2445
2446	readviews = templates.Load(develMode,
2447		viewDir+"/views/honkpage.html",
2448		viewDir+"/views/honkfrags.html",
2449		viewDir+"/views/honkers.html",
2450		viewDir+"/views/chatter.html",
2451		viewDir+"/views/hfcs.html",
2452		viewDir+"/views/combos.html",
2453		viewDir+"/views/honkform.html",
2454		viewDir+"/views/honk.html",
2455		viewDir+"/views/account.html",
2456		viewDir+"/views/about.html",
2457		viewDir+"/views/funzone.html",
2458		viewDir+"/views/login.html",
2459		viewDir+"/views/xzone.html",
2460		viewDir+"/views/msg.html",
2461		viewDir+"/views/header.html",
2462		viewDir+"/views/onts.html",
2463		viewDir+"/views/honkpage.js",
2464	)
2465	if !develMode {
2466		assets := []string{
2467			viewDir + "/views/style.css",
2468			dataDir + "/views/local.css",
2469			viewDir + "/views/honkpage.js",
2470			dataDir + "/views/local.js",
2471		}
2472		for _, s := range assets {
2473			savedassetparams[s] = getassetparam(s)
2474		}
2475		loadAvatarColors()
2476	}
2477	<-w100
2478
2479	for _, h := range preservehooks {
2480		h()
2481	}
2482
2483	mux := mux.NewRouter()
2484	mux.Use(login.Checker)
2485
2486	mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
2487
2488	posters := mux.Methods("POST").Subrouter()
2489	getters := mux.Methods("GET").Subrouter()
2490
2491	getters.HandleFunc("/", homepage)
2492	getters.HandleFunc("/home", homepage)
2493	getters.HandleFunc("/front", homepage)
2494	getters.HandleFunc("/events", homepage)
2495	getters.HandleFunc("/robots.txt", nomoroboto)
2496	getters.HandleFunc("/rss", showrss)
2497	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
2498	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showonehonk)
2499	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
2500	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
2501	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
2502	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
2503	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
2504	getters.HandleFunc("/a", avatate)
2505	getters.HandleFunc("/o", thelistingoftheontologies)
2506	getters.HandleFunc("/o/{name:.+}", showontology)
2507	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
2508	getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
2509	getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
2510	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
2511
2512	getters.HandleFunc("/flag/{code:.+}", showflag)
2513
2514	getters.HandleFunc("/server", serveractor)
2515	posters.HandleFunc("/server/inbox", serverinbox)
2516	posters.HandleFunc("/inbox", serverinbox)
2517
2518	getters.HandleFunc("/style.css", serveviewasset)
2519	getters.HandleFunc("/honkpage.js", serveviewasset)
2520	getters.HandleFunc("/wonk.js", serveviewasset)
2521	getters.HandleFunc("/local.css", servedataasset)
2522	getters.HandleFunc("/local.js", servedataasset)
2523	getters.HandleFunc("/icon.png", servedataasset)
2524	getters.HandleFunc("/favicon.ico", servedataasset)
2525
2526	getters.HandleFunc("/about", servehtml)
2527	getters.HandleFunc("/login", servehtml)
2528	posters.HandleFunc("/dologin", login.LoginFunc)
2529	getters.HandleFunc("/logout", login.LogoutFunc)
2530	getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
2531
2532	getters.HandleFunc("/bloat/wonkles", servewonkles)
2533
2534	loggedin := mux.NewRoute().Subrouter()
2535	loggedin.Use(login.Required)
2536	loggedin.HandleFunc("/first", homepage)
2537	loggedin.HandleFunc("/chatter", showchatter)
2538	loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
2539	loggedin.HandleFunc("/saved", homepage)
2540	loggedin.HandleFunc("/account", accountpage)
2541	loggedin.HandleFunc("/funzone", showfunzone)
2542	loggedin.HandleFunc("/chpass", dochpass)
2543	loggedin.HandleFunc("/atme", homepage)
2544	loggedin.HandleFunc("/longago", homepage)
2545	loggedin.HandleFunc("/hfcs", hfcspage)
2546	loggedin.HandleFunc("/xzone", xzone)
2547	loggedin.HandleFunc("/newhonk", newhonkpage)
2548	loggedin.HandleFunc("/edit", edithonkpage)
2549	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitwebhonk)))
2550	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
2551	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
2552	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
2553	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
2554	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
2555	loggedin.HandleFunc("/honkers", showhonkers)
2556	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
2557	loggedin.HandleFunc("/h", showhonker)
2558	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
2559	loggedin.HandleFunc("/c", showcombos)
2560	loggedin.HandleFunc("/t", showconvoy)
2561	loggedin.HandleFunc("/q", showsearch)
2562	loggedin.HandleFunc("/hydra", webhydra)
2563	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
2564
2565	err = http.Serve(listener, mux)
2566	if err != nil {
2567		elog.Fatal(err)
2568	}
2569}