all repos — honk @ 6149ef8718e9862b75553eacc07ae6d9da9b7f41

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