all repos — honk @ 7244bbc70cbe5a9db15ef1eda6a00d374f23fc99

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