all repos — honk @ c09ba99a73900b4913e40c3e6b66e45a23154602

my fork of honk

web.go (view raw)

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