all repos — honk @ 80d720115661b404ac9e9b10716654ae0fd920b3

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