all repos — honk @ 180b0ac9976aa302ff13313289e2eefe08b3a55a

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