all repos — honk @ c1b667916623d437082ffe0eae2ba0e70a02670d

my fork of honk

activity.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	"context"
  21	"crypto/tls"
  22	"database/sql"
  23	"fmt"
  24	"html"
  25	"io"
  26	notrand "math/rand"
  27	"net/http"
  28	"net/url"
  29	"os"
  30	"regexp"
  31	"strings"
  32	"time"
  33
  34	"humungus.tedunangst.com/r/webs/cache"
  35	"humungus.tedunangst.com/r/webs/gate"
  36	"humungus.tedunangst.com/r/webs/httpsig"
  37	"humungus.tedunangst.com/r/webs/junk"
  38	"humungus.tedunangst.com/r/webs/templates"
  39)
  40
  41var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
  42var thefakename = `application/activity+json`
  43var falsenames = []string{
  44	`application/ld+json`,
  45	`application/activity+json`,
  46}
  47var itiswhatitis = "https://www.w3.org/ns/activitystreams"
  48var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
  49
  50var fastTimeout time.Duration = 5
  51var slowTimeout time.Duration = 30
  52
  53func friendorfoe(ct string) bool {
  54	ct = strings.ToLower(ct)
  55	for _, at := range falsenames {
  56		if strings.HasPrefix(ct, at) {
  57			return true
  58		}
  59	}
  60	return false
  61}
  62
  63var develClient = &http.Client{
  64	Transport: &http.Transport{
  65		TLSClientConfig: &tls.Config{
  66			InsecureSkipVerify: true,
  67		},
  68	},
  69}
  70
  71func PostJunk(keyname string, key httpsig.PrivateKey, url string, j junk.Junk) error {
  72	return PostMsg(keyname, key, url, j.ToBytes())
  73}
  74
  75func PostMsg(keyname string, key httpsig.PrivateKey, url string, msg []byte) error {
  76	client := http.DefaultClient
  77	if develMode {
  78		client = develClient
  79	}
  80	req, err := http.NewRequest("POST", url, bytes.NewReader(msg))
  81	if err != nil {
  82		return err
  83	}
  84	req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName)
  85	req.Header.Set("Content-Type", theonetruename)
  86	httpsig.SignRequest(keyname, key, req, msg)
  87	ctx, cancel := context.WithTimeout(context.Background(), 2*slowTimeout*time.Second)
  88	defer cancel()
  89	req = req.WithContext(ctx)
  90	resp, err := client.Do(req)
  91	if err != nil {
  92		return err
  93	}
  94	resp.Body.Close()
  95	switch resp.StatusCode {
  96	case 200:
  97	case 201:
  98	case 202:
  99	default:
 100		return fmt.Errorf("http post status: %d", resp.StatusCode)
 101	}
 102	ilog.Printf("successful post: %s %d", url, resp.StatusCode)
 103	return nil
 104}
 105
 106func GetJunk(userid int64, url string) (junk.Junk, error) {
 107	return GetJunkTimeout(userid, url, slowTimeout*time.Second)
 108}
 109
 110func GetJunkFast(userid int64, url string) (junk.Junk, error) {
 111	return GetJunkTimeout(userid, url, fastTimeout*time.Second)
 112}
 113
 114func GetJunkHardMode(userid int64, url string) (junk.Junk, error) {
 115	j, err := GetJunk(userid, url)
 116	if err != nil {
 117		emsg := err.Error()
 118		if emsg == "http get status: 502" || strings.Contains(emsg, "timeout") {
 119			ilog.Printf("trying again after error: %s", emsg)
 120			time.Sleep(time.Duration(60+notrand.Int63n(60)) * time.Second)
 121			j, err = GetJunk(userid, url)
 122			if err != nil {
 123				ilog.Printf("still couldn't get it")
 124			} else {
 125				ilog.Printf("retry success!")
 126			}
 127		}
 128	}
 129	return j, err
 130}
 131
 132var flightdeck = gate.NewSerializer()
 133
 134var signGets = true
 135
 136func junkGet(userid int64, url string, args junk.GetArgs) (junk.Junk, error) {
 137	client := http.DefaultClient
 138	if args.Client != nil {
 139		client = args.Client
 140	}
 141	req, err := http.NewRequest("GET", url, nil)
 142	if err != nil {
 143		return nil, err
 144	}
 145	if args.Accept != "" {
 146		req.Header.Set("Accept", args.Accept)
 147	}
 148	if args.Agent != "" {
 149		req.Header.Set("User-Agent", args.Agent)
 150	}
 151	if signGets {
 152		var ki *KeyInfo
 153		ok := ziggies.Get(userid, &ki)
 154		if ok {
 155			httpsig.SignRequest(ki.keyname, ki.seckey, req, nil)
 156		}
 157	}
 158	if args.Timeout != 0 {
 159		ctx, cancel := context.WithTimeout(context.Background(), args.Timeout)
 160		defer cancel()
 161		req = req.WithContext(ctx)
 162	}
 163	resp, err := client.Do(req)
 164	if err != nil {
 165		return nil, err
 166	}
 167	defer resp.Body.Close()
 168
 169	if resp.StatusCode != 200 {
 170		return nil, fmt.Errorf("http get status: %d", resp.StatusCode)
 171	}
 172	return junk.Read(resp.Body)
 173}
 174
 175func GetJunkTimeout(userid int64, url string, timeout time.Duration) (junk.Junk, error) {
 176	client := http.DefaultClient
 177	if develMode {
 178		client = develClient
 179	}
 180	fn := func() (interface{}, error) {
 181		at := thefakename
 182		if strings.Contains(url, ".well-known/webfinger?resource") {
 183			at = "application/jrd+json"
 184		}
 185		j, err := junkGet(userid, url, junk.GetArgs{
 186			Accept:  at,
 187			Agent:   "honksnonk/5.0; " + serverName,
 188			Timeout: timeout,
 189			Client:  client,
 190		})
 191		return j, err
 192	}
 193
 194	ji, err := flightdeck.Call(url, fn)
 195	if err != nil {
 196		return nil, err
 197	}
 198	j := ji.(junk.Junk)
 199	return j, nil
 200}
 201
 202func fetchsome(url string) ([]byte, error) {
 203	client := http.DefaultClient
 204	if develMode {
 205		client = develClient
 206	}
 207	req, err := http.NewRequest("GET", url, nil)
 208	if err != nil {
 209		ilog.Printf("error fetching %s: %s", url, err)
 210		return nil, err
 211	}
 212	req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName)
 213	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
 214	defer cancel()
 215	req = req.WithContext(ctx)
 216	resp, err := client.Do(req)
 217	if err != nil {
 218		ilog.Printf("error fetching %s: %s", url, err)
 219		return nil, err
 220	}
 221	defer resp.Body.Close()
 222	switch resp.StatusCode {
 223	case 200:
 224	case 201:
 225	case 202:
 226	default:
 227		return nil, fmt.Errorf("http get not 200: %d %s", resp.StatusCode, url)
 228	}
 229	var buf bytes.Buffer
 230	limiter := io.LimitReader(resp.Body, 10*1024*1024)
 231	io.Copy(&buf, limiter)
 232	return buf.Bytes(), nil
 233}
 234
 235func savedonk(url string, name, desc, media string, localize bool) *Donk {
 236	if url == "" {
 237		return nil
 238	}
 239	if donk := finddonk(url); donk != nil {
 240		return donk
 241	}
 242	ilog.Printf("saving donk: %s", url)
 243	data := []byte{}
 244	if localize {
 245		fn := func() (interface{}, error) {
 246			return fetchsome(url)
 247		}
 248		ii, err := flightdeck.Call(url, fn)
 249		if err != nil {
 250			ilog.Printf("error fetching donk: %s", err)
 251			localize = false
 252			goto saveit
 253		}
 254		data = ii.([]byte)
 255
 256		if len(data) == 10*1024*1024 {
 257			ilog.Printf("truncation likely")
 258		}
 259		if strings.HasPrefix(media, "image") {
 260			img, err := shrinkit(data)
 261			if err != nil {
 262				ilog.Printf("unable to decode image: %s", err)
 263				localize = false
 264				data = []byte{}
 265				goto saveit
 266			}
 267			data = img.Data
 268			media = "image/" + img.Format
 269		} else if media == "application/pdf" {
 270			if len(data) > 1000000 {
 271				ilog.Printf("not saving large pdf")
 272				localize = false
 273				data = []byte{}
 274			}
 275		} else if len(data) > 100000 {
 276			ilog.Printf("not saving large attachment")
 277			localize = false
 278			data = []byte{}
 279		}
 280	}
 281saveit:
 282	fileid, err := savefile(name, desc, url, media, localize, data)
 283	if err != nil {
 284		elog.Printf("error saving file %s: %s", url, err)
 285		return nil
 286	}
 287	donk := new(Donk)
 288	donk.FileID = fileid
 289	return donk
 290}
 291
 292func iszonked(userid int64, xid string) bool {
 293	var id int64
 294	row := stmtFindZonk.QueryRow(userid, xid)
 295	err := row.Scan(&id)
 296	if err == nil {
 297		return true
 298	}
 299	if err != sql.ErrNoRows {
 300		ilog.Printf("error querying zonk: %s", err)
 301	}
 302	return false
 303}
 304
 305func needxonk(user *WhatAbout, x *Honk) bool {
 306	if rejectxonk(x) {
 307		return false
 308	}
 309	return needxonkid(user, x.XID)
 310}
 311func needbonkid(user *WhatAbout, xid string) bool {
 312	return needxonkidX(user, xid, true)
 313}
 314func needxonkid(user *WhatAbout, xid string) bool {
 315	return needxonkidX(user, xid, false)
 316}
 317func needxonkidX(user *WhatAbout, xid string, isannounce bool) bool {
 318	if !strings.HasPrefix(xid, "https://") {
 319		return false
 320	}
 321	if strings.HasPrefix(xid, user.URL+"/") {
 322		return false
 323	}
 324	if rejectorigin(user.ID, xid, isannounce) {
 325		ilog.Printf("rejecting origin: %s", xid)
 326		return false
 327	}
 328	if iszonked(user.ID, xid) {
 329		ilog.Printf("already zonked: %s", xid)
 330		return false
 331	}
 332	var id int64
 333	row := stmtFindXonk.QueryRow(user.ID, xid)
 334	err := row.Scan(&id)
 335	if err == nil {
 336		return false
 337	}
 338	if err != sql.ErrNoRows {
 339		ilog.Printf("error querying xonk: %s", err)
 340	}
 341	return true
 342}
 343
 344func eradicatexonk(userid int64, xid string) {
 345	xonk := getxonk(userid, xid)
 346	if xonk != nil {
 347		deletehonk(xonk.ID)
 348	}
 349	_, err := stmtSaveZonker.Exec(userid, xid, "zonk")
 350	if err != nil {
 351		elog.Printf("error eradicating: %s", err)
 352	}
 353}
 354
 355func savexonk(x *Honk) {
 356	ilog.Printf("saving xonk: %s", x.XID)
 357	go handles(x.Honker)
 358	go handles(x.Oonker)
 359	savehonk(x)
 360}
 361
 362type Box struct {
 363	In     string
 364	Out    string
 365	Shared string
 366}
 367
 368var boxofboxes = cache.New(cache.Options{Filler: func(ident string) (*Box, bool) {
 369	var info string
 370	row := stmtGetXonker.QueryRow(ident, "boxes")
 371	err := row.Scan(&info)
 372	if err != nil {
 373		dlog.Printf("need to get boxes for %s", ident)
 374		var j junk.Junk
 375		j, err = GetJunk(readyLuserOne, ident)
 376		if err != nil {
 377			dlog.Printf("error getting boxes: %s", err)
 378			return nil, false
 379		}
 380		allinjest(originate(ident), j)
 381		row = stmtGetXonker.QueryRow(ident, "boxes")
 382		err = row.Scan(&info)
 383	}
 384	if err == nil {
 385		m := strings.Split(info, " ")
 386		b := &Box{In: m[0], Out: m[1], Shared: m[2]}
 387		return b, true
 388	}
 389	return nil, false
 390}})
 391
 392func gimmexonks(user *WhatAbout, outbox string) {
 393	dlog.Printf("getting outbox: %s", outbox)
 394	j, err := GetJunk(user.ID, outbox)
 395	if err != nil {
 396		ilog.Printf("error getting outbox: %s", err)
 397		return
 398	}
 399	t, _ := j.GetString("type")
 400	origin := originate(outbox)
 401	if t == "OrderedCollection" {
 402		items, _ := j.GetArray("orderedItems")
 403		if items == nil {
 404			items, _ = j.GetArray("items")
 405		}
 406		if items == nil {
 407			obj, ok := j.GetMap("first")
 408			if ok {
 409				items, _ = obj.GetArray("orderedItems")
 410			} else {
 411				page1, ok := j.GetString("first")
 412				if ok {
 413					j, err = GetJunk(user.ID, page1)
 414					if err != nil {
 415						ilog.Printf("error getting page1: %s", err)
 416						return
 417					}
 418					items, _ = j.GetArray("orderedItems")
 419				}
 420			}
 421		}
 422		if len(items) > 20 {
 423			items = items[0:20]
 424		}
 425		for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
 426			items[i], items[j] = items[j], items[i]
 427		}
 428		for _, item := range items {
 429			obj, ok := item.(junk.Junk)
 430			if ok {
 431				xonksaver(user, obj, origin)
 432				continue
 433			}
 434			xid, ok := item.(string)
 435			if ok {
 436				if !needxonkid(user, xid) {
 437					continue
 438				}
 439				obj, err = GetJunk(user.ID, xid)
 440				if err != nil {
 441					ilog.Printf("error getting item: %s", err)
 442					continue
 443				}
 444				xonksaver(user, obj, originate(xid))
 445			}
 446		}
 447	}
 448}
 449
 450func newphone(a []string, obj junk.Junk) []string {
 451	for _, addr := range []string{"to", "cc", "attributedTo"} {
 452		who, _ := obj.GetString(addr)
 453		if who != "" {
 454			a = append(a, who)
 455		}
 456		whos, _ := obj.GetArray(addr)
 457		for _, w := range whos {
 458			who, _ := w.(string)
 459			if who != "" {
 460				a = append(a, who)
 461			}
 462		}
 463	}
 464	return a
 465}
 466
 467func extractattrto(obj junk.Junk) string {
 468	who, _ := obj.GetString("attributedTo")
 469	if who != "" {
 470		return who
 471	}
 472	o, ok := obj.GetMap("attributedTo")
 473	if ok {
 474		id, ok := o.GetString("id")
 475		if ok {
 476			return id
 477		}
 478	}
 479	arr, _ := obj.GetArray("attributedTo")
 480	for _, a := range arr {
 481		o, ok := a.(junk.Junk)
 482		if ok {
 483			t, _ := o.GetString("type")
 484			id, _ := o.GetString("id")
 485			if t == "Person" || t == "" {
 486				return id
 487			}
 488		}
 489		s, ok := a.(string)
 490		if ok {
 491			return s
 492		}
 493	}
 494	return ""
 495}
 496
 497func firstofmany(obj junk.Junk, key string) string {
 498	if val, _ := obj.GetString(key); val != "" {
 499		return val
 500	}
 501	if arr, _ := obj.GetArray(key); len(arr) > 0 {
 502		val, ok := arr[0].(string)
 503		if ok {
 504			return val
 505		}
 506	}
 507	return ""
 508}
 509
 510var re_mast0link = regexp.MustCompile(`https://[[:alnum:].]+/users/[[:alnum:]]+/statuses/[[:digit:]]+`)
 511var re_masto1ink = regexp.MustCompile(`https://[[:alnum:].]+/@[[:alnum:]]+/[[:digit:]]+`)
 512var re_misslink = regexp.MustCompile(`https://[[:alnum:].]+/notes/[[:alnum:]]+`)
 513var re_honklink = regexp.MustCompile(`https://[[:alnum:].]+/u/[[:alnum:]]+/h/[[:alnum:]]+`)
 514var re_romalink = regexp.MustCompile(`https://[[:alnum:].]+/objects/[[:alnum:]-]+`)
 515var re_qtlinks = regexp.MustCompile(`>https://[^\s<]+<`)
 516
 517func qutify(user *WhatAbout, content string) string {
 518	// well this is gross
 519	malcontent := strings.ReplaceAll(content, `</span><span class="ellipsis">`, "")
 520	malcontent = strings.ReplaceAll(malcontent, `</span><span class="invisible">`, "")
 521	mlinks := re_qtlinks.FindAllString(malcontent, -1)
 522	for _, m := range mlinks {
 523		m = m[1 : len(m)-1]
 524		dlog.Printf("consider qt: %s", m)
 525		if re_mast0link.MatchString(m) ||
 526			re_masto1ink.MatchString(m) ||
 527			re_misslink.MatchString(m) ||
 528			re_honklink.MatchString(m) ||
 529			re_romalink.MatchString(m) {
 530			j, err := GetJunk(user.ID, m)
 531			dlog.Printf("fetched %s: %s", m, err)
 532			if err == nil {
 533				q, ok := j.GetString("content")
 534				if ok {
 535					content = fmt.Sprintf("%s<blockquote>%s</blockquote>", content, q)
 536				}
 537			}
 538		}
 539	}
 540	return content
 541}
 542
 543func xonksaver(user *WhatAbout, item junk.Junk, origin string) *Honk {
 544	depth := 0
 545	maxdepth := 10
 546	currenttid := ""
 547	goingup := 0
 548	var xonkxonkfn func(item junk.Junk, origin string, isUpdate bool) *Honk
 549
 550	saveonemore := func(xid string) {
 551		dlog.Printf("getting onemore: %s", xid)
 552		if depth >= maxdepth {
 553			ilog.Printf("in too deep")
 554			return
 555		}
 556		obj, err := GetJunkHardMode(user.ID, xid)
 557		if err != nil {
 558			ilog.Printf("error getting onemore: %s: %s", xid, err)
 559			return
 560		}
 561		depth++
 562		xonkxonkfn(obj, originate(xid), false)
 563		depth--
 564	}
 565
 566	xonkxonkfn = func(item junk.Junk, origin string, isUpdate bool) *Honk {
 567		id, _ := item.GetString("id")
 568		what := firstofmany(item, "type")
 569		dt, ok := item.GetString("published")
 570		if !ok {
 571			dt = time.Now().Format(time.RFC3339)
 572		}
 573
 574		var err error
 575		var xid, rid, url, convoy string
 576		var replies []string
 577		var obj junk.Junk
 578		waspage := false
 579		switch what {
 580		case "Delete":
 581			obj, ok = item.GetMap("object")
 582			if ok {
 583				xid, _ = obj.GetString("id")
 584			} else {
 585				xid, _ = item.GetString("object")
 586			}
 587			if xid == "" {
 588				return nil
 589			}
 590			if originate(xid) != origin {
 591				ilog.Printf("forged delete: %s", xid)
 592				return nil
 593			}
 594			ilog.Printf("eradicating %s", xid)
 595			eradicatexonk(user.ID, xid)
 596			return nil
 597		case "Remove":
 598			xid, _ = item.GetString("object")
 599			targ, _ := obj.GetString("target")
 600			ilog.Printf("remove %s from %s", obj, targ)
 601			return nil
 602		case "Tombstone":
 603			xid, _ = item.GetString("id")
 604			if xid == "" {
 605				return nil
 606			}
 607			if originate(xid) != origin {
 608				ilog.Printf("forged delete: %s", xid)
 609				return nil
 610			}
 611			ilog.Printf("eradicating %s", xid)
 612			eradicatexonk(user.ID, xid)
 613			return nil
 614		case "Announce":
 615			obj, ok = item.GetMap("object")
 616			if ok {
 617				xid, _ = obj.GetString("id")
 618			} else {
 619				xid, _ = item.GetString("object")
 620			}
 621			if !needbonkid(user, xid) {
 622				return nil
 623			}
 624			dlog.Printf("getting bonk: %s", xid)
 625			obj, err = GetJunkHardMode(user.ID, xid)
 626			if err != nil {
 627				ilog.Printf("error getting bonk: %s: %s", xid, err)
 628			}
 629			origin = originate(xid)
 630			what = "bonk"
 631		case "Update":
 632			isUpdate = true
 633			fallthrough
 634		case "Create":
 635			obj, ok = item.GetMap("object")
 636			if !ok {
 637				xid, _ = item.GetString("object")
 638				dlog.Printf("getting created honk: %s", xid)
 639				if originate(xid) != origin {
 640					ilog.Printf("out of bounds %s not from %s", xid, origin)
 641					return nil
 642				}
 643				obj, err = GetJunkHardMode(user.ID, xid)
 644				if err != nil {
 645					ilog.Printf("error getting creation: %s", err)
 646				}
 647			}
 648			if obj == nil {
 649				ilog.Printf("no object for creation %s", id)
 650				return nil
 651			}
 652			return xonkxonkfn(obj, origin, isUpdate)
 653		case "Read":
 654			xid, ok = item.GetString("object")
 655			if ok {
 656				if !needxonkid(user, xid) {
 657					dlog.Printf("don't need read obj: %s", xid)
 658					return nil
 659				}
 660				obj, err = GetJunkHardMode(user.ID, xid)
 661				if err != nil {
 662					ilog.Printf("error getting read: %s", err)
 663					return nil
 664				}
 665				return xonkxonkfn(obj, originate(xid), false)
 666			}
 667			return nil
 668		case "Add":
 669			xid, ok = item.GetString("object")
 670			if ok {
 671				// check target...
 672				if !needxonkid(user, xid) {
 673					dlog.Printf("don't need added obj: %s", xid)
 674					return nil
 675				}
 676				obj, err = GetJunkHardMode(user.ID, xid)
 677				if err != nil {
 678					ilog.Printf("error getting add: %s", err)
 679					return nil
 680				}
 681				return xonkxonkfn(obj, originate(xid), false)
 682			}
 683			return nil
 684		case "Move":
 685			obj = item
 686			what = "move"
 687		case "Page":
 688			waspage = true
 689			fallthrough
 690		case "GuessWord": // dealt with below
 691			fallthrough
 692		case "Audio":
 693			fallthrough
 694		case "Image":
 695			fallthrough
 696		case "Video":
 697			fallthrough
 698		case "Question":
 699			fallthrough
 700		case "Note":
 701			fallthrough
 702		case "Article":
 703			obj = item
 704			what = "honk"
 705		case "Event":
 706			obj = item
 707			what = "event"
 708		case "ChatMessage":
 709			obj = item
 710			what = "chonk"
 711		default:
 712			ilog.Printf("unknown activity: %s", what)
 713			dumpactivity(item)
 714			return nil
 715		}
 716
 717		if obj != nil {
 718			xid, _ = obj.GetString("id")
 719		}
 720
 721		if xid == "" {
 722			ilog.Printf("don't know what xid is")
 723			item.Write(ilog.Writer())
 724			return nil
 725		}
 726		if originate(xid) != origin {
 727			if !develMode && origin != "" {
 728				ilog.Printf("original sin: %s not from %s", xid, origin)
 729				item.Write(ilog.Writer())
 730				return nil
 731			}
 732		}
 733
 734		var xonk Honk
 735		// early init
 736		xonk.XID = xid
 737		xonk.UserID = user.ID
 738		xonk.Honker, _ = item.GetString("actor")
 739		if xonk.Honker == "" {
 740			xonk.Honker, _ = item.GetString("attributedTo")
 741		}
 742		if obj != nil {
 743			if xonk.Honker == "" {
 744				xonk.Honker = extractattrto(obj)
 745			}
 746			xonk.Oonker = extractattrto(obj)
 747			if xonk.Oonker == xonk.Honker {
 748				xonk.Oonker = ""
 749			}
 750			xonk.Audience = newphone(nil, obj)
 751		}
 752		xonk.Audience = append(xonk.Audience, xonk.Honker)
 753		xonk.Audience = oneofakind(xonk.Audience)
 754		xonk.Public = loudandproud(xonk.Audience)
 755
 756		var mentions []Mention
 757		if obj != nil {
 758			ot, _ := obj.GetString("type")
 759			url, _ = obj.GetString("url")
 760			if dt2, ok := obj.GetString("published"); ok {
 761				dt = dt2
 762			}
 763			content, _ := obj.GetString("content")
 764			if !strings.HasPrefix(content, "<p>") {
 765				content = "<p>" + content
 766			}
 767			precis, _ := obj.GetString("summary")
 768			if name, ok := obj.GetString("name"); ok {
 769				if precis != "" {
 770					content = precis + "<p>" + content
 771				}
 772				precis = html.EscapeString(name)
 773			}
 774			if sens, _ := obj["sensitive"].(bool); sens && precis == "" {
 775				precis = "unspecified horror"
 776			}
 777			if waspage {
 778				content += fmt.Sprintf(`<p><a href="%s">%s</a>`, url, url)
 779				url = xid
 780			}
 781			content = qutify(user, content)
 782			rid, ok = obj.GetString("inReplyTo")
 783			if !ok {
 784				if robj, ok := obj.GetMap("inReplyTo"); ok {
 785					rid, _ = robj.GetString("id")
 786				}
 787			}
 788			convoy, _ = obj.GetString("context")
 789			if convoy == "" {
 790				convoy, _ = obj.GetString("conversation")
 791			}
 792			if ot == "Question" {
 793				if what == "honk" {
 794					what = "qonk"
 795				}
 796				content += "<ul>"
 797				ans, _ := obj.GetArray("oneOf")
 798				for _, ai := range ans {
 799					a, ok := ai.(junk.Junk)
 800					if !ok {
 801						continue
 802					}
 803					as, _ := a.GetString("name")
 804					content += "<li>" + as
 805				}
 806				ans, _ = obj.GetArray("anyOf")
 807				for _, ai := range ans {
 808					a, ok := ai.(junk.Junk)
 809					if !ok {
 810						continue
 811					}
 812					as, _ := a.GetString("name")
 813					content += "<li>" + as
 814				}
 815				content += "</ul>"
 816			}
 817			if ot == "Move" {
 818				targ, _ := obj.GetString("target")
 819				content += string(templates.Sprintf(`<p>Moved to <a href="%s">%s</a>`, targ, targ))
 820			}
 821			if ot == "GuessWord" {
 822				what = "wonk"
 823				content, _ = obj.GetString("content")
 824				xonk.Wonkles, _ = obj.GetString("wordlist")
 825				go savewonkles(xonk.Wonkles)
 826			}
 827			if what == "honk" && rid != "" {
 828				what = "tonk"
 829			}
 830			if len(content) > 90001 {
 831				ilog.Printf("content too long. truncating")
 832				content = content[:90001]
 833			}
 834
 835			xonk.Noise = content
 836			xonk.Precis = precis
 837			if rejectxonk(&xonk) {
 838				dlog.Printf("fast reject: %s", xid)
 839				return nil
 840			}
 841
 842			numatts := 0
 843			procatt := func(att junk.Junk) {
 844				at, _ := att.GetString("type")
 845				mt, _ := att.GetString("mediaType")
 846				u, ok := att.GetString("url")
 847				if !ok {
 848					if ua, ok := att.GetArray("url"); ok && len(ua) > 0 {
 849						u, ok = ua[0].(string)
 850						if !ok {
 851							if uu, ok := ua[0].(junk.Junk); ok {
 852								u, _ = uu.GetString("href")
 853								if mt == "" {
 854									mt, _ = uu.GetString("mediaType")
 855								}
 856							}
 857						}
 858					} else if uu, ok := att.GetMap("url"); ok {
 859						u, _ = uu.GetString("href")
 860						if mt == "" {
 861							mt, _ = uu.GetString("mediaType")
 862						}
 863					}
 864				}
 865				name, _ := att.GetString("name")
 866				desc, _ := att.GetString("summary")
 867				desc = html.UnescapeString(desc)
 868				if desc == "" {
 869					desc = name
 870				}
 871				localize := false
 872				if numatts > 4 {
 873					ilog.Printf("excessive attachment: %s", at)
 874				} else if at == "Document" || at == "Image" {
 875					mt = strings.ToLower(mt)
 876					dlog.Printf("attachment: %s %s", mt, u)
 877					if mt == "text/plain" || mt == "application/pdf" ||
 878						strings.HasPrefix(mt, "image") {
 879						localize = true
 880					}
 881				} else {
 882					ilog.Printf("unknown attachment: %s", at)
 883				}
 884				if skipMedia(&xonk) {
 885					localize = false
 886				}
 887				donk := savedonk(u, name, desc, mt, localize)
 888				if donk != nil {
 889					xonk.Donks = append(xonk.Donks, donk)
 890				}
 891				numatts++
 892			}
 893			atts, _ := obj.GetArray("attachment")
 894			for _, atti := range atts {
 895				att, ok := atti.(junk.Junk)
 896				if !ok {
 897					ilog.Printf("attachment that wasn't map?")
 898					continue
 899				}
 900				procatt(att)
 901			}
 902			if att, ok := obj.GetMap("attachment"); ok {
 903				procatt(att)
 904			}
 905			tags, _ := obj.GetArray("tag")
 906			for _, tagi := range tags {
 907				tag, ok := tagi.(junk.Junk)
 908				if !ok {
 909					continue
 910				}
 911				tt, _ := tag.GetString("type")
 912				name, _ := tag.GetString("name")
 913				desc, _ := tag.GetString("summary")
 914				desc = html.UnescapeString(desc)
 915				if desc == "" {
 916					desc = name
 917				}
 918				if tt == "Emoji" {
 919					icon, _ := tag.GetMap("icon")
 920					mt, _ := icon.GetString("mediaType")
 921					if mt == "" {
 922						mt = "image/png"
 923					}
 924					u, _ := icon.GetString("url")
 925					donk := savedonk(u, name, desc, mt, true)
 926					if donk != nil {
 927						xonk.Donks = append(xonk.Donks, donk)
 928					}
 929				}
 930				if tt == "Hashtag" {
 931					if name == "" || name == "#" {
 932						// skip it
 933					} else {
 934						if name[0] != '#' {
 935							name = "#" + name
 936						}
 937						xonk.Onts = append(xonk.Onts, name)
 938					}
 939				}
 940				if tt == "Place" {
 941					p := new(Place)
 942					p.Name = name
 943					p.Latitude, _ = tag.GetNumber("latitude")
 944					p.Longitude, _ = tag.GetNumber("longitude")
 945					p.Url, _ = tag.GetString("url")
 946					xonk.Place = p
 947				}
 948				if tt == "Mention" {
 949					var m Mention
 950					m.Who, _ = tag.GetString("name")
 951					m.Where, _ = tag.GetString("href")
 952					mentions = append(mentions, m)
 953				}
 954			}
 955			if starttime, ok := obj.GetString("startTime"); ok {
 956				if start, err := time.Parse(time.RFC3339, starttime); err == nil {
 957					t := new(Time)
 958					t.StartTime = start
 959					endtime, _ := obj.GetString("endTime")
 960					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
 961					dura, _ := obj.GetString("duration")
 962					if strings.HasPrefix(dura, "PT") {
 963						dura = strings.ToLower(dura[2:])
 964						d, _ := time.ParseDuration(dura)
 965						t.Duration = Duration(d)
 966					}
 967					xonk.Time = t
 968				}
 969			}
 970			if loca, ok := obj.GetMap("location"); ok {
 971				if tt, _ := loca.GetString("type"); tt == "Place" {
 972					p := new(Place)
 973					p.Name, _ = loca.GetString("name")
 974					p.Latitude, _ = loca.GetNumber("latitude")
 975					p.Longitude, _ = loca.GetNumber("longitude")
 976					p.Url, _ = loca.GetString("url")
 977					xonk.Place = p
 978				}
 979			}
 980
 981			xonk.Onts = oneofakind(xonk.Onts)
 982			replyobj, ok := obj.GetMap("replies")
 983			if ok {
 984				items, ok := replyobj.GetArray("items")
 985				if !ok {
 986					first, ok := replyobj.GetMap("first")
 987					if ok {
 988						items, _ = first.GetArray("items")
 989					}
 990				}
 991				for _, repl := range items {
 992					s, ok := repl.(string)
 993					if ok {
 994						replies = append(replies, s)
 995					}
 996				}
 997			}
 998
 999		}
1000
1001		if currenttid == "" {
1002			currenttid = convoy
1003		}
1004
1005		// init xonk
1006		xonk.What = what
1007		xonk.RID = rid
1008		xonk.Date, _ = time.Parse(time.RFC3339, dt)
1009		xonk.URL = url
1010		xonk.Format = "html"
1011		xonk.Convoy = convoy
1012		xonk.Mentions = mentions
1013		for _, m := range mentions {
1014			if m.Where == user.URL {
1015				xonk.Whofore = 1
1016			}
1017		}
1018		imaginate(&xonk)
1019
1020		if what == "chonk" {
1021			ch := Chonk{
1022				UserID: xonk.UserID,
1023				XID:    xid,
1024				Who:    xonk.Honker,
1025				Target: xonk.Honker,
1026				Date:   xonk.Date,
1027				Noise:  xonk.Noise,
1028				Format: xonk.Format,
1029				Donks:  xonk.Donks,
1030			}
1031			savechonk(&ch)
1032			return nil
1033		}
1034
1035		if isUpdate {
1036			dlog.Printf("something has changed! %s", xonk.XID)
1037			prev := getxonk(user.ID, xonk.XID)
1038			if prev == nil {
1039				ilog.Printf("didn't find old version for update: %s", xonk.XID)
1040				isUpdate = false
1041			} else {
1042				xonk.ID = prev.ID
1043				updatehonk(&xonk)
1044			}
1045		}
1046		if !isUpdate && needxonk(user, &xonk) {
1047			if rid != "" && xonk.Public {
1048				if needxonkid(user, rid) {
1049					goingup++
1050					saveonemore(rid)
1051					goingup--
1052				}
1053				if convoy == "" {
1054					xx := getxonk(user.ID, rid)
1055					if xx != nil {
1056						convoy = xx.Convoy
1057					}
1058				}
1059			}
1060			if convoy == "" {
1061				convoy = currenttid
1062			}
1063			if convoy == "" {
1064				convoy = "data:,missing-" + xfiltrate()
1065				currenttid = convoy
1066			}
1067			xonk.Convoy = convoy
1068			savexonk(&xonk)
1069		}
1070		if goingup == 0 {
1071			for _, replid := range replies {
1072				if needxonkid(user, replid) {
1073					dlog.Printf("missing a reply: %s", replid)
1074					saveonemore(replid)
1075				}
1076			}
1077		}
1078		return &xonk
1079	}
1080
1081	return xonkxonkfn(item, origin, false)
1082}
1083
1084func dumpactivity(item junk.Junk) {
1085	fd, err := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
1086	if err != nil {
1087		elog.Printf("error opening inbox! %s", err)
1088		return
1089	}
1090	defer fd.Close()
1091	item.Write(fd)
1092	io.WriteString(fd, "\n")
1093}
1094
1095func rubadubdub(user *WhatAbout, req junk.Junk) {
1096	actor, _ := req.GetString("actor")
1097	j := junk.New()
1098	j["@context"] = itiswhatitis
1099	j["id"] = user.URL + "/dub/" + xfiltrate()
1100	j["type"] = "Accept"
1101	j["actor"] = user.URL
1102	j["to"] = actor
1103	j["published"] = time.Now().UTC().Format(time.RFC3339)
1104	j["object"] = req
1105
1106	deliverate(0, user.ID, actor, j.ToBytes(), true)
1107}
1108
1109func itakeitallback(user *WhatAbout, xid string, owner string, folxid string) {
1110	j := junk.New()
1111	j["@context"] = itiswhatitis
1112	j["id"] = user.URL + "/unsub/" + folxid
1113	j["type"] = "Undo"
1114	j["actor"] = user.URL
1115	j["to"] = owner
1116	f := junk.New()
1117	f["id"] = user.URL + "/sub/" + folxid
1118	f["type"] = "Follow"
1119	f["actor"] = user.URL
1120	f["to"] = owner
1121	f["object"] = xid
1122	j["object"] = f
1123	j["published"] = time.Now().UTC().Format(time.RFC3339)
1124
1125	deliverate(0, user.ID, owner, j.ToBytes(), true)
1126}
1127
1128func subsub(user *WhatAbout, xid string, owner string, folxid string) {
1129	if xid == "" {
1130		ilog.Printf("can't subscribe to empty")
1131		return
1132	}
1133	j := junk.New()
1134	j["@context"] = itiswhatitis
1135	j["id"] = user.URL + "/sub/" + folxid
1136	j["type"] = "Follow"
1137	j["actor"] = user.URL
1138	j["to"] = owner
1139	j["object"] = xid
1140	j["published"] = time.Now().UTC().Format(time.RFC3339)
1141
1142	deliverate(0, user.ID, owner, j.ToBytes(), true)
1143}
1144
1145func activatedonks(donks []*Donk) []junk.Junk {
1146	var atts []junk.Junk
1147	for _, d := range donks {
1148		if re_emus.MatchString(d.Name) {
1149			continue
1150		}
1151		jd := junk.New()
1152		jd["mediaType"] = d.Media
1153		jd["name"] = d.Name
1154		jd["summary"] = html.EscapeString(d.Desc)
1155		jd["type"] = "Document"
1156		jd["url"] = d.URL
1157		atts = append(atts, jd)
1158	}
1159	return atts
1160}
1161
1162// returns activity, object
1163func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
1164	dt := h.Date.Format(time.RFC3339)
1165	var jo junk.Junk
1166	j := junk.New()
1167	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
1168	j["actor"] = user.URL
1169	j["published"] = dt
1170	j["to"] = h.Audience[0]
1171	if len(h.Audience) > 1 {
1172		j["cc"] = h.Audience[1:]
1173	}
1174
1175	switch h.What {
1176	case "update":
1177		fallthrough
1178	case "tonk":
1179		fallthrough
1180	case "event":
1181		fallthrough
1182	case "wonk":
1183		fallthrough
1184	case "honk":
1185		j["type"] = "Create"
1186		jo = junk.New()
1187		jo["id"] = h.XID
1188		jo["type"] = "Note"
1189		if h.What == "event" {
1190			jo["type"] = "Event"
1191		} else if h.What == "wonk" {
1192			jo["type"] = "GuessWord"
1193		}
1194		if h.What == "update" {
1195			j["type"] = "Update"
1196			jo["updated"] = dt
1197		}
1198		jo["published"] = dt
1199		jo["url"] = h.XID
1200		jo["attributedTo"] = user.URL
1201		if h.RID != "" {
1202			jo["inReplyTo"] = h.RID
1203		}
1204		if h.Convoy != "" {
1205			jo["context"] = h.Convoy
1206			jo["conversation"] = h.Convoy
1207		}
1208		jo["to"] = h.Audience[0]
1209		if len(h.Audience) > 1 {
1210			jo["cc"] = h.Audience[1:]
1211		}
1212		if !h.Public {
1213			jo["directMessage"] = true
1214		}
1215		translate(h)
1216		redoimages(h)
1217		if h.Precis != "" {
1218			jo["sensitive"] = true
1219		}
1220
1221		var replies []string
1222		for _, reply := range h.Replies {
1223			replies = append(replies, reply.XID)
1224		}
1225		if len(replies) > 0 {
1226			jr := junk.New()
1227			jr["type"] = "Collection"
1228			jr["totalItems"] = len(replies)
1229			jr["items"] = replies
1230			jo["replies"] = jr
1231		}
1232
1233		var tags []junk.Junk
1234		for _, m := range h.Mentions {
1235			t := junk.New()
1236			t["type"] = "Mention"
1237			t["name"] = m.Who
1238			t["href"] = m.Where
1239			tags = append(tags, t)
1240		}
1241		for _, o := range h.Onts {
1242			t := junk.New()
1243			t["type"] = "Hashtag"
1244			o = strings.ToLower(o)
1245			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1246			t["name"] = o
1247			tags = append(tags, t)
1248		}
1249		for _, e := range herdofemus(h.Noise) {
1250			t := junk.New()
1251			t["id"] = e.ID
1252			t["type"] = "Emoji"
1253			t["name"] = e.Name
1254			i := junk.New()
1255			i["type"] = "Image"
1256			i["mediaType"] = e.Type
1257			i["url"] = e.ID
1258			t["icon"] = i
1259			tags = append(tags, t)
1260		}
1261		for _, e := range fixupflags(h) {
1262			t := junk.New()
1263			t["id"] = e.ID
1264			t["type"] = "Emoji"
1265			t["name"] = e.Name
1266			i := junk.New()
1267			i["type"] = "Image"
1268			i["mediaType"] = "image/png"
1269			i["url"] = e.ID
1270			t["icon"] = i
1271			tags = append(tags, t)
1272		}
1273		if len(tags) > 0 {
1274			jo["tag"] = tags
1275		}
1276		if p := h.Place; p != nil {
1277			t := junk.New()
1278			t["type"] = "Place"
1279			if p.Name != "" {
1280				t["name"] = p.Name
1281			}
1282			if p.Latitude != 0 {
1283				t["latitude"] = p.Latitude
1284			}
1285			if p.Longitude != 0 {
1286				t["longitude"] = p.Longitude
1287			}
1288			if p.Url != "" {
1289				t["url"] = p.Url
1290			}
1291			jo["location"] = t
1292		}
1293		if t := h.Time; t != nil {
1294			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1295			if t.Duration != 0 {
1296				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1297			}
1298		}
1299		if w := h.Wonkles; w != "" {
1300			jo["wordlist"] = w
1301		}
1302		atts := activatedonks(h.Donks)
1303		if len(atts) > 0 {
1304			jo["attachment"] = atts
1305		}
1306		jo["summary"] = html.EscapeString(h.Precis)
1307		jo["content"] = h.Noise
1308		j["object"] = jo
1309	case "bonk":
1310		j["type"] = "Announce"
1311		if h.Convoy != "" {
1312			j["context"] = h.Convoy
1313		}
1314		j["object"] = h.XID
1315	case "unbonk":
1316		b := junk.New()
1317		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1318		b["type"] = "Announce"
1319		b["actor"] = user.URL
1320		if h.Convoy != "" {
1321			b["context"] = h.Convoy
1322		}
1323		b["object"] = h.XID
1324		j["type"] = "Undo"
1325		j["object"] = b
1326	case "zonk":
1327		j["type"] = "Delete"
1328		j["object"] = h.XID
1329	case "ack":
1330		j["type"] = "Read"
1331		j["object"] = h.XID
1332		if h.Convoy != "" {
1333			j["context"] = h.Convoy
1334		}
1335	case "react":
1336		j["type"] = "EmojiReact"
1337		j["object"] = h.XID
1338		if h.Convoy != "" {
1339			j["context"] = h.Convoy
1340		}
1341		j["content"] = h.Noise
1342	case "deack":
1343		b := junk.New()
1344		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1345		b["type"] = "Read"
1346		b["actor"] = user.URL
1347		b["object"] = h.XID
1348		if h.Convoy != "" {
1349			b["context"] = h.Convoy
1350		}
1351		j["type"] = "Undo"
1352		j["object"] = b
1353	}
1354
1355	return j, jo
1356}
1357
1358var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1359	row := stmtAnyXonk.QueryRow(xid)
1360	honk := scanhonk(row)
1361	if honk == nil || !honk.Public {
1362		return nil, true
1363	}
1364	user, _ := butwhatabout(honk.Username)
1365	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1366	reversehonks(rawhonks)
1367	for _, h := range rawhonks {
1368		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1369			honk.Replies = append(honk.Replies, h)
1370		}
1371	}
1372	donksforhonks([]*Honk{honk})
1373	_, j := jonkjonk(user, honk)
1374	if j == nil {
1375		elog.Fatalf("what just happened? %v", honk)
1376	}
1377	j["@context"] = itiswhatitis
1378
1379	return j.ToBytes(), true
1380}, Limit: 128})
1381
1382func gimmejonk(xid string) ([]byte, bool) {
1383	var j []byte
1384	ok := oldjonks.Get(xid, &j)
1385	return j, ok
1386}
1387
1388func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1389	rcpts := make(map[string]bool)
1390	for _, a := range addresses {
1391		if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1392			continue
1393		}
1394		if a[0] == '%' {
1395			rcpts[a] = true
1396			continue
1397		}
1398		var box *Box
1399		ok := boxofboxes.Get(a, &box)
1400		if ok && useshared && box.Shared != "" {
1401			rcpts["%"+box.Shared] = true
1402		} else {
1403			rcpts[a] = true
1404		}
1405	}
1406	return rcpts
1407}
1408
1409func chonkifymsg(user *WhatAbout, ch *Chonk) []byte {
1410	dt := ch.Date.Format(time.RFC3339)
1411	aud := []string{ch.Target}
1412
1413	jo := junk.New()
1414	jo["id"] = ch.XID
1415	jo["type"] = "ChatMessage"
1416	jo["published"] = dt
1417	jo["attributedTo"] = user.URL
1418	jo["to"] = aud
1419	jo["content"] = ch.HTML
1420	atts := activatedonks(ch.Donks)
1421	if len(atts) > 0 {
1422		jo["attachment"] = atts
1423	}
1424	var tags []junk.Junk
1425	for _, e := range herdofemus(ch.Noise) {
1426		t := junk.New()
1427		t["id"] = e.ID
1428		t["type"] = "Emoji"
1429		t["name"] = e.Name
1430		i := junk.New()
1431		i["type"] = "Image"
1432		i["mediaType"] = e.Type
1433		i["url"] = e.ID
1434		t["icon"] = i
1435		tags = append(tags, t)
1436	}
1437	if len(tags) > 0 {
1438		jo["tag"] = tags
1439	}
1440
1441	j := junk.New()
1442	j["@context"] = itiswhatitis
1443	j["id"] = user.URL + "/" + "honk" + "/" + shortxid(ch.XID)
1444	j["type"] = "Create"
1445	j["actor"] = user.URL
1446	j["published"] = dt
1447	j["to"] = aud
1448	j["object"] = jo
1449
1450	return j.ToBytes()
1451}
1452
1453func sendchonk(user *WhatAbout, ch *Chonk) {
1454	msg := chonkifymsg(user, ch)
1455
1456	rcpts := make(map[string]bool)
1457	rcpts[ch.Target] = true
1458	for a := range rcpts {
1459		go deliverate(0, user.ID, a, msg, true)
1460	}
1461}
1462
1463func honkworldwide(user *WhatAbout, honk *Honk) {
1464	jonk, _ := jonkjonk(user, honk)
1465	jonk["@context"] = itiswhatitis
1466	msg := jonk.ToBytes()
1467
1468	rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1469
1470	if honk.Public {
1471		for _, h := range getdubs(user.ID) {
1472			if h.XID == user.URL {
1473				continue
1474			}
1475			var box *Box
1476			ok := boxofboxes.Get(h.XID, &box)
1477			if ok && box.Shared != "" {
1478				rcpts["%"+box.Shared] = true
1479			} else {
1480				rcpts[h.XID] = true
1481			}
1482		}
1483		for _, f := range getbacktracks(honk.XID) {
1484			if f[0] == '%' {
1485				rcpts[f] = true
1486			} else {
1487				var box *Box
1488				ok := boxofboxes.Get(f, &box)
1489				if ok && box.Shared != "" {
1490					rcpts["%"+box.Shared] = true
1491				} else {
1492					rcpts[f] = true
1493				}
1494			}
1495		}
1496	}
1497	for a := range rcpts {
1498		go deliverate(0, user.ID, a, msg, doesitmatter(honk.What))
1499	}
1500	if honk.Public && len(honk.Onts) > 0 {
1501		collectiveaction(honk)
1502	}
1503}
1504
1505func doesitmatter(what string) bool {
1506	switch what {
1507	case "ack":
1508		return false
1509	case "react":
1510		return false
1511	case "deack":
1512		return false
1513	}
1514	return true
1515}
1516
1517func collectiveaction(honk *Honk) {
1518	user := getserveruser()
1519	for _, ont := range honk.Onts {
1520		dubs := getnameddubs(readyLuserOne, ont)
1521		if len(dubs) == 0 {
1522			continue
1523		}
1524		j := junk.New()
1525		j["@context"] = itiswhatitis
1526		j["type"] = "Add"
1527		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1528		j["actor"] = user.URL
1529		j["object"] = honk.XID
1530		j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1531		rcpts := make(map[string]bool)
1532		for _, dub := range dubs {
1533			var box *Box
1534			ok := boxofboxes.Get(dub.XID, &box)
1535			if ok && box.Shared != "" {
1536				rcpts["%"+box.Shared] = true
1537			} else {
1538				rcpts[dub.XID] = true
1539			}
1540		}
1541		msg := j.ToBytes()
1542		for a := range rcpts {
1543			go deliverate(0, user.ID, a, msg, false)
1544		}
1545	}
1546}
1547
1548func junkuser(user *WhatAbout) junk.Junk {
1549	j := junk.New()
1550	j["@context"] = itiswhatitis
1551	j["id"] = user.URL
1552	j["inbox"] = user.URL + "/inbox"
1553	j["outbox"] = user.URL + "/outbox"
1554	j["name"] = user.Display
1555	j["preferredUsername"] = user.Name
1556	j["summary"] = user.HTAbout
1557	var tags []junk.Junk
1558	for _, o := range user.Onts {
1559		t := junk.New()
1560		t["type"] = "Hashtag"
1561		o = strings.ToLower(o)
1562		t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1563		t["name"] = o
1564		tags = append(tags, t)
1565	}
1566	if len(tags) > 0 {
1567		j["tag"] = tags
1568	}
1569
1570	if user.ID > 0 {
1571		j["type"] = "Person"
1572		j["url"] = user.URL
1573		j["followers"] = user.URL + "/followers"
1574		j["following"] = user.URL + "/following"
1575		a := junk.New()
1576		a["type"] = "Image"
1577		a["mediaType"] = "image/png"
1578		if ava := user.Options.Avatar; ava != "" {
1579			a["url"] = ava
1580		} else {
1581			u := fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1582			a["url"] = u
1583		}
1584		j["icon"] = a
1585		if ban := user.Options.Banner; ban != "" {
1586			a := junk.New()
1587			a["type"] = "Image"
1588			a["mediaType"] = "image/jpg"
1589			a["url"] = ban
1590			j["image"] = a
1591		}
1592	} else {
1593		j["type"] = "Service"
1594	}
1595	k := junk.New()
1596	k["id"] = user.URL + "#key"
1597	k["owner"] = user.URL
1598	k["publicKeyPem"] = user.Key
1599	j["publicKey"] = k
1600
1601	return j
1602}
1603
1604var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1605	user, err := butwhatabout(name)
1606	if err != nil {
1607		return nil, false
1608	}
1609	var buf bytes.Buffer
1610	j := junkuser(user)
1611	j.Write(&buf)
1612	return buf.Bytes(), true
1613}, Duration: 1 * time.Minute})
1614
1615func asjonker(name string) ([]byte, bool) {
1616	var j []byte
1617	ok := oldjonkers.Get(name, &j)
1618	return j, ok
1619}
1620
1621var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1622	m := strings.Split(name, "@")
1623	if len(m) != 2 {
1624		dlog.Printf("bad fish name: %s", name)
1625		return "", true
1626	}
1627	var href string
1628	row := stmtGetXonker.QueryRow(name, "fishname")
1629	err := row.Scan(&href)
1630	if err == nil {
1631		return href, true
1632	}
1633	dlog.Printf("fishing for %s", name)
1634	j, err := GetJunkFast(readyLuserOne, fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1635	if err != nil {
1636		ilog.Printf("failed to go fish %s: %s", name, err)
1637		return "", true
1638	}
1639	links, _ := j.GetArray("links")
1640	for _, li := range links {
1641		l, ok := li.(junk.Junk)
1642		if !ok {
1643			continue
1644		}
1645		href, _ := l.GetString("href")
1646		rel, _ := l.GetString("rel")
1647		t, _ := l.GetString("type")
1648		if rel == "self" && friendorfoe(t) {
1649			when := time.Now().UTC().Format(dbtimeformat)
1650			_, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1651			if err != nil {
1652				elog.Printf("error saving fishname: %s", err)
1653			}
1654			return href, true
1655		}
1656	}
1657	return href, true
1658}, Duration: 1 * time.Minute})
1659
1660func gofish(name string) string {
1661	if name[0] == '@' {
1662		name = name[1:]
1663	}
1664	var href string
1665	handfull.Get(name, &href)
1666	return href
1667}
1668
1669func investigate(name string) (*SomeThing, error) {
1670	if name == "" {
1671		return nil, fmt.Errorf("no name")
1672	}
1673	if name[0] == '@' {
1674		name = gofish(name)
1675	}
1676	if name == "" {
1677		return nil, fmt.Errorf("no name")
1678	}
1679	obj, err := GetJunkFast(readyLuserOne, name)
1680	if err != nil {
1681		return nil, err
1682	}
1683	allinjest(originate(name), obj)
1684	return somethingabout(obj)
1685}
1686
1687func somethingabout(obj junk.Junk) (*SomeThing, error) {
1688	info := new(SomeThing)
1689	t, _ := obj.GetString("type")
1690	switch t {
1691	case "Person":
1692		fallthrough
1693	case "Organization":
1694		fallthrough
1695	case "Application":
1696		fallthrough
1697	case "Service":
1698		info.What = SomeActor
1699	case "OrderedCollection":
1700		fallthrough
1701	case "Collection":
1702		info.What = SomeCollection
1703	default:
1704		return nil, fmt.Errorf("unknown object type")
1705	}
1706	info.XID, _ = obj.GetString("id")
1707	info.Name, _ = obj.GetString("preferredUsername")
1708	if info.Name == "" {
1709		info.Name, _ = obj.GetString("name")
1710	}
1711	info.Owner, _ = obj.GetString("attributedTo")
1712	if info.Owner == "" {
1713		info.Owner = info.XID
1714	}
1715	return info, nil
1716}
1717
1718func allinjest(origin string, obj junk.Junk) {
1719	keyobj, ok := obj.GetMap("publicKey")
1720	if ok {
1721		ingestpubkey(origin, keyobj)
1722	}
1723	ingestboxes(origin, obj)
1724	ingesthandle(origin, obj)
1725}
1726
1727func ingestpubkey(origin string, obj junk.Junk) {
1728	keyobj, ok := obj.GetMap("publicKey")
1729	if ok {
1730		obj = keyobj
1731	}
1732	keyname, ok := obj.GetString("id")
1733	var data string
1734	row := stmtGetXonker.QueryRow(keyname, "pubkey")
1735	err := row.Scan(&data)
1736	if err == nil {
1737		return
1738	}
1739	if !ok || origin != originate(keyname) {
1740		ilog.Printf("bad key origin %s <> %s", origin, keyname)
1741		return
1742	}
1743	dlog.Printf("ingesting a needed pubkey: %s", keyname)
1744	owner, ok := obj.GetString("owner")
1745	if !ok {
1746		ilog.Printf("error finding %s pubkey owner", keyname)
1747		return
1748	}
1749	data, ok = obj.GetString("publicKeyPem")
1750	if !ok {
1751		ilog.Printf("error finding %s pubkey", keyname)
1752		return
1753	}
1754	if originate(owner) != origin {
1755		ilog.Printf("bad key owner: %s <> %s", owner, origin)
1756		return
1757	}
1758	_, _, err = httpsig.DecodeKey(data)
1759	if err != nil {
1760		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
1761		return
1762	}
1763	when := time.Now().UTC().Format(dbtimeformat)
1764	_, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1765	if err != nil {
1766		elog.Printf("error saving key: %s", err)
1767	}
1768}
1769
1770func ingestboxes(origin string, obj junk.Junk) {
1771	ident, _ := obj.GetString("id")
1772	if ident == "" {
1773		return
1774	}
1775	if originate(ident) != origin {
1776		return
1777	}
1778	var info string
1779	row := stmtGetXonker.QueryRow(ident, "boxes")
1780	err := row.Scan(&info)
1781	if err == nil {
1782		return
1783	}
1784	dlog.Printf("ingesting boxes: %s", ident)
1785	inbox, _ := obj.GetString("inbox")
1786	outbox, _ := obj.GetString("outbox")
1787	sbox, _ := obj.GetString("endpoints", "sharedInbox")
1788	if inbox != "" {
1789		when := time.Now().UTC().Format(dbtimeformat)
1790		m := strings.Join([]string{inbox, outbox, sbox}, " ")
1791		_, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1792		if err != nil {
1793			elog.Printf("error saving boxes: %s", err)
1794		}
1795	}
1796}
1797
1798func ingesthandle(origin string, obj junk.Junk) {
1799	xid, _ := obj.GetString("id")
1800	if xid == "" {
1801		return
1802	}
1803	if originate(xid) != origin {
1804		return
1805	}
1806	var handle string
1807	row := stmtGetXonker.QueryRow(xid, "handle")
1808	err := row.Scan(&handle)
1809	if err == nil {
1810		return
1811	}
1812	handle, _ = obj.GetString("preferredUsername")
1813	if handle != "" {
1814		when := time.Now().UTC().Format(dbtimeformat)
1815		_, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1816		if err != nil {
1817			elog.Printf("error saving handle: %s", err)
1818		}
1819	}
1820}
1821
1822func updateMe(username string) {
1823	var user *WhatAbout
1824	somenamedusers.Get(username, &user)
1825	dt := time.Now().UTC().Format(time.RFC3339)
1826	j := junk.New()
1827	j["@context"] = itiswhatitis
1828	j["id"] = fmt.Sprintf("%s/upme/%s/%d", user.URL, user.Name, time.Now().Unix())
1829	j["actor"] = user.URL
1830	j["published"] = dt
1831	j["to"] = thewholeworld
1832	j["type"] = "Update"
1833	j["object"] = junkuser(user)
1834
1835	msg := j.ToBytes()
1836
1837	rcpts := make(map[string]bool)
1838	for _, f := range getdubs(user.ID) {
1839		if f.XID == user.URL {
1840			continue
1841		}
1842		var box *Box
1843		boxofboxes.Get(f.XID, &box)
1844		if box != nil && box.Shared != "" {
1845			rcpts["%"+box.Shared] = true
1846		} else {
1847			rcpts[f.XID] = true
1848		}
1849	}
1850	for a := range rcpts {
1851		go deliverate(0, user.ID, a, msg, false)
1852	}
1853}
1854
1855func followme(user *WhatAbout, who string, name string, j junk.Junk) {
1856	folxid, _ := j.GetString("id")
1857
1858	ilog.Printf("updating honker follow: %s %s", who, folxid)
1859
1860	var x string
1861	db := opendatabase()
1862	row := db.QueryRow("select xid from honkers where name = ? and xid = ? and userid = ? and flavor in ('dub', 'undub')", name, who, user.ID)
1863	err := row.Scan(&x)
1864	if err != sql.ErrNoRows {
1865		ilog.Printf("duplicate follow request: %s", who)
1866		_, err = stmtUpdateFlavor.Exec("dub", folxid, user.ID, name, who, "undub")
1867		if err != nil {
1868			elog.Printf("error updating honker: %s", err)
1869		}
1870	} else {
1871		stmtSaveDub.Exec(user.ID, name, who, "dub", folxid)
1872	}
1873	go rubadubdub(user, j)
1874}
1875
1876func unfollowme(user *WhatAbout, who string, name string, j junk.Junk) {
1877	var folxid string
1878	if who == "" {
1879		folxid, _ = j.GetString("object")
1880
1881		db := opendatabase()
1882		row := db.QueryRow("select xid, name from honkers where userid = ? and folxid = ? and flavor in ('dub', 'undub')", user.ID, folxid)
1883		err := row.Scan(&who, &name)
1884		if err != nil {
1885			if err != sql.ErrNoRows {
1886				elog.Printf("error scanning honker: %s", err)
1887			}
1888			return
1889		}
1890	}
1891
1892	ilog.Printf("updating honker undo: %s %s", who, folxid)
1893	_, err := stmtUpdateFlavor.Exec("undub", folxid, user.ID, name, who, "dub")
1894	if err != nil {
1895		elog.Printf("error updating honker: %s", err)
1896		return
1897	}
1898}
1899
1900func followyou(user *WhatAbout, honkerid int64) {
1901	var url, owner string
1902	db := opendatabase()
1903	row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1904		honkerid, user.ID)
1905	err := row.Scan(&url, &owner)
1906	if err != nil {
1907		elog.Printf("can't get honker xid: %s", err)
1908		return
1909	}
1910	folxid := xfiltrate()
1911	ilog.Printf("subscribing to %s", url)
1912	_, err = db.Exec("update honkers set flavor = ?, folxid = ? where honkerid = ?", "presub", folxid, honkerid)
1913	if err != nil {
1914		elog.Printf("error updating honker: %s", err)
1915		return
1916	}
1917	go subsub(user, url, owner, folxid)
1918
1919}
1920func unfollowyou(user *WhatAbout, honkerid int64) {
1921	db := opendatabase()
1922	row := db.QueryRow("select xid, owner, folxid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1923		honkerid, user.ID)
1924	var url, owner, folxid string
1925	err := row.Scan(&url, &owner, &folxid)
1926	if err != nil {
1927		elog.Printf("can't get honker xid: %s", err)
1928		return
1929	}
1930	ilog.Printf("unsubscribing from %s", url)
1931	_, err = db.Exec("update honkers set flavor = ? where honkerid = ?", "unsub", honkerid)
1932	if err != nil {
1933		elog.Printf("error updating honker: %s", err)
1934		return
1935	}
1936	go itakeitallback(user, url, owner, folxid)
1937}
1938
1939func followyou2(user *WhatAbout, j junk.Junk) {
1940	who, _ := j.GetString("actor")
1941
1942	ilog.Printf("updating honker accept: %s", who)
1943	db := opendatabase()
1944	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub')",
1945		user.ID, who)
1946	var name, folxid string
1947	err := row.Scan(&name, &folxid)
1948	if err != nil {
1949		elog.Printf("can't get honker name: %s", err)
1950		return
1951	}
1952	_, err = stmtUpdateFlavor.Exec("sub", folxid, user.ID, name, who, "presub")
1953	if err != nil {
1954		elog.Printf("error updating honker: %s", err)
1955		return
1956	}
1957}
1958
1959func nofollowyou2(user *WhatAbout, j junk.Junk) {
1960	who, _ := j.GetString("actor")
1961
1962	ilog.Printf("updating honker reject: %s", who)
1963	db := opendatabase()
1964	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
1965		user.ID, who)
1966	var name, folxid string
1967	err := row.Scan(&name, &folxid)
1968	if err != nil {
1969		elog.Printf("can't get honker name: %s", err)
1970		return
1971	}
1972	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "presub")
1973	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "sub")
1974	if err != nil {
1975		elog.Printf("error updating honker: %s", err)
1976		return
1977	}
1978}