all repos — honk @ 95a60dea408cd956190b04edd9ff05e728248bf0

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		translate(h)
1385		redoimages(h)
1386		if h.Precis != "" {
1387			jo["sensitive"] = true
1388		}
1389
1390		var replies []string
1391		for _, reply := range h.Replies {
1392			replies = append(replies, reply.XID)
1393		}
1394		if len(replies) > 0 {
1395			jr := junk.New()
1396			jr["type"] = "Collection"
1397			jr["totalItems"] = len(replies)
1398			jr["items"] = replies
1399			jo["replies"] = jr
1400		}
1401
1402		var tags []junk.Junk
1403		for _, m := range h.Mentions {
1404			t := junk.New()
1405			t["type"] = "Mention"
1406			t["name"] = m.Who
1407			t["href"] = m.Where
1408			tags = append(tags, t)
1409		}
1410		for _, o := range h.Onts {
1411			t := junk.New()
1412			t["type"] = "Hashtag"
1413			o = strings.ToLower(o)
1414			t["href"] = serverURL("/o/%s", o[1:])
1415			t["name"] = o
1416			tags = append(tags, t)
1417		}
1418		for _, e := range herdofemus(h.Noise) {
1419			t := junk.New()
1420			t["id"] = e.ID
1421			t["type"] = "Emoji"
1422			t["name"] = e.Name
1423			i := junk.New()
1424			i["type"] = "Image"
1425			i["mediaType"] = e.Type
1426			i["url"] = e.ID
1427			t["icon"] = i
1428			tags = append(tags, t)
1429		}
1430		for _, e := range fixupflags(h) {
1431			t := junk.New()
1432			t["id"] = e.ID
1433			t["type"] = "Emoji"
1434			t["name"] = e.Name
1435			i := junk.New()
1436			i["type"] = "Image"
1437			i["mediaType"] = "image/png"
1438			i["url"] = e.ID
1439			t["icon"] = i
1440			tags = append(tags, t)
1441		}
1442		if len(tags) > 0 {
1443			jo["tag"] = tags
1444		}
1445		if p := h.Place; p != nil {
1446			t := junk.New()
1447			t["type"] = "Place"
1448			if p.Name != "" {
1449				t["name"] = p.Name
1450			}
1451			if p.Latitude != 0 {
1452				t["latitude"] = p.Latitude
1453			}
1454			if p.Longitude != 0 {
1455				t["longitude"] = p.Longitude
1456			}
1457			if p.Url != "" {
1458				t["url"] = p.Url
1459			}
1460			jo["location"] = t
1461		}
1462		if t := h.Time; t != nil {
1463			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1464			if t.Duration != 0 {
1465				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1466			}
1467		}
1468		atts := activatedonks(h.Donks)
1469		if h.Link != "" {
1470			jo["type"] = "Page"
1471			jl := junk.New()
1472			jl["type"] = "Link"
1473			jl["href"] = h.Link
1474			atts = append(atts, jl)
1475		}
1476		if len(atts) > 0 {
1477			jo["attachment"] = atts
1478		}
1479		if h.LegalName != "" {
1480			jo["name"] = h.LegalName
1481		}
1482		if h.Precis != "" {
1483			jo["summary"] = h.Precis
1484		}
1485		jo["content"] = h.Noise
1486		j["object"] = jo
1487	case "bonk":
1488		j["type"] = "Announce"
1489		if h.Convoy != "" {
1490			j["context"] = h.Convoy
1491		}
1492		j["object"] = h.XID
1493	case "unbonk":
1494		b := junk.New()
1495		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1496		b["type"] = "Announce"
1497		b["actor"] = user.URL
1498		if h.Convoy != "" {
1499			b["context"] = h.Convoy
1500		}
1501		b["object"] = h.XID
1502		j["type"] = "Undo"
1503		j["object"] = b
1504	case "zonk":
1505		j["type"] = "Delete"
1506		j["object"] = h.XID
1507	case "ack":
1508		j["type"] = "Read"
1509		j["object"] = h.XID
1510		if h.Convoy != "" {
1511			j["context"] = h.Convoy
1512		}
1513	case "react":
1514		j["type"] = "EmojiReact"
1515		j["object"] = h.XID
1516		if h.Convoy != "" {
1517			j["context"] = h.Convoy
1518		}
1519		j["content"] = h.Noise
1520	case "deack":
1521		b := junk.New()
1522		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1523		b["type"] = "Read"
1524		b["actor"] = user.URL
1525		b["object"] = h.XID
1526		if h.Convoy != "" {
1527			b["context"] = h.Convoy
1528		}
1529		j["type"] = "Undo"
1530		j["object"] = b
1531	}
1532
1533	return j, jo
1534}
1535
1536var oldjonks = gencache.New(gencache.Options[string, []byte]{Fill: func(xid string) ([]byte, bool) {
1537	row := stmtAnyXonk.QueryRow(xid)
1538	honk := scanhonk(row)
1539	if honk == nil || !honk.Public {
1540		return nil, true
1541	}
1542	user, _ := butwhatabout(honk.Username)
1543	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1544	reversehonks(rawhonks)
1545	for _, h := range rawhonks {
1546		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1547			honk.Replies = append(honk.Replies, h)
1548		}
1549	}
1550	donksforhonks([]*Honk{honk})
1551	_, j := jonkjonk(user, honk)
1552	if j == nil {
1553		elog.Fatalf("what just happened? %v", honk)
1554	}
1555	j["@context"] = itiswhatitis
1556
1557	return j.ToBytes(), true
1558}, Limit: 128})
1559
1560func gimmejonk(xid string) ([]byte, bool) {
1561	j, ok := oldjonks.Get(xid)
1562	return j, ok
1563}
1564
1565func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1566	rcpts := make(map[string]bool)
1567	for _, a := range addresses {
1568		if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1569			continue
1570		}
1571		if a[0] == '%' {
1572			rcpts[a] = true
1573			continue
1574		}
1575		box, ok := boxofboxes.Get(a)
1576		if ok && useshared && box.Shared != "" {
1577			rcpts["%"+box.Shared] = true
1578		} else {
1579			rcpts[a] = true
1580		}
1581	}
1582	return rcpts
1583}
1584
1585func chonkifymsg(user *WhatAbout, rcpt string, ch *Chonk) []byte {
1586	dt := ch.Date.Format(time.RFC3339)
1587	aud := []string{ch.Target}
1588
1589	jo := junk.New()
1590	jo["id"] = ch.XID
1591	jo["type"] = "ChatMessage"
1592	jo["published"] = dt
1593	jo["attributedTo"] = user.URL
1594	jo["to"] = aud
1595	content := string(ch.HTML)
1596	if user.ChatSecKey.key != nil {
1597		if pubkey, ok := getchatkey(rcpt); ok {
1598			var err error
1599			content, err = encryptString(content, user.ChatSecKey, pubkey)
1600			if err != nil {
1601				ilog.Printf("failure encrypting chonk: %s", err)
1602			}
1603			jo[chatKeyProp] = user.Options.ChatPubKey
1604		}
1605	}
1606	jo["content"] = content
1607
1608	atts := activatedonks(ch.Donks)
1609	if len(atts) > 0 {
1610		jo["attachment"] = atts
1611	}
1612	var tags []junk.Junk
1613	for _, e := range herdofemus(ch.Noise) {
1614		t := junk.New()
1615		t["id"] = e.ID
1616		t["type"] = "Emoji"
1617		t["name"] = e.Name
1618		i := junk.New()
1619		i["type"] = "Image"
1620		i["mediaType"] = e.Type
1621		i["url"] = e.ID
1622		t["icon"] = i
1623		tags = append(tags, t)
1624	}
1625	if len(tags) > 0 {
1626		jo["tag"] = tags
1627	}
1628
1629	j := junk.New()
1630	j["@context"] = itiswhatitis
1631	j["id"] = user.URL + "/" + "honk" + "/" + shortxid(ch.XID)
1632	j["type"] = "Create"
1633	j["actor"] = user.URL
1634	j["published"] = dt
1635	j["to"] = aud
1636	j["object"] = jo
1637
1638	return j.ToBytes()
1639}
1640
1641func sendchonk(user *WhatAbout, ch *Chonk) {
1642	rcpts := make(map[string]bool)
1643	rcpts[ch.Target] = true
1644	for a := range rcpts {
1645		msg := chonkifymsg(user, a, ch)
1646		go deliverate(user.ID, a, msg)
1647	}
1648}
1649
1650func honkworldwide(user *WhatAbout, honk *Honk) {
1651	jonk, _ := jonkjonk(user, honk)
1652	jonk["@context"] = itiswhatitis
1653	msg := jonk.ToBytes()
1654
1655	rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1656
1657	if honk.Public {
1658		for _, h := range getdubs(user.ID) {
1659			if h.XID == user.URL {
1660				continue
1661			}
1662			box, ok := boxofboxes.Get(h.XID)
1663			if ok && box.Shared != "" {
1664				rcpts["%"+box.Shared] = true
1665			} else {
1666				rcpts[h.XID] = true
1667			}
1668		}
1669		for _, f := range getbacktracks(honk.XID) {
1670			if f[0] == '%' {
1671				rcpts[f] = true
1672			} else {
1673				box, ok := boxofboxes.Get(f)
1674				if ok && box.Shared != "" {
1675					rcpts["%"+box.Shared] = true
1676				} else {
1677					rcpts[f] = true
1678				}
1679			}
1680		}
1681	}
1682	for a := range rcpts {
1683		go deliverate(user.ID, a, msg)
1684	}
1685	if honk.Public && len(honk.Onts) > 0 {
1686		collectiveaction(honk)
1687	}
1688}
1689
1690func collectiveaction(honk *Honk) {
1691	user := getserveruser()
1692	for _, ont := range honk.Onts {
1693		dubs := getnameddubs(readyLuserOne, ont)
1694		if len(dubs) == 0 {
1695			continue
1696		}
1697		j := junk.New()
1698		j["@context"] = itiswhatitis
1699		j["type"] = "Add"
1700		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1701		j["actor"] = user.URL
1702		j["object"] = honk.XID
1703		j["target"] = serverURL("/o/%s", ont[1:])
1704		rcpts := make(map[string]bool)
1705		for _, dub := range dubs {
1706			box, ok := boxofboxes.Get(dub.XID)
1707			if ok && box.Shared != "" {
1708				rcpts["%"+box.Shared] = true
1709			} else {
1710				rcpts[dub.XID] = true
1711			}
1712		}
1713		msg := j.ToBytes()
1714		for a := range rcpts {
1715			go deliverate(user.ID, a, msg)
1716		}
1717	}
1718}
1719
1720func junkuser(user *WhatAbout) junk.Junk {
1721	j := junk.New()
1722	j["@context"] = []string{itiswhatitis, papersplease}
1723	j["id"] = user.URL
1724	j["inbox"] = user.URL + "/inbox"
1725	j["outbox"] = user.URL + "/outbox"
1726	j["name"] = user.Display
1727	j["preferredUsername"] = user.Name
1728	j["summary"] = user.HTAbout
1729	var tags []junk.Junk
1730	for _, o := range user.Onts {
1731		t := junk.New()
1732		t["type"] = "Hashtag"
1733		o = strings.ToLower(o)
1734		t["href"] = serverURL("/o/%s", o[1:])
1735		t["name"] = o
1736		tags = append(tags, t)
1737	}
1738	if len(tags) > 0 {
1739		j["tag"] = tags
1740	}
1741
1742	if user.ID > 0 {
1743		j["type"] = "Person"
1744		j["url"] = user.URL
1745		j["followers"] = user.URL + "/followers"
1746		j["following"] = user.URL + "/following"
1747		a := junk.New()
1748		a["type"] = "Image"
1749		a["mediaType"] = "image/png"
1750		a["url"] = avatarURL(user)
1751		j["icon"] = a
1752		if ban := user.Options.Banner; ban != "" {
1753			a := junk.New()
1754			a["type"] = "Image"
1755			a["mediaType"] = "image/jpg"
1756			a["url"] = ban
1757			j["image"] = a
1758		}
1759	} else {
1760		j["type"] = "Service"
1761	}
1762	k := junk.New()
1763	k["id"] = user.URL + "#key"
1764	k["owner"] = user.URL
1765	k["publicKeyPem"] = user.Key
1766	j["publicKey"] = k
1767	j[chatKeyProp] = user.Options.ChatPubKey
1768
1769	return j
1770}
1771
1772var oldjonkers = gencache.New(gencache.Options[string, []byte]{Fill: func(name string) ([]byte, bool) {
1773	user, err := butwhatabout(name)
1774	if err != nil {
1775		return nil, false
1776	}
1777	j := junkuser(user)
1778	return j.ToBytes(), true
1779}, Duration: 1 * time.Minute})
1780
1781func asjonker(name string) ([]byte, bool) {
1782	j, ok := oldjonkers.Get(name)
1783	return j, ok
1784}
1785
1786var handfull = gencache.New(gencache.Options[string, string]{Fill: func(name string) (string, bool) {
1787	m := strings.Split(name, "@")
1788	if len(m) != 2 {
1789		dlog.Printf("bad fish name: %s", name)
1790		return "", true
1791	}
1792	var href string
1793	row := stmtGetXonker.QueryRow(name, "fishname")
1794	err := row.Scan(&href)
1795	if err == nil {
1796		return href, true
1797	}
1798	dlog.Printf("fishing for %s", name)
1799	j, err := GetJunkFast(readyLuserOne, fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1800	if err != nil {
1801		ilog.Printf("failed to go fish %s: %s", name, err)
1802		return "", true
1803	}
1804	links, _ := j.GetArray("links")
1805	for _, li := range links {
1806		l, ok := li.(junk.Junk)
1807		if !ok {
1808			continue
1809		}
1810		href, _ := l.GetString("href")
1811		rel, _ := l.GetString("rel")
1812		t, _ := l.GetString("type")
1813		if rel == "self" && friendorfoe(t) {
1814			when := time.Now().UTC().Format(dbtimeformat)
1815			_, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1816			if err != nil {
1817				elog.Printf("error saving fishname: %s", err)
1818			}
1819			return href, true
1820		}
1821	}
1822	return href, true
1823}, Duration: 1 * time.Minute})
1824
1825func gofish(name string) string {
1826	if name[0] == '@' {
1827		name = name[1:]
1828	}
1829	href, _ := handfull.Get(name)
1830	return href
1831}
1832
1833func investigate(name string) (*SomeThing, error) {
1834	if name == "" {
1835		return nil, fmt.Errorf("no name")
1836	}
1837	if name[0] == '@' {
1838		name = gofish(name)
1839	}
1840	if name == "" {
1841		return nil, fmt.Errorf("no name")
1842	}
1843	obj, err := GetJunkFast(readyLuserOne, name)
1844	if err != nil {
1845		return nil, err
1846	}
1847	allinjest(originate(name), obj)
1848	return somethingabout(obj)
1849}
1850
1851func somethingabout(obj junk.Junk) (*SomeThing, error) {
1852	info := new(SomeThing)
1853	t, _ := obj.GetString("type")
1854	isowned := false
1855	switch t {
1856	case "Person":
1857		fallthrough
1858	case "Group":
1859		fallthrough
1860	case "Organization":
1861		fallthrough
1862	case "Application":
1863		fallthrough
1864	case "Service":
1865		info.What = SomeActor
1866	case "OrderedCollection":
1867		isowned = true
1868		fallthrough
1869	case "Collection":
1870		info.What = SomeCollection
1871	default:
1872		return nil, fmt.Errorf("unknown object type")
1873	}
1874	info.XID, _ = obj.GetString("id")
1875	info.Name, _ = obj.GetString("preferredUsername")
1876	if info.Name == "" {
1877		info.Name, _ = obj.GetString("name")
1878	}
1879	if isowned {
1880		info.Owner, _ = obj.GetString("attributedTo")
1881	}
1882	if info.Owner == "" {
1883		info.Owner = info.XID
1884	}
1885	return info, nil
1886}
1887
1888func allinjest(origin string, obj junk.Junk) {
1889	ident, _ := obj.GetString("id")
1890	if ident == "" {
1891		return
1892	}
1893	if originate(ident) != origin {
1894		return
1895	}
1896	keyobj, ok := obj.GetMap("publicKey")
1897	if ok {
1898		ingestpubkey(origin, keyobj)
1899	}
1900	ingestboxes(origin, obj)
1901	ingesthandle(origin, obj)
1902	chatkey, ok := obj.GetString(chatKeyProp)
1903	if ok {
1904		when := time.Now().UTC().Format(dbtimeformat)
1905		_, err := stmtSaveXonker.Exec(ident, chatkey, chatKeyProp, when)
1906		if err != nil {
1907			elog.Printf("error saving chatkey: %s", err)
1908		}
1909	}
1910}
1911
1912func ingestpubkey(origin string, obj junk.Junk) {
1913	keyobj, ok := obj.GetMap("publicKey")
1914	if ok {
1915		obj = keyobj
1916	}
1917	keyname, ok := obj.GetString("id")
1918	var data string
1919	row := stmtGetXonker.QueryRow(keyname, "pubkey")
1920	err := row.Scan(&data)
1921	if err == nil {
1922		return
1923	}
1924	if !ok || origin != originate(keyname) {
1925		ilog.Printf("bad key origin %s <> %s", origin, keyname)
1926		return
1927	}
1928	dlog.Printf("ingesting a needed pubkey: %s", keyname)
1929	owner, ok := obj.GetString("owner")
1930	if !ok {
1931		ilog.Printf("error finding %s pubkey owner", keyname)
1932		return
1933	}
1934	data, ok = obj.GetString("publicKeyPem")
1935	if !ok {
1936		ilog.Printf("error finding %s pubkey", keyname)
1937		return
1938	}
1939	if originate(owner) != origin {
1940		ilog.Printf("bad key owner: %s <> %s", owner, origin)
1941		return
1942	}
1943	_, _, err = httpsig.DecodeKey(data)
1944	if err != nil {
1945		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
1946		return
1947	}
1948	when := time.Now().UTC().Format(dbtimeformat)
1949	_, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1950	if err != nil {
1951		elog.Printf("error saving key: %s", err)
1952	}
1953}
1954
1955func ingestboxes(origin string, obj junk.Junk) {
1956	ident, _ := obj.GetString("id")
1957	if ident == "" {
1958		return
1959	}
1960	if originate(ident) != origin {
1961		return
1962	}
1963	var info string
1964	row := stmtGetXonker.QueryRow(ident, "boxes")
1965	err := row.Scan(&info)
1966	if err == nil {
1967		return
1968	}
1969	dlog.Printf("ingesting boxes: %s", ident)
1970	inbox, _ := obj.GetString("inbox")
1971	outbox, _ := obj.GetString("outbox")
1972	sbox, _ := obj.GetString("endpoints", "sharedInbox")
1973	if inbox != "" {
1974		when := time.Now().UTC().Format(dbtimeformat)
1975		m := strings.Join([]string{inbox, outbox, sbox}, " ")
1976		_, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1977		if err != nil {
1978			elog.Printf("error saving boxes: %s", err)
1979		}
1980	}
1981}
1982
1983func ingesthandle(origin string, obj junk.Junk) {
1984	xid, _ := obj.GetString("id")
1985	if xid == "" {
1986		return
1987	}
1988	if originate(xid) != origin {
1989		return
1990	}
1991	var handle string
1992	row := stmtGetXonker.QueryRow(xid, "handle")
1993	err := row.Scan(&handle)
1994	if err == nil {
1995		return
1996	}
1997	handle, _ = obj.GetString("preferredUsername")
1998	if handle != "" {
1999		when := time.Now().UTC().Format(dbtimeformat)
2000		_, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
2001		if err != nil {
2002			elog.Printf("error saving handle: %s", err)
2003		}
2004	}
2005}
2006
2007func updateMe(username string) {
2008	user, _ := somenamedusers.Get(username)
2009	dt := time.Now().UTC().Format(time.RFC3339)
2010	j := junk.New()
2011	j["@context"] = itiswhatitis
2012	j["id"] = fmt.Sprintf("%s/upme/%s/%d", user.URL, user.Name, time.Now().Unix())
2013	j["actor"] = user.URL
2014	j["published"] = dt
2015	j["to"] = thewholeworld
2016	j["type"] = "Update"
2017	j["object"] = junkuser(user)
2018
2019	msg := j.ToBytes()
2020
2021	rcpts := make(map[string]bool)
2022	for _, f := range getdubs(user.ID) {
2023		if f.XID == user.URL {
2024			continue
2025		}
2026		box, ok := boxofboxes.Get(f.XID)
2027		if ok && box.Shared != "" {
2028			rcpts["%"+box.Shared] = true
2029		} else {
2030			rcpts[f.XID] = true
2031		}
2032	}
2033	for a := range rcpts {
2034		go deliverate(user.ID, a, msg)
2035	}
2036}
2037
2038func followme(user *WhatAbout, who string, name string, j junk.Junk) {
2039	folxid, _ := j.GetString("id")
2040
2041	ilog.Printf("updating honker follow: %s %s", who, folxid)
2042
2043	var x string
2044	db := opendatabase()
2045	row := db.QueryRow("select xid from honkers where name = ? and xid = ? and userid = ? and flavor in ('dub', 'undub')", name, who, user.ID)
2046	err := row.Scan(&x)
2047	if err != sql.ErrNoRows {
2048		ilog.Printf("duplicate follow request: %s", who)
2049		_, err = stmtUpdateFlavor.Exec("dub", folxid, user.ID, name, who, "undub")
2050		if err != nil {
2051			elog.Printf("error updating honker: %s", err)
2052		}
2053	} else {
2054		stmtSaveDub.Exec(user.ID, name, who, "dub", folxid)
2055	}
2056	go rubadubdub(user, j)
2057}
2058
2059func unfollowme(user *WhatAbout, who string, name string, j junk.Junk) {
2060	var folxid string
2061	if who == "" {
2062		folxid, _ = j.GetString("object")
2063
2064		db := opendatabase()
2065		row := db.QueryRow("select xid, name from honkers where userid = ? and folxid = ? and flavor in ('dub', 'undub')", user.ID, folxid)
2066		err := row.Scan(&who, &name)
2067		if err != nil {
2068			if err != sql.ErrNoRows {
2069				elog.Printf("error scanning honker: %s", err)
2070			}
2071			return
2072		}
2073	}
2074
2075	ilog.Printf("updating honker undo: %s %s", who, folxid)
2076	_, err := stmtUpdateFlavor.Exec("undub", folxid, user.ID, name, who, "dub")
2077	if err != nil {
2078		elog.Printf("error updating honker: %s", err)
2079		return
2080	}
2081}
2082
2083func followyou(user *WhatAbout, honkerid int64, sync bool) {
2084	var url, owner string
2085	db := opendatabase()
2086	row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
2087		honkerid, user.ID)
2088	err := row.Scan(&url, &owner)
2089	if err != nil {
2090		elog.Printf("can't get honker xid: %s", err)
2091		return
2092	}
2093	folxid := xfiltrate()
2094	ilog.Printf("subscribing to %s", url)
2095	_, err = db.Exec("update honkers set flavor = ?, folxid = ? where honkerid = ?", "presub", folxid, honkerid)
2096	if err != nil {
2097		elog.Printf("error updating honker: %s", err)
2098		return
2099	}
2100	if sync {
2101		subsub(user, url, owner, folxid)
2102	} else {
2103		go subsub(user, url, owner, folxid)
2104	}
2105
2106}
2107func unfollowyou(user *WhatAbout, honkerid int64, sync bool) {
2108	db := opendatabase()
2109	row := db.QueryRow("select xid, owner, folxid, flavor from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
2110		honkerid, user.ID)
2111	var url, owner, folxid, flavor string
2112	err := row.Scan(&url, &owner, &folxid, &flavor)
2113	if err != nil {
2114		elog.Printf("can't get honker xid: %s", err)
2115		return
2116	}
2117	if flavor == "peep" {
2118		return
2119	}
2120	ilog.Printf("unsubscribing from %s", url)
2121	_, err = db.Exec("update honkers set flavor = ? where honkerid = ?", "unsub", honkerid)
2122	if err != nil {
2123		elog.Printf("error updating honker: %s", err)
2124		return
2125	}
2126	if sync {
2127		itakeitallback(user, url, owner, folxid)
2128	} else {
2129		go itakeitallback(user, url, owner, folxid)
2130	}
2131}
2132
2133func followyou2(user *WhatAbout, j junk.Junk) {
2134	who, _ := j.GetString("actor")
2135
2136	ilog.Printf("updating honker accept: %s", who)
2137	db := opendatabase()
2138	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
2139		user.ID, who)
2140	var name, folxid string
2141	err := row.Scan(&name, &folxid)
2142	if err != nil {
2143		elog.Printf("can't get honker name: %s", err)
2144		return
2145	}
2146	_, err = stmtUpdateFlavor.Exec("sub", folxid, user.ID, name, who, "presub")
2147	if err != nil {
2148		elog.Printf("error updating honker: %s", err)
2149		return
2150	}
2151}
2152
2153func nofollowyou2(user *WhatAbout, j junk.Junk) {
2154	who, _ := j.GetString("actor")
2155
2156	ilog.Printf("updating honker reject: %s", who)
2157	db := opendatabase()
2158	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
2159		user.ID, who)
2160	var name, folxid string
2161	err := row.Scan(&name, &folxid)
2162	if err != nil {
2163		elog.Printf("can't get honker name: %s", err)
2164		return
2165	}
2166	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "presub")
2167	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "sub")
2168	if err != nil {
2169		elog.Printf("error updating honker: %s", err)
2170		return
2171	}
2172}