all repos — honk @ 07adb29f734f3f610b06d2732d9991956292c692

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