all repos — honk @ f6841be8c997c563df8d94eb125b5b6b3cfa196f

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