all repos — honk @ 16d59f1a3bb26fe187f025437fac8caca1cd8d64

my fork of honk

web.go (view raw)

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