all repos — honk @ ac0ed31df7c70b44be8b6c1037fa45b2cb472a03

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