all repos — honk @ bb405e2587bec4acbf533f696a52c40af888c641

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"
  23	"html/template"
  24	"io"
  25	"log"
  26	notrand "math/rand"
  27	"net/http"
  28	"net/url"
  29	"os"
  30	"sort"
  31	"strconv"
  32	"strings"
  33	"time"
  34
  35	"github.com/gorilla/mux"
  36	"humungus.tedunangst.com/r/webs/css"
  37	"humungus.tedunangst.com/r/webs/htfilter"
  38	"humungus.tedunangst.com/r/webs/httpsig"
  39	"humungus.tedunangst.com/r/webs/image"
  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.SkinnyCSS {
  57		return "main { max-width: 700px; }"
  58	}
  59	return ""
  60}
  61
  62func getInfo(r *http.Request) map[string]interface{} {
  63	u := login.GetUserInfo(r)
  64	templinfo := make(map[string]interface{})
  65	templinfo["StyleParam"] = getassetparam("views/style.css")
  66	templinfo["LocalStyleParam"] = getassetparam("views/local.css")
  67	templinfo["JSParam"] = getassetparam("views/honkpage.js")
  68	templinfo["UserStyle"] = getuserstyle(u)
  69	templinfo["ServerName"] = serverName
  70	templinfo["IconName"] = iconName
  71	templinfo["UserInfo"] = u
  72	templinfo["UserSep"] = userSep
  73	if u != nil {
  74		var combos []string
  75		combocache.Get(u.UserID, &combos)
  76		templinfo["Combos"] = combos
  77	}
  78	return templinfo
  79}
  80
  81func homepage(w http.ResponseWriter, r *http.Request) {
  82	templinfo := getInfo(r)
  83	u := login.GetUserInfo(r)
  84	var honks []*Honk
  85	var userid int64 = -1
  86	if r.URL.Path == "/front" || u == nil {
  87		honks = getpublichonks()
  88	} else {
  89		userid = u.UserID
  90		if r.URL.Path == "/atme" {
  91			templinfo["PageName"] = "atme"
  92			honks = gethonksforme(userid)
  93		} else if r.URL.Path == "/first" {
  94			templinfo["PageName"] = "first"
  95			honks = gethonksforuser(userid)
  96			honks = osmosis(honks, userid)
  97		} else {
  98			templinfo["PageName"] = "home"
  99			honks = gethonksforuser(userid)
 100			honks = osmosis(honks, userid)
 101		}
 102		if len(honks) > 0 {
 103			templinfo["TopXID"] = honks[0].XID
 104		}
 105		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 106	}
 107
 108	templinfo["ShowRSS"] = true
 109	templinfo["ServerMessage"] = serverMsg
 110	honkpage(w, u, honks, templinfo)
 111}
 112
 113func showfunzone(w http.ResponseWriter, r *http.Request) {
 114	var emunames, memenames []string
 115	dir, err := os.Open("emus")
 116	if err == nil {
 117		emunames, _ = dir.Readdirnames(0)
 118		dir.Close()
 119	}
 120	for i, e := range emunames {
 121		if len(e) > 4 {
 122			emunames[i] = e[:len(e)-4]
 123		}
 124	}
 125	dir, err = os.Open("memes")
 126	if err == nil {
 127		memenames, _ = dir.Readdirnames(0)
 128		dir.Close()
 129	}
 130	templinfo := getInfo(r)
 131	templinfo["Emus"] = emunames
 132	templinfo["Memes"] = memenames
 133	err = readviews.Execute(w, "funzone.html", templinfo)
 134	if err != nil {
 135		log.Print(err)
 136	}
 137}
 138
 139func showrss(w http.ResponseWriter, r *http.Request) {
 140	name := mux.Vars(r)["name"]
 141
 142	var honks []*Honk
 143	if name != "" {
 144		honks = gethonksbyuser(name, false)
 145	} else {
 146		honks = getpublichonks()
 147	}
 148	if len(honks) > 20 {
 149		honks = honks[0:20]
 150	}
 151	reverbolate(-1, honks)
 152
 153	home := fmt.Sprintf("https://%s/", serverName)
 154	base := home
 155	if name != "" {
 156		home += "u/" + name
 157		name += " "
 158	}
 159	feed := rss.Feed{
 160		Title:       name + "honk",
 161		Link:        home,
 162		Description: name + "honk rss",
 163		Image: &rss.Image{
 164			URL:   base + "icon.png",
 165			Title: name + "honk rss",
 166			Link:  home,
 167		},
 168	}
 169	var modtime time.Time
 170	for _, honk := range honks {
 171		if !firstclass(honk) {
 172			continue
 173		}
 174		desc := string(honk.HTML)
 175		if t := honk.Time; t != nil {
 176			desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM EDT Mon Jan 02"))
 177			if t.Duration != 0 {
 178				desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
 179			}
 180		}
 181		if p := honk.Place; p != nil {
 182			desc += fmt.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
 183				html.EscapeString(p.Url), html.EscapeString(p.Name), p.Latitude, p.Longitude)
 184		}
 185		for _, d := range honk.Donks {
 186			desc += fmt.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
 187				d.URL, html.EscapeString(d.Name))
 188		}
 189
 190		feed.Items = append(feed.Items, &rss.Item{
 191			Title:       fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
 192			Description: rss.CData{Data: desc},
 193			Link:        honk.URL,
 194			PubDate:     honk.Date.Format(time.RFC1123),
 195			Guid:        &rss.Guid{IsPermaLink: true, Value: honk.URL},
 196		})
 197		if honk.Date.After(modtime) {
 198			modtime = honk.Date
 199		}
 200	}
 201	w.Header().Set("Cache-Control", "max-age=300")
 202	w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
 203
 204	err := feed.Write(w)
 205	if err != nil {
 206		log.Printf("error writing rss: %s", err)
 207	}
 208}
 209
 210func crappola(j junk.Junk) bool {
 211	t, _ := j.GetString("type")
 212	a, _ := j.GetString("actor")
 213	o, _ := j.GetString("object")
 214	if t == "Delete" && a == o {
 215		log.Printf("crappola from %s", a)
 216		return true
 217	}
 218	return false
 219}
 220
 221func ping(user *WhatAbout, who string) {
 222	var box *Box
 223	ok := boxofboxes.Get(who, &box)
 224	if !ok {
 225		log.Printf("no inbox to ping %s", who)
 226		return
 227	}
 228	j := junk.New()
 229	j["@context"] = itiswhatitis
 230	j["type"] = "Ping"
 231	j["id"] = user.URL + "/ping/" + xfiltrate()
 232	j["actor"] = user.URL
 233	j["to"] = who
 234	keyname, key := ziggy(user.Name)
 235	err := PostJunk(keyname, key, box.In, j)
 236	if err != nil {
 237		log.Printf("can't send ping: %s", err)
 238		return
 239	}
 240	log.Printf("sent ping to %s: %s", who, j["id"])
 241}
 242
 243func pong(user *WhatAbout, who string, obj string) {
 244	var box *Box
 245	ok := boxofboxes.Get(who, &box)
 246	if !ok {
 247		log.Printf("no inbox to pong %s", who)
 248		return
 249	}
 250	j := junk.New()
 251	j["@context"] = itiswhatitis
 252	j["type"] = "Pong"
 253	j["id"] = user.URL + "/pong/" + xfiltrate()
 254	j["actor"] = user.URL
 255	j["to"] = who
 256	j["object"] = obj
 257	keyname, key := ziggy(user.Name)
 258	err := PostJunk(keyname, key, box.In, j)
 259	if err != nil {
 260		log.Printf("can't send pong: %s", err)
 261		return
 262	}
 263}
 264
 265func inbox(w http.ResponseWriter, r *http.Request) {
 266	name := mux.Vars(r)["name"]
 267	user, err := butwhatabout(name)
 268	if err != nil {
 269		http.NotFound(w, r)
 270		return
 271	}
 272	if stealthmode(user.ID, r) {
 273		http.NotFound(w, r)
 274		return
 275	}
 276	var buf bytes.Buffer
 277	io.Copy(&buf, r.Body)
 278	payload := buf.Bytes()
 279	j, err := junk.Read(bytes.NewReader(payload))
 280	if err != nil {
 281		log.Printf("bad payload: %s", err)
 282		io.WriteString(os.Stdout, "bad payload\n")
 283		os.Stdout.Write(payload)
 284		io.WriteString(os.Stdout, "\n")
 285		return
 286	}
 287	if crappola(j) {
 288		return
 289	}
 290	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 291	if err != nil {
 292		log.Printf("inbox message failed signature: %s", err)
 293		if keyname != "" {
 294			keyname, err = makeitworksomehowwithoutregardforkeycontinuity(keyname, r, payload)
 295			if err != nil {
 296				log.Printf("still failed: %s", err)
 297			}
 298		}
 299		if err != nil {
 300			return
 301		}
 302	}
 303	what, _ := j.GetString("type")
 304	if what == "Like" {
 305		return
 306	}
 307	who, _ := j.GetString("actor")
 308	origin := keymatch(keyname, who)
 309	if origin == "" {
 310		log.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 311		return
 312	}
 313	if rejectactor(user.ID, who) {
 314		return
 315	}
 316	switch what {
 317	case "Ping":
 318		obj, _ := j.GetString("id")
 319		log.Printf("ping from %s: %s", who, obj)
 320		pong(user, who, obj)
 321	case "Pong":
 322		obj, _ := j.GetString("object")
 323		log.Printf("pong from %s: %s", who, obj)
 324	case "Follow":
 325		obj, _ := j.GetString("object")
 326		if obj == user.URL {
 327			log.Printf("updating honker follow: %s", who)
 328
 329			db := opendatabase()
 330			row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('dub', 'undub')", who, user.ID)
 331			var x string
 332			err = row.Scan(&x)
 333			if err != sql.ErrNoRows {
 334				log.Printf("duplicate follow request: %s", who)
 335				_, err = stmtUpdateFlavor.Exec("dub", user.ID, who, "undub")
 336				if err != nil {
 337					log.Printf("error updating honker: %s", err)
 338				}
 339			} else {
 340				stmtSaveDub.Exec(user.ID, who, who, "dub")
 341			}
 342			go rubadubdub(user, j)
 343		} else {
 344			log.Printf("can't follow %s", obj)
 345		}
 346	case "Accept":
 347		log.Printf("updating honker accept: %s", who)
 348		_, err = stmtUpdateFlavor.Exec("sub", user.ID, who, "presub")
 349		if err != nil {
 350			log.Printf("error updating honker: %s", err)
 351			return
 352		}
 353	case "Update":
 354		obj, ok := j.GetMap("object")
 355		if ok {
 356			what, _ := obj.GetString("type")
 357			switch what {
 358			case "Person":
 359				return
 360			case "Question":
 361				return
 362			case "Note":
 363				go xonksaver(user, j, origin)
 364				return
 365			}
 366		}
 367		log.Printf("unknown Update activity")
 368		fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 369		j.Write(fd)
 370		io.WriteString(fd, "\n")
 371		fd.Close()
 372
 373	case "Undo":
 374		obj, ok := j.GetMap("object")
 375		if !ok {
 376			log.Printf("unknown undo no object")
 377		} else {
 378			what, _ := obj.GetString("type")
 379			switch what {
 380			case "Follow":
 381				log.Printf("updating honker undo: %s", who)
 382				_, err = stmtUpdateFlavor.Exec("undub", user.ID, who, "dub")
 383				if err != nil {
 384					log.Printf("error updating honker: %s", err)
 385					return
 386				}
 387			case "Announce":
 388				xid, _ := obj.GetString("object")
 389				log.Printf("undo announce: %s", xid)
 390			case "Like":
 391			default:
 392				log.Printf("unknown undo: %s", what)
 393			}
 394		}
 395	default:
 396		go xonksaver(user, j, origin)
 397	}
 398}
 399
 400func ximport(w http.ResponseWriter, r *http.Request) {
 401	u := login.GetUserInfo(r)
 402	xid := r.FormValue("xid")
 403	xonk := getxonk(u.UserID, xid)
 404	if xonk == nil {
 405		p, _ := investigate(xid)
 406		if p != nil {
 407			xid = p.XID
 408		}
 409		j, err := GetJunk(xid)
 410		if err != nil {
 411			http.Error(w, "error getting external object", http.StatusInternalServerError)
 412			log.Printf("error getting external object: %s", err)
 413			return
 414		}
 415		log.Printf("importing %s", xid)
 416		user, _ := butwhatabout(u.Username)
 417
 418		what, _ := j.GetString("type")
 419		if isactor(what) {
 420			outbox, _ := j.GetString("outbox")
 421			gimmexonks(user, outbox)
 422			http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
 423			return
 424		}
 425		xonk = xonksaver(user, j, originate(xid))
 426	}
 427	convoy := ""
 428	if xonk != nil {
 429		convoy = xonk.Convoy
 430	}
 431	http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
 432}
 433
 434func xzone(w http.ResponseWriter, r *http.Request) {
 435	u := login.GetUserInfo(r)
 436	rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
 437	if err != nil {
 438		log.Printf("query err: %s", err)
 439		return
 440	}
 441	defer rows.Close()
 442	var honkers []Honker
 443	for rows.Next() {
 444		var xid string
 445		rows.Scan(&xid)
 446		honkers = append(honkers, Honker{XID: xid})
 447	}
 448	rows.Close()
 449	for i, _ := range honkers {
 450		_, honkers[i].Handle = handles(honkers[i].XID)
 451	}
 452	templinfo := getInfo(r)
 453	templinfo["XCSRF"] = login.GetCSRF("ximport", r)
 454	templinfo["Honkers"] = honkers
 455	err = readviews.Execute(w, "xzone.html", templinfo)
 456	if err != nil {
 457		log.Print(err)
 458	}
 459}
 460
 461func outbox(w http.ResponseWriter, r *http.Request) {
 462	name := mux.Vars(r)["name"]
 463	user, err := butwhatabout(name)
 464	if err != nil {
 465		http.NotFound(w, r)
 466		return
 467	}
 468	if stealthmode(user.ID, r) {
 469		http.NotFound(w, r)
 470		return
 471	}
 472
 473	honks := gethonksbyuser(name, false)
 474	if len(honks) > 20 {
 475		honks = honks[0:20]
 476	}
 477
 478	var jonks []junk.Junk
 479	for _, h := range honks {
 480		j, _ := jonkjonk(user, h)
 481		jonks = append(jonks, j)
 482	}
 483
 484	j := junk.New()
 485	j["@context"] = itiswhatitis
 486	j["id"] = user.URL + "/outbox"
 487	j["type"] = "OrderedCollection"
 488	j["totalItems"] = len(jonks)
 489	j["orderedItems"] = jonks
 490
 491	w.Header().Set("Content-Type", theonetruename)
 492	j.Write(w)
 493}
 494
 495func emptiness(w http.ResponseWriter, r *http.Request) {
 496	name := mux.Vars(r)["name"]
 497	user, err := butwhatabout(name)
 498	if err != nil {
 499		http.NotFound(w, r)
 500		return
 501	}
 502	if stealthmode(user.ID, r) {
 503		http.NotFound(w, r)
 504		return
 505	}
 506	colname := "/followers"
 507	if strings.HasSuffix(r.URL.Path, "/following") {
 508		colname = "/following"
 509	}
 510	j := junk.New()
 511	j["@context"] = itiswhatitis
 512	j["id"] = user.URL + colname
 513	j["type"] = "OrderedCollection"
 514	j["totalItems"] = 0
 515	j["orderedItems"] = []junk.Junk{}
 516
 517	w.Header().Set("Content-Type", theonetruename)
 518	j.Write(w)
 519}
 520
 521func showuser(w http.ResponseWriter, r *http.Request) {
 522	name := mux.Vars(r)["name"]
 523	user, err := butwhatabout(name)
 524	if err != nil {
 525		log.Printf("user not found %s: %s", name, err)
 526		http.NotFound(w, r)
 527		return
 528	}
 529	if stealthmode(user.ID, r) {
 530		http.NotFound(w, r)
 531		return
 532	}
 533	if friendorfoe(r.Header.Get("Accept")) {
 534		j := asjonker(user)
 535		w.Header().Set("Content-Type", theonetruename)
 536		j.Write(w)
 537		return
 538	}
 539	u := login.GetUserInfo(r)
 540	honks := gethonksbyuser(name, u != nil && u.Username == name)
 541	templinfo := getInfo(r)
 542	filt := htfilter.New()
 543	templinfo["Name"] = user.Name
 544	whatabout := user.About
 545	whatabout = markitzero(user.About)
 546	templinfo["WhatAbout"], _ = filt.String(whatabout)
 547	templinfo["ServerMessage"] = ""
 548	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 549	honkpage(w, u, honks, templinfo)
 550}
 551
 552func showhonker(w http.ResponseWriter, r *http.Request) {
 553	u := login.GetUserInfo(r)
 554	name := mux.Vars(r)["name"]
 555	var honks []*Honk
 556	if name == "" {
 557		name = r.FormValue("xid")
 558		honks = gethonksbyxonker(u.UserID, name)
 559	} else {
 560		honks = gethonksbyhonker(u.UserID, name)
 561	}
 562	name = html.EscapeString(name)
 563	msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, name, name)
 564	templinfo := getInfo(r)
 565	templinfo["PageName"] = "honker"
 566	templinfo["ServerMessage"] = template.HTML(msg)
 567	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 568	honkpage(w, u, honks, templinfo)
 569}
 570
 571func showcombo(w http.ResponseWriter, r *http.Request) {
 572	name := mux.Vars(r)["name"]
 573	u := login.GetUserInfo(r)
 574	honks := gethonksbycombo(u.UserID, name)
 575	honks = osmosis(honks, u.UserID)
 576	templinfo := getInfo(r)
 577	templinfo["PageName"] = "combo"
 578	templinfo["PageArg"] = "name"
 579	templinfo["ServerMessage"] = "honks by combo: " + name
 580	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 581	if len(honks) > 0 {
 582		templinfo["TopXID"] = honks[0].XID
 583	}
 584	honkpage(w, u, honks, templinfo)
 585}
 586func showconvoy(w http.ResponseWriter, r *http.Request) {
 587	c := r.FormValue("c")
 588	u := login.GetUserInfo(r)
 589	honks := gethonksbyconvoy(u.UserID, c)
 590	templinfo := getInfo(r)
 591	templinfo["ServerMessage"] = "honks in convoy: " + c
 592	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 593	honkpage(w, u, honks, templinfo)
 594}
 595func showsearch(w http.ResponseWriter, r *http.Request) {
 596	q := r.FormValue("q")
 597	u := login.GetUserInfo(r)
 598	honks := gethonksbysearch(u.UserID, q)
 599	templinfo := getInfo(r)
 600	templinfo["ServerMessage"] = "honks for search: " + q
 601	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 602	honkpage(w, u, honks, templinfo)
 603}
 604func showontology(w http.ResponseWriter, r *http.Request) {
 605	name := mux.Vars(r)["name"]
 606	u := login.GetUserInfo(r)
 607	var userid int64 = -1
 608	if u != nil {
 609		userid = u.UserID
 610	}
 611	honks := gethonksbyontology(userid, "#"+name)
 612	templinfo := getInfo(r)
 613	templinfo["ServerMessage"] = "honks by ontology: " + name
 614	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 615	honkpage(w, u, honks, templinfo)
 616}
 617
 618func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 619	u := login.GetUserInfo(r)
 620	var userid int64 = -1
 621	if u != nil {
 622		userid = u.UserID
 623	}
 624	rows, err := stmtSelectOnts.Query(userid)
 625	if err != nil {
 626		log.Printf("selection error: %s", err)
 627		return
 628	}
 629	defer rows.Close()
 630	var onts [][]string
 631	for rows.Next() {
 632		var o string
 633		err := rows.Scan(&o)
 634		if err != nil {
 635			log.Printf("error scanning ont: %s", err)
 636			continue
 637		}
 638		onts = append(onts, []string{o, o[1:]})
 639	}
 640	if u == nil {
 641		w.Header().Set("Cache-Control", "max-age=300")
 642	}
 643	templinfo := getInfo(r)
 644	templinfo["Onts"] = onts
 645	err = readviews.Execute(w, "onts.html", templinfo)
 646	if err != nil {
 647		log.Print(err)
 648	}
 649}
 650
 651func showhonk(w http.ResponseWriter, r *http.Request) {
 652	name := mux.Vars(r)["name"]
 653	user, err := butwhatabout(name)
 654	if err != nil {
 655		http.NotFound(w, r)
 656		return
 657	}
 658	if stealthmode(user.ID, r) {
 659		http.NotFound(w, r)
 660		return
 661	}
 662
 663	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
 664	honk := getxonk(user.ID, xid)
 665	if honk == nil {
 666		http.NotFound(w, r)
 667		return
 668	}
 669	u := login.GetUserInfo(r)
 670	if u != nil && u.UserID != user.ID {
 671		u = nil
 672	}
 673	if !honk.Public {
 674		if u == nil {
 675			http.NotFound(w, r)
 676			return
 677
 678		}
 679		templinfo := getInfo(r)
 680		templinfo["ServerMessage"] = "one honk maybe more"
 681		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 682		honkpage(w, u, []*Honk{honk}, templinfo)
 683		return
 684	}
 685	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
 686	if friendorfoe(r.Header.Get("Accept")) {
 687		for _, h := range rawhonks {
 688			if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
 689				honk.Replies = append(honk.Replies, h)
 690			}
 691		}
 692		donksforhonks([]*Honk{honk})
 693		_, j := jonkjonk(user, honk)
 694		j["@context"] = itiswhatitis
 695		w.Header().Set("Content-Type", theonetruename)
 696		j.Write(w)
 697		return
 698	}
 699	var honks []*Honk
 700	for _, h := range rawhonks {
 701		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
 702			honks = append(honks, h)
 703		}
 704	}
 705
 706	templinfo := getInfo(r)
 707	templinfo["ServerMessage"] = "one honk maybe more"
 708	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 709	honkpage(w, u, honks, templinfo)
 710}
 711
 712func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
 713	var userid int64 = -1
 714	if u != nil {
 715		userid = u.UserID
 716	}
 717	if u == nil {
 718		w.Header().Set("Cache-Control", "max-age=60")
 719	}
 720	reverbolate(userid, honks)
 721	templinfo["Honks"] = honks
 722	err := readviews.Execute(w, "honkpage.html", templinfo)
 723	if err != nil {
 724		log.Print(err)
 725	}
 726}
 727
 728func saveuser(w http.ResponseWriter, r *http.Request) {
 729	whatabout := r.FormValue("whatabout")
 730	u := login.GetUserInfo(r)
 731	db := opendatabase()
 732	options := ""
 733	if r.FormValue("skinny") == "skinny" {
 734		options += " skinny "
 735	}
 736	_, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
 737	if err != nil {
 738		log.Printf("error bouting what: %s", err)
 739	}
 740
 741	http.Redirect(w, r, "/account", http.StatusSeeOther)
 742}
 743
 744func submitbonk(w http.ResponseWriter, r *http.Request) {
 745	xid := r.FormValue("xid")
 746	userinfo := login.GetUserInfo(r)
 747	user, _ := butwhatabout(userinfo.Username)
 748
 749	log.Printf("bonking %s", xid)
 750
 751	xonk := getxonk(userinfo.UserID, xid)
 752	if xonk == nil {
 753		return
 754	}
 755	if !xonk.Public {
 756		return
 757	}
 758	donksforhonks([]*Honk{xonk})
 759
 760	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
 761	if err != nil {
 762		log.Printf("error acking bonk: %s", err)
 763	}
 764
 765	oonker := xonk.Oonker
 766	if oonker == "" {
 767		oonker = xonk.Honker
 768	}
 769	dt := time.Now().UTC()
 770	bonk := Honk{
 771		UserID:   userinfo.UserID,
 772		Username: userinfo.Username,
 773		What:     "bonk",
 774		Honker:   user.URL,
 775		Oonker:   oonker,
 776		XID:      xonk.XID,
 777		RID:      xonk.RID,
 778		Noise:    xonk.Noise,
 779		Precis:   xonk.Precis,
 780		URL:      xonk.URL,
 781		Date:     dt,
 782		Donks:    xonk.Donks,
 783		Whofore:  2,
 784		Convoy:   xonk.Convoy,
 785		Audience: []string{thewholeworld, oonker},
 786		Public:   true,
 787	}
 788
 789	bonk.Format = "html"
 790
 791	err = savehonk(&bonk)
 792	if err != nil {
 793		log.Printf("uh oh")
 794		return
 795	}
 796
 797	go honkworldwide(user, &bonk)
 798}
 799
 800func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
 801	zonk := Honk{
 802		What:     what,
 803		XID:      xonk.XID,
 804		Date:     time.Now().UTC(),
 805		Audience: oneofakind(xonk.Audience),
 806	}
 807	zonk.Public = !keepitquiet(zonk.Audience)
 808
 809	log.Printf("announcing %sed honk: %s", what, xonk.XID)
 810	go honkworldwide(user, &zonk)
 811}
 812
 813func zonkit(w http.ResponseWriter, r *http.Request) {
 814	wherefore := r.FormValue("wherefore")
 815	what := r.FormValue("what")
 816	userinfo := login.GetUserInfo(r)
 817	user, _ := butwhatabout(userinfo.Username)
 818
 819	if wherefore == "ack" {
 820		xonk := getxonk(userinfo.UserID, what)
 821		if xonk != nil {
 822			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
 823			if err != nil {
 824				log.Printf("error acking: %s", err)
 825			}
 826			sendzonkofsorts(xonk, user, "ack")
 827		}
 828		return
 829	}
 830
 831	if wherefore == "deack" {
 832		xonk := getxonk(userinfo.UserID, what)
 833		if xonk != nil {
 834			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
 835			if err != nil {
 836				log.Printf("error deacking: %s", err)
 837			}
 838			sendzonkofsorts(xonk, user, "deack")
 839		}
 840		return
 841	}
 842
 843	if wherefore == "unbonk" {
 844		xonk := getbonk(userinfo.UserID, what)
 845		if xonk != nil {
 846			deletehonk(xonk.ID)
 847			xonk = getxonk(userinfo.UserID, what)
 848			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
 849			if err != nil {
 850				log.Printf("error unbonking: %s", err)
 851			}
 852			sendzonkofsorts(xonk, user, "unbonk")
 853		}
 854		return
 855	}
 856
 857	log.Printf("zonking %s %s", wherefore, what)
 858	if wherefore == "zonk" {
 859		xonk := getxonk(userinfo.UserID, what)
 860		if xonk != nil {
 861			deletehonk(xonk.ID)
 862			if xonk.Whofore == 2 || xonk.Whofore == 3 {
 863				sendzonkofsorts(xonk, user, "zonk")
 864			}
 865		}
 866	}
 867	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
 868	if err != nil {
 869		log.Printf("error saving zonker: %s", err)
 870		return
 871	}
 872}
 873
 874func edithonkpage(w http.ResponseWriter, r *http.Request) {
 875	u := login.GetUserInfo(r)
 876	user, _ := butwhatabout(u.Username)
 877	xid := r.FormValue("xid")
 878	honk := getxonk(u.UserID, xid)
 879	if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 880		log.Printf("no edit")
 881		return
 882	}
 883
 884	noise := honk.Noise
 885	if honk.Precis != "" {
 886		noise = honk.Precis + "\n\n" + noise
 887	}
 888
 889	honks := []*Honk{honk}
 890	donksforhonks(honks)
 891	reverbolate(u.UserID, honks)
 892	templinfo := getInfo(r)
 893	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 894	templinfo["Honks"] = honks
 895	templinfo["Noise"] = noise
 896	templinfo["ServerMessage"] = "honk edit"
 897	templinfo["UpdateXID"] = honk.XID
 898	if len(honk.Donks) > 0 {
 899		templinfo["SavedFile"] = honk.Donks[0].XID
 900	}
 901	err := readviews.Execute(w, "honkpage.html", templinfo)
 902	if err != nil {
 903		log.Print(err)
 904	}
 905}
 906
 907// what a hot mess this function is
 908func submithonk(w http.ResponseWriter, r *http.Request) {
 909	rid := r.FormValue("rid")
 910	noise := r.FormValue("noise")
 911
 912	userinfo := login.GetUserInfo(r)
 913	user, _ := butwhatabout(userinfo.Username)
 914
 915	dt := time.Now().UTC()
 916	updatexid := r.FormValue("updatexid")
 917	var honk *Honk
 918	if updatexid != "" {
 919		honk = getxonk(userinfo.UserID, updatexid)
 920		if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 921			log.Printf("not saving edit")
 922			return
 923		}
 924		honk.Date = dt
 925		honk.What = "update"
 926		honk.Format = "markdown"
 927	} else {
 928		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
 929		what := "honk"
 930		if rid != "" {
 931			what = "tonk"
 932		}
 933		honk = &Honk{
 934			UserID:   userinfo.UserID,
 935			Username: userinfo.Username,
 936			What:     what,
 937			Honker:   user.URL,
 938			XID:      xid,
 939			Date:     dt,
 940			Format:   "markdown",
 941		}
 942	}
 943
 944	noise = hooterize(noise)
 945	honk.Noise = noise
 946	translate(honk)
 947
 948	var convoy string
 949	if rid != "" {
 950		xonk := getxonk(userinfo.UserID, rid)
 951		if xonk != nil {
 952			if xonk.Public {
 953				honk.Audience = append(honk.Audience, xonk.Audience...)
 954			}
 955			convoy = xonk.Convoy
 956		} else {
 957			xonkaud, c := whosthere(rid)
 958			honk.Audience = append(honk.Audience, xonkaud...)
 959			convoy = c
 960		}
 961		for i, a := range honk.Audience {
 962			if a == thewholeworld {
 963				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
 964				break
 965			}
 966		}
 967		honk.RID = rid
 968	} else {
 969		honk.Audience = []string{thewholeworld}
 970	}
 971	if honk.Noise != "" && honk.Noise[0] == '@' {
 972		honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
 973	} else {
 974		honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
 975	}
 976
 977	if convoy == "" {
 978		convoy = "data:,electrichonkytonk-" + xfiltrate()
 979	}
 980	butnottooloud(honk.Audience)
 981	honk.Audience = oneofakind(honk.Audience)
 982	if len(honk.Audience) == 0 {
 983		log.Printf("honk to nowhere")
 984		http.Error(w, "honk to nowhere...", http.StatusNotFound)
 985		return
 986	}
 987	honk.Public = !keepitquiet(honk.Audience)
 988	honk.Convoy = convoy
 989
 990	donkxid := r.FormValue("donkxid")
 991	if donkxid == "" {
 992		file, filehdr, err := r.FormFile("donk")
 993		if err == nil {
 994			var buf bytes.Buffer
 995			io.Copy(&buf, file)
 996			file.Close()
 997			data := buf.Bytes()
 998			xid := xfiltrate()
 999			var media, name string
1000			img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
1001			if err == nil {
1002				data = img.Data
1003				format := img.Format
1004				media = "image/" + format
1005				if format == "jpeg" {
1006					format = "jpg"
1007				}
1008				name = xid + "." + format
1009				xid = name
1010			} else {
1011				maxsize := 100000
1012				if len(data) > maxsize {
1013					log.Printf("bad image: %s too much text: %d", err, len(data))
1014					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1015					return
1016				}
1017				for i := 0; i < len(data); i++ {
1018					if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1019						log.Printf("bad image: %s not text: %d", err, data[i])
1020						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1021						return
1022					}
1023				}
1024				media = "text/plain"
1025				name = filehdr.Filename
1026				if name == "" {
1027					name = xid + ".txt"
1028				}
1029				xid += ".txt"
1030			}
1031			desc := r.FormValue("donkdesc")
1032			if desc == "" {
1033				desc = name
1034			}
1035			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1036			fileid, err := savefile(xid, name, desc, url, media, true, data)
1037			if err != nil {
1038				log.Printf("unable to save image: %s", err)
1039				return
1040			}
1041			var d Donk
1042			d.FileID = fileid
1043			honk.Donks = append(honk.Donks, &d)
1044			donkxid = d.XID
1045		}
1046	} else {
1047		xid := donkxid
1048		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1049		donk := finddonk(url)
1050		if donk != nil {
1051			honk.Donks = append(honk.Donks, donk)
1052		} else {
1053			log.Printf("can't find file: %s", xid)
1054		}
1055	}
1056	herd := herdofemus(honk.Noise)
1057	for _, e := range herd {
1058		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1059		if donk != nil {
1060			donk.Name = e.Name
1061			honk.Donks = append(honk.Donks, donk)
1062		}
1063	}
1064	memetize(honk)
1065
1066	placename := r.FormValue("placename")
1067	placelat := r.FormValue("placelat")
1068	placelong := r.FormValue("placelong")
1069	if placename != "" || placelat != "" || placelong != "" {
1070		p := new(Place)
1071		p.Name = placename
1072		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1073		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1074		p.Url = r.FormValue("placeurl")
1075		honk.Place = p
1076	}
1077	timestart := r.FormValue("timestart")
1078	if timestart != "" {
1079		t := new(Time)
1080		now := time.Now().Local()
1081		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1082			start, err := time.ParseInLocation(layout, timestart, now.Location())
1083			if err == nil {
1084				if start.Year() == 0 {
1085					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1086				}
1087				t.StartTime = start
1088				break
1089			}
1090		}
1091		timeend := r.FormValue("timeend")
1092		dur, err := time.ParseDuration(timeend)
1093		if err == nil {
1094			t.Duration = Duration(dur)
1095		}
1096		if !t.StartTime.IsZero() {
1097			honk.What = "event"
1098			honk.Time = t
1099		}
1100	}
1101
1102	if honk.Public {
1103		honk.Whofore = 2
1104	} else {
1105		honk.Whofore = 3
1106	}
1107
1108	// back to markdown
1109	honk.Noise = noise
1110
1111	if r.FormValue("preview") == "preview" {
1112		honks := []*Honk{honk}
1113		reverbolate(userinfo.UserID, honks)
1114		templinfo := getInfo(r)
1115		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1116		templinfo["Honks"] = honks
1117		templinfo["InReplyTo"] = r.FormValue("rid")
1118		templinfo["Noise"] = r.FormValue("noise")
1119		templinfo["SavedFile"] = donkxid
1120		templinfo["ServerMessage"] = "honk preview"
1121		err := readviews.Execute(w, "honkpage.html", templinfo)
1122		if err != nil {
1123			log.Print(err)
1124		}
1125		return
1126	}
1127
1128	if updatexid != "" {
1129		updatehonk(honk)
1130	} else {
1131		err := savehonk(honk)
1132		if err != nil {
1133			log.Printf("uh oh")
1134			return
1135		}
1136	}
1137
1138	// reload for consistency
1139	honk.Donks = nil
1140	donksforhonks([]*Honk{honk})
1141
1142	go honkworldwide(user, honk)
1143
1144	http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1145}
1146
1147func showhonkers(w http.ResponseWriter, r *http.Request) {
1148	userinfo := login.GetUserInfo(r)
1149	templinfo := getInfo(r)
1150	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1151	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1152	err := readviews.Execute(w, "honkers.html", templinfo)
1153	if err != nil {
1154		log.Print(err)
1155	}
1156}
1157
1158var combocache = cacheNew(cacheOptions{Filler: func(userid int64) ([]string, bool) {
1159	honkers := gethonkers(userid)
1160	var combos []string
1161	for _, h := range honkers {
1162		combos = append(combos, h.Combos...)
1163	}
1164	for i, c := range combos {
1165		if c == "-" {
1166			combos[i] = ""
1167		}
1168	}
1169	combos = oneofakind(combos)
1170	sort.Strings(combos)
1171	return combos, true
1172}})
1173
1174func showcombos(w http.ResponseWriter, r *http.Request) {
1175	userinfo := login.GetUserInfo(r)
1176	var combos []string
1177	combocache.Get(userinfo.UserID, &combos)
1178	templinfo := getInfo(r)
1179	err := readviews.Execute(w, "combos.html", templinfo)
1180	if err != nil {
1181		log.Print(err)
1182	}
1183}
1184
1185func submithonker(w http.ResponseWriter, r *http.Request) {
1186	u := login.GetUserInfo(r)
1187	name := r.FormValue("name")
1188	url := r.FormValue("url")
1189	peep := r.FormValue("peep")
1190	combos := r.FormValue("combos")
1191	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1192
1193	defer combocache.Clear(u.UserID)
1194
1195	if honkerid > 0 {
1196		goodbye := r.FormValue("goodbye")
1197		if goodbye == "F" {
1198			db := opendatabase()
1199			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1200				honkerid, u.UserID)
1201			err := row.Scan(&url)
1202			if err != nil {
1203				log.Printf("can't get honker xid: %s", err)
1204				return
1205			}
1206			log.Printf("unsubscribing from %s", url)
1207			user, _ := butwhatabout(u.Username)
1208			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, url, "sub")
1209			if err != nil {
1210				log.Printf("error updating honker: %s", err)
1211				return
1212			}
1213			go itakeitallback(user, url)
1214
1215			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1216			return
1217		}
1218		if goodbye == "X" {
1219			db := opendatabase()
1220			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep')",
1221				honkerid, u.UserID)
1222			err := row.Scan(&url)
1223			if err != nil {
1224				log.Printf("can't get honker xid: %s", err)
1225				return
1226			}
1227			log.Printf("resubscribing to %s", url)
1228			user, _ := butwhatabout(u.Username)
1229			_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "unsub")
1230			if err == nil {
1231				_, err = stmtUpdateFlavor.Exec("presub", u.UserID, url, "peep")
1232			}
1233			if err != nil {
1234				log.Printf("error updating honker: %s", err)
1235				return
1236			}
1237			go subsub(user, url)
1238
1239			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1240			return
1241		}
1242		combos = " " + strings.TrimSpace(combos) + " "
1243		_, err := stmtUpdateHonker.Exec(name, combos, honkerid, u.UserID)
1244		if err != nil {
1245			log.Printf("update honker err: %s", err)
1246			return
1247		}
1248		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1249		return
1250	}
1251
1252	flavor := "presub"
1253	if peep == "peep" {
1254		flavor = "peep"
1255	}
1256	p, err := investigate(url)
1257	if err != nil {
1258		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1259		log.Printf("failed to investigate honker: %s", err)
1260		return
1261	}
1262	url = p.XID
1263
1264	db := opendatabase()
1265	row := db.QueryRow("select xid from honkers where xid = ? and userid = ? and flavor in ('sub', 'unsub', 'peep')", url, u.UserID)
1266	var x string
1267	err = row.Scan(&x)
1268	if err != sql.ErrNoRows {
1269		http.Error(w, "it seems you are already subscribed to them", http.StatusInternalServerError)
1270		if err != nil {
1271			log.Printf("honker scan err: %s", err)
1272		}
1273		return
1274	}
1275
1276	if name == "" {
1277		name = p.Handle
1278	}
1279	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1280	if err != nil {
1281		log.Print(err)
1282		return
1283	}
1284	if flavor == "presub" {
1285		user, _ := butwhatabout(u.Username)
1286		go subsub(user, url)
1287	}
1288	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1289}
1290
1291func hfcspage(w http.ResponseWriter, r *http.Request) {
1292	userinfo := login.GetUserInfo(r)
1293
1294	filters := getfilters(userinfo.UserID, filtAny)
1295
1296	templinfo := getInfo(r)
1297	templinfo["Filters"] = filters
1298	templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
1299	err := readviews.Execute(w, "hfcs.html", templinfo)
1300	if err != nil {
1301		log.Print(err)
1302	}
1303}
1304
1305func savehfcs(w http.ResponseWriter, r *http.Request) {
1306	userinfo := login.GetUserInfo(r)
1307	itsok := r.FormValue("itsok")
1308	if itsok == "iforgiveyou" {
1309		hfcsid, _ := strconv.ParseInt(r.FormValue("hfcsid"), 10, 0)
1310		_, err := stmtDeleteFilter.Exec(userinfo.UserID, hfcsid)
1311		if err != nil {
1312			log.Printf("error deleting filter: %s", err)
1313		}
1314		filtcache.Clear(userinfo.UserID)
1315		http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1316		return
1317	}
1318
1319	filt := new(Filter)
1320	filt.Name = r.FormValue("name")
1321	filt.Date = time.Now().UTC()
1322	filt.Actor = r.FormValue("actor")
1323	filt.IncludeAudience = r.FormValue("incaud") == "yes"
1324	filt.Text = r.FormValue("filttext")
1325	filt.IsAnnounce = r.FormValue("isannounce") == "yes"
1326	filt.AnnounceOf = r.FormValue("announceof")
1327	filt.Reject = r.FormValue("doreject") == "yes"
1328	filt.SkipMedia = r.FormValue("doskipmedia") == "yes"
1329	filt.Hide = r.FormValue("dohide") == "yes"
1330	filt.Collapse = r.FormValue("docollapse") == "yes"
1331	filt.Rewrite = r.FormValue("filtrewrite")
1332	filt.Replace = r.FormValue("filtreplace")
1333
1334	if filt.Actor == "" && filt.Text == "" {
1335		log.Printf("blank filter")
1336		return
1337	}
1338
1339	j, err := jsonify(filt)
1340	if err == nil {
1341		_, err = stmtSaveFilter.Exec(userinfo.UserID, j)
1342	}
1343	if err != nil {
1344		log.Printf("error saving filter: %s", err)
1345	}
1346
1347	filtcache.Clear(userinfo.UserID)
1348	http.Redirect(w, r, "/hfcs", http.StatusSeeOther)
1349}
1350
1351func accountpage(w http.ResponseWriter, r *http.Request) {
1352	u := login.GetUserInfo(r)
1353	user, _ := butwhatabout(u.Username)
1354	templinfo := getInfo(r)
1355	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1356	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1357	templinfo["User"] = user
1358	err := readviews.Execute(w, "account.html", templinfo)
1359	if err != nil {
1360		log.Print(err)
1361	}
1362}
1363
1364func dochpass(w http.ResponseWriter, r *http.Request) {
1365	err := login.ChangePassword(w, r)
1366	if err != nil {
1367		log.Printf("error changing password: %s", err)
1368	}
1369	http.Redirect(w, r, "/account", http.StatusSeeOther)
1370}
1371
1372func fingerlicker(w http.ResponseWriter, r *http.Request) {
1373	orig := r.FormValue("resource")
1374
1375	log.Printf("finger lick: %s", orig)
1376
1377	if strings.HasPrefix(orig, "acct:") {
1378		orig = orig[5:]
1379	}
1380
1381	name := orig
1382	idx := strings.LastIndexByte(name, '/')
1383	if idx != -1 {
1384		name = name[idx+1:]
1385		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1386			log.Printf("foreign request rejected")
1387			name = ""
1388		}
1389	} else {
1390		idx = strings.IndexByte(name, '@')
1391		if idx != -1 {
1392			name = name[:idx]
1393			if name+"@"+serverName != orig {
1394				log.Printf("foreign request rejected")
1395				name = ""
1396			}
1397		}
1398	}
1399	user, err := butwhatabout(name)
1400	if err != nil {
1401		http.NotFound(w, r)
1402		return
1403	}
1404	if stealthmode(user.ID, r) {
1405		http.NotFound(w, r)
1406		return
1407	}
1408
1409	j := junk.New()
1410	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1411	j["aliases"] = []string{user.URL}
1412	var links []junk.Junk
1413	l := junk.New()
1414	l["rel"] = "self"
1415	l["type"] = `application/activity+json`
1416	l["href"] = user.URL
1417	links = append(links, l)
1418	j["links"] = links
1419
1420	w.Header().Set("Cache-Control", "max-age=3600")
1421	w.Header().Set("Content-Type", "application/jrd+json")
1422	j.Write(w)
1423}
1424
1425func somedays() string {
1426	secs := 432000 + notrand.Int63n(432000)
1427	return fmt.Sprintf("%d", secs)
1428}
1429
1430func avatate(w http.ResponseWriter, r *http.Request) {
1431	n := r.FormValue("a")
1432	a := avatar(n)
1433	w.Header().Set("Cache-Control", "max-age="+somedays())
1434	w.Write(a)
1435}
1436
1437func servecss(w http.ResponseWriter, r *http.Request) {
1438	fd, err := os.Open("views" + r.URL.Path)
1439	if err != nil {
1440		http.NotFound(w, r)
1441		return
1442	}
1443	w.Header().Set("Cache-Control", "max-age=0")
1444	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1445	err = css.Filter(fd, w)
1446	if err != nil {
1447		log.Printf("error filtering css: %s", err)
1448	}
1449}
1450func serveasset(w http.ResponseWriter, r *http.Request) {
1451	w.Header().Set("Cache-Control", "max-age=7776000")
1452	http.ServeFile(w, r, "views"+r.URL.Path)
1453}
1454func servehelp(w http.ResponseWriter, r *http.Request) {
1455	name := mux.Vars(r)["name"]
1456	w.Header().Set("Cache-Control", "max-age=600")
1457	http.ServeFile(w, r, "docs/"+name)
1458}
1459func servehtml(w http.ResponseWriter, r *http.Request) {
1460	templinfo := getInfo(r)
1461	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1462	if err != nil {
1463		log.Print(err)
1464	}
1465}
1466func serveemu(w http.ResponseWriter, r *http.Request) {
1467	xid := mux.Vars(r)["xid"]
1468	w.Header().Set("Cache-Control", "max-age="+somedays())
1469	http.ServeFile(w, r, "emus/"+xid)
1470}
1471func servememe(w http.ResponseWriter, r *http.Request) {
1472	xid := mux.Vars(r)["xid"]
1473	w.Header().Set("Cache-Control", "max-age="+somedays())
1474	http.ServeFile(w, r, "memes/"+xid)
1475}
1476
1477func servefile(w http.ResponseWriter, r *http.Request) {
1478	xid := mux.Vars(r)["xid"]
1479	row := stmtGetFileData.QueryRow(xid)
1480	var media string
1481	var data []byte
1482	err := row.Scan(&media, &data)
1483	if err != nil {
1484		log.Printf("error loading file: %s", err)
1485		http.NotFound(w, r)
1486		return
1487	}
1488	w.Header().Set("Content-Type", media)
1489	w.Header().Set("X-Content-Type-Options", "nosniff")
1490	w.Header().Set("Cache-Control", "max-age="+somedays())
1491	w.Write(data)
1492}
1493
1494func nomoroboto(w http.ResponseWriter, r *http.Request) {
1495	io.WriteString(w, "User-agent: *\n")
1496	io.WriteString(w, "Disallow: /a\n")
1497	io.WriteString(w, "Disallow: /d\n")
1498	io.WriteString(w, "Disallow: /meme\n")
1499	for _, u := range allusers() {
1500		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1501	}
1502}
1503
1504func webhydra(w http.ResponseWriter, r *http.Request) {
1505	u := login.GetUserInfo(r)
1506	userid := u.UserID
1507	templinfo := getInfo(r)
1508	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1509	page := r.FormValue("page")
1510	var honks []*Honk
1511	switch page {
1512	case "atme":
1513		honks = gethonksforme(userid)
1514		templinfo["ServerMessage"] = "at me!"
1515	case "home":
1516		honks = gethonksforuser(userid)
1517		honks = osmosis(honks, userid)
1518		templinfo["ServerMessage"] = serverMsg
1519	case "first":
1520		honks = gethonksforuserfirstclass(userid)
1521		honks = osmosis(honks, userid)
1522		templinfo["ServerMessage"] = "first class only"
1523	case "combo":
1524		c := r.FormValue("c")
1525		honks = gethonksbycombo(userid, c)
1526		templinfo["ServerMessage"] = "honks by combo: " + c
1527	case "convoy":
1528		c := r.FormValue("c")
1529		honks = gethonksbyconvoy(userid, c)
1530		templinfo["ServerMessage"] = "honks in convoy: " + c
1531	case "honker":
1532		xid := r.FormValue("xid")
1533		if strings.IndexByte(xid, '@') != -1 {
1534			xid = gofish(xid)
1535		}
1536		honks = gethonksbyxonker(userid, xid)
1537		xid = html.EscapeString(xid)
1538		msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, xid, xid)
1539		templinfo["ServerMessage"] = template.HTML(msg)
1540	default:
1541		http.NotFound(w, r)
1542	}
1543	if len(honks) > 0 {
1544		templinfo["TopXID"] = honks[0].XID
1545	}
1546	if topxid := r.FormValue("topxid"); topxid != "" {
1547		for i, h := range honks {
1548			if h.XID == topxid {
1549				honks = honks[0:i]
1550				break
1551			}
1552		}
1553		log.Printf("topxid %d frags", len(honks))
1554	}
1555	reverbolate(userid, honks)
1556	templinfo["Honks"] = honks
1557	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1558	err := readviews.Execute(w, "honkfrags.html", templinfo)
1559	if err != nil {
1560		log.Printf("frag error: %s", err)
1561	}
1562}
1563
1564func serve() {
1565	db := opendatabase()
1566	login.Init(db)
1567
1568	listener, err := openListener()
1569	if err != nil {
1570		log.Fatal(err)
1571	}
1572	go redeliverator()
1573
1574	debug := false
1575	getconfig("debug", &debug)
1576	readviews = templates.Load(debug,
1577		"views/honkpage.html",
1578		"views/honkfrags.html",
1579		"views/honkers.html",
1580		"views/hfcs.html",
1581		"views/combos.html",
1582		"views/honkform.html",
1583		"views/honk.html",
1584		"views/account.html",
1585		"views/about.html",
1586		"views/funzone.html",
1587		"views/login.html",
1588		"views/xzone.html",
1589		"views/header.html",
1590		"views/onts.html",
1591		"views/honkpage.js",
1592	)
1593	if !debug {
1594		assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1595		for _, s := range assets {
1596			savedassetparams[s] = getassetparam(s)
1597		}
1598	}
1599
1600	mux := mux.NewRouter()
1601	mux.Use(login.Checker)
1602
1603	posters := mux.Methods("POST").Subrouter()
1604	getters := mux.Methods("GET").Subrouter()
1605
1606	getters.HandleFunc("/", homepage)
1607	getters.HandleFunc("/home", homepage)
1608	getters.HandleFunc("/front", homepage)
1609	getters.HandleFunc("/robots.txt", nomoroboto)
1610	getters.HandleFunc("/rss", showrss)
1611	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1612	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1613	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1614	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1615	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1616	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1617	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1618	getters.HandleFunc("/a", avatate)
1619	getters.HandleFunc("/o", thelistingoftheontologies)
1620	getters.HandleFunc("/o/{name:.+}", showontology)
1621	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1622	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1623	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1624	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1625
1626	getters.HandleFunc("/style.css", servecss)
1627	getters.HandleFunc("/local.css", servecss)
1628	getters.HandleFunc("/honkpage.js", serveasset)
1629	getters.HandleFunc("/about", servehtml)
1630	getters.HandleFunc("/login", servehtml)
1631	posters.HandleFunc("/dologin", login.LoginFunc)
1632	getters.HandleFunc("/logout", login.LogoutFunc)
1633	getters.HandleFunc("/help/{name:[[:alnum:]_.-]+}", servehelp)
1634
1635	loggedin := mux.NewRoute().Subrouter()
1636	loggedin.Use(login.Required)
1637	loggedin.HandleFunc("/account", accountpage)
1638	loggedin.HandleFunc("/funzone", showfunzone)
1639	loggedin.HandleFunc("/chpass", dochpass)
1640	loggedin.HandleFunc("/atme", homepage)
1641	loggedin.HandleFunc("/hfcs", hfcspage)
1642	loggedin.HandleFunc("/xzone", xzone)
1643	loggedin.HandleFunc("/edit", edithonkpage)
1644	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1645	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1646	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1647	loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
1648	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1649	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1650	loggedin.HandleFunc("/honkers", showhonkers)
1651	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1652	loggedin.HandleFunc("/h", showhonker)
1653	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1654	loggedin.HandleFunc("/c", showcombos)
1655	loggedin.HandleFunc("/t", showconvoy)
1656	loggedin.HandleFunc("/q", showsearch)
1657	loggedin.HandleFunc("/hydra", webhydra)
1658	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1659
1660	err = http.Serve(listener, mux)
1661	if err != nil {
1662		log.Fatal(err)
1663	}
1664}