all repos — honk @ ab793b88d0e934bf7b621cc82b4d347db98577b6

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