all repos — honk @ 8b47d53f2687a02b63f6e8df47c4bd80010d73cd

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