all repos — honk @ 6c85e589f03653a5e73b1d6dec5858ca54092931

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		var donk Donk
1026		row := stmtFindFile.QueryRow(url)
1027		err := row.Scan(&donk.FileID)
1028		if err == nil {
1029			honk.Donks = append(honk.Donks, &donk)
1030		} else {
1031			log.Printf("can't find file: %s", xid)
1032		}
1033	}
1034	herd := herdofemus(honk.Noise)
1035	for _, e := range herd {
1036		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1037		if donk != nil {
1038			donk.Name = e.Name
1039			honk.Donks = append(honk.Donks, donk)
1040		}
1041	}
1042	memetize(honk)
1043
1044	placename := r.FormValue("placename")
1045	placelat := r.FormValue("placelat")
1046	placelong := r.FormValue("placelong")
1047	if placename != "" || placelat != "" || placelong != "" {
1048		p := new(Place)
1049		p.Name = placename
1050		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1051		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1052		p.Url = r.FormValue("placeurl")
1053		honk.Place = p
1054	}
1055
1056	if honk.Public {
1057		honk.Whofore = 2
1058	} else {
1059		honk.Whofore = 3
1060	}
1061
1062	// back to markdown
1063	honk.Noise = noise
1064
1065	if r.FormValue("preview") == "preview" {
1066		honks := []*Honk{honk}
1067		reverbolate(userinfo.UserID, honks)
1068		templinfo := getInfo(r)
1069		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1070		templinfo["Honks"] = honks
1071		templinfo["InReplyTo"] = r.FormValue("rid")
1072		templinfo["Noise"] = r.FormValue("noise")
1073		templinfo["SavedFile"] = donkxid
1074		templinfo["ServerMessage"] = "honk preview"
1075		err := readviews.Execute(w, "honkpage.html", templinfo)
1076		if err != nil {
1077			log.Print(err)
1078		}
1079		return
1080	}
1081
1082	if updatexid != "" {
1083		updatehonk(honk)
1084	} else {
1085		err := savehonk(honk)
1086		if err != nil {
1087			log.Printf("uh oh")
1088			return
1089		}
1090	}
1091
1092	// reload for consistency
1093	honk.Donks = nil
1094	donksforhonks([]*Honk{honk})
1095
1096	go honkworldwide(user, honk)
1097
1098	http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1099}
1100
1101func showhonkers(w http.ResponseWriter, r *http.Request) {
1102	userinfo := login.GetUserInfo(r)
1103	templinfo := getInfo(r)
1104	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1105	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1106	err := readviews.Execute(w, "honkers.html", templinfo)
1107	if err != nil {
1108		log.Print(err)
1109	}
1110}
1111
1112var combocache = cacheNew(func(key interface{}) (interface{}, bool) {
1113	userid := key.(int64)
1114	honkers := gethonkers(userid)
1115	var combos []string
1116	for _, h := range honkers {
1117		combos = append(combos, h.Combos...)
1118	}
1119	for i, c := range combos {
1120		if c == "-" {
1121			combos[i] = ""
1122		}
1123	}
1124	combos = oneofakind(combos)
1125	sort.Strings(combos)
1126	return combos, true
1127})
1128
1129func showcombos(w http.ResponseWriter, r *http.Request) {
1130	userinfo := login.GetUserInfo(r)
1131	var combos []string
1132	combocache.Get(userinfo.UserID, &combos)
1133	templinfo := getInfo(r)
1134	err := readviews.Execute(w, "combos.html", templinfo)
1135	if err != nil {
1136		log.Print(err)
1137	}
1138}
1139
1140func submithonker(w http.ResponseWriter, r *http.Request) {
1141	u := login.GetUserInfo(r)
1142	name := r.FormValue("name")
1143	url := r.FormValue("url")
1144	peep := r.FormValue("peep")
1145	combos := r.FormValue("combos")
1146	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1147
1148	defer combocache.Clear(u.UserID)
1149
1150	if honkerid > 0 {
1151		goodbye := r.FormValue("goodbye")
1152		if goodbye == "F" {
1153			db := opendatabase()
1154			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ?",
1155				honkerid, u.UserID)
1156			var xid string
1157			err := row.Scan(&xid)
1158			if err != nil {
1159				log.Printf("can't get honker xid: %s", err)
1160				return
1161			}
1162			log.Printf("unsubscribing from %s", xid)
1163			user, _ := butwhatabout(u.Username)
1164			go itakeitallback(user, xid)
1165			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, xid, "sub")
1166			if err != nil {
1167				log.Printf("error updating honker: %s", err)
1168				return
1169			}
1170
1171			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1172			return
1173		}
1174		combos = " " + strings.TrimSpace(combos) + " "
1175		_, err := stmtUpdateCombos.Exec(combos, honkerid, u.UserID)
1176		if err != nil {
1177			log.Printf("update honker err: %s", err)
1178			return
1179		}
1180		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1181		return
1182	}
1183
1184	flavor := "presub"
1185	if peep == "peep" {
1186		flavor = "peep"
1187	}
1188	p, err := investigate(url)
1189	if err != nil {
1190		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1191		log.Printf("failed to investigate honker")
1192		return
1193	}
1194	url = p.XID
1195	if name == "" {
1196		name = p.Handle
1197	}
1198	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1199	if err != nil {
1200		log.Print(err)
1201		return
1202	}
1203	if flavor == "presub" {
1204		user, _ := butwhatabout(u.Username)
1205		go subsub(user, url)
1206	}
1207	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1208}
1209
1210func zonkzone(w http.ResponseWriter, r *http.Request) {
1211	userinfo := login.GetUserInfo(r)
1212	rows, err := stmtGetZonkers.Query(userinfo.UserID)
1213	if err != nil {
1214		log.Printf("err: %s", err)
1215		return
1216	}
1217	defer rows.Close()
1218	var zonkers []Zonker
1219	for rows.Next() {
1220		var z Zonker
1221		rows.Scan(&z.ID, &z.Name, &z.Wherefore)
1222		zonkers = append(zonkers, z)
1223	}
1224	sort.Slice(zonkers, func(i, j int) bool {
1225		w1 := zonkers[i].Wherefore
1226		w2 := zonkers[j].Wherefore
1227		if w1 == w2 {
1228			return zonkers[i].Name < zonkers[j].Name
1229		}
1230		if w1 == "zonvoy" {
1231			w1 = "zzzzzzz"
1232		}
1233		if w2 == "zonvoy" {
1234			w2 = "zzzzzzz"
1235		}
1236		return w1 < w2
1237	})
1238
1239	templinfo := getInfo(r)
1240	templinfo["Zonkers"] = zonkers
1241	templinfo["ZonkCSRF"] = login.GetCSRF("zonkzonk", r)
1242	err = readviews.Execute(w, "zonkers.html", templinfo)
1243	if err != nil {
1244		log.Print(err)
1245	}
1246}
1247
1248func zonkzonk(w http.ResponseWriter, r *http.Request) {
1249	userinfo := login.GetUserInfo(r)
1250	itsok := r.FormValue("itsok")
1251	if itsok == "iforgiveyou" {
1252		zonkerid, _ := strconv.ParseInt(r.FormValue("zonkerid"), 10, 0)
1253		db := opendatabase()
1254		db.Exec("delete from zonkers where userid = ? and zonkerid = ?",
1255			userinfo.UserID, zonkerid)
1256		bitethethumbs()
1257		http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1258		return
1259	}
1260	wherefore := r.FormValue("wherefore")
1261	name := r.FormValue("name")
1262	if name == "" {
1263		return
1264	}
1265	switch wherefore {
1266	case "zonker":
1267	case "zomain":
1268	case "zonvoy":
1269	case "zord":
1270	case "zilence":
1271	case "zoggle":
1272	default:
1273		return
1274	}
1275	db := opendatabase()
1276	db.Exec("insert into zonkers (userid, name, wherefore) values (?, ?, ?)",
1277		userinfo.UserID, name, wherefore)
1278
1279	if wherefore != "zonvoy" {
1280		bitethethumbs()
1281	}
1282
1283	http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1284}
1285
1286func accountpage(w http.ResponseWriter, r *http.Request) {
1287	u := login.GetUserInfo(r)
1288	user, _ := butwhatabout(u.Username)
1289	templinfo := getInfo(r)
1290	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1291	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1292	templinfo["User"] = user
1293	err := readviews.Execute(w, "account.html", templinfo)
1294	if err != nil {
1295		log.Print(err)
1296	}
1297}
1298
1299func dochpass(w http.ResponseWriter, r *http.Request) {
1300	err := login.ChangePassword(w, r)
1301	if err != nil {
1302		log.Printf("error changing password: %s", err)
1303	}
1304	http.Redirect(w, r, "/account", http.StatusSeeOther)
1305}
1306
1307func fingerlicker(w http.ResponseWriter, r *http.Request) {
1308	orig := r.FormValue("resource")
1309
1310	log.Printf("finger lick: %s", orig)
1311
1312	if strings.HasPrefix(orig, "acct:") {
1313		orig = orig[5:]
1314	}
1315
1316	name := orig
1317	idx := strings.LastIndexByte(name, '/')
1318	if idx != -1 {
1319		name = name[idx+1:]
1320		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1321			log.Printf("foreign request rejected")
1322			name = ""
1323		}
1324	} else {
1325		idx = strings.IndexByte(name, '@')
1326		if idx != -1 {
1327			name = name[:idx]
1328			if name+"@"+serverName != orig {
1329				log.Printf("foreign request rejected")
1330				name = ""
1331			}
1332		}
1333	}
1334	user, err := butwhatabout(name)
1335	if err != nil {
1336		http.NotFound(w, r)
1337		return
1338	}
1339	if stealthmode(user.ID, r) {
1340		http.NotFound(w, r)
1341		return
1342	}
1343
1344	j := junk.New()
1345	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1346	j["aliases"] = []string{user.URL}
1347	var links []junk.Junk
1348	l := junk.New()
1349	l["rel"] = "self"
1350	l["type"] = `application/activity+json`
1351	l["href"] = user.URL
1352	links = append(links, l)
1353	j["links"] = links
1354
1355	w.Header().Set("Cache-Control", "max-age=3600")
1356	w.Header().Set("Content-Type", "application/jrd+json")
1357	j.Write(w)
1358}
1359
1360func somedays() string {
1361	secs := 432000 + notrand.Int63n(432000)
1362	return fmt.Sprintf("%d", secs)
1363}
1364
1365func avatate(w http.ResponseWriter, r *http.Request) {
1366	n := r.FormValue("a")
1367	a := avatar(n)
1368	w.Header().Set("Cache-Control", "max-age="+somedays())
1369	w.Write(a)
1370}
1371
1372func servecss(w http.ResponseWriter, r *http.Request) {
1373	fd, err := os.Open("views" + r.URL.Path)
1374	if err != nil {
1375		http.NotFound(w, r)
1376		return
1377	}
1378	w.Header().Set("Cache-Control", "max-age=0")
1379	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1380	err = css.Filter(fd, w)
1381	if err != nil {
1382		log.Printf("error filtering css: %s", err)
1383	}
1384}
1385func serveasset(w http.ResponseWriter, r *http.Request) {
1386	w.Header().Set("Cache-Control", "max-age=7776000")
1387	http.ServeFile(w, r, "views"+r.URL.Path)
1388}
1389func servehtml(w http.ResponseWriter, r *http.Request) {
1390	templinfo := getInfo(r)
1391	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1392	if err != nil {
1393		log.Print(err)
1394	}
1395}
1396func serveemu(w http.ResponseWriter, r *http.Request) {
1397	xid := mux.Vars(r)["xid"]
1398	w.Header().Set("Cache-Control", "max-age="+somedays())
1399	http.ServeFile(w, r, "emus/"+xid)
1400}
1401func servememe(w http.ResponseWriter, r *http.Request) {
1402	xid := mux.Vars(r)["xid"]
1403	w.Header().Set("Cache-Control", "max-age="+somedays())
1404	http.ServeFile(w, r, "memes/"+xid)
1405}
1406
1407func servefile(w http.ResponseWriter, r *http.Request) {
1408	xid := mux.Vars(r)["xid"]
1409	row := stmtGetFileData.QueryRow(xid)
1410	var media string
1411	var data []byte
1412	err := row.Scan(&media, &data)
1413	if err != nil {
1414		log.Printf("error loading file: %s", err)
1415		http.NotFound(w, r)
1416		return
1417	}
1418	w.Header().Set("Content-Type", media)
1419	w.Header().Set("X-Content-Type-Options", "nosniff")
1420	w.Header().Set("Cache-Control", "max-age="+somedays())
1421	w.Write(data)
1422}
1423
1424func nomoroboto(w http.ResponseWriter, r *http.Request) {
1425	io.WriteString(w, "User-agent: *\n")
1426	io.WriteString(w, "Disallow: /a\n")
1427	io.WriteString(w, "Disallow: /d\n")
1428	io.WriteString(w, "Disallow: /meme\n")
1429	for _, u := range allusers() {
1430		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1431	}
1432}
1433
1434func webhydra(w http.ResponseWriter, r *http.Request) {
1435	u := login.GetUserInfo(r)
1436	userid := u.UserID
1437	templinfo := getInfo(r)
1438	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1439	page := r.FormValue("page")
1440	var honks []*Honk
1441	switch page {
1442	case "atme":
1443		honks = gethonksforme(userid)
1444	case "home":
1445		honks = gethonksforuser(userid)
1446		honks = osmosis(honks, userid)
1447	case "first":
1448		honks = gethonksforuserfirstclass(userid)
1449		honks = osmosis(honks, userid)
1450	case "combo":
1451		c := r.FormValue("c")
1452		honks = gethonksbycombo(userid, c)
1453	case "convoy":
1454		c := r.FormValue("c")
1455		honks = gethonksbyconvoy(userid, c)
1456	case "honker":
1457		xid := r.FormValue("xid")
1458		if strings.IndexByte(xid, '@') != -1 {
1459			xid = gofish(xid)
1460		}
1461		honks = gethonksbyxonker(userid, xid)
1462	default:
1463		http.NotFound(w, r)
1464	}
1465	if len(honks) > 0 {
1466		templinfo["TopXID"] = honks[0].XID
1467	}
1468	if topxid := r.FormValue("topxid"); topxid != "" {
1469		for i, h := range honks {
1470			if h.XID == topxid {
1471				honks = honks[0:i]
1472				break
1473			}
1474		}
1475		log.Printf("topxid %d frags", len(honks))
1476	}
1477	reverbolate(userid, honks)
1478	templinfo["Honks"] = honks
1479	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1480	err := readviews.Execute(w, "honkfrags.html", templinfo)
1481	if err != nil {
1482		log.Printf("frag error: %s", err)
1483	}
1484}
1485
1486func serve() {
1487	db := opendatabase()
1488	login.Init(db)
1489
1490	listener, err := openListener()
1491	if err != nil {
1492		log.Fatal(err)
1493	}
1494	go redeliverator()
1495
1496	debug := false
1497	getconfig("debug", &debug)
1498	readviews = templates.Load(debug,
1499		"views/honkpage.html",
1500		"views/honkfrags.html",
1501		"views/honkers.html",
1502		"views/zonkers.html",
1503		"views/combos.html",
1504		"views/honkform.html",
1505		"views/honk.html",
1506		"views/account.html",
1507		"views/about.html",
1508		"views/funzone.html",
1509		"views/login.html",
1510		"views/xzone.html",
1511		"views/header.html",
1512		"views/onts.html",
1513		"views/honkpage.js",
1514	)
1515	if !debug {
1516		assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1517		for _, s := range assets {
1518			savedassetparams[s] = getassetparam(s)
1519		}
1520	}
1521
1522	bitethethumbs()
1523
1524	mux := mux.NewRouter()
1525	mux.Use(login.Checker)
1526
1527	posters := mux.Methods("POST").Subrouter()
1528	getters := mux.Methods("GET").Subrouter()
1529
1530	getters.HandleFunc("/", homepage)
1531	getters.HandleFunc("/home", homepage)
1532	getters.HandleFunc("/front", homepage)
1533	getters.HandleFunc("/robots.txt", nomoroboto)
1534	getters.HandleFunc("/rss", showrss)
1535	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1536	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1537	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1538	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1539	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1540	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1541	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1542	getters.HandleFunc("/a", avatate)
1543	getters.HandleFunc("/o", thelistingoftheontologies)
1544	getters.HandleFunc("/o/{name:.+}", showontology)
1545	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1546	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1547	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1548	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1549
1550	getters.HandleFunc("/style.css", servecss)
1551	getters.HandleFunc("/local.css", servecss)
1552	getters.HandleFunc("/honkpage.js", serveasset)
1553	getters.HandleFunc("/about", servehtml)
1554	getters.HandleFunc("/login", servehtml)
1555	posters.HandleFunc("/dologin", login.LoginFunc)
1556	getters.HandleFunc("/logout", login.LogoutFunc)
1557
1558	loggedin := mux.NewRoute().Subrouter()
1559	loggedin.Use(login.Required)
1560	loggedin.HandleFunc("/account", accountpage)
1561	loggedin.HandleFunc("/funzone", showfunzone)
1562	loggedin.HandleFunc("/chpass", dochpass)
1563	loggedin.HandleFunc("/atme", homepage)
1564	loggedin.HandleFunc("/zonkzone", zonkzone)
1565	loggedin.HandleFunc("/xzone", xzone)
1566	loggedin.HandleFunc("/edit", edithonkpage)
1567	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1568	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1569	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1570	loggedin.Handle("/zonkzonk", login.CSRFWrap("zonkzonk", http.HandlerFunc(zonkzonk)))
1571	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1572	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1573	loggedin.HandleFunc("/honkers", showhonkers)
1574	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1575	loggedin.HandleFunc("/h", showhonker)
1576	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1577	loggedin.HandleFunc("/c", showcombos)
1578	loggedin.HandleFunc("/t", showconvoy)
1579	loggedin.HandleFunc("/q", showsearch)
1580	loggedin.HandleFunc("/hydra", webhydra)
1581	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1582
1583	err = http.Serve(listener, mux)
1584	if err != nil {
1585		log.Fatal(err)
1586	}
1587}