all repos — honk @ 9447d067132c6eb078f0d89114999ce8b48c8d0b

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