all repos — honk @ 389115d658ec02a28a8fa5e3ab9b78462d2e93a1

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