all repos — honk @ ef154c38b3942560cfaa8ef27b1e8e4a705fb0a1

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