all repos — honk @ 1f6ccdb2fdf8c122629409d5f53d9fdb03193041

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