all repos — honk @ 254d2ab513a185cb1457835fbd0d01e6befdb97b

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