all repos — honk @ 6762420a77a92594067be4edc6e62473d7dda14d

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