all repos — honk @ 0b8fb01b8a4c0efcf1cbb285e1a2450eeeee0e6d

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