all repos — honk @ 4e3436d573bf6adc3554f9c70faf7c3815a311f9

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