all repos — honk @ 071b0b07c557aaa083185fdc0444898127ea7a5b

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	"compress/gzip"
  21	"crypto/rsa"
  22	"database/sql"
  23	"fmt"
  24	"io"
  25	"log"
  26	"net/http"
  27	"net/url"
  28	"os"
  29	"regexp"
  30	"strings"
  31	"sync"
  32	"time"
  33
  34	"humungus.tedunangst.com/r/webs/image"
  35	"humungus.tedunangst.com/r/webs/junk"
  36)
  37
  38var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
  39var thefakename = `application/activity+json`
  40var falsenames = []string{
  41	`application/ld+json`,
  42	`application/activity+json`,
  43}
  44var itiswhatitis = "https://www.w3.org/ns/activitystreams"
  45var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
  46
  47func friendorfoe(ct string) bool {
  48	ct = strings.ToLower(ct)
  49	for _, at := range falsenames {
  50		if strings.HasPrefix(ct, at) {
  51			return true
  52		}
  53	}
  54	return false
  55}
  56
  57func PostJunk(keyname string, key *rsa.PrivateKey, url string, j junk.Junk) error {
  58	var buf bytes.Buffer
  59	j.Write(&buf)
  60	return PostMsg(keyname, key, url, buf.Bytes())
  61}
  62
  63func PostMsg(keyname string, key *rsa.PrivateKey, url string, msg []byte) error {
  64	client := http.DefaultClient
  65	req, err := http.NewRequest("POST", url, bytes.NewReader(msg))
  66	if err != nil {
  67		return err
  68	}
  69	req.Header.Set("User-Agent", "honksnonk/5.0")
  70	req.Header.Set("Content-Type", theonetruename)
  71	zig(keyname, key, req, msg)
  72	resp, err := client.Do(req)
  73	if err != nil {
  74		return err
  75	}
  76	resp.Body.Close()
  77	switch resp.StatusCode {
  78	case 200:
  79	case 201:
  80	case 202:
  81	default:
  82		return fmt.Errorf("http post status: %d", resp.StatusCode)
  83	}
  84	log.Printf("successful post: %s %d", url, resp.StatusCode)
  85	return nil
  86}
  87
  88type gzCloser struct {
  89	r     *gzip.Reader
  90	under io.ReadCloser
  91}
  92
  93func (gz *gzCloser) Read(p []byte) (int, error) {
  94	return gz.r.Read(p)
  95}
  96
  97func (gz *gzCloser) Close() error {
  98	defer gz.under.Close()
  99	return gz.r.Close()
 100}
 101
 102func GetJunk(url string) (junk.Junk, error) {
 103	client := http.DefaultClient
 104	req, err := http.NewRequest("GET", url, nil)
 105	if err != nil {
 106		return nil, err
 107	}
 108	at := thefakename
 109	if strings.Contains(url, ".well-known/webfinger?resource") {
 110		at = "application/jrd+json"
 111	}
 112	req.Header.Set("Accept", at)
 113	req.Header.Set("Accept-Encoding", "gzip")
 114	req.Header.Set("User-Agent", "honksnonk/5.0")
 115	resp, err := client.Do(req)
 116	if err != nil {
 117		log.Printf("first get failed: %s", err)
 118		resp, err = client.Do(req)
 119		if err != nil {
 120			return nil, err
 121		}
 122		log.Printf("retry succeeded!")
 123	}
 124	if resp.StatusCode != 200 {
 125		resp.Body.Close()
 126		return nil, fmt.Errorf("http get status: %d", resp.StatusCode)
 127	}
 128	if strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
 129		gz, err := gzip.NewReader(resp.Body)
 130		if err != nil {
 131			resp.Body.Close()
 132			return nil, err
 133		}
 134		resp.Body = &gzCloser{r: gz, under: resp.Body}
 135	}
 136	defer resp.Body.Close()
 137	j, err := junk.Read(resp.Body)
 138	return j, err
 139}
 140
 141func savedonk(url string, name, media string, localize bool) *Donk {
 142	if url == "" {
 143		return nil
 144	}
 145	var donk Donk
 146	row := stmtFindFile.QueryRow(url)
 147	err := row.Scan(&donk.FileID)
 148	if err == nil {
 149		return &donk
 150	}
 151	log.Printf("saving donk: %s", url)
 152	if err != nil && err != sql.ErrNoRows {
 153		log.Printf("error querying: %s", err)
 154	}
 155	xid := xfiltrate()
 156	data := []byte{}
 157	if localize {
 158		resp, err := http.Get(url)
 159		if err != nil {
 160			log.Printf("error fetching %s: %s", url, err)
 161			localize = false
 162			goto saveit
 163		}
 164		defer resp.Body.Close()
 165		if resp.StatusCode != 200 {
 166			localize = false
 167			goto saveit
 168		}
 169		var buf bytes.Buffer
 170		io.Copy(&buf, resp.Body)
 171
 172		data = buf.Bytes()
 173		if strings.HasPrefix(media, "image") {
 174			img, err := image.Vacuum(&buf, image.Params{MaxWidth: 2048, MaxHeight: 2048})
 175			if err != nil {
 176				log.Printf("unable to decode image: %s", err)
 177				localize = false
 178				data = []byte{}
 179				goto saveit
 180			}
 181			data = img.Data
 182			media = "image/" + img.Format
 183		} else if len(data) > 100000 {
 184			log.Printf("not saving large attachment")
 185			localize = false
 186			data = []byte{}
 187		}
 188	}
 189saveit:
 190	res, err := stmtSaveFile.Exec(xid, name, url, media, localize, data)
 191	if err != nil {
 192		log.Printf("error saving file %s: %s", url, err)
 193		return nil
 194	}
 195	donk.FileID, _ = res.LastInsertId()
 196	return &donk
 197}
 198
 199func iszonked(userid int64, xid string) bool {
 200	row := stmtFindZonk.QueryRow(userid, xid)
 201	var id int64
 202	err := row.Scan(&id)
 203	if err == nil {
 204		return true
 205	}
 206	if err != sql.ErrNoRows {
 207		log.Printf("err querying zonk: %s", err)
 208	}
 209	return false
 210}
 211
 212func needxonk(user *WhatAbout, x *Honk) bool {
 213	if x.What == "eradicate" {
 214		return true
 215	}
 216	if thoudostbitethythumb(user.ID, x.Audience, x.XID) {
 217		log.Printf("not saving thumb biter? %s via %s", x.XID, x.Honker)
 218		return false
 219	}
 220	return needxonkid(user, x.XID)
 221}
 222func needxonkid(user *WhatAbout, xid string) bool {
 223	if strings.HasPrefix(xid, user.URL+"/h/") {
 224		return false
 225	}
 226	if iszonked(user.ID, xid) {
 227		log.Printf("already zonked: %s", xid)
 228		return false
 229	}
 230	row := stmtFindXonk.QueryRow(user.ID, xid)
 231	var id int64
 232	err := row.Scan(&id)
 233	if err == nil {
 234		return false
 235	}
 236	if err != sql.ErrNoRows {
 237		log.Printf("err querying xonk: %s", err)
 238	}
 239	return true
 240}
 241
 242func savexonk(user *WhatAbout, x *Honk) {
 243	if x.What == "eradicate" {
 244		log.Printf("eradicating %s by %s", x.XID, x.Honker)
 245		xonk := getxonk(user.ID, x.XID)
 246		if xonk != nil {
 247			stmtZonkDonks.Exec(xonk.ID)
 248			_, err := stmtZonkIt.Exec(user.ID, x.XID)
 249			if err != nil {
 250				log.Printf("error eradicating: %s", err)
 251			}
 252		}
 253		stmtSaveZonker.Exec(user.ID, x.XID, "zonk")
 254		return
 255	}
 256	log.Printf("saving xonk: %s", x.XID)
 257	dt := x.Date.UTC().Format(dbtimeformat)
 258	aud := strings.Join(x.Audience, " ")
 259	whofore := 0
 260	if strings.Contains(aud, user.URL) {
 261		whofore = 1
 262	}
 263	res, err := stmtSaveHonk.Exec(x.UserID, x.What, x.Honker, x.XID, x.RID, dt, x.URL, aud,
 264		x.Noise, x.Convoy, whofore, "html", x.Precis, x.Oonker)
 265	if err != nil {
 266		log.Printf("err saving xonk: %s", err)
 267		return
 268	}
 269	x.ID, _ = res.LastInsertId()
 270	for _, d := range x.Donks {
 271		_, err = stmtSaveDonk.Exec(x.ID, d.FileID)
 272		if err != nil {
 273			log.Printf("err saving donk: %s", err)
 274			return
 275		}
 276	}
 277}
 278
 279type Box struct {
 280	In     string
 281	Out    string
 282	Shared string
 283}
 284
 285var boxofboxes = make(map[string]*Box)
 286var boxlock sync.Mutex
 287var boxinglock sync.Mutex
 288
 289func getboxes(ident string) (*Box, error) {
 290	boxlock.Lock()
 291	b, ok := boxofboxes[ident]
 292	boxlock.Unlock()
 293	if ok {
 294		return b, nil
 295	}
 296
 297	boxinglock.Lock()
 298	defer boxinglock.Unlock()
 299
 300	boxlock.Lock()
 301	b, ok = boxofboxes[ident]
 302	boxlock.Unlock()
 303	if ok {
 304		return b, nil
 305	}
 306
 307	var info string
 308	row := stmtGetXonker.QueryRow(ident, "boxes")
 309	err := row.Scan(&info)
 310	if err != nil {
 311		j, err := GetJunk(ident)
 312		if err != nil {
 313			return nil, err
 314		}
 315		inbox, _ := j.GetString("inbox")
 316		outbox, _ := j.GetString("outbox")
 317		sbox, _ := j.FindString([]string{"endpoints", "sharedInbox"})
 318		b = &Box{In: inbox, Out: outbox, Shared: sbox}
 319		if inbox != "" {
 320			m := strings.Join([]string{inbox, outbox, sbox}, " ")
 321			_, err = stmtSaveXonker.Exec(ident, m, "boxes")
 322			if err != nil {
 323				log.Printf("error saving boxes: %s", err)
 324			}
 325		}
 326	} else {
 327		m := strings.Split(info, " ")
 328		b = &Box{In: m[0], Out: m[1], Shared: m[2]}
 329	}
 330
 331	boxlock.Lock()
 332	boxofboxes[ident] = b
 333	boxlock.Unlock()
 334	return b, nil
 335}
 336
 337func gimmexonks(user *WhatAbout, outbox string) {
 338	log.Printf("getting outbox: %s", outbox)
 339	j, err := GetJunk(outbox)
 340	if err != nil {
 341		log.Printf("error getting outbox: %s", err)
 342		return
 343	}
 344	t, _ := j.GetString("type")
 345	origin := originate(outbox)
 346	if t == "OrderedCollection" {
 347		items, _ := j.GetArray("orderedItems")
 348		if items == nil {
 349			obj, ok := j.GetMap("first")
 350			if ok {
 351				items, _ = obj.GetArray("orderedItems")
 352			} else {
 353				page1, _ := j.GetString("first")
 354				j, err = GetJunk(page1)
 355				if err != nil {
 356					log.Printf("error gettings page1: %s", err)
 357					return
 358				}
 359				items, _ = j.GetArray("orderedItems")
 360			}
 361		}
 362		if len(items) > 20 {
 363			items = items[0:20]
 364		}
 365		for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
 366			items[i], items[j] = items[j], items[i]
 367		}
 368		for _, item := range items {
 369			obj, ok := item.(junk.Junk)
 370			if !ok {
 371				continue
 372			}
 373			xonk := xonkxonk(user, obj, origin)
 374			if xonk != nil {
 375				savexonk(user, xonk)
 376			}
 377		}
 378	}
 379}
 380
 381func peeppeep() {
 382	user, _ := butwhatabout("htest")
 383	honkers := gethonkers(user.ID)
 384	for _, f := range honkers {
 385		if f.Flavor != "peep" {
 386			continue
 387		}
 388		log.Printf("getting updates: %s", f.XID)
 389		box, err := getboxes(f.XID)
 390		if err != nil {
 391			log.Printf("error getting outbox: %s", err)
 392			continue
 393		}
 394		gimmexonks(user, box.Out)
 395	}
 396}
 397func whosthere(xid string) ([]string, string) {
 398	obj, err := GetJunk(xid)
 399	if err != nil {
 400		log.Printf("error getting remote xonk: %s", err)
 401		return nil, ""
 402	}
 403	convoy, _ := obj.GetString("context")
 404	if convoy == "" {
 405		convoy, _ = obj.GetString("conversation")
 406	}
 407	return newphone(nil, obj), convoy
 408}
 409
 410func newphone(a []string, obj junk.Junk) []string {
 411	for _, addr := range []string{"to", "cc", "attributedTo"} {
 412		who, _ := obj.GetString(addr)
 413		if who != "" {
 414			a = append(a, who)
 415		}
 416		whos, _ := obj.GetArray(addr)
 417		for _, w := range whos {
 418			who, _ := w.(string)
 419			if who != "" {
 420				a = append(a, who)
 421			}
 422		}
 423	}
 424	return a
 425}
 426
 427func extractattrto(obj junk.Junk) string {
 428	who, _ := obj.GetString("attributedTo")
 429	if who != "" {
 430		return who
 431	}
 432	arr, _ := obj.GetArray("attributedTo")
 433	for _, a := range arr {
 434		o, ok := a.(junk.Junk)
 435		if ok {
 436			t, _ := o.GetString("type")
 437			id, _ := o.GetString("id")
 438			if t == "Person" || t == "" {
 439				return id
 440			}
 441		}
 442	}
 443	return ""
 444}
 445
 446func consumeactivity(user *WhatAbout, j junk.Junk, origin string) {
 447	xonk := xonkxonk(user, j, origin)
 448	if xonk != nil {
 449		savexonk(user, xonk)
 450	}
 451}
 452
 453func xonkxonk(user *WhatAbout, item junk.Junk, origin string) *Honk {
 454	depth := 0
 455	maxdepth := 4
 456	currenttid := ""
 457	var xonkxonkfn func(item junk.Junk, origin string) *Honk
 458
 459	saveoneup := func(xid string) {
 460		log.Printf("getting oneup: %s", xid)
 461		if depth >= maxdepth {
 462			log.Printf("in too deep")
 463			return
 464		}
 465		obj, err := GetJunk(xid)
 466		if err != nil {
 467			log.Printf("error getting oneup: %s", err)
 468			return
 469		}
 470		depth++
 471		xonk := xonkxonkfn(obj, originate(xid))
 472		if xonk != nil {
 473			savexonk(user, xonk)
 474		}
 475		depth--
 476	}
 477
 478	xonkxonkfn = func(item junk.Junk, origin string) *Honk {
 479		// id, _ := item.GetString( "id")
 480		what, _ := item.GetString("type")
 481		dt, _ := item.GetString("published")
 482
 483		var audience []string
 484		var err error
 485		var xid, rid, url, content, precis, convoy, oonker string
 486		var obj junk.Junk
 487		var ok bool
 488		switch what {
 489		case "Announce":
 490			obj, ok = item.GetMap("object")
 491			if ok {
 492				xid, _ = obj.GetString("id")
 493			} else {
 494				xid, _ = item.GetString("object")
 495			}
 496			if !needxonkid(user, xid) {
 497				return nil
 498			}
 499			log.Printf("getting bonk: %s", xid)
 500			obj, err = GetJunk(xid)
 501			if err != nil {
 502				log.Printf("error regetting: %s", err)
 503			}
 504			origin = originate(xid)
 505			what = "bonk"
 506		case "Create":
 507			obj, _ = item.GetMap("object")
 508			what = "honk"
 509		case "Delete":
 510			obj, _ = item.GetMap("object")
 511			xid, _ = item.GetString("object")
 512			what = "eradicate"
 513		case "Video":
 514			fallthrough
 515		case "Question":
 516			fallthrough
 517		case "Note":
 518			fallthrough
 519		case "Article":
 520			fallthrough
 521		case "Page":
 522			obj = item
 523			what = "honk"
 524		default:
 525			log.Printf("unknown activity: %s", what)
 526			fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 527			item.Write(fd)
 528			io.WriteString(fd, "\n")
 529			fd.Close()
 530			return nil
 531		}
 532
 533		var xonk Honk
 534		who, _ := item.GetString("actor")
 535		if obj != nil {
 536			if who == "" {
 537				who = extractattrto(obj)
 538			}
 539			oonker = extractattrto(obj)
 540			ot, _ := obj.GetString("type")
 541			url, _ = obj.GetString("url")
 542			if ot == "Tombstone" {
 543				xid, _ = obj.GetString("id")
 544			} else {
 545				audience = newphone(audience, obj)
 546				xid, _ = obj.GetString("id")
 547				precis, _ = obj.GetString("summary")
 548				content, _ = obj.GetString("content")
 549				if !strings.HasPrefix(content, "<p>") {
 550					content = "<p>" + content
 551				}
 552				rid, _ = obj.GetString("inReplyTo")
 553				convoy, _ = obj.GetString("context")
 554				if convoy == "" {
 555					convoy, _ = obj.GetString("conversation")
 556				}
 557				if ot == "Question" {
 558					if what == "honk" {
 559						what = "qonk"
 560					}
 561					content += "<ul>"
 562					ans, _ := obj.GetArray("oneOf")
 563					for _, ai := range ans {
 564						a, ok := ai.(junk.Junk)
 565						if !ok {
 566							continue
 567						}
 568						as, _ := a.GetString("name")
 569						content += "<li>" + as
 570					}
 571					ans, _ = obj.GetArray("anyOf")
 572					for _, ai := range ans {
 573						a, ok := ai.(junk.Junk)
 574						if !ok {
 575							continue
 576						}
 577						as, _ := a.GetString("name")
 578						content += "<li>" + as
 579					}
 580					content += "</ul>"
 581				}
 582				if what == "honk" && rid != "" {
 583					what = "tonk"
 584				}
 585			}
 586			atts, _ := obj.GetArray("attachment")
 587			for i, atti := range atts {
 588				att, ok := atti.(junk.Junk)
 589				if !ok {
 590					continue
 591				}
 592				at, _ := att.GetString("type")
 593				mt, _ := att.GetString("mediaType")
 594				u, _ := att.GetString("url")
 595				name, _ := att.GetString("name")
 596				localize := false
 597				if i > 4 {
 598					log.Printf("excessive attachment: %s", at)
 599				} else if at == "Document" || at == "Image" {
 600					mt = strings.ToLower(mt)
 601					log.Printf("attachment: %s %s", mt, u)
 602					if mt == "text/plain" || strings.HasPrefix(mt, "image") {
 603						localize = true
 604					}
 605				} else {
 606					log.Printf("unknown attachment: %s", at)
 607				}
 608				donk := savedonk(u, name, mt, localize)
 609				if donk != nil {
 610					xonk.Donks = append(xonk.Donks, donk)
 611				}
 612			}
 613			tags, _ := obj.GetArray("tag")
 614			for _, tagi := range tags {
 615				tag, ok := tagi.(junk.Junk)
 616				if !ok {
 617					continue
 618				}
 619				tt, _ := tag.GetString("type")
 620				name, _ := tag.GetString("name")
 621				if tt == "Emoji" {
 622					icon, _ := tag.GetMap("icon")
 623					mt, _ := icon.GetString("mediaType")
 624					if mt == "" {
 625						mt = "image/png"
 626					}
 627					u, _ := icon.GetString("url")
 628					donk := savedonk(u, name, mt, true)
 629					if donk != nil {
 630						xonk.Donks = append(xonk.Donks, donk)
 631					}
 632				}
 633			}
 634		}
 635		if originate(xid) != origin {
 636			log.Printf("original sin: %s <> %s", xid, origin)
 637			item.Write(os.Stdout)
 638			return nil
 639		}
 640		audience = append(audience, who)
 641
 642		audience = oneofakind(audience)
 643
 644		if currenttid == "" {
 645			currenttid = convoy
 646		}
 647
 648		if oonker == who {
 649			oonker = ""
 650		}
 651		xonk.UserID = user.ID
 652		xonk.What = what
 653		xonk.Honker = who
 654		xonk.XID = xid
 655		xonk.RID = rid
 656		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 657		xonk.URL = url
 658		xonk.Noise = content
 659		xonk.Precis = precis
 660		xonk.Audience = audience
 661		xonk.Oonker = oonker
 662
 663		if needxonk(user, &xonk) {
 664			if rid != "" {
 665				if needxonkid(user, rid) {
 666					saveoneup(rid)
 667				}
 668			}
 669			if convoy == "" {
 670				convoy = currenttid
 671			}
 672			xonk.Convoy = convoy
 673			return &xonk
 674		}
 675		return nil
 676	}
 677
 678	return xonkxonkfn(item, origin)
 679}
 680
 681func rubadubdub(user *WhatAbout, req junk.Junk) {
 682	xid, _ := req.GetString("id")
 683	actor, _ := req.GetString("actor")
 684	j := junk.New()
 685	j["@context"] = itiswhatitis
 686	j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
 687	j["type"] = "Accept"
 688	j["actor"] = user.URL
 689	j["to"] = actor
 690	j["published"] = time.Now().UTC().Format(time.RFC3339)
 691	j["object"] = req
 692
 693	var buf bytes.Buffer
 694	j.Write(&buf)
 695	msg := buf.Bytes()
 696
 697	deliverate(0, user.Name, actor, msg)
 698}
 699
 700func itakeitallback(user *WhatAbout, xid string) {
 701	j := junk.New()
 702	j["@context"] = itiswhatitis
 703	j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
 704	j["type"] = "Undo"
 705	j["actor"] = user.URL
 706	j["to"] = xid
 707	f := junk.New()
 708	f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 709	f["type"] = "Follow"
 710	f["actor"] = user.URL
 711	f["to"] = xid
 712	f["object"] = xid
 713	j["object"] = f
 714	j["published"] = time.Now().UTC().Format(time.RFC3339)
 715
 716	var buf bytes.Buffer
 717	j.Write(&buf)
 718	msg := buf.Bytes()
 719
 720	deliverate(0, user.Name, xid, msg)
 721}
 722
 723func subsub(user *WhatAbout, xid string) {
 724	j := junk.New()
 725	j["@context"] = itiswhatitis
 726	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 727	j["type"] = "Follow"
 728	j["actor"] = user.URL
 729	j["to"] = xid
 730	j["object"] = xid
 731	j["published"] = time.Now().UTC().Format(time.RFC3339)
 732
 733	var buf bytes.Buffer
 734	j.Write(&buf)
 735	msg := buf.Bytes()
 736
 737	deliverate(0, user.Name, xid, msg)
 738}
 739
 740var re_spicy = regexp.MustCompile("^(\U0001f336\ufe0f?){3,}")
 741
 742func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 743	dt := h.Date.Format(time.RFC3339)
 744	var jo junk.Junk
 745	j := junk.New()
 746	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 747	j["actor"] = user.URL
 748	j["published"] = dt
 749	if h.Public {
 750		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
 751	} else {
 752		j["to"] = h.Audience[0]
 753	}
 754	if len(h.Audience) > 1 {
 755		j["cc"] = h.Audience[1:]
 756	}
 757
 758	switch h.What {
 759	case "tonk":
 760		fallthrough
 761	case "honk":
 762		j["type"] = "Create"
 763
 764		jo = junk.New()
 765		jo["id"] = h.XID
 766		jo["type"] = "Note"
 767		jo["published"] = dt
 768		jo["url"] = h.XID
 769		jo["attributedTo"] = user.URL
 770		if h.RID != "" {
 771			jo["inReplyTo"] = h.RID
 772		}
 773		if h.Convoy != "" {
 774			jo["context"] = h.Convoy
 775			jo["conversation"] = h.Convoy
 776		}
 777		jo["to"] = h.Audience[0]
 778		if len(h.Audience) > 1 {
 779			jo["cc"] = h.Audience[1:]
 780		}
 781		if !h.Public {
 782			jo["directMessage"] = true
 783		}
 784		jo["summary"] = h.Precis
 785		jo["content"] = mentionize(h.Noise)
 786		if strings.HasPrefix(h.Precis, "DZ:") {
 787			jo["sensitive"] = true
 788		} else if peppers := re_spicy.FindString(h.Noise); peppers != "" {
 789			jo["summary"] = peppers
 790			jo["sensitive"] = true
 791		}
 792
 793		var tags []interface{}
 794		g := bunchofgrapes(h.Noise)
 795		for _, m := range g {
 796			t := junk.New()
 797			t["type"] = "Mention"
 798			t["name"] = m.who
 799			t["href"] = m.where
 800			tags = append(tags, t)
 801		}
 802		ooo := ontologies(h.Noise)
 803		for _, o := range ooo {
 804			t := junk.New()
 805			t["type"] = "Hashtag"
 806			t["name"] = o
 807			tags = append(tags, t)
 808		}
 809		herd := herdofemus(h.Noise)
 810		for _, e := range herd {
 811			t := junk.New()
 812			t["id"] = e.ID
 813			t["type"] = "Emoji"
 814			t["name"] = e.Name
 815			i := junk.New()
 816			i["type"] = "Image"
 817			i["mediaType"] = "image/png"
 818			i["url"] = e.ID
 819			t["icon"] = i
 820			tags = append(tags, t)
 821		}
 822		if len(tags) > 0 {
 823			jo["tag"] = tags
 824		}
 825		var atts []interface{}
 826		for _, d := range h.Donks {
 827			if re_emus.MatchString(d.Name) {
 828				continue
 829			}
 830			jd := junk.New()
 831			jd["mediaType"] = d.Media
 832			jd["name"] = d.Name
 833			jd["type"] = "Document"
 834			jd["url"] = d.URL
 835			atts = append(atts, jd)
 836		}
 837		if len(atts) > 0 {
 838			jo["attachment"] = atts
 839		}
 840		j["object"] = jo
 841	case "bonk":
 842		j["type"] = "Announce"
 843		if h.Convoy != "" {
 844			j["context"] = h.Convoy
 845		}
 846		j["object"] = h.XID
 847	case "zonk":
 848		j["type"] = "Delete"
 849		j["object"] = h.XID
 850	}
 851
 852	return j, jo
 853}
 854
 855func honkworldwide(user *WhatAbout, honk *Honk) {
 856	jonk, _ := jonkjonk(user, honk)
 857	jonk["@context"] = itiswhatitis
 858	var buf bytes.Buffer
 859	jonk.Write(&buf)
 860	msg := buf.Bytes()
 861
 862	rcpts := make(map[string]bool)
 863	for _, a := range honk.Audience {
 864		if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
 865			box, _ := getboxes(a)
 866			if box != nil {
 867				if honk.Public && box.Shared != "" {
 868					rcpts["%"+box.Shared] = true
 869				} else {
 870					rcpts["%"+box.In] = true
 871				}
 872			} else {
 873				rcpts[a] = true
 874			}
 875		}
 876	}
 877	if honk.Public {
 878		for _, f := range getdubs(user.ID) {
 879			box, _ := getboxes(f.XID)
 880			if box != nil && box.Shared != "" {
 881				rcpts["%"+box.Shared] = true
 882			} else {
 883				rcpts[f.XID] = true
 884			}
 885		}
 886	}
 887	for a := range rcpts {
 888		go deliverate(0, user.Name, a, msg)
 889	}
 890}
 891
 892func asjonker(user *WhatAbout) junk.Junk {
 893	about := obfusbreak(user.About)
 894
 895	j := junk.New()
 896	j["@context"] = itiswhatitis
 897	j["id"] = user.URL
 898	j["type"] = "Person"
 899	j["inbox"] = user.URL + "/inbox"
 900	j["outbox"] = user.URL + "/outbox"
 901	j["followers"] = user.URL + "/followers"
 902	j["following"] = user.URL + "/following"
 903	j["name"] = user.Display
 904	j["preferredUsername"] = user.Name
 905	j["summary"] = about
 906	j["url"] = user.URL
 907	a := junk.New()
 908	a["type"] = "Image"
 909	a["mediaType"] = "image/png"
 910	a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
 911	j["icon"] = a
 912	k := junk.New()
 913	k["id"] = user.URL + "#key"
 914	k["owner"] = user.URL
 915	k["publicKeyPem"] = user.Key
 916	j["publicKey"] = k
 917
 918	return j
 919}
 920
 921var handfull = make(map[string]string)
 922var handlock sync.Mutex
 923
 924func gofish(name string) string {
 925	if name[0] == '@' {
 926		name = name[1:]
 927	}
 928	m := strings.Split(name, "@")
 929	if len(m) != 2 {
 930		log.Printf("bad fish name: %s", name)
 931		return ""
 932	}
 933	handlock.Lock()
 934	ref, ok := handfull[name]
 935	handlock.Unlock()
 936	if ok {
 937		return ref
 938	}
 939	row := stmtGetXonker.QueryRow(name, "fishname")
 940	var href string
 941	err := row.Scan(&href)
 942	if err == nil {
 943		handlock.Lock()
 944		handfull[name] = href
 945		handlock.Unlock()
 946		return href
 947	}
 948	log.Printf("fishing for %s", name)
 949	j, err := GetJunk(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
 950	if err != nil {
 951		log.Printf("failed to go fish %s: %s", name, err)
 952		handlock.Lock()
 953		handfull[name] = ""
 954		handlock.Unlock()
 955		return ""
 956	}
 957	links, _ := j.GetArray("links")
 958	for _, li := range links {
 959		l, ok := li.(junk.Junk)
 960		if !ok {
 961			continue
 962		}
 963		href, _ := l.GetString("href")
 964		rel, _ := l.GetString("rel")
 965		t, _ := l.GetString("type")
 966		if rel == "self" && friendorfoe(t) {
 967			stmtSaveXonker.Exec(name, href, "fishname")
 968			handlock.Lock()
 969			handfull[name] = href
 970			handlock.Unlock()
 971			return href
 972		}
 973	}
 974	handlock.Lock()
 975	handfull[name] = ""
 976	handlock.Unlock()
 977	return ""
 978}
 979
 980func investigate(name string) string {
 981	if name == "" {
 982		return ""
 983	}
 984	if name[0] == '@' {
 985		name = gofish(name)
 986	}
 987	if name == "" {
 988		return ""
 989	}
 990	obj, err := GetJunk(name)
 991	if err != nil {
 992		log.Printf("error investigating honker: %s", err)
 993		return ""
 994	}
 995	t, _ := obj.GetString("type")
 996	id, _ := obj.GetString("id")
 997	if t != "Person" {
 998		log.Printf("it's not a person! %s", name)
 999		return ""
1000	}
1001	return id
1002}