all repos — honk @ 27931774809051fb985782e0271da58e3911c851

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