all repos — honk @ c2664b500d197b9cecf1a8adb0fca2c6705cb687

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	"fmt"
  21	"html"
  22	"html/template"
  23	"io"
  24	"log"
  25	notrand "math/rand"
  26	"net/http"
  27	"net/url"
  28	"os"
  29	"sort"
  30	"strconv"
  31	"strings"
  32	"time"
  33
  34	"github.com/gorilla/mux"
  35	"humungus.tedunangst.com/r/webs/css"
  36	"humungus.tedunangst.com/r/webs/htfilter"
  37	"humungus.tedunangst.com/r/webs/httpsig"
  38	"humungus.tedunangst.com/r/webs/image"
  39	"humungus.tedunangst.com/r/webs/junk"
  40	"humungus.tedunangst.com/r/webs/login"
  41	"humungus.tedunangst.com/r/webs/rss"
  42	"humungus.tedunangst.com/r/webs/templates"
  43)
  44
  45var readviews *templates.Template
  46
  47var userSep = "u"
  48var honkSep = "h"
  49
  50func getuserstyle(u *login.UserInfo) template.CSS {
  51	if u == nil {
  52		return ""
  53	}
  54	user, _ := butwhatabout(u.Username)
  55	if user.SkinnyCSS {
  56		return "main { max-width: 700px; }"
  57	}
  58	return ""
  59}
  60
  61func getInfo(r *http.Request) map[string]interface{} {
  62	u := login.GetUserInfo(r)
  63	templinfo := make(map[string]interface{})
  64	templinfo["StyleParam"] = getassetparam("views/style.css")
  65	templinfo["LocalStyleParam"] = getassetparam("views/local.css")
  66	templinfo["JSParam"] = getassetparam("views/honkpage.js")
  67	templinfo["UserStyle"] = getuserstyle(u)
  68	templinfo["ServerName"] = serverName
  69	templinfo["IconName"] = iconName
  70	templinfo["UserInfo"] = u
  71	templinfo["UserSep"] = userSep
  72	if u != nil {
  73		var combos []string
  74		combocache.Get(u.UserID, &combos)
  75		templinfo["Combos"] = combos
  76	}
  77	return templinfo
  78}
  79
  80func homepage(w http.ResponseWriter, r *http.Request) {
  81	templinfo := getInfo(r)
  82	u := login.GetUserInfo(r)
  83	var honks []*Honk
  84	var userid int64 = -1
  85	if r.URL.Path == "/front" || u == nil {
  86		honks = getpublichonks()
  87	} else {
  88		userid = u.UserID
  89		if r.URL.Path == "/atme" {
  90			templinfo["PageName"] = "atme"
  91			honks = gethonksforme(userid)
  92		} else if r.URL.Path == "/first" {
  93			templinfo["PageName"] = "first"
  94			honks = gethonksforuser(userid)
  95			honks = osmosis(honks, userid)
  96		} else {
  97			templinfo["PageName"] = "home"
  98			honks = gethonksforuser(userid)
  99			honks = osmosis(honks, userid)
 100		}
 101		if len(honks) > 0 {
 102			templinfo["TopXID"] = honks[0].XID
 103		}
 104		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 105	}
 106
 107	templinfo["ShowRSS"] = true
 108	templinfo["ServerMessage"] = serverMsg
 109	honkpage(w, u, honks, templinfo)
 110}
 111
 112func showfunzone(w http.ResponseWriter, r *http.Request) {
 113	var emunames, memenames []string
 114	dir, err := os.Open("emus")
 115	if err == nil {
 116		emunames, _ = dir.Readdirnames(0)
 117		dir.Close()
 118	}
 119	for i, e := range emunames {
 120		if len(e) > 4 {
 121			emunames[i] = e[:len(e)-4]
 122		}
 123	}
 124	dir, err = os.Open("memes")
 125	if err == nil {
 126		memenames, _ = dir.Readdirnames(0)
 127		dir.Close()
 128	}
 129	templinfo := getInfo(r)
 130	templinfo["Emus"] = emunames
 131	templinfo["Memes"] = memenames
 132	err = readviews.Execute(w, "funzone.html", templinfo)
 133	if err != nil {
 134		log.Print(err)
 135	}
 136}
 137
 138func showrss(w http.ResponseWriter, r *http.Request) {
 139	name := mux.Vars(r)["name"]
 140
 141	var honks []*Honk
 142	if name != "" {
 143		honks = gethonksbyuser(name, false)
 144	} else {
 145		honks = getpublichonks()
 146	}
 147	if len(honks) > 20 {
 148		honks = honks[0:20]
 149	}
 150	reverbolate(-1, honks)
 151
 152	home := fmt.Sprintf("https://%s/", serverName)
 153	base := home
 154	if name != "" {
 155		home += "u/" + name
 156		name += " "
 157	}
 158	feed := rss.Feed{
 159		Title:       name + "honk",
 160		Link:        home,
 161		Description: name + "honk rss",
 162		Image: &rss.Image{
 163			URL:   base + "icon.png",
 164			Title: name + "honk rss",
 165			Link:  home,
 166		},
 167	}
 168	var modtime time.Time
 169	for _, honk := range honks {
 170		if !firstclass(honk) {
 171			continue
 172		}
 173		desc := string(honk.HTML)
 174		for _, d := range honk.Donks {
 175			desc += fmt.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
 176				d.URL, html.EscapeString(d.Name))
 177		}
 178
 179		feed.Items = append(feed.Items, &rss.Item{
 180			Title:       fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
 181			Description: rss.CData{desc},
 182			Link:        honk.URL,
 183			PubDate:     honk.Date.Format(time.RFC1123),
 184			Guid:        &rss.Guid{IsPermaLink: true, Value: honk.URL},
 185		})
 186		if honk.Date.After(modtime) {
 187			modtime = honk.Date
 188		}
 189	}
 190	w.Header().Set("Cache-Control", "max-age=300")
 191	w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
 192
 193	err := feed.Write(w)
 194	if err != nil {
 195		log.Printf("error writing rss: %s", err)
 196	}
 197}
 198
 199func crappola(j junk.Junk) bool {
 200	t, _ := j.GetString("type")
 201	a, _ := j.GetString("actor")
 202	o, _ := j.GetString("object")
 203	if t == "Delete" && a == o {
 204		log.Printf("crappola from %s", a)
 205		return true
 206	}
 207	return false
 208}
 209
 210func ping(user *WhatAbout, who string) {
 211	box, err := getboxes(who)
 212	if err != nil {
 213		log.Printf("no inbox for ping: %s", err)
 214		return
 215	}
 216	j := junk.New()
 217	j["@context"] = itiswhatitis
 218	j["type"] = "Ping"
 219	j["id"] = user.URL + "/ping/" + xfiltrate()
 220	j["actor"] = user.URL
 221	j["to"] = who
 222	keyname, key := ziggy(user.Name)
 223	err = PostJunk(keyname, key, box.In, j)
 224	if err != nil {
 225		log.Printf("can't send ping: %s", err)
 226		return
 227	}
 228	log.Printf("sent ping to %s: %s", who, j["id"])
 229}
 230
 231func pong(user *WhatAbout, who string, obj string) {
 232	box, err := getboxes(who)
 233	if err != nil {
 234		log.Printf("no inbox for pong %s : %s", who, err)
 235		return
 236	}
 237	j := junk.New()
 238	j["@context"] = itiswhatitis
 239	j["type"] = "Pong"
 240	j["id"] = user.URL + "/pong/" + xfiltrate()
 241	j["actor"] = user.URL
 242	j["to"] = who
 243	j["object"] = obj
 244	keyname, key := ziggy(user.Name)
 245	err = PostJunk(keyname, key, box.In, j)
 246	if err != nil {
 247		log.Printf("can't send pong: %s", err)
 248		return
 249	}
 250}
 251
 252func inbox(w http.ResponseWriter, r *http.Request) {
 253	name := mux.Vars(r)["name"]
 254	user, err := butwhatabout(name)
 255	if err != nil {
 256		http.NotFound(w, r)
 257		return
 258	}
 259	if stealthmode(user.ID, r) {
 260		http.NotFound(w, r)
 261		return
 262	}
 263	var buf bytes.Buffer
 264	io.Copy(&buf, r.Body)
 265	payload := buf.Bytes()
 266	j, err := junk.Read(bytes.NewReader(payload))
 267	if err != nil {
 268		log.Printf("bad payload: %s", err)
 269		io.WriteString(os.Stdout, "bad payload\n")
 270		os.Stdout.Write(payload)
 271		io.WriteString(os.Stdout, "\n")
 272		return
 273	}
 274	if crappola(j) {
 275		return
 276	}
 277	keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
 278	if err != nil {
 279		log.Printf("inbox message failed signature: %s", err)
 280		if keyname != "" {
 281			keyname, err = makeitworksomehowwithoutregardforkeycontinuity(keyname, r, payload)
 282			if err != nil {
 283				log.Printf("still failed: %s", err)
 284			}
 285		}
 286		if err != nil {
 287			return
 288		}
 289	}
 290	what, _ := j.GetString("type")
 291	if what == "Like" {
 292		return
 293	}
 294	who, _ := j.GetString("actor")
 295	origin := keymatch(keyname, who)
 296	if origin == "" {
 297		log.Printf("keyname actor mismatch: %s <> %s", keyname, who)
 298		return
 299	}
 300	objid, _ := j.GetString("id")
 301	if thoudostbitethythumb(user.ID, []string{who}, objid) {
 302		log.Printf("ignoring thumb sucker %s", who)
 303		return
 304	}
 305	switch what {
 306	case "Ping":
 307		obj, _ := j.GetString("id")
 308		log.Printf("ping from %s: %s", who, obj)
 309		pong(user, who, obj)
 310	case "Pong":
 311		obj, _ := j.GetString("object")
 312		log.Printf("pong from %s: %s", who, obj)
 313	case "Follow":
 314		obj, _ := j.GetString("object")
 315		if obj == user.URL {
 316			log.Printf("updating honker follow: %s", who)
 317			stmtSaveDub.Exec(user.ID, who, who, "dub")
 318			go rubadubdub(user, j)
 319		} else {
 320			log.Printf("can't follow %s", obj)
 321		}
 322	case "Accept":
 323		log.Printf("updating honker accept: %s", who)
 324		_, err = stmtUpdateFlavor.Exec("sub", user.ID, who, "presub")
 325		if err != nil {
 326			log.Printf("error updating honker: %s", err)
 327			return
 328		}
 329	case "Update":
 330		obj, ok := j.GetMap("object")
 331		if ok {
 332			what, _ := obj.GetString("type")
 333			switch what {
 334			case "Person":
 335				return
 336			case "Question":
 337				return
 338			case "Note":
 339				go xonksaver(user, j, origin)
 340				return
 341			}
 342		}
 343		log.Printf("unknown Update activity")
 344		fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 345		j.Write(fd)
 346		io.WriteString(fd, "\n")
 347		fd.Close()
 348
 349	case "Undo":
 350		obj, ok := j.GetMap("object")
 351		if !ok {
 352			log.Printf("unknown undo no object")
 353		} else {
 354			what, _ := obj.GetString("type")
 355			switch what {
 356			case "Follow":
 357				log.Printf("updating honker undo: %s", who)
 358				_, err = stmtUpdateFlavor.Exec("undub", user.ID, who, "dub")
 359				if err != nil {
 360					log.Printf("error updating honker: %s", err)
 361					return
 362				}
 363			case "Announce":
 364				xid, _ := obj.GetString("object")
 365				log.Printf("undo announce: %s", xid)
 366			case "Like":
 367			default:
 368				log.Printf("unknown undo: %s", what)
 369			}
 370		}
 371	default:
 372		go xonksaver(user, j, origin)
 373	}
 374}
 375
 376func ximport(w http.ResponseWriter, r *http.Request) {
 377	u := login.GetUserInfo(r)
 378	xid := r.FormValue("xid")
 379	xonk := getxonk(u.UserID, xid)
 380	if xonk == nil {
 381		p, _ := investigate(xid)
 382		if p != nil {
 383			xid = p.XID
 384		}
 385		j, err := GetJunk(xid)
 386		if err != nil {
 387			http.Error(w, "error getting external object", http.StatusInternalServerError)
 388			log.Printf("error getting external object: %s", err)
 389			return
 390		}
 391		log.Printf("importing %s", xid)
 392		user, _ := butwhatabout(u.Username)
 393
 394		what, _ := j.GetString("type")
 395		if isactor(what) {
 396			outbox, _ := j.GetString("outbox")
 397			gimmexonks(user, outbox)
 398			http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
 399			return
 400		}
 401		xonk = xonksaver(user, j, originate(xid))
 402	}
 403	convoy := ""
 404	if xonk != nil {
 405		convoy = xonk.Convoy
 406	}
 407	http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
 408}
 409
 410func xzone(w http.ResponseWriter, r *http.Request) {
 411	u := login.GetUserInfo(r)
 412	rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
 413	if err != nil {
 414		log.Printf("query err: %s", err)
 415		return
 416	}
 417	defer rows.Close()
 418	var honkers []Honker
 419	for rows.Next() {
 420		var xid string
 421		rows.Scan(&xid)
 422		honkers = append(honkers, Honker{XID: xid})
 423	}
 424	rows.Close()
 425	for i, _ := range honkers {
 426		_, honkers[i].Handle = handles(honkers[i].XID)
 427	}
 428	templinfo := getInfo(r)
 429	templinfo["XCSRF"] = login.GetCSRF("ximport", r)
 430	templinfo["Honkers"] = honkers
 431	err = readviews.Execute(w, "xzone.html", templinfo)
 432	if err != nil {
 433		log.Print(err)
 434	}
 435}
 436
 437func outbox(w http.ResponseWriter, r *http.Request) {
 438	name := mux.Vars(r)["name"]
 439	user, err := butwhatabout(name)
 440	if err != nil {
 441		http.NotFound(w, r)
 442		return
 443	}
 444	if stealthmode(user.ID, r) {
 445		http.NotFound(w, r)
 446		return
 447	}
 448
 449	honks := gethonksbyuser(name, false)
 450	if len(honks) > 20 {
 451		honks = honks[0:20]
 452	}
 453
 454	var jonks []junk.Junk
 455	for _, h := range honks {
 456		j, _ := jonkjonk(user, h)
 457		jonks = append(jonks, j)
 458	}
 459
 460	j := junk.New()
 461	j["@context"] = itiswhatitis
 462	j["id"] = user.URL + "/outbox"
 463	j["type"] = "OrderedCollection"
 464	j["totalItems"] = len(jonks)
 465	j["orderedItems"] = jonks
 466
 467	w.Header().Set("Content-Type", theonetruename)
 468	j.Write(w)
 469}
 470
 471func emptiness(w http.ResponseWriter, r *http.Request) {
 472	name := mux.Vars(r)["name"]
 473	user, err := butwhatabout(name)
 474	if err != nil {
 475		http.NotFound(w, r)
 476		return
 477	}
 478	if stealthmode(user.ID, r) {
 479		http.NotFound(w, r)
 480		return
 481	}
 482	colname := "/followers"
 483	if strings.HasSuffix(r.URL.Path, "/following") {
 484		colname = "/following"
 485	}
 486	j := junk.New()
 487	j["@context"] = itiswhatitis
 488	j["id"] = user.URL + colname
 489	j["type"] = "OrderedCollection"
 490	j["totalItems"] = 0
 491	j["orderedItems"] = []junk.Junk{}
 492
 493	w.Header().Set("Content-Type", theonetruename)
 494	j.Write(w)
 495}
 496
 497func showuser(w http.ResponseWriter, r *http.Request) {
 498	name := mux.Vars(r)["name"]
 499	user, err := butwhatabout(name)
 500	if err != nil {
 501		log.Printf("user not found %s: %s", name, err)
 502		http.NotFound(w, r)
 503		return
 504	}
 505	if stealthmode(user.ID, r) {
 506		http.NotFound(w, r)
 507		return
 508	}
 509	if friendorfoe(r.Header.Get("Accept")) {
 510		j := asjonker(user)
 511		w.Header().Set("Content-Type", theonetruename)
 512		j.Write(w)
 513		return
 514	}
 515	u := login.GetUserInfo(r)
 516	honks := gethonksbyuser(name, u != nil && u.Username == name)
 517	templinfo := getInfo(r)
 518	filt := htfilter.New()
 519	templinfo["Name"] = user.Name
 520	whatabout := user.About
 521	whatabout = obfusbreak(user.About)
 522	templinfo["WhatAbout"], _ = filt.String(whatabout)
 523	templinfo["ServerMessage"] = ""
 524	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 525	honkpage(w, u, honks, templinfo)
 526}
 527
 528func showhonker(w http.ResponseWriter, r *http.Request) {
 529	u := login.GetUserInfo(r)
 530	name := mux.Vars(r)["name"]
 531	var honks []*Honk
 532	if name == "" {
 533		name = r.FormValue("xid")
 534		honks = gethonksbyxonker(u.UserID, name)
 535	} else {
 536		honks = gethonksbyhonker(u.UserID, name)
 537	}
 538	name = html.EscapeString(name)
 539	msg := fmt.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>`, name, name)
 540	templinfo := getInfo(r)
 541	templinfo["PageName"] = "honker"
 542	templinfo["ServerMessage"] = template.HTML(msg)
 543	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 544	honkpage(w, u, honks, templinfo)
 545}
 546
 547func showcombo(w http.ResponseWriter, r *http.Request) {
 548	name := mux.Vars(r)["name"]
 549	u := login.GetUserInfo(r)
 550	honks := gethonksbycombo(u.UserID, name)
 551	honks = osmosis(honks, u.UserID)
 552	templinfo := getInfo(r)
 553	templinfo["PageName"] = "combo"
 554	templinfo["PageArg"] = "name"
 555	templinfo["ServerMessage"] = "honks by combo: " + name
 556	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 557	if len(honks) > 0 {
 558		templinfo["TopXID"] = honks[0].XID
 559	}
 560	honkpage(w, u, honks, templinfo)
 561}
 562func showconvoy(w http.ResponseWriter, r *http.Request) {
 563	c := r.FormValue("c")
 564	u := login.GetUserInfo(r)
 565	honks := gethonksbyconvoy(u.UserID, c)
 566	templinfo := getInfo(r)
 567	templinfo["ServerMessage"] = "honks in convoy: " + c
 568	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 569	honkpage(w, u, honks, templinfo)
 570}
 571func showsearch(w http.ResponseWriter, r *http.Request) {
 572	q := r.FormValue("q")
 573	u := login.GetUserInfo(r)
 574	honks := gethonksbysearch(u.UserID, q)
 575	templinfo := getInfo(r)
 576	templinfo["ServerMessage"] = "honks for search: " + q
 577	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 578	honkpage(w, u, honks, templinfo)
 579}
 580func showontology(w http.ResponseWriter, r *http.Request) {
 581	name := mux.Vars(r)["name"]
 582	u := login.GetUserInfo(r)
 583	var userid int64 = -1
 584	if u != nil {
 585		userid = u.UserID
 586	}
 587	honks := gethonksbyontology(userid, "#"+name)
 588	templinfo := getInfo(r)
 589	templinfo["ServerMessage"] = "honks by ontology: " + name
 590	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 591	honkpage(w, u, honks, templinfo)
 592}
 593
 594func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
 595	u := login.GetUserInfo(r)
 596	var userid int64 = -1
 597	if u != nil {
 598		userid = u.UserID
 599	}
 600	rows, err := stmtSelectOnts.Query(userid)
 601	if err != nil {
 602		log.Printf("selection error: %s", err)
 603		return
 604	}
 605	defer rows.Close()
 606	var onts [][]string
 607	for rows.Next() {
 608		var o string
 609		err := rows.Scan(&o)
 610		if err != nil {
 611			log.Printf("error scanning ont: %s", err)
 612			continue
 613		}
 614		onts = append(onts, []string{o, o[1:]})
 615	}
 616	if u == nil {
 617		w.Header().Set("Cache-Control", "max-age=300")
 618	}
 619	templinfo := getInfo(r)
 620	templinfo["Onts"] = onts
 621	err = readviews.Execute(w, "onts.html", templinfo)
 622	if err != nil {
 623		log.Print(err)
 624	}
 625}
 626
 627func showhonk(w http.ResponseWriter, r *http.Request) {
 628	name := mux.Vars(r)["name"]
 629	user, err := butwhatabout(name)
 630	if err != nil {
 631		http.NotFound(w, r)
 632		return
 633	}
 634	if stealthmode(user.ID, r) {
 635		http.NotFound(w, r)
 636		return
 637	}
 638
 639	xid := fmt.Sprintf("https://%s%s", serverName, r.URL.Path)
 640	honk := getxonk(user.ID, xid)
 641	if honk == nil {
 642		http.NotFound(w, r)
 643		return
 644	}
 645	u := login.GetUserInfo(r)
 646	if u != nil && u.UserID != user.ID {
 647		u = nil
 648	}
 649	if !honk.Public {
 650		if u == nil {
 651			http.NotFound(w, r)
 652			return
 653
 654		}
 655		templinfo := getInfo(r)
 656		templinfo["ServerMessage"] = "one honk maybe more"
 657		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 658		honkpage(w, u, []*Honk{honk}, templinfo)
 659		return
 660	}
 661	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
 662	if friendorfoe(r.Header.Get("Accept")) {
 663		for _, h := range rawhonks {
 664			if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
 665				honk.Replies = append(honk.Replies, h)
 666			}
 667		}
 668		donksforhonks([]*Honk{honk})
 669		_, j := jonkjonk(user, honk)
 670		j["@context"] = itiswhatitis
 671		w.Header().Set("Content-Type", theonetruename)
 672		j.Write(w)
 673		return
 674	}
 675	var honks []*Honk
 676	for _, h := range rawhonks {
 677		if h.Public && (h.Whofore == 2 || h.IsAcked()) {
 678			honks = append(honks, h)
 679		}
 680	}
 681
 682	templinfo := getInfo(r)
 683	templinfo["ServerMessage"] = "one honk maybe more"
 684	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 685	honkpage(w, u, honks, templinfo)
 686}
 687
 688func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
 689	var userid int64 = -1
 690	if u != nil {
 691		userid = u.UserID
 692	}
 693	if u == nil {
 694		w.Header().Set("Cache-Control", "max-age=60")
 695	}
 696	reverbolate(userid, honks)
 697	templinfo["Honks"] = honks
 698	err := readviews.Execute(w, "honkpage.html", templinfo)
 699	if err != nil {
 700		log.Print(err)
 701	}
 702}
 703
 704func saveuser(w http.ResponseWriter, r *http.Request) {
 705	whatabout := r.FormValue("whatabout")
 706	u := login.GetUserInfo(r)
 707	db := opendatabase()
 708	options := ""
 709	if r.FormValue("skinny") == "skinny" {
 710		options += " skinny "
 711	}
 712	_, err := db.Exec("update users set about = ?, options = ? where username = ?", whatabout, options, u.Username)
 713	if err != nil {
 714		log.Printf("error bouting what: %s", err)
 715	}
 716
 717	http.Redirect(w, r, "/account", http.StatusSeeOther)
 718}
 719
 720func submitbonk(w http.ResponseWriter, r *http.Request) {
 721	xid := r.FormValue("xid")
 722	userinfo := login.GetUserInfo(r)
 723	user, _ := butwhatabout(userinfo.Username)
 724
 725	log.Printf("bonking %s", xid)
 726
 727	xonk := getxonk(userinfo.UserID, xid)
 728	if xonk == nil {
 729		return
 730	}
 731	if !xonk.Public {
 732		return
 733	}
 734	donksforhonks([]*Honk{xonk})
 735
 736	_, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
 737	if err != nil {
 738		log.Printf("error acking bonk: %s", err)
 739	}
 740
 741	oonker := xonk.Oonker
 742	if oonker == "" {
 743		oonker = xonk.Honker
 744	}
 745	dt := time.Now().UTC()
 746	bonk := Honk{
 747		UserID:   userinfo.UserID,
 748		Username: userinfo.Username,
 749		What:     "bonk",
 750		Honker:   user.URL,
 751		Oonker:   oonker,
 752		XID:      xonk.XID,
 753		RID:      xonk.RID,
 754		Noise:    xonk.Noise,
 755		Precis:   xonk.Precis,
 756		URL:      xonk.URL,
 757		Date:     dt,
 758		Donks:    xonk.Donks,
 759		Whofore:  2,
 760		Convoy:   xonk.Convoy,
 761		Audience: []string{thewholeworld, oonker},
 762		Public:   true,
 763	}
 764
 765	bonk.Format = "html"
 766
 767	err = savehonk(&bonk)
 768	if err != nil {
 769		log.Printf("uh oh")
 770		return
 771	}
 772
 773	go honkworldwide(user, &bonk)
 774}
 775
 776func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string) {
 777	zonk := Honk{
 778		What:     what,
 779		XID:      xonk.XID,
 780		Date:     time.Now().UTC(),
 781		Audience: oneofakind(xonk.Audience),
 782	}
 783	zonk.Public = !keepitquiet(zonk.Audience)
 784
 785	log.Printf("announcing %sed honk: %s", what, xonk.XID)
 786	go honkworldwide(user, &zonk)
 787}
 788
 789func zonkit(w http.ResponseWriter, r *http.Request) {
 790	wherefore := r.FormValue("wherefore")
 791	what := r.FormValue("what")
 792	userinfo := login.GetUserInfo(r)
 793	user, _ := butwhatabout(userinfo.Username)
 794
 795	if wherefore == "ack" {
 796		xonk := getxonk(userinfo.UserID, what)
 797		if xonk != nil {
 798			_, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
 799			if err != nil {
 800				log.Printf("error acking: %s", err)
 801			}
 802			sendzonkofsorts(xonk, user, "ack")
 803		}
 804		return
 805	}
 806
 807	if wherefore == "deack" {
 808		xonk := getxonk(userinfo.UserID, what)
 809		if xonk != nil {
 810			_, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
 811			if err != nil {
 812				log.Printf("error deacking: %s", err)
 813			}
 814			sendzonkofsorts(xonk, user, "deack")
 815		}
 816		return
 817	}
 818
 819	if wherefore == "unbonk" {
 820		xonk := getbonk(userinfo.UserID, what)
 821		if xonk != nil {
 822			deletehonk(xonk.ID)
 823			xonk = getxonk(userinfo.UserID, what)
 824			_, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
 825			if err != nil {
 826				log.Printf("error unbonking: %s", err)
 827			}
 828			sendzonkofsorts(xonk, user, "unbonk")
 829		}
 830		return
 831	}
 832
 833	log.Printf("zonking %s %s", wherefore, what)
 834	if wherefore == "zonk" {
 835		xonk := getxonk(userinfo.UserID, what)
 836		if xonk != nil {
 837			deletehonk(xonk.ID)
 838			if xonk.Whofore == 2 || xonk.Whofore == 3 {
 839				sendzonkofsorts(xonk, user, "zonk")
 840			}
 841		}
 842	}
 843	_, err := stmtSaveZonker.Exec(userinfo.UserID, what, wherefore)
 844	if err != nil {
 845		log.Printf("error saving zonker: %s", err)
 846		return
 847	}
 848}
 849
 850func edithonkpage(w http.ResponseWriter, r *http.Request) {
 851	u := login.GetUserInfo(r)
 852	user, _ := butwhatabout(u.Username)
 853	xid := r.FormValue("xid")
 854	honk := getxonk(u.UserID, xid)
 855	if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 856		log.Printf("no edit")
 857		return
 858	}
 859
 860	noise := honk.Noise
 861	if honk.Precis != "" {
 862		noise = honk.Precis + "\n\n" + noise
 863	}
 864
 865	honks := []*Honk{honk}
 866	donksforhonks(honks)
 867	reverbolate(u.UserID, honks)
 868	templinfo := getInfo(r)
 869	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
 870	templinfo["Honks"] = honks
 871	templinfo["Noise"] = noise
 872	templinfo["ServerMessage"] = "honk edit"
 873	templinfo["UpdateXID"] = honk.XID
 874	if len(honk.Donks) > 0 {
 875		templinfo["SavedFile"] = honk.Donks[0].XID
 876	}
 877	err := readviews.Execute(w, "honkpage.html", templinfo)
 878	if err != nil {
 879		log.Print(err)
 880	}
 881}
 882
 883// what a hot mess this function is
 884func submithonk(w http.ResponseWriter, r *http.Request) {
 885	rid := r.FormValue("rid")
 886	noise := r.FormValue("noise")
 887
 888	userinfo := login.GetUserInfo(r)
 889	user, _ := butwhatabout(userinfo.Username)
 890
 891	dt := time.Now().UTC()
 892	updatexid := r.FormValue("updatexid")
 893	var honk *Honk
 894	if updatexid != "" {
 895		honk = getxonk(userinfo.UserID, updatexid)
 896		if honk == nil || honk.Honker != user.URL || honk.What != "honk" {
 897			log.Printf("not saving edit")
 898			return
 899		}
 900		honk.Date = dt
 901		honk.What = "update"
 902		honk.Format = "markdown"
 903	} else {
 904		xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
 905		what := "honk"
 906		if rid != "" {
 907			what = "tonk"
 908		}
 909		honk = &Honk{
 910			UserID:   userinfo.UserID,
 911			Username: userinfo.Username,
 912			What:     what,
 913			Honker:   user.URL,
 914			XID:      xid,
 915			Date:     dt,
 916			Format:   "markdown",
 917		}
 918	}
 919
 920	noise = hooterize(noise)
 921	honk.Noise = noise
 922	translate(honk)
 923
 924	var convoy string
 925	if rid != "" {
 926		xonk := getxonk(userinfo.UserID, rid)
 927		if xonk != nil {
 928			if xonk.Public {
 929				honk.Audience = append(honk.Audience, xonk.Audience...)
 930			}
 931			convoy = xonk.Convoy
 932		} else {
 933			xonkaud, c := whosthere(rid)
 934			honk.Audience = append(honk.Audience, xonkaud...)
 935			convoy = c
 936		}
 937		for i, a := range honk.Audience {
 938			if a == thewholeworld {
 939				honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
 940				break
 941			}
 942		}
 943		honk.RID = rid
 944	} else {
 945		honk.Audience = []string{thewholeworld}
 946	}
 947	if honk.Noise != "" && honk.Noise[0] == '@' {
 948		honk.Audience = append(grapevine(honk.Noise), honk.Audience...)
 949	} else {
 950		honk.Audience = append(honk.Audience, grapevine(honk.Noise)...)
 951	}
 952
 953	if convoy == "" {
 954		convoy = "data:,electrichonkytonk-" + xfiltrate()
 955	}
 956	butnottooloud(honk.Audience)
 957	honk.Audience = oneofakind(honk.Audience)
 958	if len(honk.Audience) == 0 {
 959		log.Printf("honk to nowhere")
 960		http.Error(w, "honk to nowhere...", http.StatusNotFound)
 961		return
 962	}
 963	honk.Public = !keepitquiet(honk.Audience)
 964	honk.Convoy = convoy
 965
 966	donkxid := r.FormValue("donkxid")
 967	if donkxid == "" {
 968		file, filehdr, err := r.FormFile("donk")
 969		if err == nil {
 970			var buf bytes.Buffer
 971			io.Copy(&buf, file)
 972			file.Close()
 973			data := buf.Bytes()
 974			xid := xfiltrate()
 975			var media, name string
 976			img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
 977			if err == nil {
 978				data = img.Data
 979				format := img.Format
 980				media = "image/" + format
 981				if format == "jpeg" {
 982					format = "jpg"
 983				}
 984				name = xid + "." + format
 985				xid = name
 986			} else {
 987				maxsize := 100000
 988				if len(data) > maxsize {
 989					log.Printf("bad image: %s too much text: %d", err, len(data))
 990					http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
 991					return
 992				}
 993				for i := 0; i < len(data); i++ {
 994					if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
 995						log.Printf("bad image: %s not text: %d", err, data[i])
 996						http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
 997						return
 998					}
 999				}
1000				media = "text/plain"
1001				name = filehdr.Filename
1002				if name == "" {
1003					name = xid + ".txt"
1004				}
1005				xid += ".txt"
1006			}
1007			desc := r.FormValue("donkdesc")
1008			if desc == "" {
1009				desc = name
1010			}
1011			url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1012			fileid, err := savefile(xid, name, desc, url, media, true, data)
1013			if err != nil {
1014				log.Printf("unable to save image: %s", err)
1015				return
1016			}
1017			var d Donk
1018			d.FileID = fileid
1019			honk.Donks = append(honk.Donks, &d)
1020			donkxid = d.XID
1021		}
1022	} else {
1023		xid := donkxid
1024		url := fmt.Sprintf("https://%s/d/%s", serverName, xid)
1025		donk := finddonk(url)
1026		if donk != nil {
1027			honk.Donks = append(honk.Donks, donk)
1028		} else {
1029			log.Printf("can't find file: %s", xid)
1030		}
1031	}
1032	herd := herdofemus(honk.Noise)
1033	for _, e := range herd {
1034		donk := savedonk(e.ID, e.Name, e.Name, "image/png", true)
1035		if donk != nil {
1036			donk.Name = e.Name
1037			honk.Donks = append(honk.Donks, donk)
1038		}
1039	}
1040	memetize(honk)
1041
1042	placename := r.FormValue("placename")
1043	placelat := r.FormValue("placelat")
1044	placelong := r.FormValue("placelong")
1045	if placename != "" || placelat != "" || placelong != "" {
1046		p := new(Place)
1047		p.Name = placename
1048		p.Latitude, _ = strconv.ParseFloat(placelat, 64)
1049		p.Longitude, _ = strconv.ParseFloat(placelong, 64)
1050		p.Url = r.FormValue("placeurl")
1051		honk.Place = p
1052	}
1053	timestart := r.FormValue("timestart")
1054	if timestart != "" {
1055		t := new(Time)
1056		now := time.Now().Local()
1057		for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
1058			start, err := time.ParseInLocation(layout, timestart, now.Location())
1059			if err == nil {
1060				if start.Year() == 0 {
1061					start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
1062				}
1063				t.StartTime = start
1064				break
1065			}
1066		}
1067		timeend := r.FormValue("timeend")
1068		dur, err := time.ParseDuration(timeend)
1069		if err == nil {
1070			t.Duration = Duration(dur)
1071		}
1072		if !t.StartTime.IsZero() {
1073			honk.What = "event"
1074			honk.Time = t
1075		}
1076	}
1077
1078	if honk.Public {
1079		honk.Whofore = 2
1080	} else {
1081		honk.Whofore = 3
1082	}
1083
1084	// back to markdown
1085	honk.Noise = noise
1086
1087	if r.FormValue("preview") == "preview" {
1088		honks := []*Honk{honk}
1089		reverbolate(userinfo.UserID, honks)
1090		templinfo := getInfo(r)
1091		templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1092		templinfo["Honks"] = honks
1093		templinfo["InReplyTo"] = r.FormValue("rid")
1094		templinfo["Noise"] = r.FormValue("noise")
1095		templinfo["SavedFile"] = donkxid
1096		templinfo["ServerMessage"] = "honk preview"
1097		err := readviews.Execute(w, "honkpage.html", templinfo)
1098		if err != nil {
1099			log.Print(err)
1100		}
1101		return
1102	}
1103
1104	if updatexid != "" {
1105		updatehonk(honk)
1106	} else {
1107		err := savehonk(honk)
1108		if err != nil {
1109			log.Printf("uh oh")
1110			return
1111		}
1112	}
1113
1114	// reload for consistency
1115	honk.Donks = nil
1116	donksforhonks([]*Honk{honk})
1117
1118	go honkworldwide(user, honk)
1119
1120	http.Redirect(w, r, honk.XID, http.StatusSeeOther)
1121}
1122
1123func showhonkers(w http.ResponseWriter, r *http.Request) {
1124	userinfo := login.GetUserInfo(r)
1125	templinfo := getInfo(r)
1126	templinfo["Honkers"] = gethonkers(userinfo.UserID)
1127	templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
1128	err := readviews.Execute(w, "honkers.html", templinfo)
1129	if err != nil {
1130		log.Print(err)
1131	}
1132}
1133
1134var combocache = cacheNew(func(key interface{}) (interface{}, bool) {
1135	userid := key.(int64)
1136	honkers := gethonkers(userid)
1137	var combos []string
1138	for _, h := range honkers {
1139		combos = append(combos, h.Combos...)
1140	}
1141	for i, c := range combos {
1142		if c == "-" {
1143			combos[i] = ""
1144		}
1145	}
1146	combos = oneofakind(combos)
1147	sort.Strings(combos)
1148	return combos, true
1149})
1150
1151func showcombos(w http.ResponseWriter, r *http.Request) {
1152	userinfo := login.GetUserInfo(r)
1153	var combos []string
1154	combocache.Get(userinfo.UserID, &combos)
1155	templinfo := getInfo(r)
1156	err := readviews.Execute(w, "combos.html", templinfo)
1157	if err != nil {
1158		log.Print(err)
1159	}
1160}
1161
1162func submithonker(w http.ResponseWriter, r *http.Request) {
1163	u := login.GetUserInfo(r)
1164	name := r.FormValue("name")
1165	url := r.FormValue("url")
1166	peep := r.FormValue("peep")
1167	combos := r.FormValue("combos")
1168	honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
1169
1170	defer combocache.Clear(u.UserID)
1171
1172	if honkerid > 0 {
1173		goodbye := r.FormValue("goodbye")
1174		if goodbye == "F" {
1175			db := opendatabase()
1176			row := db.QueryRow("select xid from honkers where honkerid = ? and userid = ?",
1177				honkerid, u.UserID)
1178			var xid string
1179			err := row.Scan(&xid)
1180			if err != nil {
1181				log.Printf("can't get honker xid: %s", err)
1182				return
1183			}
1184			log.Printf("unsubscribing from %s", xid)
1185			user, _ := butwhatabout(u.Username)
1186			go itakeitallback(user, xid)
1187			_, err = stmtUpdateFlavor.Exec("unsub", u.UserID, xid, "sub")
1188			if err != nil {
1189				log.Printf("error updating honker: %s", err)
1190				return
1191			}
1192
1193			http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1194			return
1195		}
1196		combos = " " + strings.TrimSpace(combos) + " "
1197		_, err := stmtUpdateCombos.Exec(combos, honkerid, u.UserID)
1198		if err != nil {
1199			log.Printf("update honker err: %s", err)
1200			return
1201		}
1202		http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1203		return
1204	}
1205
1206	flavor := "presub"
1207	if peep == "peep" {
1208		flavor = "peep"
1209	}
1210	p, err := investigate(url)
1211	if err != nil {
1212		http.Error(w, "error investigating: "+err.Error(), http.StatusInternalServerError)
1213		log.Printf("failed to investigate honker")
1214		return
1215	}
1216	url = p.XID
1217	if name == "" {
1218		name = p.Handle
1219	}
1220	_, err = stmtSaveHonker.Exec(u.UserID, name, url, flavor, combos)
1221	if err != nil {
1222		log.Print(err)
1223		return
1224	}
1225	if flavor == "presub" {
1226		user, _ := butwhatabout(u.Username)
1227		go subsub(user, url)
1228	}
1229	http.Redirect(w, r, "/honkers", http.StatusSeeOther)
1230}
1231
1232func zonkzone(w http.ResponseWriter, r *http.Request) {
1233	userinfo := login.GetUserInfo(r)
1234	rows, err := stmtGetZonkers.Query(userinfo.UserID)
1235	if err != nil {
1236		log.Printf("err: %s", err)
1237		return
1238	}
1239	defer rows.Close()
1240	var zonkers []Zonker
1241	for rows.Next() {
1242		var z Zonker
1243		rows.Scan(&z.ID, &z.Name, &z.Wherefore)
1244		zonkers = append(zonkers, z)
1245	}
1246	sort.Slice(zonkers, func(i, j int) bool {
1247		w1 := zonkers[i].Wherefore
1248		w2 := zonkers[j].Wherefore
1249		if w1 == w2 {
1250			return zonkers[i].Name < zonkers[j].Name
1251		}
1252		if w1 == "zonvoy" {
1253			w1 = "zzzzzzz"
1254		}
1255		if w2 == "zonvoy" {
1256			w2 = "zzzzzzz"
1257		}
1258		return w1 < w2
1259	})
1260
1261	templinfo := getInfo(r)
1262	templinfo["Zonkers"] = zonkers
1263	templinfo["ZonkCSRF"] = login.GetCSRF("zonkzonk", r)
1264	err = readviews.Execute(w, "zonkers.html", templinfo)
1265	if err != nil {
1266		log.Print(err)
1267	}
1268}
1269
1270func zonkzonk(w http.ResponseWriter, r *http.Request) {
1271	userinfo := login.GetUserInfo(r)
1272	itsok := r.FormValue("itsok")
1273	if itsok == "iforgiveyou" {
1274		zonkerid, _ := strconv.ParseInt(r.FormValue("zonkerid"), 10, 0)
1275		db := opendatabase()
1276		db.Exec("delete from zonkers where userid = ? and zonkerid = ?",
1277			userinfo.UserID, zonkerid)
1278		bitethethumbs()
1279		http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1280		return
1281	}
1282	wherefore := r.FormValue("wherefore")
1283	name := r.FormValue("name")
1284	if name == "" {
1285		return
1286	}
1287	switch wherefore {
1288	case "zonker":
1289	case "zomain":
1290	case "zonvoy":
1291	case "zord":
1292	case "zilence":
1293	case "zoggle":
1294	default:
1295		return
1296	}
1297	db := opendatabase()
1298	db.Exec("insert into zonkers (userid, name, wherefore) values (?, ?, ?)",
1299		userinfo.UserID, name, wherefore)
1300
1301	if wherefore != "zonvoy" {
1302		bitethethumbs()
1303	}
1304
1305	http.Redirect(w, r, "/zonkzone", http.StatusSeeOther)
1306}
1307
1308func accountpage(w http.ResponseWriter, r *http.Request) {
1309	u := login.GetUserInfo(r)
1310	user, _ := butwhatabout(u.Username)
1311	templinfo := getInfo(r)
1312	templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
1313	templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
1314	templinfo["User"] = user
1315	err := readviews.Execute(w, "account.html", templinfo)
1316	if err != nil {
1317		log.Print(err)
1318	}
1319}
1320
1321func dochpass(w http.ResponseWriter, r *http.Request) {
1322	err := login.ChangePassword(w, r)
1323	if err != nil {
1324		log.Printf("error changing password: %s", err)
1325	}
1326	http.Redirect(w, r, "/account", http.StatusSeeOther)
1327}
1328
1329func fingerlicker(w http.ResponseWriter, r *http.Request) {
1330	orig := r.FormValue("resource")
1331
1332	log.Printf("finger lick: %s", orig)
1333
1334	if strings.HasPrefix(orig, "acct:") {
1335		orig = orig[5:]
1336	}
1337
1338	name := orig
1339	idx := strings.LastIndexByte(name, '/')
1340	if idx != -1 {
1341		name = name[idx+1:]
1342		if fmt.Sprintf("https://%s/%s/%s", serverName, userSep, name) != orig {
1343			log.Printf("foreign request rejected")
1344			name = ""
1345		}
1346	} else {
1347		idx = strings.IndexByte(name, '@')
1348		if idx != -1 {
1349			name = name[:idx]
1350			if name+"@"+serverName != orig {
1351				log.Printf("foreign request rejected")
1352				name = ""
1353			}
1354		}
1355	}
1356	user, err := butwhatabout(name)
1357	if err != nil {
1358		http.NotFound(w, r)
1359		return
1360	}
1361	if stealthmode(user.ID, r) {
1362		http.NotFound(w, r)
1363		return
1364	}
1365
1366	j := junk.New()
1367	j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, serverName)
1368	j["aliases"] = []string{user.URL}
1369	var links []junk.Junk
1370	l := junk.New()
1371	l["rel"] = "self"
1372	l["type"] = `application/activity+json`
1373	l["href"] = user.URL
1374	links = append(links, l)
1375	j["links"] = links
1376
1377	w.Header().Set("Cache-Control", "max-age=3600")
1378	w.Header().Set("Content-Type", "application/jrd+json")
1379	j.Write(w)
1380}
1381
1382func somedays() string {
1383	secs := 432000 + notrand.Int63n(432000)
1384	return fmt.Sprintf("%d", secs)
1385}
1386
1387func avatate(w http.ResponseWriter, r *http.Request) {
1388	n := r.FormValue("a")
1389	a := avatar(n)
1390	w.Header().Set("Cache-Control", "max-age="+somedays())
1391	w.Write(a)
1392}
1393
1394func servecss(w http.ResponseWriter, r *http.Request) {
1395	fd, err := os.Open("views" + r.URL.Path)
1396	if err != nil {
1397		http.NotFound(w, r)
1398		return
1399	}
1400	w.Header().Set("Cache-Control", "max-age=0")
1401	w.Header().Set("Content-Type", "text/css; charset=utf-8")
1402	err = css.Filter(fd, w)
1403	if err != nil {
1404		log.Printf("error filtering css: %s", err)
1405	}
1406}
1407func serveasset(w http.ResponseWriter, r *http.Request) {
1408	w.Header().Set("Cache-Control", "max-age=7776000")
1409	http.ServeFile(w, r, "views"+r.URL.Path)
1410}
1411func servehtml(w http.ResponseWriter, r *http.Request) {
1412	templinfo := getInfo(r)
1413	err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
1414	if err != nil {
1415		log.Print(err)
1416	}
1417}
1418func serveemu(w http.ResponseWriter, r *http.Request) {
1419	xid := mux.Vars(r)["xid"]
1420	w.Header().Set("Cache-Control", "max-age="+somedays())
1421	http.ServeFile(w, r, "emus/"+xid)
1422}
1423func servememe(w http.ResponseWriter, r *http.Request) {
1424	xid := mux.Vars(r)["xid"]
1425	w.Header().Set("Cache-Control", "max-age="+somedays())
1426	http.ServeFile(w, r, "memes/"+xid)
1427}
1428
1429func servefile(w http.ResponseWriter, r *http.Request) {
1430	xid := mux.Vars(r)["xid"]
1431	row := stmtGetFileData.QueryRow(xid)
1432	var media string
1433	var data []byte
1434	err := row.Scan(&media, &data)
1435	if err != nil {
1436		log.Printf("error loading file: %s", err)
1437		http.NotFound(w, r)
1438		return
1439	}
1440	w.Header().Set("Content-Type", media)
1441	w.Header().Set("X-Content-Type-Options", "nosniff")
1442	w.Header().Set("Cache-Control", "max-age="+somedays())
1443	w.Write(data)
1444}
1445
1446func nomoroboto(w http.ResponseWriter, r *http.Request) {
1447	io.WriteString(w, "User-agent: *\n")
1448	io.WriteString(w, "Disallow: /a\n")
1449	io.WriteString(w, "Disallow: /d\n")
1450	io.WriteString(w, "Disallow: /meme\n")
1451	for _, u := range allusers() {
1452		fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
1453	}
1454}
1455
1456func webhydra(w http.ResponseWriter, r *http.Request) {
1457	u := login.GetUserInfo(r)
1458	userid := u.UserID
1459	templinfo := getInfo(r)
1460	templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1461	page := r.FormValue("page")
1462	var honks []*Honk
1463	switch page {
1464	case "atme":
1465		honks = gethonksforme(userid)
1466	case "home":
1467		honks = gethonksforuser(userid)
1468		honks = osmosis(honks, userid)
1469	case "first":
1470		honks = gethonksforuserfirstclass(userid)
1471		honks = osmosis(honks, userid)
1472	case "combo":
1473		c := r.FormValue("c")
1474		honks = gethonksbycombo(userid, c)
1475	case "convoy":
1476		c := r.FormValue("c")
1477		honks = gethonksbyconvoy(userid, c)
1478	case "honker":
1479		xid := r.FormValue("xid")
1480		if strings.IndexByte(xid, '@') != -1 {
1481			xid = gofish(xid)
1482		}
1483		honks = gethonksbyxonker(userid, xid)
1484	default:
1485		http.NotFound(w, r)
1486	}
1487	if len(honks) > 0 {
1488		templinfo["TopXID"] = honks[0].XID
1489	}
1490	if topxid := r.FormValue("topxid"); topxid != "" {
1491		for i, h := range honks {
1492			if h.XID == topxid {
1493				honks = honks[0:i]
1494				break
1495			}
1496		}
1497		log.Printf("topxid %d frags", len(honks))
1498	}
1499	reverbolate(userid, honks)
1500	templinfo["Honks"] = honks
1501	w.Header().Set("Content-Type", "text/html; charset=utf-8")
1502	err := readviews.Execute(w, "honkfrags.html", templinfo)
1503	if err != nil {
1504		log.Printf("frag error: %s", err)
1505	}
1506}
1507
1508func serve() {
1509	db := opendatabase()
1510	login.Init(db)
1511
1512	listener, err := openListener()
1513	if err != nil {
1514		log.Fatal(err)
1515	}
1516	go redeliverator()
1517
1518	debug := false
1519	getconfig("debug", &debug)
1520	readviews = templates.Load(debug,
1521		"views/honkpage.html",
1522		"views/honkfrags.html",
1523		"views/honkers.html",
1524		"views/zonkers.html",
1525		"views/combos.html",
1526		"views/honkform.html",
1527		"views/honk.html",
1528		"views/account.html",
1529		"views/about.html",
1530		"views/funzone.html",
1531		"views/login.html",
1532		"views/xzone.html",
1533		"views/header.html",
1534		"views/onts.html",
1535		"views/honkpage.js",
1536	)
1537	if !debug {
1538		assets := []string{"views/style.css", "views/local.css", "views/honkpage.js"}
1539		for _, s := range assets {
1540			savedassetparams[s] = getassetparam(s)
1541		}
1542	}
1543
1544	bitethethumbs()
1545
1546	mux := mux.NewRouter()
1547	mux.Use(login.Checker)
1548
1549	posters := mux.Methods("POST").Subrouter()
1550	getters := mux.Methods("GET").Subrouter()
1551
1552	getters.HandleFunc("/", homepage)
1553	getters.HandleFunc("/home", homepage)
1554	getters.HandleFunc("/front", homepage)
1555	getters.HandleFunc("/robots.txt", nomoroboto)
1556	getters.HandleFunc("/rss", showrss)
1557	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}", showuser)
1558	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/"+honkSep+"/{xid:[[:alnum:]]+}", showhonk)
1559	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/rss", showrss)
1560	posters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/inbox", inbox)
1561	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/outbox", outbox)
1562	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/followers", emptiness)
1563	getters.HandleFunc("/"+userSep+"/{name:[[:alnum:]]+}/following", emptiness)
1564	getters.HandleFunc("/a", avatate)
1565	getters.HandleFunc("/o", thelistingoftheontologies)
1566	getters.HandleFunc("/o/{name:.+}", showontology)
1567	getters.HandleFunc("/d/{xid:[[:alnum:].]+}", servefile)
1568	getters.HandleFunc("/emu/{xid:[[:alnum:]_.-]+}", serveemu)
1569	getters.HandleFunc("/meme/{xid:[[:alnum:]_.-]+}", servememe)
1570	getters.HandleFunc("/.well-known/webfinger", fingerlicker)
1571
1572	getters.HandleFunc("/style.css", servecss)
1573	getters.HandleFunc("/local.css", servecss)
1574	getters.HandleFunc("/honkpage.js", serveasset)
1575	getters.HandleFunc("/about", servehtml)
1576	getters.HandleFunc("/login", servehtml)
1577	posters.HandleFunc("/dologin", login.LoginFunc)
1578	getters.HandleFunc("/logout", login.LogoutFunc)
1579
1580	loggedin := mux.NewRoute().Subrouter()
1581	loggedin.Use(login.Required)
1582	loggedin.HandleFunc("/account", accountpage)
1583	loggedin.HandleFunc("/funzone", showfunzone)
1584	loggedin.HandleFunc("/chpass", dochpass)
1585	loggedin.HandleFunc("/atme", homepage)
1586	loggedin.HandleFunc("/zonkzone", zonkzone)
1587	loggedin.HandleFunc("/xzone", xzone)
1588	loggedin.HandleFunc("/edit", edithonkpage)
1589	loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(submithonk)))
1590	loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
1591	loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
1592	loggedin.Handle("/zonkzonk", login.CSRFWrap("zonkzonk", http.HandlerFunc(zonkzonk)))
1593	loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
1594	loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
1595	loggedin.HandleFunc("/honkers", showhonkers)
1596	loggedin.HandleFunc("/h/{name:[[:alnum:]_.-]+}", showhonker)
1597	loggedin.HandleFunc("/h", showhonker)
1598	loggedin.HandleFunc("/c/{name:[[:alnum:]_.-]+}", showcombo)
1599	loggedin.HandleFunc("/c", showcombos)
1600	loggedin.HandleFunc("/t", showconvoy)
1601	loggedin.HandleFunc("/q", showsearch)
1602	loggedin.HandleFunc("/hydra", webhydra)
1603	loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(submithonker)))
1604
1605	err = http.Serve(listener, mux)
1606	if err != nil {
1607		log.Fatal(err)
1608	}
1609}