all repos — honk @ 4dc42a9ed445ac4351aaa15f9742065dacce3558

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