all repos — honk @ 208575209010353f8ee3cb1dab82cd69500e2ea1

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