all repos — honk @ c6cd59310deb31536f43e1faf43072b3f6832940

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