all repos — honk @ a11b47be988540caf73eac09d7b87c15bdffbebc

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					}
1071				}
1072				for _, repl := range items {
1073					s, ok := repl.(string)
1074					if ok {
1075						replies = append(replies, s)
1076					}
1077				}
1078			}
1079
1080		}
1081
1082		if currenttid == "" {
1083			currenttid = convoy
1084		}
1085
1086		// init xonk
1087		xonk.What = what
1088		xonk.RID = rid
1089		xonk.Date, _ = time.Parse(time.RFC3339, dt)
1090		xonk.URL = url
1091		xonk.Format = "html"
1092		xonk.Convoy = convoy
1093		xonk.Mentions = mentions
1094		for _, m := range mentions {
1095			if m.Where == user.URL {
1096				xonk.Whofore = 1
1097			}
1098		}
1099		imaginate(&xonk)
1100
1101		if what == "chonk" {
1102			target, _ := obj.GetString("to")
1103			if target == user.URL {
1104				target = xonk.Honker
1105			}
1106			ch := Chonk{
1107				UserID: xonk.UserID,
1108				XID:    xid,
1109				Who:    xonk.Honker,
1110				Target: target,
1111				Date:   xonk.Date,
1112				Noise:  xonk.Noise,
1113				Format: xonk.Format,
1114				Donks:  xonk.Donks,
1115			}
1116			savechonk(&ch)
1117			return nil
1118		}
1119
1120		if isUpdate {
1121			dlog.Printf("something has changed! %s", xonk.XID)
1122			prev := getxonk(user.ID, xonk.XID)
1123			if prev == nil {
1124				ilog.Printf("didn't find old version for update: %s", xonk.XID)
1125				isUpdate = false
1126			} else {
1127				xonk.ID = prev.ID
1128				updatehonk(&xonk)
1129			}
1130		}
1131		if !isUpdate && needxonk(user, &xonk) {
1132			if rid != "" && xonk.Public {
1133				if needxonkid(user, rid) {
1134					goingup++
1135					saveonemore(rid)
1136					goingup--
1137				}
1138				if convoy == "" {
1139					xx := getxonk(user.ID, rid)
1140					if xx != nil {
1141						convoy = xx.Convoy
1142					}
1143				}
1144			}
1145			if convoy == "" {
1146				convoy = currenttid
1147			}
1148			if convoy == "" {
1149				convoy = xonk.XID
1150				currenttid = convoy
1151			}
1152			xonk.Convoy = convoy
1153			savexonk(&xonk)
1154		}
1155		if goingup == 0 {
1156			for _, replid := range replies {
1157				if needxonkid(user, replid) {
1158					dlog.Printf("missing a reply: %s", replid)
1159					saveonemore(replid)
1160				}
1161			}
1162		}
1163		return &xonk
1164	}
1165
1166	return xonkxonkfn(item, origin, false, "")
1167}
1168
1169func dumpactivity(item junk.Junk) {
1170	fd, err := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
1171	if err != nil {
1172		elog.Printf("error opening inbox! %s", err)
1173		return
1174	}
1175	defer fd.Close()
1176	item.Write(fd)
1177	io.WriteString(fd, "\n")
1178}
1179
1180func rubadubdub(user *WhatAbout, req junk.Junk) {
1181	actor, _ := req.GetString("actor")
1182	j := junk.New()
1183	j["@context"] = itiswhatitis
1184	j["id"] = user.URL + "/dub/" + xfiltrate()
1185	j["type"] = "Accept"
1186	j["actor"] = user.URL
1187	j["to"] = actor
1188	j["published"] = time.Now().UTC().Format(time.RFC3339)
1189	j["object"] = req
1190
1191	deliverate(user.ID, actor, j.ToBytes())
1192}
1193
1194func itakeitallback(user *WhatAbout, xid string, owner string, folxid string) {
1195	j := junk.New()
1196	j["@context"] = itiswhatitis
1197	j["id"] = user.URL + "/unsub/" + folxid
1198	j["type"] = "Undo"
1199	j["actor"] = user.URL
1200	j["to"] = owner
1201	f := junk.New()
1202	f["id"] = user.URL + "/sub/" + folxid
1203	f["type"] = "Follow"
1204	f["actor"] = user.URL
1205	f["to"] = owner
1206	f["object"] = xid
1207	j["object"] = f
1208	j["published"] = time.Now().UTC().Format(time.RFC3339)
1209
1210	deliverate(user.ID, owner, j.ToBytes())
1211}
1212
1213func subsub(user *WhatAbout, xid string, owner string, folxid string) {
1214	if xid == "" {
1215		ilog.Printf("can't subscribe to empty")
1216		return
1217	}
1218	j := junk.New()
1219	j["@context"] = itiswhatitis
1220	j["id"] = user.URL + "/sub/" + folxid
1221	j["type"] = "Follow"
1222	j["actor"] = user.URL
1223	j["to"] = owner
1224	j["object"] = xid
1225	j["published"] = time.Now().UTC().Format(time.RFC3339)
1226
1227	deliverate(user.ID, owner, j.ToBytes())
1228}
1229
1230func activatedonks(donks []*Donk) []junk.Junk {
1231	var atts []junk.Junk
1232	for _, d := range donks {
1233		if re_emus.MatchString(d.Name) {
1234			continue
1235		}
1236		jd := junk.New()
1237		jd["mediaType"] = d.Media
1238		jd["name"] = d.Name
1239		jd["summary"] = html.EscapeString(d.Desc)
1240		jd["type"] = "Document"
1241		jd["url"] = d.URL
1242		atts = append(atts, jd)
1243	}
1244	return atts
1245}
1246
1247// returns activity, object
1248func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
1249	dt := h.Date.Format(time.RFC3339)
1250	var jo junk.Junk
1251	j := junk.New()
1252	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
1253	j["actor"] = user.URL
1254	j["published"] = dt
1255	j["to"] = h.Audience[0]
1256	if len(h.Audience) > 1 {
1257		j["cc"] = h.Audience[1:]
1258	}
1259
1260	switch h.What {
1261	case "update":
1262		fallthrough
1263	case "event":
1264		fallthrough
1265	case "honk":
1266		j["type"] = "Create"
1267		jo = junk.New()
1268		jo["id"] = h.XID
1269		jo["type"] = "Note"
1270		if h.What == "event" {
1271			jo["type"] = "Event"
1272		}
1273		if h.What == "update" {
1274			j["type"] = "Update"
1275			jo["updated"] = dt
1276		}
1277		jo["published"] = dt
1278		jo["url"] = h.XID
1279		jo["attributedTo"] = user.URL
1280		if h.RID != "" {
1281			jo["inReplyTo"] = h.RID
1282		}
1283		if h.Convoy != "" {
1284			jo["context"] = h.Convoy
1285			jo["conversation"] = h.Convoy
1286		}
1287		jo["to"] = h.Audience[0]
1288		if len(h.Audience) > 1 {
1289			jo["cc"] = h.Audience[1:]
1290		}
1291		if !h.Public {
1292			jo["directMessage"] = true
1293		}
1294		h.Noise = re_retag.ReplaceAllString(h.Noise, "")
1295		translate(h)
1296		redoimages(h)
1297		if h.Precis != "" {
1298			jo["sensitive"] = true
1299		}
1300
1301		var replies []string
1302		for _, reply := range h.Replies {
1303			replies = append(replies, reply.XID)
1304		}
1305		if len(replies) > 0 {
1306			jr := junk.New()
1307			jr["type"] = "Collection"
1308			jr["totalItems"] = len(replies)
1309			jr["items"] = replies
1310			jo["replies"] = jr
1311		}
1312
1313		var tags []junk.Junk
1314		for _, m := range h.Mentions {
1315			t := junk.New()
1316			t["type"] = "Mention"
1317			t["name"] = m.Who
1318			t["href"] = m.Where
1319			tags = append(tags, t)
1320		}
1321		for _, o := range h.Onts {
1322			t := junk.New()
1323			t["type"] = "Hashtag"
1324			o = strings.ToLower(o)
1325			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1326			t["name"] = o
1327			tags = append(tags, t)
1328		}
1329		for _, e := range herdofemus(h.Noise) {
1330			t := junk.New()
1331			t["id"] = e.ID
1332			t["type"] = "Emoji"
1333			t["name"] = e.Name
1334			i := junk.New()
1335			i["type"] = "Image"
1336			i["mediaType"] = e.Type
1337			i["url"] = e.ID
1338			t["icon"] = i
1339			tags = append(tags, t)
1340		}
1341		for _, e := range fixupflags(h) {
1342			t := junk.New()
1343			t["id"] = e.ID
1344			t["type"] = "Emoji"
1345			t["name"] = e.Name
1346			i := junk.New()
1347			i["type"] = "Image"
1348			i["mediaType"] = "image/png"
1349			i["url"] = e.ID
1350			t["icon"] = i
1351			tags = append(tags, t)
1352		}
1353		if len(tags) > 0 {
1354			jo["tag"] = tags
1355		}
1356		if p := h.Place; p != nil {
1357			t := junk.New()
1358			t["type"] = "Place"
1359			if p.Name != "" {
1360				t["name"] = p.Name
1361			}
1362			if p.Latitude != 0 {
1363				t["latitude"] = p.Latitude
1364			}
1365			if p.Longitude != 0 {
1366				t["longitude"] = p.Longitude
1367			}
1368			if p.Url != "" {
1369				t["url"] = p.Url
1370			}
1371			jo["location"] = t
1372		}
1373		if t := h.Time; t != nil {
1374			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1375			if t.Duration != 0 {
1376				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1377			}
1378		}
1379		atts := activatedonks(h.Donks)
1380		if len(atts) > 0 {
1381			jo["attachment"] = atts
1382		}
1383		jo["summary"] = h.Precis
1384		jo["content"] = h.Noise
1385		j["object"] = jo
1386	case "bonk":
1387		j["type"] = "Announce"
1388		if h.Convoy != "" {
1389			j["context"] = h.Convoy
1390		}
1391		j["object"] = h.XID
1392	case "unbonk":
1393		b := junk.New()
1394		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1395		b["type"] = "Announce"
1396		b["actor"] = user.URL
1397		if h.Convoy != "" {
1398			b["context"] = h.Convoy
1399		}
1400		b["object"] = h.XID
1401		j["type"] = "Undo"
1402		j["object"] = b
1403	case "zonk":
1404		j["type"] = "Delete"
1405		j["object"] = h.XID
1406	case "ack":
1407		j["type"] = "Read"
1408		j["object"] = h.XID
1409		if h.Convoy != "" {
1410			j["context"] = h.Convoy
1411		}
1412	case "react":
1413		j["type"] = "EmojiReact"
1414		j["object"] = h.XID
1415		if h.Convoy != "" {
1416			j["context"] = h.Convoy
1417		}
1418		j["content"] = h.Noise
1419	case "deack":
1420		b := junk.New()
1421		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1422		b["type"] = "Read"
1423		b["actor"] = user.URL
1424		b["object"] = h.XID
1425		if h.Convoy != "" {
1426			b["context"] = h.Convoy
1427		}
1428		j["type"] = "Undo"
1429		j["object"] = b
1430	}
1431
1432	return j, jo
1433}
1434
1435var oldjonks = gencache.New(gencache.Options[string, []byte]{Fill: func(xid string) ([]byte, bool) {
1436	row := stmtAnyXonk.QueryRow(xid)
1437	honk := scanhonk(row)
1438	if honk == nil || !honk.Public {
1439		return nil, true
1440	}
1441	user, _ := butwhatabout(honk.Username)
1442	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1443	reversehonks(rawhonks)
1444	for _, h := range rawhonks {
1445		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1446			honk.Replies = append(honk.Replies, h)
1447		}
1448	}
1449	donksforhonks([]*Honk{honk})
1450	_, j := jonkjonk(user, honk)
1451	if j == nil {
1452		elog.Fatalf("what just happened? %v", honk)
1453	}
1454	j["@context"] = itiswhatitis
1455
1456	return j.ToBytes(), true
1457}, Limit: 128})
1458
1459func gimmejonk(xid string) ([]byte, bool) {
1460	j, ok := oldjonks.Get(xid)
1461	return j, ok
1462}
1463
1464func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1465	rcpts := make(map[string]bool)
1466	for _, a := range addresses {
1467		if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1468			continue
1469		}
1470		if a[0] == '%' {
1471			rcpts[a] = true
1472			continue
1473		}
1474		box, ok := boxofboxes.Get(a)
1475		if ok && useshared && box.Shared != "" {
1476			rcpts["%"+box.Shared] = true
1477		} else {
1478			rcpts[a] = true
1479		}
1480	}
1481	return rcpts
1482}
1483
1484func chonkifymsg(user *WhatAbout, ch *Chonk) []byte {
1485	dt := ch.Date.Format(time.RFC3339)
1486	aud := []string{ch.Target}
1487
1488	jo := junk.New()
1489	jo["id"] = ch.XID
1490	jo["type"] = "ChatMessage"
1491	jo["published"] = dt
1492	jo["attributedTo"] = user.URL
1493	jo["to"] = aud
1494	jo["content"] = ch.HTML
1495	atts := activatedonks(ch.Donks)
1496	if len(atts) > 0 {
1497		jo["attachment"] = atts
1498	}
1499	var tags []junk.Junk
1500	for _, e := range herdofemus(ch.Noise) {
1501		t := junk.New()
1502		t["id"] = e.ID
1503		t["type"] = "Emoji"
1504		t["name"] = e.Name
1505		i := junk.New()
1506		i["type"] = "Image"
1507		i["mediaType"] = e.Type
1508		i["url"] = e.ID
1509		t["icon"] = i
1510		tags = append(tags, t)
1511	}
1512	if len(tags) > 0 {
1513		jo["tag"] = tags
1514	}
1515
1516	j := junk.New()
1517	j["@context"] = itiswhatitis
1518	j["id"] = user.URL + "/" + "honk" + "/" + shortxid(ch.XID)
1519	j["type"] = "Create"
1520	j["actor"] = user.URL
1521	j["published"] = dt
1522	j["to"] = aud
1523	j["object"] = jo
1524
1525	return j.ToBytes()
1526}
1527
1528func sendchonk(user *WhatAbout, ch *Chonk) {
1529	msg := chonkifymsg(user, ch)
1530
1531	rcpts := make(map[string]bool)
1532	rcpts[ch.Target] = true
1533	for a := range rcpts {
1534		go deliverate(user.ID, a, msg)
1535	}
1536}
1537
1538func honkworldwide(user *WhatAbout, honk *Honk) {
1539	jonk, _ := jonkjonk(user, honk)
1540	jonk["@context"] = itiswhatitis
1541	msg := jonk.ToBytes()
1542
1543	rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1544
1545	if honk.Public {
1546		for _, h := range getdubs(user.ID) {
1547			if h.XID == user.URL {
1548				continue
1549			}
1550			box, ok := boxofboxes.Get(h.XID)
1551			if ok && box.Shared != "" {
1552				rcpts["%"+box.Shared] = true
1553			} else {
1554				rcpts[h.XID] = true
1555			}
1556		}
1557		for _, f := range getbacktracks(honk.XID) {
1558			if f[0] == '%' {
1559				rcpts[f] = true
1560			} else {
1561				box, ok := boxofboxes.Get(f)
1562				if ok && box.Shared != "" {
1563					rcpts["%"+box.Shared] = true
1564				} else {
1565					rcpts[f] = true
1566				}
1567			}
1568		}
1569	}
1570	for a := range rcpts {
1571		go deliverate(user.ID, a, msg)
1572	}
1573	if honk.Public && len(honk.Onts) > 0 {
1574		collectiveaction(honk)
1575	}
1576}
1577
1578func collectiveaction(honk *Honk) {
1579	user := getserveruser()
1580	for _, ont := range honk.Onts {
1581		dubs := getnameddubs(readyLuserOne, ont)
1582		if len(dubs) == 0 {
1583			continue
1584		}
1585		j := junk.New()
1586		j["@context"] = itiswhatitis
1587		j["type"] = "Add"
1588		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1589		j["actor"] = user.URL
1590		j["object"] = honk.XID
1591		j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1592		rcpts := make(map[string]bool)
1593		for _, dub := range dubs {
1594			box, ok := boxofboxes.Get(dub.XID)
1595			if ok && box.Shared != "" {
1596				rcpts["%"+box.Shared] = true
1597			} else {
1598				rcpts[dub.XID] = true
1599			}
1600		}
1601		msg := j.ToBytes()
1602		for a := range rcpts {
1603			go deliverate(user.ID, a, msg)
1604		}
1605	}
1606}
1607
1608func junkuser(user *WhatAbout) junk.Junk {
1609	j := junk.New()
1610	j["@context"] = itiswhatitis
1611	j["id"] = user.URL
1612	j["inbox"] = user.URL + "/inbox"
1613	j["outbox"] = user.URL + "/outbox"
1614	j["name"] = user.Display
1615	j["preferredUsername"] = user.Name
1616	j["summary"] = user.HTAbout
1617	var tags []junk.Junk
1618	for _, o := range user.Onts {
1619		t := junk.New()
1620		t["type"] = "Hashtag"
1621		o = strings.ToLower(o)
1622		t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1623		t["name"] = o
1624		tags = append(tags, t)
1625	}
1626	if len(tags) > 0 {
1627		j["tag"] = tags
1628	}
1629
1630	if user.ID > 0 {
1631		j["type"] = "Person"
1632		j["url"] = user.URL
1633		j["followers"] = user.URL + "/followers"
1634		j["following"] = user.URL + "/following"
1635		a := junk.New()
1636		a["type"] = "Image"
1637		a["mediaType"] = "image/png"
1638		a["url"] = avatarURL(user)
1639		j["icon"] = a
1640		if ban := user.Options.Banner; ban != "" {
1641			a := junk.New()
1642			a["type"] = "Image"
1643			a["mediaType"] = "image/jpg"
1644			a["url"] = ban
1645			j["image"] = a
1646		}
1647	} else {
1648		j["type"] = "Service"
1649	}
1650	k := junk.New()
1651	k["id"] = user.URL + "#key"
1652	k["owner"] = user.URL
1653	k["publicKeyPem"] = user.Key
1654	j["publicKey"] = k
1655
1656	return j
1657}
1658
1659var oldjonkers = gencache.New(gencache.Options[string, []byte]{Fill: func(name string) ([]byte, bool) {
1660	user, err := butwhatabout(name)
1661	if err != nil {
1662		return nil, false
1663	}
1664	j := junkuser(user)
1665	return j.ToBytes(), true
1666}, Duration: 1 * time.Minute})
1667
1668func asjonker(name string) ([]byte, bool) {
1669	j, ok := oldjonkers.Get(name)
1670	return j, ok
1671}
1672
1673var handfull = gencache.New(gencache.Options[string, string]{Fill: func(name string) (string, bool) {
1674	m := strings.Split(name, "@")
1675	if len(m) != 2 {
1676		dlog.Printf("bad fish name: %s", name)
1677		return "", true
1678	}
1679	var href string
1680	row := stmtGetXonker.QueryRow(name, "fishname")
1681	err := row.Scan(&href)
1682	if err == nil {
1683		return href, true
1684	}
1685	dlog.Printf("fishing for %s", name)
1686	j, err := GetJunkFast(readyLuserOne, fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1687	if err != nil {
1688		ilog.Printf("failed to go fish %s: %s", name, err)
1689		return "", true
1690	}
1691	links, _ := j.GetArray("links")
1692	for _, li := range links {
1693		l, ok := li.(junk.Junk)
1694		if !ok {
1695			continue
1696		}
1697		href, _ := l.GetString("href")
1698		rel, _ := l.GetString("rel")
1699		t, _ := l.GetString("type")
1700		if rel == "self" && friendorfoe(t) {
1701			when := time.Now().UTC().Format(dbtimeformat)
1702			_, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1703			if err != nil {
1704				elog.Printf("error saving fishname: %s", err)
1705			}
1706			return href, true
1707		}
1708	}
1709	return href, true
1710}, Duration: 1 * time.Minute})
1711
1712func gofish(name string) string {
1713	if name[0] == '@' {
1714		name = name[1:]
1715	}
1716	href, _ := handfull.Get(name)
1717	return href
1718}
1719
1720func investigate(name string) (*SomeThing, error) {
1721	if name == "" {
1722		return nil, fmt.Errorf("no name")
1723	}
1724	if name[0] == '@' {
1725		name = gofish(name)
1726	}
1727	if name == "" {
1728		return nil, fmt.Errorf("no name")
1729	}
1730	obj, err := GetJunkFast(readyLuserOne, name)
1731	if err != nil {
1732		return nil, err
1733	}
1734	allinjest(originate(name), obj)
1735	return somethingabout(obj)
1736}
1737
1738func somethingabout(obj junk.Junk) (*SomeThing, error) {
1739	info := new(SomeThing)
1740	t, _ := obj.GetString("type")
1741	isowned := false
1742	switch t {
1743	case "Person":
1744		fallthrough
1745	case "Group":
1746		fallthrough
1747	case "Organization":
1748		fallthrough
1749	case "Application":
1750		fallthrough
1751	case "Service":
1752		info.What = SomeActor
1753	case "OrderedCollection":
1754		isowned = true
1755		fallthrough
1756	case "Collection":
1757		info.What = SomeCollection
1758	default:
1759		return nil, fmt.Errorf("unknown object type")
1760	}
1761	info.XID, _ = obj.GetString("id")
1762	info.Name, _ = obj.GetString("preferredUsername")
1763	if info.Name == "" {
1764		info.Name, _ = obj.GetString("name")
1765	}
1766	if isowned {
1767		info.Owner, _ = obj.GetString("attributedTo")
1768	}
1769	if info.Owner == "" {
1770		info.Owner = info.XID
1771	}
1772	return info, nil
1773}
1774
1775func allinjest(origin string, obj junk.Junk) {
1776	keyobj, ok := obj.GetMap("publicKey")
1777	if ok {
1778		ingestpubkey(origin, keyobj)
1779	}
1780	ingestboxes(origin, obj)
1781	ingesthandle(origin, obj)
1782}
1783
1784func ingestpubkey(origin string, obj junk.Junk) {
1785	keyobj, ok := obj.GetMap("publicKey")
1786	if ok {
1787		obj = keyobj
1788	}
1789	keyname, ok := obj.GetString("id")
1790	var data string
1791	row := stmtGetXonker.QueryRow(keyname, "pubkey")
1792	err := row.Scan(&data)
1793	if err == nil {
1794		return
1795	}
1796	if !ok || origin != originate(keyname) {
1797		ilog.Printf("bad key origin %s <> %s", origin, keyname)
1798		return
1799	}
1800	dlog.Printf("ingesting a needed pubkey: %s", keyname)
1801	owner, ok := obj.GetString("owner")
1802	if !ok {
1803		ilog.Printf("error finding %s pubkey owner", keyname)
1804		return
1805	}
1806	data, ok = obj.GetString("publicKeyPem")
1807	if !ok {
1808		ilog.Printf("error finding %s pubkey", keyname)
1809		return
1810	}
1811	if originate(owner) != origin {
1812		ilog.Printf("bad key owner: %s <> %s", owner, origin)
1813		return
1814	}
1815	_, _, err = httpsig.DecodeKey(data)
1816	if err != nil {
1817		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
1818		return
1819	}
1820	when := time.Now().UTC().Format(dbtimeformat)
1821	_, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1822	if err != nil {
1823		elog.Printf("error saving key: %s", err)
1824	}
1825}
1826
1827func ingestboxes(origin string, obj junk.Junk) {
1828	ident, _ := obj.GetString("id")
1829	if ident == "" {
1830		return
1831	}
1832	if originate(ident) != origin {
1833		return
1834	}
1835	var info string
1836	row := stmtGetXonker.QueryRow(ident, "boxes")
1837	err := row.Scan(&info)
1838	if err == nil {
1839		return
1840	}
1841	dlog.Printf("ingesting boxes: %s", ident)
1842	inbox, _ := obj.GetString("inbox")
1843	outbox, _ := obj.GetString("outbox")
1844	sbox, _ := obj.GetString("endpoints", "sharedInbox")
1845	if inbox != "" {
1846		when := time.Now().UTC().Format(dbtimeformat)
1847		m := strings.Join([]string{inbox, outbox, sbox}, " ")
1848		_, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1849		if err != nil {
1850			elog.Printf("error saving boxes: %s", err)
1851		}
1852	}
1853}
1854
1855func ingesthandle(origin string, obj junk.Junk) {
1856	xid, _ := obj.GetString("id")
1857	if xid == "" {
1858		return
1859	}
1860	if originate(xid) != origin {
1861		return
1862	}
1863	var handle string
1864	row := stmtGetXonker.QueryRow(xid, "handle")
1865	err := row.Scan(&handle)
1866	if err == nil {
1867		return
1868	}
1869	handle, _ = obj.GetString("preferredUsername")
1870	if handle != "" {
1871		when := time.Now().UTC().Format(dbtimeformat)
1872		_, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1873		if err != nil {
1874			elog.Printf("error saving handle: %s", err)
1875		}
1876	}
1877}
1878
1879func updateMe(username string) {
1880	user, _ := somenamedusers.Get(username)
1881	dt := time.Now().UTC().Format(time.RFC3339)
1882	j := junk.New()
1883	j["@context"] = itiswhatitis
1884	j["id"] = fmt.Sprintf("%s/upme/%s/%d", user.URL, user.Name, time.Now().Unix())
1885	j["actor"] = user.URL
1886	j["published"] = dt
1887	j["to"] = thewholeworld
1888	j["type"] = "Update"
1889	j["object"] = junkuser(user)
1890
1891	msg := j.ToBytes()
1892
1893	rcpts := make(map[string]bool)
1894	for _, f := range getdubs(user.ID) {
1895		if f.XID == user.URL {
1896			continue
1897		}
1898		box, ok := boxofboxes.Get(f.XID)
1899		if ok && box.Shared != "" {
1900			rcpts["%"+box.Shared] = true
1901		} else {
1902			rcpts[f.XID] = true
1903		}
1904	}
1905	for a := range rcpts {
1906		go deliverate(user.ID, a, msg)
1907	}
1908}
1909
1910func followme(user *WhatAbout, who string, name string, j junk.Junk) {
1911	folxid, _ := j.GetString("id")
1912
1913	ilog.Printf("updating honker follow: %s %s", who, folxid)
1914
1915	var x string
1916	db := opendatabase()
1917	row := db.QueryRow("select xid from honkers where name = ? and xid = ? and userid = ? and flavor in ('dub', 'undub')", name, who, user.ID)
1918	err := row.Scan(&x)
1919	if err != sql.ErrNoRows {
1920		ilog.Printf("duplicate follow request: %s", who)
1921		_, err = stmtUpdateFlavor.Exec("dub", folxid, user.ID, name, who, "undub")
1922		if err != nil {
1923			elog.Printf("error updating honker: %s", err)
1924		}
1925	} else {
1926		stmtSaveDub.Exec(user.ID, name, who, "dub", folxid)
1927	}
1928	go rubadubdub(user, j)
1929}
1930
1931func unfollowme(user *WhatAbout, who string, name string, j junk.Junk) {
1932	var folxid string
1933	if who == "" {
1934		folxid, _ = j.GetString("object")
1935
1936		db := opendatabase()
1937		row := db.QueryRow("select xid, name from honkers where userid = ? and folxid = ? and flavor in ('dub', 'undub')", user.ID, folxid)
1938		err := row.Scan(&who, &name)
1939		if err != nil {
1940			if err != sql.ErrNoRows {
1941				elog.Printf("error scanning honker: %s", err)
1942			}
1943			return
1944		}
1945	}
1946
1947	ilog.Printf("updating honker undo: %s %s", who, folxid)
1948	_, err := stmtUpdateFlavor.Exec("undub", folxid, user.ID, name, who, "dub")
1949	if err != nil {
1950		elog.Printf("error updating honker: %s", err)
1951		return
1952	}
1953}
1954
1955func followyou(user *WhatAbout, honkerid int64, sync bool) {
1956	var url, owner string
1957	db := opendatabase()
1958	row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1959		honkerid, user.ID)
1960	err := row.Scan(&url, &owner)
1961	if err != nil {
1962		elog.Printf("can't get honker xid: %s", err)
1963		return
1964	}
1965	folxid := xfiltrate()
1966	ilog.Printf("subscribing to %s", url)
1967	_, err = db.Exec("update honkers set flavor = ?, folxid = ? where honkerid = ?", "presub", folxid, honkerid)
1968	if err != nil {
1969		elog.Printf("error updating honker: %s", err)
1970		return
1971	}
1972	if sync {
1973		subsub(user, url, owner, folxid)
1974	} else {
1975		go subsub(user, url, owner, folxid)
1976	}
1977
1978}
1979func unfollowyou(user *WhatAbout, honkerid int64, sync bool) {
1980	db := opendatabase()
1981	row := db.QueryRow("select xid, owner, folxid, flavor from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1982		honkerid, user.ID)
1983	var url, owner, folxid, flavor string
1984	err := row.Scan(&url, &owner, &folxid, &flavor)
1985	if err != nil {
1986		elog.Printf("can't get honker xid: %s", err)
1987		return
1988	}
1989	if flavor == "peep" {
1990		return
1991	}
1992	ilog.Printf("unsubscribing from %s", url)
1993	_, err = db.Exec("update honkers set flavor = ? where honkerid = ?", "unsub", honkerid)
1994	if err != nil {
1995		elog.Printf("error updating honker: %s", err)
1996		return
1997	}
1998	if sync {
1999		itakeitallback(user, url, owner, folxid)
2000	} else {
2001		go itakeitallback(user, url, owner, folxid)
2002	}
2003}
2004
2005func followyou2(user *WhatAbout, j junk.Junk) {
2006	who, _ := j.GetString("actor")
2007
2008	ilog.Printf("updating honker accept: %s", who)
2009	db := opendatabase()
2010	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
2011		user.ID, who)
2012	var name, folxid string
2013	err := row.Scan(&name, &folxid)
2014	if err != nil {
2015		elog.Printf("can't get honker name: %s", err)
2016		return
2017	}
2018	_, err = stmtUpdateFlavor.Exec("sub", folxid, user.ID, name, who, "presub")
2019	if err != nil {
2020		elog.Printf("error updating honker: %s", err)
2021		return
2022	}
2023}
2024
2025func nofollowyou2(user *WhatAbout, j junk.Junk) {
2026	who, _ := j.GetString("actor")
2027
2028	ilog.Printf("updating honker reject: %s", who)
2029	db := opendatabase()
2030	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
2031		user.ID, who)
2032	var name, folxid string
2033	err := row.Scan(&name, &folxid)
2034	if err != nil {
2035		elog.Printf("can't get honker name: %s", err)
2036		return
2037	}
2038	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "presub")
2039	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "sub")
2040	if err != nil {
2041		elog.Printf("error updating honker: %s", err)
2042		return
2043	}
2044}