all repos — honk @ 3e762070945eb7278dc469bc75ddf05fc4aef576

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