all repos — honk @ c617a17cf9533832487a08802bf407774b139598

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