all repos — honk @ 6c47ffec6b71064bdb4f1ff80488cb7df69d2495

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	res, err := stmtSaveHonk.Exec(x.UserID, x.What, x.Honker, x.XID, x.RID, dt, x.URL, aud,
 256		x.Noise, x.Convoy, whofore, "html", x.Precis, x.Oonker)
 257	if err != nil {
 258		log.Printf("err saving xonk: %s", err)
 259		return
 260	}
 261	x.ID, _ = res.LastInsertId()
 262	for _, d := range x.Donks {
 263		_, err = stmtSaveDonk.Exec(x.ID, d.FileID)
 264		if err != nil {
 265			log.Printf("err saving donk: %s", err)
 266			return
 267		}
 268	}
 269}
 270
 271type Box struct {
 272	In     string
 273	Out    string
 274	Shared string
 275}
 276
 277var boxofboxes = make(map[string]*Box)
 278var boxlock sync.Mutex
 279var boxinglock sync.Mutex
 280
 281func getboxes(ident string) (*Box, error) {
 282	boxlock.Lock()
 283	b, ok := boxofboxes[ident]
 284	boxlock.Unlock()
 285	if ok {
 286		return b, nil
 287	}
 288
 289	boxinglock.Lock()
 290	defer boxinglock.Unlock()
 291
 292	boxlock.Lock()
 293	b, ok = boxofboxes[ident]
 294	boxlock.Unlock()
 295	if ok {
 296		return b, nil
 297	}
 298
 299	var info string
 300	row := stmtGetXonker.QueryRow(ident, "boxes")
 301	err := row.Scan(&info)
 302	if err != nil {
 303		j, err := GetJunk(ident)
 304		if err != nil {
 305			return nil, err
 306		}
 307		inbox, _ := j.GetString("inbox")
 308		outbox, _ := j.GetString("outbox")
 309		sbox, _ := j.FindString([]string{"endpoints", "sharedInbox"})
 310		b = &Box{In: inbox, Out: outbox, Shared: sbox}
 311		if inbox != "" {
 312			m := strings.Join([]string{inbox, outbox, sbox}, " ")
 313			_, err = stmtSaveXonker.Exec(ident, m, "boxes")
 314			if err != nil {
 315				log.Printf("error saving boxes: %s", err)
 316			}
 317		}
 318	} else {
 319		m := strings.Split(info, " ")
 320		b = &Box{In: m[0], Out: m[1], Shared: m[2]}
 321	}
 322
 323	boxlock.Lock()
 324	boxofboxes[ident] = b
 325	boxlock.Unlock()
 326	return b, nil
 327}
 328
 329func gimmexonks(user *WhatAbout, outbox string) {
 330	log.Printf("getting outbox: %s", outbox)
 331	j, err := GetJunk(outbox)
 332	if err != nil {
 333		log.Printf("error getting outbox: %s", err)
 334		return
 335	}
 336	t, _ := j.GetString("type")
 337	origin := originate(outbox)
 338	if t == "OrderedCollection" {
 339		items, _ := j.GetArray("orderedItems")
 340		if items == nil {
 341			obj, ok := j.GetMap("first")
 342			if ok {
 343				items, _ = obj.GetArray("orderedItems")
 344			} else {
 345				page1, _ := j.GetString("first")
 346				j, err = GetJunk(page1)
 347				if err != nil {
 348					log.Printf("error gettings page1: %s", err)
 349					return
 350				}
 351				items, _ = j.GetArray("orderedItems")
 352			}
 353		}
 354		if len(items) > 20 {
 355			items = items[0:20]
 356		}
 357		for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
 358			items[i], items[j] = items[j], items[i]
 359		}
 360		for _, item := range items {
 361			obj, ok := item.(junk.Junk)
 362			if !ok {
 363				continue
 364			}
 365			xonk := xonkxonk(user, obj, origin)
 366			if xonk != nil {
 367				savexonk(user, xonk)
 368			}
 369		}
 370	}
 371}
 372
 373func peeppeep() {
 374	user, _ := butwhatabout("htest")
 375	honkers := gethonkers(user.ID)
 376	for _, f := range honkers {
 377		if f.Flavor != "peep" {
 378			continue
 379		}
 380		log.Printf("getting updates: %s", f.XID)
 381		box, err := getboxes(f.XID)
 382		if err != nil {
 383			log.Printf("error getting outbox: %s", err)
 384			continue
 385		}
 386		gimmexonks(user, box.Out)
 387	}
 388}
 389func whosthere(xid string) ([]string, string) {
 390	obj, err := GetJunk(xid)
 391	if err != nil {
 392		log.Printf("error getting remote xonk: %s", err)
 393		return nil, ""
 394	}
 395	convoy, _ := obj.GetString("context")
 396	if convoy == "" {
 397		convoy, _ = obj.GetString("conversation")
 398	}
 399	return newphone(nil, obj), convoy
 400}
 401
 402func newphone(a []string, obj junk.Junk) []string {
 403	for _, addr := range []string{"to", "cc", "attributedTo"} {
 404		who, _ := obj.GetString(addr)
 405		if who != "" {
 406			a = append(a, who)
 407		}
 408		whos, _ := obj.GetArray(addr)
 409		for _, w := range whos {
 410			who, _ := w.(string)
 411			if who != "" {
 412				a = append(a, who)
 413			}
 414		}
 415	}
 416	return a
 417}
 418
 419func extractattrto(obj junk.Junk) string {
 420	who, _ := obj.GetString("attributedTo")
 421	if who != "" {
 422		return who
 423	}
 424	o, ok := obj.GetMap("attributedTo")
 425	if ok {
 426		id, ok := o.GetString("id")
 427		if ok {
 428			return id
 429		}
 430	}
 431	arr, _ := obj.GetArray("attributedTo")
 432	for _, a := range arr {
 433		o, ok := a.(junk.Junk)
 434		if ok {
 435			t, _ := o.GetString("type")
 436			id, _ := o.GetString("id")
 437			if t == "Person" || t == "" {
 438				return id
 439			}
 440		}
 441	}
 442	return ""
 443}
 444
 445func consumeactivity(user *WhatAbout, j junk.Junk, origin string) {
 446	xonk := xonkxonk(user, j, origin)
 447	if xonk != nil {
 448		savexonk(user, xonk)
 449	}
 450}
 451
 452func xonkxonk(user *WhatAbout, item junk.Junk, origin string) *Honk {
 453	depth := 0
 454	maxdepth := 10
 455	currenttid := ""
 456	var xonkxonkfn func(item junk.Junk, origin string) *Honk
 457
 458	saveoneup := func(xid string) {
 459		log.Printf("getting oneup: %s", xid)
 460		if depth >= maxdepth {
 461			log.Printf("in too deep")
 462			return
 463		}
 464		obj, err := GetJunkHardMode(xid)
 465		if err != nil {
 466			log.Printf("error getting oneup: %s", err)
 467			return
 468		}
 469		depth++
 470		xonk := xonkxonkfn(obj, originate(xid))
 471		if xonk != nil {
 472			savexonk(user, xonk)
 473		}
 474		depth--
 475	}
 476
 477	xonkxonkfn = func(item junk.Junk, origin string) *Honk {
 478		// id, _ := item.GetString( "id")
 479		what, _ := item.GetString("type")
 480		dt, _ := item.GetString("published")
 481
 482		var audience []string
 483		var err error
 484		var xid, rid, url, content, precis, convoy, oonker string
 485		var obj junk.Junk
 486		var ok bool
 487		switch what {
 488		case "Announce":
 489			obj, ok = item.GetMap("object")
 490			if ok {
 491				xid, _ = obj.GetString("id")
 492			} else {
 493				xid, _ = item.GetString("object")
 494			}
 495			if !needxonkid(user, xid) {
 496				return nil
 497			}
 498			log.Printf("getting bonk: %s", xid)
 499			obj, err = GetJunkHardMode(xid)
 500			origin = originate(xid)
 501			what = "bonk"
 502		case "Create":
 503			obj, ok = item.GetMap("object")
 504			if !ok {
 505				xid, _ = obj.GetString("object")
 506				log.Printf("getting created honk: %s", xid)
 507				obj, err = GetJunkHardMode(xid)
 508				if err != nil {
 509					log.Printf("error getting creation: %s", err)
 510				}
 511			}
 512			what = "honk"
 513		case "Delete":
 514			obj, _ = item.GetMap("object")
 515			xid, _ = item.GetString("object")
 516			what = "eradicate"
 517		case "Video":
 518			fallthrough
 519		case "Question":
 520			fallthrough
 521		case "Note":
 522			fallthrough
 523		case "Article":
 524			fallthrough
 525		case "Page":
 526			obj = item
 527			what = "honk"
 528		default:
 529			log.Printf("unknown activity: %s", what)
 530			fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 531			item.Write(fd)
 532			io.WriteString(fd, "\n")
 533			fd.Close()
 534			return nil
 535		}
 536
 537		var xonk Honk
 538		who, _ := item.GetString("actor")
 539		if obj != nil {
 540			if who == "" {
 541				who = extractattrto(obj)
 542			}
 543			oonker = extractattrto(obj)
 544			ot, _ := obj.GetString("type")
 545			url, _ = obj.GetString("url")
 546			if ot == "Tombstone" {
 547				xid, _ = obj.GetString("id")
 548			} else {
 549				audience = newphone(audience, obj)
 550				xid, _ = obj.GetString("id")
 551				precis, _ = obj.GetString("summary")
 552				if precis == "" {
 553					precis, _ = obj.GetString("name")
 554				}
 555				content, _ = obj.GetString("content")
 556				if !strings.HasPrefix(content, "<p>") {
 557					content = "<p>" + content
 558				}
 559				sens, _ := obj["sensitive"].(bool)
 560				if sens && precis == "" {
 561					precis = "unspecified horror"
 562				}
 563				rid, ok = obj.GetString("inReplyTo")
 564				if !ok {
 565					robj, ok := obj.GetMap("inReplyTo")
 566					if ok {
 567						rid, _ = robj.GetString("id")
 568					}
 569				}
 570				convoy, _ = obj.GetString("context")
 571				if convoy == "" {
 572					convoy, _ = obj.GetString("conversation")
 573				}
 574				if ot == "Question" {
 575					if what == "honk" {
 576						what = "qonk"
 577					}
 578					content += "<ul>"
 579					ans, _ := obj.GetArray("oneOf")
 580					for _, ai := range ans {
 581						a, ok := ai.(junk.Junk)
 582						if !ok {
 583							continue
 584						}
 585						as, _ := a.GetString("name")
 586						content += "<li>" + as
 587					}
 588					ans, _ = obj.GetArray("anyOf")
 589					for _, ai := range ans {
 590						a, ok := ai.(junk.Junk)
 591						if !ok {
 592							continue
 593						}
 594						as, _ := a.GetString("name")
 595						content += "<li>" + as
 596					}
 597					content += "</ul>"
 598				}
 599				if what == "honk" && rid != "" {
 600					what = "tonk"
 601				}
 602			}
 603			atts, _ := obj.GetArray("attachment")
 604			for i, atti := range atts {
 605				att, ok := atti.(junk.Junk)
 606				if !ok {
 607					continue
 608				}
 609				at, _ := att.GetString("type")
 610				mt, _ := att.GetString("mediaType")
 611				u, _ := att.GetString("url")
 612				name, _ := att.GetString("name")
 613				localize := false
 614				if i > 4 {
 615					log.Printf("excessive attachment: %s", at)
 616				} else if at == "Document" || at == "Image" {
 617					mt = strings.ToLower(mt)
 618					log.Printf("attachment: %s %s", mt, u)
 619					if mt == "text/plain" || strings.HasPrefix(mt, "image") {
 620						localize = true
 621					}
 622				} else {
 623					log.Printf("unknown attachment: %s", at)
 624				}
 625				donk := savedonk(u, name, mt, localize)
 626				if donk != nil {
 627					xonk.Donks = append(xonk.Donks, donk)
 628				}
 629			}
 630			tags, _ := obj.GetArray("tag")
 631			for _, tagi := range tags {
 632				tag, ok := tagi.(junk.Junk)
 633				if !ok {
 634					continue
 635				}
 636				tt, _ := tag.GetString("type")
 637				name, _ := tag.GetString("name")
 638				if tt == "Emoji" {
 639					icon, _ := tag.GetMap("icon")
 640					mt, _ := icon.GetString("mediaType")
 641					if mt == "" {
 642						mt = "image/png"
 643					}
 644					u, _ := icon.GetString("url")
 645					donk := savedonk(u, name, mt, true)
 646					if donk != nil {
 647						xonk.Donks = append(xonk.Donks, donk)
 648					}
 649				}
 650			}
 651		}
 652		if originate(xid) != origin {
 653			log.Printf("original sin: %s <> %s", xid, origin)
 654			item.Write(os.Stdout)
 655			return nil
 656		}
 657		audience = append(audience, who)
 658
 659		audience = oneofakind(audience)
 660
 661		if currenttid == "" {
 662			currenttid = convoy
 663		}
 664
 665		if oonker == who {
 666			oonker = ""
 667		}
 668		xonk.UserID = user.ID
 669		xonk.What = what
 670		xonk.Honker = who
 671		xonk.XID = xid
 672		xonk.RID = rid
 673		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 674		xonk.URL = url
 675		xonk.Noise = content
 676		xonk.Precis = precis
 677		xonk.Audience = audience
 678		xonk.Oonker = oonker
 679
 680		if needxonk(user, &xonk) {
 681			if rid != "" {
 682				if needxonkid(user, rid) {
 683					saveoneup(rid)
 684				}
 685			}
 686			if convoy == "" {
 687				convoy = currenttid
 688			}
 689			xonk.Convoy = convoy
 690			return &xonk
 691		}
 692		return nil
 693	}
 694
 695	return xonkxonkfn(item, origin)
 696}
 697
 698func rubadubdub(user *WhatAbout, req junk.Junk) {
 699	xid, _ := req.GetString("id")
 700	actor, _ := req.GetString("actor")
 701	j := junk.New()
 702	j["@context"] = itiswhatitis
 703	j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
 704	j["type"] = "Accept"
 705	j["actor"] = user.URL
 706	j["to"] = actor
 707	j["published"] = time.Now().UTC().Format(time.RFC3339)
 708	j["object"] = req
 709
 710	var buf bytes.Buffer
 711	j.Write(&buf)
 712	msg := buf.Bytes()
 713
 714	deliverate(0, user.Name, actor, msg)
 715}
 716
 717func itakeitallback(user *WhatAbout, xid string) {
 718	j := junk.New()
 719	j["@context"] = itiswhatitis
 720	j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
 721	j["type"] = "Undo"
 722	j["actor"] = user.URL
 723	j["to"] = xid
 724	f := junk.New()
 725	f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 726	f["type"] = "Follow"
 727	f["actor"] = user.URL
 728	f["to"] = xid
 729	f["object"] = xid
 730	j["object"] = f
 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
 740func subsub(user *WhatAbout, xid string) {
 741	j := junk.New()
 742	j["@context"] = itiswhatitis
 743	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 744	j["type"] = "Follow"
 745	j["actor"] = user.URL
 746	j["to"] = xid
 747	j["object"] = xid
 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 jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 758	dt := h.Date.Format(time.RFC3339)
 759	var jo junk.Junk
 760	j := junk.New()
 761	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 762	j["actor"] = user.URL
 763	j["published"] = dt
 764	if h.Public {
 765		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
 766	} else {
 767		j["to"] = h.Audience[0]
 768	}
 769	if len(h.Audience) > 1 {
 770		j["cc"] = h.Audience[1:]
 771	}
 772
 773	switch h.What {
 774	case "tonk":
 775		fallthrough
 776	case "honk":
 777		j["type"] = "Create"
 778
 779		jo = junk.New()
 780		jo["id"] = h.XID
 781		jo["type"] = "Note"
 782		jo["published"] = dt
 783		jo["url"] = h.XID
 784		jo["attributedTo"] = user.URL
 785		if h.RID != "" {
 786			jo["inReplyTo"] = h.RID
 787		}
 788		if h.Convoy != "" {
 789			jo["context"] = h.Convoy
 790			jo["conversation"] = h.Convoy
 791		}
 792		jo["to"] = h.Audience[0]
 793		if len(h.Audience) > 1 {
 794			jo["cc"] = h.Audience[1:]
 795		}
 796		if !h.Public {
 797			jo["directMessage"] = true
 798		}
 799		jo["summary"] = h.Precis
 800		jo["content"] = mentionize(h.Noise)
 801		if strings.HasPrefix(h.Precis, "DZ:") {
 802			jo["sensitive"] = true
 803		}
 804
 805		var tags []junk.Junk
 806		g := bunchofgrapes(h.Noise)
 807		for _, m := range g {
 808			t := junk.New()
 809			t["type"] = "Mention"
 810			t["name"] = m.who
 811			t["href"] = m.where
 812			tags = append(tags, t)
 813		}
 814		ooo := ontologies(h.Noise)
 815		for _, o := range ooo {
 816			t := junk.New()
 817			t["type"] = "Hashtag"
 818			t["name"] = o
 819			tags = append(tags, t)
 820		}
 821		herd := herdofemus(h.Noise)
 822		for _, e := range herd {
 823			t := junk.New()
 824			t["id"] = e.ID
 825			t["type"] = "Emoji"
 826			t["name"] = e.Name
 827			i := junk.New()
 828			i["type"] = "Image"
 829			i["mediaType"] = "image/png"
 830			i["url"] = e.ID
 831			t["icon"] = i
 832			tags = append(tags, t)
 833		}
 834		if len(tags) > 0 {
 835			jo["tag"] = tags
 836		}
 837		var atts []junk.Junk
 838		for _, d := range h.Donks {
 839			if re_emus.MatchString(d.Name) {
 840				continue
 841			}
 842			jd := junk.New()
 843			jd["mediaType"] = d.Media
 844			jd["name"] = d.Name
 845			jd["type"] = "Document"
 846			jd["url"] = d.URL
 847			atts = append(atts, jd)
 848		}
 849		if len(atts) > 0 {
 850			jo["attachment"] = atts
 851		}
 852		j["object"] = jo
 853	case "bonk":
 854		j["type"] = "Announce"
 855		if h.Convoy != "" {
 856			j["context"] = h.Convoy
 857		}
 858		j["object"] = h.XID
 859	case "zonk":
 860		j["type"] = "Delete"
 861		j["object"] = h.XID
 862	}
 863
 864	return j, jo
 865}
 866
 867func honkworldwide(user *WhatAbout, honk *Honk) {
 868	jonk, _ := jonkjonk(user, honk)
 869	jonk["@context"] = itiswhatitis
 870	var buf bytes.Buffer
 871	jonk.Write(&buf)
 872	msg := buf.Bytes()
 873
 874	rcpts := make(map[string]bool)
 875	for _, a := range honk.Audience {
 876		if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
 877			box, _ := getboxes(a)
 878			if box != nil && honk.Public && box.Shared != "" {
 879				rcpts["%"+box.Shared] = true
 880			} else {
 881				rcpts[a] = true
 882			}
 883		}
 884	}
 885	if honk.Public {
 886		for _, f := range getdubs(user.ID) {
 887			box, _ := getboxes(f.XID)
 888			if box != nil && box.Shared != "" {
 889				rcpts["%"+box.Shared] = true
 890			} else {
 891				rcpts[f.XID] = true
 892			}
 893		}
 894	}
 895	for a := range rcpts {
 896		go deliverate(0, user.Name, a, msg)
 897	}
 898}
 899
 900func asjonker(user *WhatAbout) junk.Junk {
 901	about := obfusbreak(user.About)
 902
 903	j := junk.New()
 904	j["@context"] = itiswhatitis
 905	j["id"] = user.URL
 906	j["type"] = "Person"
 907	j["inbox"] = user.URL + "/inbox"
 908	j["outbox"] = user.URL + "/outbox"
 909	j["followers"] = user.URL + "/followers"
 910	j["following"] = user.URL + "/following"
 911	j["name"] = user.Display
 912	j["preferredUsername"] = user.Name
 913	j["summary"] = about
 914	j["url"] = user.URL
 915	a := junk.New()
 916	a["type"] = "Image"
 917	a["mediaType"] = "image/png"
 918	a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
 919	j["icon"] = a
 920	k := junk.New()
 921	k["id"] = user.URL + "#key"
 922	k["owner"] = user.URL
 923	k["publicKeyPem"] = user.Key
 924	j["publicKey"] = k
 925
 926	return j
 927}
 928
 929var handfull = make(map[string]string)
 930var handlock sync.Mutex
 931
 932func gofish(name string) string {
 933	if name[0] == '@' {
 934		name = name[1:]
 935	}
 936	m := strings.Split(name, "@")
 937	if len(m) != 2 {
 938		log.Printf("bad fish name: %s", name)
 939		return ""
 940	}
 941	handlock.Lock()
 942	ref, ok := handfull[name]
 943	handlock.Unlock()
 944	if ok {
 945		return ref
 946	}
 947	row := stmtGetXonker.QueryRow(name, "fishname")
 948	var href string
 949	err := row.Scan(&href)
 950	if err == nil {
 951		handlock.Lock()
 952		handfull[name] = href
 953		handlock.Unlock()
 954		return href
 955	}
 956	log.Printf("fishing for %s", name)
 957	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
 958	if err != nil {
 959		log.Printf("failed to go fish %s: %s", name, err)
 960		handlock.Lock()
 961		handfull[name] = ""
 962		handlock.Unlock()
 963		return ""
 964	}
 965	links, _ := j.GetArray("links")
 966	for _, li := range links {
 967		l, ok := li.(junk.Junk)
 968		if !ok {
 969			continue
 970		}
 971		href, _ := l.GetString("href")
 972		rel, _ := l.GetString("rel")
 973		t, _ := l.GetString("type")
 974		if rel == "self" && friendorfoe(t) {
 975			_, err := stmtSaveXonker.Exec(name, href, "fishname")
 976			if err != nil {
 977				log.Printf("error saving fishname: %s", err)
 978			}
 979			handlock.Lock()
 980			handfull[name] = href
 981			handlock.Unlock()
 982			return href
 983		}
 984	}
 985	handlock.Lock()
 986	handfull[name] = ""
 987	handlock.Unlock()
 988	return ""
 989}
 990
 991func isactor(t string) bool {
 992	switch t {
 993	case "Person":
 994	case "Application":
 995	case "Service":
 996	default:
 997		return false
 998	}
 999	return true
1000}
1001
1002func investigate(name string) *Honker {
1003	if name == "" {
1004		return nil
1005	}
1006	if name[0] == '@' {
1007		name = gofish(name)
1008	}
1009	if name == "" {
1010		return nil
1011	}
1012	log.Printf("digging up some info on %s", name)
1013	obj, err := GetJunkFast(name)
1014	if err != nil {
1015		log.Printf("error investigating honker: %s", err)
1016		return nil
1017	}
1018	t, _ := obj.GetString("type")
1019	if !isactor(t) {
1020		log.Printf("it's not a person! %s", name)
1021		return nil
1022	}
1023	xid, _ := obj.GetString("id")
1024	handle, _ := obj.GetString("preferredUsername")
1025	return &Honker{XID: xid, Handle: handle}
1026}