all repos — honk @ a1f5e5b57cae0f06fad03d6a18ebf94a24912897

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				sens, _ := obj["sensitive"].(bool)
 553				if sens && precis == "" {
 554					precis = "unspecified horror"
 555				}
 556				rid, _ = obj.GetString("inReplyTo")
 557				convoy, _ = obj.GetString("context")
 558				if convoy == "" {
 559					convoy, _ = obj.GetString("conversation")
 560				}
 561				if ot == "Question" {
 562					if what == "honk" {
 563						what = "qonk"
 564					}
 565					content += "<ul>"
 566					ans, _ := obj.GetArray("oneOf")
 567					for _, ai := range ans {
 568						a, ok := ai.(junk.Junk)
 569						if !ok {
 570							continue
 571						}
 572						as, _ := a.GetString("name")
 573						content += "<li>" + as
 574					}
 575					ans, _ = obj.GetArray("anyOf")
 576					for _, ai := range ans {
 577						a, ok := ai.(junk.Junk)
 578						if !ok {
 579							continue
 580						}
 581						as, _ := a.GetString("name")
 582						content += "<li>" + as
 583					}
 584					content += "</ul>"
 585				}
 586				if what == "honk" && rid != "" {
 587					what = "tonk"
 588				}
 589			}
 590			atts, _ := obj.GetArray("attachment")
 591			for i, atti := range atts {
 592				att, ok := atti.(junk.Junk)
 593				if !ok {
 594					continue
 595				}
 596				at, _ := att.GetString("type")
 597				mt, _ := att.GetString("mediaType")
 598				u, _ := att.GetString("url")
 599				name, _ := att.GetString("name")
 600				localize := false
 601				if i > 4 {
 602					log.Printf("excessive attachment: %s", at)
 603				} else if at == "Document" || at == "Image" {
 604					mt = strings.ToLower(mt)
 605					log.Printf("attachment: %s %s", mt, u)
 606					if mt == "text/plain" || strings.HasPrefix(mt, "image") {
 607						localize = true
 608					}
 609				} else {
 610					log.Printf("unknown attachment: %s", at)
 611				}
 612				donk := savedonk(u, name, mt, localize)
 613				if donk != nil {
 614					xonk.Donks = append(xonk.Donks, donk)
 615				}
 616			}
 617			tags, _ := obj.GetArray("tag")
 618			for _, tagi := range tags {
 619				tag, ok := tagi.(junk.Junk)
 620				if !ok {
 621					continue
 622				}
 623				tt, _ := tag.GetString("type")
 624				name, _ := tag.GetString("name")
 625				if tt == "Emoji" {
 626					icon, _ := tag.GetMap("icon")
 627					mt, _ := icon.GetString("mediaType")
 628					if mt == "" {
 629						mt = "image/png"
 630					}
 631					u, _ := icon.GetString("url")
 632					donk := savedonk(u, name, mt, true)
 633					if donk != nil {
 634						xonk.Donks = append(xonk.Donks, donk)
 635					}
 636				}
 637			}
 638		}
 639		if originate(xid) != origin {
 640			log.Printf("original sin: %s <> %s", xid, origin)
 641			item.Write(os.Stdout)
 642			return nil
 643		}
 644		audience = append(audience, who)
 645
 646		audience = oneofakind(audience)
 647
 648		if currenttid == "" {
 649			currenttid = convoy
 650		}
 651
 652		if oonker == who {
 653			oonker = ""
 654		}
 655		xonk.UserID = user.ID
 656		xonk.What = what
 657		xonk.Honker = who
 658		xonk.XID = xid
 659		xonk.RID = rid
 660		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 661		xonk.URL = url
 662		xonk.Noise = content
 663		xonk.Precis = precis
 664		xonk.Audience = audience
 665		xonk.Oonker = oonker
 666
 667		if needxonk(user, &xonk) {
 668			if rid != "" {
 669				if needxonkid(user, rid) {
 670					saveoneup(rid)
 671				}
 672			}
 673			if convoy == "" {
 674				convoy = currenttid
 675			}
 676			xonk.Convoy = convoy
 677			return &xonk
 678		}
 679		return nil
 680	}
 681
 682	return xonkxonkfn(item, origin)
 683}
 684
 685func rubadubdub(user *WhatAbout, req junk.Junk) {
 686	xid, _ := req.GetString("id")
 687	actor, _ := req.GetString("actor")
 688	j := junk.New()
 689	j["@context"] = itiswhatitis
 690	j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
 691	j["type"] = "Accept"
 692	j["actor"] = user.URL
 693	j["to"] = actor
 694	j["published"] = time.Now().UTC().Format(time.RFC3339)
 695	j["object"] = req
 696
 697	var buf bytes.Buffer
 698	j.Write(&buf)
 699	msg := buf.Bytes()
 700
 701	deliverate(0, user.Name, actor, msg)
 702}
 703
 704func itakeitallback(user *WhatAbout, xid string) {
 705	j := junk.New()
 706	j["@context"] = itiswhatitis
 707	j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
 708	j["type"] = "Undo"
 709	j["actor"] = user.URL
 710	j["to"] = xid
 711	f := junk.New()
 712	f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 713	f["type"] = "Follow"
 714	f["actor"] = user.URL
 715	f["to"] = xid
 716	f["object"] = xid
 717	j["object"] = f
 718	j["published"] = time.Now().UTC().Format(time.RFC3339)
 719
 720	var buf bytes.Buffer
 721	j.Write(&buf)
 722	msg := buf.Bytes()
 723
 724	deliverate(0, user.Name, xid, msg)
 725}
 726
 727func subsub(user *WhatAbout, xid string) {
 728	j := junk.New()
 729	j["@context"] = itiswhatitis
 730	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 731	j["type"] = "Follow"
 732	j["actor"] = user.URL
 733	j["to"] = xid
 734	j["object"] = xid
 735	j["published"] = time.Now().UTC().Format(time.RFC3339)
 736
 737	var buf bytes.Buffer
 738	j.Write(&buf)
 739	msg := buf.Bytes()
 740
 741	deliverate(0, user.Name, xid, msg)
 742}
 743
 744var re_spicy = regexp.MustCompile("^(\U0001f336\ufe0f?){3,}")
 745
 746func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 747	dt := h.Date.Format(time.RFC3339)
 748	var jo junk.Junk
 749	j := junk.New()
 750	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 751	j["actor"] = user.URL
 752	j["published"] = dt
 753	if h.Public {
 754		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
 755	} else {
 756		j["to"] = h.Audience[0]
 757	}
 758	if len(h.Audience) > 1 {
 759		j["cc"] = h.Audience[1:]
 760	}
 761
 762	switch h.What {
 763	case "tonk":
 764		fallthrough
 765	case "honk":
 766		j["type"] = "Create"
 767
 768		jo = junk.New()
 769		jo["id"] = h.XID
 770		jo["type"] = "Note"
 771		jo["published"] = dt
 772		jo["url"] = h.XID
 773		jo["attributedTo"] = user.URL
 774		if h.RID != "" {
 775			jo["inReplyTo"] = h.RID
 776		}
 777		if h.Convoy != "" {
 778			jo["context"] = h.Convoy
 779			jo["conversation"] = h.Convoy
 780		}
 781		jo["to"] = h.Audience[0]
 782		if len(h.Audience) > 1 {
 783			jo["cc"] = h.Audience[1:]
 784		}
 785		if !h.Public {
 786			jo["directMessage"] = true
 787		}
 788		jo["summary"] = h.Precis
 789		jo["content"] = mentionize(h.Noise)
 790		if strings.HasPrefix(h.Precis, "DZ:") {
 791			jo["sensitive"] = true
 792		} else if peppers := re_spicy.FindString(h.Noise); peppers != "" {
 793			jo["summary"] = peppers
 794			jo["sensitive"] = true
 795		}
 796
 797		var tags []interface{}
 798		g := bunchofgrapes(h.Noise)
 799		for _, m := range g {
 800			t := junk.New()
 801			t["type"] = "Mention"
 802			t["name"] = m.who
 803			t["href"] = m.where
 804			tags = append(tags, t)
 805		}
 806		ooo := ontologies(h.Noise)
 807		for _, o := range ooo {
 808			t := junk.New()
 809			t["type"] = "Hashtag"
 810			t["name"] = o
 811			tags = append(tags, t)
 812		}
 813		herd := herdofemus(h.Noise)
 814		for _, e := range herd {
 815			t := junk.New()
 816			t["id"] = e.ID
 817			t["type"] = "Emoji"
 818			t["name"] = e.Name
 819			i := junk.New()
 820			i["type"] = "Image"
 821			i["mediaType"] = "image/png"
 822			i["url"] = e.ID
 823			t["icon"] = i
 824			tags = append(tags, t)
 825		}
 826		if len(tags) > 0 {
 827			jo["tag"] = tags
 828		}
 829		var atts []interface{}
 830		for _, d := range h.Donks {
 831			if re_emus.MatchString(d.Name) {
 832				continue
 833			}
 834			jd := junk.New()
 835			jd["mediaType"] = d.Media
 836			jd["name"] = d.Name
 837			jd["type"] = "Document"
 838			jd["url"] = d.URL
 839			atts = append(atts, jd)
 840		}
 841		if len(atts) > 0 {
 842			jo["attachment"] = atts
 843		}
 844		j["object"] = jo
 845	case "bonk":
 846		j["type"] = "Announce"
 847		if h.Convoy != "" {
 848			j["context"] = h.Convoy
 849		}
 850		j["object"] = h.XID
 851	case "zonk":
 852		j["type"] = "Delete"
 853		j["object"] = h.XID
 854	}
 855
 856	return j, jo
 857}
 858
 859func honkworldwide(user *WhatAbout, honk *Honk) {
 860	jonk, _ := jonkjonk(user, honk)
 861	jonk["@context"] = itiswhatitis
 862	var buf bytes.Buffer
 863	jonk.Write(&buf)
 864	msg := buf.Bytes()
 865
 866	rcpts := make(map[string]bool)
 867	for _, a := range honk.Audience {
 868		if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
 869			box, _ := getboxes(a)
 870			if box != nil {
 871				if honk.Public && box.Shared != "" {
 872					rcpts["%"+box.Shared] = true
 873				} else {
 874					rcpts["%"+box.In] = true
 875				}
 876			} else {
 877				rcpts[a] = true
 878			}
 879		}
 880	}
 881	if honk.Public {
 882		for _, f := range getdubs(user.ID) {
 883			box, _ := getboxes(f.XID)
 884			if box != nil && box.Shared != "" {
 885				rcpts["%"+box.Shared] = true
 886			} else {
 887				rcpts[f.XID] = true
 888			}
 889		}
 890	}
 891	for a := range rcpts {
 892		go deliverate(0, user.Name, a, msg)
 893	}
 894}
 895
 896func asjonker(user *WhatAbout) junk.Junk {
 897	about := obfusbreak(user.About)
 898
 899	j := junk.New()
 900	j["@context"] = itiswhatitis
 901	j["id"] = user.URL
 902	j["type"] = "Person"
 903	j["inbox"] = user.URL + "/inbox"
 904	j["outbox"] = user.URL + "/outbox"
 905	j["followers"] = user.URL + "/followers"
 906	j["following"] = user.URL + "/following"
 907	j["name"] = user.Display
 908	j["preferredUsername"] = user.Name
 909	j["summary"] = about
 910	j["url"] = user.URL
 911	a := junk.New()
 912	a["type"] = "Image"
 913	a["mediaType"] = "image/png"
 914	a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
 915	j["icon"] = a
 916	k := junk.New()
 917	k["id"] = user.URL + "#key"
 918	k["owner"] = user.URL
 919	k["publicKeyPem"] = user.Key
 920	j["publicKey"] = k
 921
 922	return j
 923}
 924
 925var handfull = make(map[string]string)
 926var handlock sync.Mutex
 927
 928func gofish(name string) string {
 929	if name[0] == '@' {
 930		name = name[1:]
 931	}
 932	m := strings.Split(name, "@")
 933	if len(m) != 2 {
 934		log.Printf("bad fish name: %s", name)
 935		return ""
 936	}
 937	handlock.Lock()
 938	ref, ok := handfull[name]
 939	handlock.Unlock()
 940	if ok {
 941		return ref
 942	}
 943	row := stmtGetXonker.QueryRow(name, "fishname")
 944	var href string
 945	err := row.Scan(&href)
 946	if err == nil {
 947		handlock.Lock()
 948		handfull[name] = href
 949		handlock.Unlock()
 950		return href
 951	}
 952	log.Printf("fishing for %s", name)
 953	j, err := GetJunk(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
 954	if err != nil {
 955		log.Printf("failed to go fish %s: %s", name, err)
 956		handlock.Lock()
 957		handfull[name] = ""
 958		handlock.Unlock()
 959		return ""
 960	}
 961	links, _ := j.GetArray("links")
 962	for _, li := range links {
 963		l, ok := li.(junk.Junk)
 964		if !ok {
 965			continue
 966		}
 967		href, _ := l.GetString("href")
 968		rel, _ := l.GetString("rel")
 969		t, _ := l.GetString("type")
 970		if rel == "self" && friendorfoe(t) {
 971			stmtSaveXonker.Exec(name, href, "fishname")
 972			handlock.Lock()
 973			handfull[name] = href
 974			handlock.Unlock()
 975			return href
 976		}
 977	}
 978	handlock.Lock()
 979	handfull[name] = ""
 980	handlock.Unlock()
 981	return ""
 982}
 983
 984func isactor(t string) bool {
 985	switch t {
 986	case "Person":
 987	case "Application":
 988	case "Service":
 989	default:
 990		return false
 991	}
 992	return true
 993}
 994
 995func investigate(name string) string {
 996	if name == "" {
 997		return ""
 998	}
 999	if name[0] == '@' {
1000		name = gofish(name)
1001	}
1002	if name == "" {
1003		return ""
1004	}
1005	obj, err := GetJunk(name)
1006	if err != nil {
1007		log.Printf("error investigating honker: %s", err)
1008		return ""
1009	}
1010	t, _ := obj.GetString("type")
1011	if !isactor(t) {
1012		log.Printf("it's not a person! %s", name)
1013		return ""
1014	}
1015	id, _ := obj.GetString("id")
1016	return id
1017}