all repos — honk @ f2c8378d3a59920db7bf35fa3c182c2529db70ed

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