all repos — honk @ dea3cb9d2c80622a1ff6273f60ac0fa87e0d3847

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