all repos — honk @ 90903da8e866912e74605556a6d8300afc7fbfa2

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