all repos — honk @ 29e3db72ba1159e40932bb8af9b87ebd579d19a5

my fork of honk

web.go (view raw)

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