all repos — honk @ 30a6d352a8e21cd935f375bc7f06b8a6342b79b8

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