all repos — honk @ 41a07fd9627aa61e8b45ca94bc2a41ee75a5a09b

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