all repos — honk @ v0.8.4

my fork of honk

web.go (view raw)

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