all repos — honk @ c822a66ae25ec3e1638b620a074d756c022f0906

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