all repos — honk @ e2c6e21093741f27092b4ff017fff619dd1f0173

my fork of honk

web.go (view raw)

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