all repos — honk @ 00f50e19b5b54c849d988ca9816372c4c41c27e3

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	"database/sql"
  21	"errors"
  22	"fmt"
  23	"html"
  24	"io"
  25	"log"
  26	notrand "math/rand"
  27	"net/http"
  28	"net/url"
  29	"os"
  30	"strings"
  31	"time"
  32
  33	"humungus.tedunangst.com/r/webs/cache"
  34	"humungus.tedunangst.com/r/webs/gate"
  35	"humungus.tedunangst.com/r/webs/httpsig"
  36	"humungus.tedunangst.com/r/webs/junk"
  37	"humungus.tedunangst.com/r/webs/templates"
  38)
  39
  40var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
  41var thefakename = `application/activity+json`
  42var falsenames = []string{
  43	`application/ld+json`,
  44	`application/activity+json`,
  45}
  46var itiswhatitis = "https://www.w3.org/ns/activitystreams"
  47var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
  48
  49func friendorfoe(ct string) bool {
  50	ct = strings.ToLower(ct)
  51	for _, at := range falsenames {
  52		if strings.HasPrefix(ct, at) {
  53			return true
  54		}
  55	}
  56	return false
  57}
  58
  59func PostJunk(keyname string, key httpsig.PrivateKey, url string, j junk.Junk) error {
  60	return PostMsg(keyname, key, url, j.ToBytes())
  61}
  62
  63func PostMsg(keyname string, key httpsig.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
  88type JunkError struct {
  89	Junk junk.Junk
  90	Err  error
  91}
  92
  93func GetJunk(url string) (junk.Junk, error) {
  94	return GetJunkTimeout(url, 30*time.Second)
  95}
  96
  97func GetJunkFast(url string) (junk.Junk, error) {
  98	return GetJunkTimeout(url, 5*time.Second)
  99}
 100
 101func GetJunkHardMode(url string) (junk.Junk, error) {
 102	j, err := GetJunk(url)
 103	if err != nil {
 104		emsg := err.Error()
 105		if emsg == "http get status: 502" || strings.Contains(emsg, "timeout") {
 106			log.Printf("trying again after error: %s", emsg)
 107			time.Sleep(time.Duration(60+notrand.Int63n(60)) * time.Second)
 108			j, err = GetJunk(url)
 109			if err != nil {
 110				log.Printf("still couldn't get it")
 111			} else {
 112				log.Printf("retry success!")
 113			}
 114		}
 115	}
 116	return j, err
 117}
 118
 119var flightdeck = gate.NewSerializer()
 120
 121func GetJunkTimeout(url string, timeout time.Duration) (junk.Junk, error) {
 122
 123	fn := func() (interface{}, error) {
 124		at := thefakename
 125		if strings.Contains(url, ".well-known/webfinger?resource") {
 126			at = "application/jrd+json"
 127		}
 128		j, err := junk.Get(url, junk.GetArgs{
 129			Accept:  at,
 130			Agent:   "honksnonk/5.0; " + serverName,
 131			Timeout: timeout,
 132		})
 133		return j, err
 134	}
 135
 136	ji, err := flightdeck.Call(url, fn)
 137	if err != nil {
 138		return nil, err
 139	}
 140	j := ji.(junk.Junk)
 141	return j, nil
 142}
 143
 144func fetchsome(url string) ([]byte, error) {
 145	resp, err := http.Get(url)
 146	if err != nil {
 147		log.Printf("error fetching %s: %s", url, err)
 148		return nil, err
 149	}
 150	defer resp.Body.Close()
 151	if resp.StatusCode != 200 {
 152		return nil, errors.New("not 200")
 153	}
 154	var buf bytes.Buffer
 155	limiter := io.LimitReader(resp.Body, 10*1024*1024)
 156	io.Copy(&buf, limiter)
 157	return buf.Bytes(), nil
 158}
 159
 160func savedonk(url string, name, desc, media string, localize bool) *Donk {
 161	if url == "" {
 162		return nil
 163	}
 164	donk := finddonk(url)
 165	if donk != nil {
 166		return donk
 167	}
 168	donk = new(Donk)
 169	log.Printf("saving donk: %s", url)
 170	xid := xfiltrate()
 171	data := []byte{}
 172	if localize {
 173		fn := func() (interface{}, error) {
 174			return fetchsome(url)
 175		}
 176		ii, err := flightdeck.Call(url, fn)
 177		if err != nil {
 178			log.Printf("error fetching donk: %s", err)
 179			localize = false
 180			goto saveit
 181		}
 182		data = ii.([]byte)
 183
 184		if len(data) == 10*1024*1024 {
 185			log.Printf("truncation likely")
 186		}
 187		if strings.HasPrefix(media, "image") {
 188			img, err := shrinkit(data)
 189			if err != nil {
 190				log.Printf("unable to decode image: %s", err)
 191				localize = false
 192				data = []byte{}
 193				goto saveit
 194			}
 195			data = img.Data
 196			format := img.Format
 197			media = "image/" + format
 198			if format == "jpeg" {
 199				format = "jpg"
 200			}
 201			xid = xid + "." + format
 202		} else if media == "application/pdf" {
 203			if len(data) > 1000000 {
 204				log.Printf("not saving large pdf")
 205				localize = false
 206				data = []byte{}
 207			}
 208		} else if len(data) > 100000 {
 209			log.Printf("not saving large attachment")
 210			localize = false
 211			data = []byte{}
 212		}
 213	}
 214saveit:
 215	fileid, err := savefile(xid, name, desc, url, media, localize, data)
 216	if err != nil {
 217		log.Printf("error saving file %s: %s", url, err)
 218		return nil
 219	}
 220	donk.FileID = fileid
 221	donk.XID = xid
 222	return donk
 223}
 224
 225func iszonked(userid int64, xid string) bool {
 226	var id int64
 227	row := stmtFindZonk.QueryRow(userid, xid)
 228	err := row.Scan(&id)
 229	if err == nil {
 230		return true
 231	}
 232	if err != sql.ErrNoRows {
 233		log.Printf("error querying zonk: %s", err)
 234	}
 235	return false
 236}
 237
 238func needxonk(user *WhatAbout, x *Honk) bool {
 239	if rejectxonk(x) {
 240		return false
 241	}
 242	return needxonkid(user, x.XID)
 243}
 244func needbonkid(user *WhatAbout, xid string) bool {
 245	return needxonkidX(user, xid, true)
 246}
 247func needxonkid(user *WhatAbout, xid string) bool {
 248	return needxonkidX(user, xid, false)
 249}
 250func needxonkidX(user *WhatAbout, xid string, isannounce bool) bool {
 251	if !strings.HasPrefix(xid, "https://") {
 252		return false
 253	}
 254	if strings.HasPrefix(xid, user.URL+"/") {
 255		return false
 256	}
 257	if rejectorigin(user.ID, xid, isannounce) {
 258		log.Printf("rejecting origin: %s", xid)
 259		return false
 260	}
 261	if iszonked(user.ID, xid) {
 262		log.Printf("already zonked: %s", xid)
 263		return false
 264	}
 265	var id int64
 266	row := stmtFindXonk.QueryRow(user.ID, xid)
 267	err := row.Scan(&id)
 268	if err == nil {
 269		return false
 270	}
 271	if err != sql.ErrNoRows {
 272		log.Printf("error querying xonk: %s", err)
 273	}
 274	return true
 275}
 276
 277func eradicatexonk(userid int64, xid string) {
 278	xonk := getxonk(userid, xid)
 279	if xonk != nil {
 280		deletehonk(xonk.ID)
 281	}
 282	_, err := stmtSaveZonker.Exec(userid, xid, "zonk")
 283	if err != nil {
 284		log.Printf("error eradicating: %s", err)
 285	}
 286}
 287
 288func savexonk(x *Honk) {
 289	log.Printf("saving xonk: %s", x.XID)
 290	go handles(x.Honker)
 291	go handles(x.Oonker)
 292	savehonk(x)
 293}
 294
 295type Box struct {
 296	In     string
 297	Out    string
 298	Shared string
 299}
 300
 301var boxofboxes = cache.New(cache.Options{Filler: func(ident string) (*Box, bool) {
 302	var info string
 303	row := stmtGetXonker.QueryRow(ident, "boxes")
 304	err := row.Scan(&info)
 305	if err != nil {
 306		log.Printf("need to get boxes for %s", ident)
 307		var j junk.Junk
 308		j, err = GetJunk(ident)
 309		if err != nil {
 310			log.Printf("error getting boxes: %s", err)
 311			return nil, false
 312		}
 313		allinjest(originate(ident), j)
 314		row = stmtGetXonker.QueryRow(ident, "boxes")
 315		err = row.Scan(&info)
 316	}
 317	if err == nil {
 318		m := strings.Split(info, " ")
 319		b := &Box{In: m[0], Out: m[1], Shared: m[2]}
 320		return b, true
 321	}
 322	return nil, false
 323}})
 324
 325func gimmexonks(user *WhatAbout, outbox string) {
 326	log.Printf("getting outbox: %s", outbox)
 327	j, err := GetJunk(outbox)
 328	if err != nil {
 329		log.Printf("error getting outbox: %s", err)
 330		return
 331	}
 332	t, _ := j.GetString("type")
 333	origin := originate(outbox)
 334	if t == "OrderedCollection" {
 335		items, _ := j.GetArray("orderedItems")
 336		if items == nil {
 337			items, _ = j.GetArray("items")
 338		}
 339		if items == nil {
 340			obj, ok := j.GetMap("first")
 341			if ok {
 342				items, _ = obj.GetArray("orderedItems")
 343			} else {
 344				page1, ok := j.GetString("first")
 345				if ok {
 346					j, err = GetJunk(page1)
 347					if err != nil {
 348						log.Printf("error gettings page1: %s", err)
 349						return
 350					}
 351					items, _ = j.GetArray("orderedItems")
 352				}
 353			}
 354		}
 355		if len(items) > 20 {
 356			items = items[0:20]
 357		}
 358		for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
 359			items[i], items[j] = items[j], items[i]
 360		}
 361		for _, item := range items {
 362			obj, ok := item.(junk.Junk)
 363			if ok {
 364				xonksaver(user, obj, origin)
 365				continue
 366			}
 367			xid, ok := item.(string)
 368			if ok {
 369				if !needxonkid(user, xid) {
 370					continue
 371				}
 372				obj, err = GetJunk(xid)
 373				if err != nil {
 374					log.Printf("error getting item: %s", err)
 375					continue
 376				}
 377				xonksaver(user, obj, originate(xid))
 378			}
 379		}
 380	}
 381}
 382
 383func newphone(a []string, obj junk.Junk) []string {
 384	for _, addr := range []string{"to", "cc", "attributedTo"} {
 385		who, _ := obj.GetString(addr)
 386		if who != "" {
 387			a = append(a, who)
 388		}
 389		whos, _ := obj.GetArray(addr)
 390		for _, w := range whos {
 391			who, _ := w.(string)
 392			if who != "" {
 393				a = append(a, who)
 394			}
 395		}
 396	}
 397	return a
 398}
 399
 400func extractattrto(obj junk.Junk) string {
 401	who, _ := obj.GetString("attributedTo")
 402	if who != "" {
 403		return who
 404	}
 405	o, ok := obj.GetMap("attributedTo")
 406	if ok {
 407		id, ok := o.GetString("id")
 408		if ok {
 409			return id
 410		}
 411	}
 412	arr, _ := obj.GetArray("attributedTo")
 413	for _, a := range arr {
 414		o, ok := a.(junk.Junk)
 415		if ok {
 416			t, _ := o.GetString("type")
 417			id, _ := o.GetString("id")
 418			if t == "Person" || t == "" {
 419				return id
 420			}
 421		}
 422		s, ok := a.(string)
 423		if ok {
 424			return s
 425		}
 426	}
 427	return ""
 428}
 429
 430func xonksaver(user *WhatAbout, item junk.Junk, origin string) *Honk {
 431	depth := 0
 432	maxdepth := 10
 433	currenttid := ""
 434	goingup := 0
 435	var xonkxonkfn func(item junk.Junk, origin string) *Honk
 436
 437	saveonemore := func(xid string) {
 438		log.Printf("getting onemore: %s", xid)
 439		if depth >= maxdepth {
 440			log.Printf("in too deep")
 441			return
 442		}
 443		obj, err := GetJunkHardMode(xid)
 444		if err != nil {
 445			log.Printf("error getting onemore: %s: %s", xid, err)
 446			return
 447		}
 448		depth++
 449		xonkxonkfn(obj, originate(xid))
 450		depth--
 451	}
 452
 453	xonkxonkfn = func(item junk.Junk, origin string) *Honk {
 454		// id, _ := item.GetString( "id")
 455		what, _ := item.GetString("type")
 456		dt, ok := item.GetString("published")
 457		if !ok {
 458			dt = time.Now().Format(time.RFC3339)
 459		}
 460
 461		var err error
 462		var xid, rid, url, content, precis, convoy string
 463		var replies []string
 464		var obj junk.Junk
 465		isUpdate := false
 466		switch what {
 467		case "Delete":
 468			obj, ok = item.GetMap("object")
 469			if ok {
 470				xid, _ = obj.GetString("id")
 471			} else {
 472				xid, _ = item.GetString("object")
 473			}
 474			if xid == "" {
 475				return nil
 476			}
 477			if originate(xid) != origin {
 478				log.Printf("forged delete: %s", xid)
 479				return nil
 480			}
 481			log.Printf("eradicating %s", xid)
 482			eradicatexonk(user.ID, xid)
 483			return nil
 484		case "Tombstone":
 485			xid, _ = item.GetString("id")
 486			if xid == "" {
 487				return nil
 488			}
 489			if originate(xid) != origin {
 490				log.Printf("forged delete: %s", xid)
 491				return nil
 492			}
 493			log.Printf("eradicating %s", xid)
 494			eradicatexonk(user.ID, xid)
 495			return nil
 496		case "Announce":
 497			obj, ok = item.GetMap("object")
 498			if ok {
 499				xid, _ = obj.GetString("id")
 500			} else {
 501				xid, _ = item.GetString("object")
 502			}
 503			if !needbonkid(user, xid) {
 504				return nil
 505			}
 506			log.Printf("getting bonk: %s", xid)
 507			obj, err = GetJunkHardMode(xid)
 508			if err != nil {
 509				log.Printf("error getting bonk: %s: %s", xid, err)
 510			}
 511			origin = originate(xid)
 512			what = "bonk"
 513		case "Update":
 514			isUpdate = true
 515			fallthrough
 516		case "Create":
 517			obj, ok = item.GetMap("object")
 518			if !ok {
 519				xid, _ = item.GetString("object")
 520				log.Printf("getting created honk: %s", xid)
 521				obj, err = GetJunkHardMode(xid)
 522				if err != nil {
 523					log.Printf("error getting creation: %s", err)
 524				}
 525			}
 526			what = "honk"
 527			if obj != nil {
 528				t, _ := obj.GetString("type")
 529				switch t {
 530				case "Event":
 531					what = "event"
 532				}
 533			}
 534		case "Read":
 535			xid, ok = item.GetString("object")
 536			if ok {
 537				if !needxonkid(user, xid) {
 538					log.Printf("don't need read obj: %s", xid)
 539					return nil
 540				}
 541				obj, err = GetJunkHardMode(xid)
 542				if err != nil {
 543					log.Printf("error getting read: %s", err)
 544					return nil
 545				}
 546				return xonkxonkfn(obj, originate(xid))
 547			}
 548			return nil
 549		case "Add":
 550			xid, ok = item.GetString("object")
 551			if ok {
 552				// check target...
 553				if !needxonkid(user, xid) {
 554					log.Printf("don't need added obj: %s", xid)
 555					return nil
 556				}
 557				obj, err = GetJunkHardMode(xid)
 558				if err != nil {
 559					log.Printf("error getting add: %s", err)
 560					return nil
 561				}
 562				return xonkxonkfn(obj, originate(xid))
 563			}
 564			return nil
 565		case "Move":
 566			obj = item
 567			what = "move"
 568		case "Audio":
 569			fallthrough
 570		case "Image":
 571			fallthrough
 572		case "Video":
 573			fallthrough
 574		case "Question":
 575			fallthrough
 576		case "Note":
 577			fallthrough
 578		case "Article":
 579			fallthrough
 580		case "Page":
 581			obj = item
 582			what = "honk"
 583		case "Event":
 584			obj = item
 585			what = "event"
 586		default:
 587			log.Printf("unknown activity: %s", what)
 588			dumpactivity(item)
 589			return nil
 590		}
 591
 592		if obj != nil {
 593			xid, _ = obj.GetString("id")
 594		}
 595
 596		if xid == "" {
 597			log.Printf("don't know what xid is")
 598			item.Write(os.Stdout)
 599			return nil
 600		}
 601		if originate(xid) != origin {
 602			log.Printf("original sin: %s <> %s", xid, origin)
 603			item.Write(os.Stdout)
 604			return nil
 605		}
 606
 607		var xonk Honk
 608		// early init
 609		xonk.XID = xid
 610		xonk.UserID = user.ID
 611		xonk.Honker, _ = item.GetString("actor")
 612		if xonk.Honker == "" {
 613			xonk.Honker, _ = item.GetString("attributedTo")
 614		}
 615		if obj != nil {
 616			if xonk.Honker == "" {
 617				xonk.Honker = extractattrto(obj)
 618			}
 619			xonk.Oonker = extractattrto(obj)
 620			if xonk.Oonker == xonk.Honker {
 621				xonk.Oonker = ""
 622			}
 623			xonk.Audience = newphone(nil, obj)
 624		}
 625		xonk.Audience = append(xonk.Audience, xonk.Honker)
 626		xonk.Audience = oneofakind(xonk.Audience)
 627
 628		var mentions []Mention
 629		if obj != nil {
 630			ot, _ := obj.GetString("type")
 631			url, _ = obj.GetString("url")
 632			if dt2, ok := obj.GetString("published"); ok {
 633				dt = dt2
 634			}
 635			content, _ = obj.GetString("content")
 636			if !strings.HasPrefix(content, "<p>") {
 637				content = "<p>" + content
 638			}
 639			precis, _ = obj.GetString("summary")
 640			if name, ok := obj.GetString("name"); ok {
 641				if precis != "" {
 642					content = precis + "<p>" + content
 643				}
 644				precis = html.EscapeString(name)
 645			}
 646			if sens, _ := obj["sensitive"].(bool); sens && precis == "" {
 647				precis = "unspecified horror"
 648			}
 649			rid, ok = obj.GetString("inReplyTo")
 650			if !ok {
 651				if robj, ok := obj.GetMap("inReplyTo"); ok {
 652					rid, _ = robj.GetString("id")
 653				}
 654			}
 655			convoy, _ = obj.GetString("context")
 656			if convoy == "" {
 657				convoy, _ = obj.GetString("conversation")
 658			}
 659			if ot == "Question" {
 660				if what == "honk" {
 661					what = "qonk"
 662				}
 663				content += "<ul>"
 664				ans, _ := obj.GetArray("oneOf")
 665				for _, ai := range ans {
 666					a, ok := ai.(junk.Junk)
 667					if !ok {
 668						continue
 669					}
 670					as, _ := a.GetString("name")
 671					content += "<li>" + as
 672				}
 673				ans, _ = obj.GetArray("anyOf")
 674				for _, ai := range ans {
 675					a, ok := ai.(junk.Junk)
 676					if !ok {
 677						continue
 678					}
 679					as, _ := a.GetString("name")
 680					content += "<li>" + as
 681				}
 682				content += "</ul>"
 683			}
 684			if ot == "Move" {
 685				targ, _ := obj.GetString("target")
 686				content += string(templates.Sprintf(`<p>Moved to <a href="%s">%s</a>`, targ, targ))
 687			}
 688			if what == "honk" && rid != "" {
 689				what = "tonk"
 690			}
 691			atts, _ := obj.GetArray("attachment")
 692			for i, atti := range atts {
 693				if rejectxonk(&xonk) {
 694					log.Printf("skipping rejected attachment: %s", xid)
 695					continue
 696				}
 697				att, ok := atti.(junk.Junk)
 698				if !ok {
 699					continue
 700				}
 701				at, _ := att.GetString("type")
 702				mt, _ := att.GetString("mediaType")
 703				u, _ := att.GetString("url")
 704				name, _ := att.GetString("name")
 705				desc, _ := att.GetString("summary")
 706				if desc == "" {
 707					desc = name
 708				}
 709				localize := false
 710				if i > 4 {
 711					log.Printf("excessive attachment: %s", at)
 712				} else if at == "Document" || at == "Image" {
 713					mt = strings.ToLower(mt)
 714					log.Printf("attachment: %s %s", mt, u)
 715					if mt == "text/plain" || mt == "application/pdf" ||
 716						strings.HasPrefix(mt, "image") {
 717						localize = true
 718					}
 719				} else {
 720					log.Printf("unknown attachment: %s", at)
 721				}
 722				if skipMedia(&xonk) {
 723					localize = false
 724				}
 725				donk := savedonk(u, name, desc, mt, localize)
 726				if donk != nil {
 727					xonk.Donks = append(xonk.Donks, donk)
 728				}
 729			}
 730			tags, _ := obj.GetArray("tag")
 731			for _, tagi := range tags {
 732				if rejectxonk(&xonk) {
 733					log.Printf("skipping rejected attachment: %s", xid)
 734					continue
 735				}
 736				tag, ok := tagi.(junk.Junk)
 737				if !ok {
 738					continue
 739				}
 740				tt, _ := tag.GetString("type")
 741				name, _ := tag.GetString("name")
 742				desc, _ := tag.GetString("summary")
 743				if desc == "" {
 744					desc = name
 745				}
 746				if tt == "Emoji" {
 747					icon, _ := tag.GetMap("icon")
 748					mt, _ := icon.GetString("mediaType")
 749					if mt == "" {
 750						mt = "image/png"
 751					}
 752					u, _ := icon.GetString("url")
 753					donk := savedonk(u, name, desc, mt, true)
 754					if donk != nil {
 755						xonk.Donks = append(xonk.Donks, donk)
 756					}
 757				}
 758				if tt == "Hashtag" {
 759					if name == "" || name == "#" {
 760						// skip it
 761					} else {
 762						if name[0] != '#' {
 763							name = "#" + name
 764						}
 765						xonk.Onts = append(xonk.Onts, name)
 766					}
 767				}
 768				if tt == "Place" {
 769					p := new(Place)
 770					p.Name = name
 771					p.Latitude, _ = tag["latitude"].(float64)
 772					p.Longitude, _ = tag["longitude"].(float64)
 773					p.Url, _ = tag.GetString("url")
 774					xonk.Place = p
 775				}
 776				if tt == "Mention" {
 777					var m Mention
 778					m.Who, _ = tag.GetString("name")
 779					m.Where, _ = tag.GetString("href")
 780					mentions = append(mentions, m)
 781				}
 782			}
 783			if starttime, ok := obj.GetString("startTime"); ok {
 784				if start, err := time.Parse(time.RFC3339, starttime); err == nil {
 785					t := new(Time)
 786					t.StartTime = start
 787					endtime, _ := obj.GetString("endTime")
 788					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
 789					dura, _ := obj.GetString("duration")
 790					if strings.HasPrefix(dura, "PT") {
 791						dura = strings.ToLower(dura[2:])
 792						d, _ := time.ParseDuration(dura)
 793						t.Duration = Duration(d)
 794					}
 795					xonk.Time = t
 796				}
 797			}
 798			if loca, ok := obj.GetMap("location"); ok {
 799				if tt, _ := loca.GetString("type"); tt == "Place" {
 800					p := new(Place)
 801					p.Name, _ = loca.GetString("name")
 802					p.Latitude, _ = loca["latitude"].(float64)
 803					p.Longitude, _ = loca["longitude"].(float64)
 804					p.Url, _ = loca.GetString("url")
 805					xonk.Place = p
 806				}
 807			}
 808
 809			xonk.Onts = oneofakind(xonk.Onts)
 810			replyobj, ok := obj.GetMap("replies")
 811			if ok {
 812				items, ok := replyobj.GetArray("items")
 813				if !ok {
 814					first, ok := replyobj.GetMap("first")
 815					if ok {
 816						items, _ = first.GetArray("items")
 817					}
 818				}
 819				for _, repl := range items {
 820					s, ok := repl.(string)
 821					if ok {
 822						replies = append(replies, s)
 823					}
 824				}
 825			}
 826
 827		}
 828
 829		if currenttid == "" {
 830			currenttid = convoy
 831		}
 832
 833		if len(content) > 90001 {
 834			log.Printf("content too long. truncating")
 835			content = content[:90001]
 836		}
 837
 838		// init xonk
 839		xonk.What = what
 840		xonk.RID = rid
 841		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 842		xonk.URL = url
 843		xonk.Noise = content
 844		xonk.Precis = precis
 845		xonk.Format = "html"
 846		xonk.Convoy = convoy
 847		xonk.Mentions = mentions
 848		for _, m := range mentions {
 849			if m.Where == user.URL {
 850				xonk.Whofore = 1
 851			}
 852		}
 853		imaginate(&xonk)
 854
 855		if isUpdate {
 856			log.Printf("something has changed! %s", xonk.XID)
 857			prev := getxonk(user.ID, xonk.XID)
 858			if prev == nil {
 859				log.Printf("didn't find old version for update: %s", xonk.XID)
 860				isUpdate = false
 861			} else {
 862				xonk.ID = prev.ID
 863				updatehonk(&xonk)
 864			}
 865		}
 866		if !isUpdate && needxonk(user, &xonk) {
 867			if rid != "" {
 868				if needxonkid(user, rid) {
 869					goingup++
 870					saveonemore(rid)
 871					goingup--
 872				}
 873				if convoy == "" {
 874					xx := getxonk(user.ID, rid)
 875					if xx != nil {
 876						convoy = xx.Convoy
 877					}
 878				}
 879			}
 880			if convoy == "" {
 881				convoy = currenttid
 882			}
 883			if convoy == "" {
 884				convoy = "data:,missing-" + xfiltrate()
 885				currenttid = convoy
 886			}
 887			xonk.Convoy = convoy
 888			savexonk(&xonk)
 889		}
 890		if goingup == 0 {
 891			for _, replid := range replies {
 892				if needxonkid(user, replid) {
 893					log.Printf("missing a reply: %s", replid)
 894					saveonemore(replid)
 895				}
 896			}
 897		}
 898		return &xonk
 899	}
 900
 901	return xonkxonkfn(item, origin)
 902}
 903
 904func dumpactivity(item junk.Junk) {
 905	fd, err := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 906	if err != nil {
 907		log.Printf("error opening inbox! %s", err)
 908		return
 909	}
 910	defer fd.Close()
 911	item.Write(fd)
 912	io.WriteString(fd, "\n")
 913}
 914
 915func rubadubdub(user *WhatAbout, req junk.Junk) {
 916	xid, _ := req.GetString("id")
 917	actor, _ := req.GetString("actor")
 918	j := junk.New()
 919	j["@context"] = itiswhatitis
 920	j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
 921	j["type"] = "Accept"
 922	j["actor"] = user.URL
 923	j["to"] = actor
 924	j["published"] = time.Now().UTC().Format(time.RFC3339)
 925	j["object"] = req
 926
 927	deliverate(0, user.ID, actor, j.ToBytes())
 928}
 929
 930func itakeitallback(user *WhatAbout, xid string) {
 931	j := junk.New()
 932	j["@context"] = itiswhatitis
 933	j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
 934	j["type"] = "Undo"
 935	j["actor"] = user.URL
 936	j["to"] = xid
 937	f := junk.New()
 938	f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 939	f["type"] = "Follow"
 940	f["actor"] = user.URL
 941	f["to"] = xid
 942	f["object"] = xid
 943	j["object"] = f
 944	j["published"] = time.Now().UTC().Format(time.RFC3339)
 945
 946	deliverate(0, user.ID, xid, j.ToBytes())
 947}
 948
 949func subsub(user *WhatAbout, xid string, owner string) {
 950	if xid == "" {
 951		log.Printf("can't subscribe to empty")
 952		return
 953	}
 954	j := junk.New()
 955	j["@context"] = itiswhatitis
 956	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 957	j["type"] = "Follow"
 958	j["actor"] = user.URL
 959	j["to"] = owner
 960	j["object"] = xid
 961	j["published"] = time.Now().UTC().Format(time.RFC3339)
 962
 963	deliverate(0, user.ID, owner, j.ToBytes())
 964}
 965
 966// returns activity, object
 967func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 968	dt := h.Date.Format(time.RFC3339)
 969	var jo junk.Junk
 970	j := junk.New()
 971	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 972	j["actor"] = user.URL
 973	j["published"] = dt
 974	if h.Public {
 975		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
 976	} else {
 977		j["to"] = h.Audience[0]
 978	}
 979	if len(h.Audience) > 1 {
 980		j["cc"] = h.Audience[1:]
 981	}
 982
 983	switch h.What {
 984	case "update":
 985		fallthrough
 986	case "tonk":
 987		fallthrough
 988	case "event":
 989		fallthrough
 990	case "honk":
 991		j["type"] = "Create"
 992		if h.What == "update" {
 993			j["type"] = "Update"
 994		}
 995
 996		jo = junk.New()
 997		jo["id"] = h.XID
 998		jo["type"] = "Note"
 999		if h.What == "event" {
1000			jo["type"] = "Event"
1001		}
1002		jo["published"] = dt
1003		jo["url"] = h.XID
1004		jo["attributedTo"] = user.URL
1005		if h.RID != "" {
1006			jo["inReplyTo"] = h.RID
1007		}
1008		if h.Convoy != "" {
1009			jo["context"] = h.Convoy
1010			jo["conversation"] = h.Convoy
1011		}
1012		jo["to"] = h.Audience[0]
1013		if len(h.Audience) > 1 {
1014			jo["cc"] = h.Audience[1:]
1015		}
1016		if !h.Public {
1017			jo["directMessage"] = true
1018		}
1019		mentions := bunchofgrapes(h.Noise)
1020		translate(h)
1021		redoimages(h)
1022		jo["summary"] = html.EscapeString(h.Precis)
1023		jo["content"] = h.Noise
1024		if h.Precis != "" {
1025			jo["sensitive"] = true
1026		}
1027
1028		var replies []string
1029		for _, reply := range h.Replies {
1030			replies = append(replies, reply.XID)
1031		}
1032		if len(replies) > 0 {
1033			jr := junk.New()
1034			jr["type"] = "Collection"
1035			jr["totalItems"] = len(replies)
1036			jr["items"] = replies
1037			jo["replies"] = jr
1038		}
1039
1040		var tags []junk.Junk
1041		for _, m := range mentions {
1042			t := junk.New()
1043			t["type"] = "Mention"
1044			t["name"] = m.Who
1045			t["href"] = m.Where
1046			tags = append(tags, t)
1047		}
1048		for _, o := range h.Onts {
1049			t := junk.New()
1050			t["type"] = "Hashtag"
1051			o = strings.ToLower(o)
1052			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1053			t["name"] = o
1054			tags = append(tags, t)
1055		}
1056		for _, e := range herdofemus(h.Noise) {
1057			t := junk.New()
1058			t["id"] = e.ID
1059			t["type"] = "Emoji"
1060			t["name"] = e.Name
1061			i := junk.New()
1062			i["type"] = "Image"
1063			i["mediaType"] = "image/png"
1064			i["url"] = e.ID
1065			t["icon"] = i
1066			tags = append(tags, t)
1067		}
1068		if len(tags) > 0 {
1069			jo["tag"] = tags
1070		}
1071		if p := h.Place; p != nil {
1072			t := junk.New()
1073			t["type"] = "Place"
1074			if p.Name != "" {
1075				t["name"] = p.Name
1076			}
1077			if p.Latitude != 0 {
1078				t["latitude"] = p.Latitude
1079			}
1080			if p.Longitude != 0 {
1081				t["longitude"] = p.Longitude
1082			}
1083			if p.Url != "" {
1084				t["url"] = p.Url
1085			}
1086			jo["location"] = t
1087		}
1088		if t := h.Time; t != nil {
1089			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1090			if t.Duration != 0 {
1091				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1092			}
1093		}
1094		var atts []junk.Junk
1095		for _, d := range h.Donks {
1096			if re_emus.MatchString(d.Name) {
1097				continue
1098			}
1099			jd := junk.New()
1100			jd["mediaType"] = d.Media
1101			jd["name"] = d.Name
1102			jd["summary"] = html.EscapeString(d.Desc)
1103			jd["type"] = "Document"
1104			jd["url"] = d.URL
1105			atts = append(atts, jd)
1106		}
1107		if len(atts) > 0 {
1108			jo["attachment"] = atts
1109		}
1110		j["object"] = jo
1111	case "bonk":
1112		j["type"] = "Announce"
1113		if h.Convoy != "" {
1114			j["context"] = h.Convoy
1115		}
1116		j["object"] = h.XID
1117	case "unbonk":
1118		b := junk.New()
1119		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1120		b["type"] = "Announce"
1121		b["actor"] = user.URL
1122		if h.Convoy != "" {
1123			b["context"] = h.Convoy
1124		}
1125		b["object"] = h.XID
1126		j["type"] = "Undo"
1127		j["object"] = b
1128	case "zonk":
1129		j["type"] = "Delete"
1130		j["object"] = h.XID
1131	case "ack":
1132		j["type"] = "Read"
1133		j["object"] = h.XID
1134		if h.Convoy != "" {
1135			j["context"] = h.Convoy
1136		}
1137	case "react":
1138		j["type"] = "EmojiReact"
1139		j["object"] = h.XID
1140		if h.Convoy != "" {
1141			j["context"] = h.Convoy
1142		}
1143		j["content"] = user.Options.Reaction
1144	case "deack":
1145		b := junk.New()
1146		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1147		b["type"] = "Read"
1148		b["actor"] = user.URL
1149		b["object"] = h.XID
1150		if h.Convoy != "" {
1151			b["context"] = h.Convoy
1152		}
1153		j["type"] = "Undo"
1154		j["object"] = b
1155	}
1156
1157	return j, jo
1158}
1159
1160var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1161	row := stmtAnyXonk.QueryRow(xid)
1162	honk := scanhonk(row)
1163	if honk == nil || !honk.Public {
1164		return nil, true
1165	}
1166	user, _ := butwhatabout(honk.Username)
1167	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1168	reversehonks(rawhonks)
1169	for _, h := range rawhonks {
1170		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1171			honk.Replies = append(honk.Replies, h)
1172		}
1173	}
1174	donksforhonks([]*Honk{honk})
1175	_, j := jonkjonk(user, honk)
1176	j["@context"] = itiswhatitis
1177
1178	return j.ToBytes(), true
1179}, Limit: 128})
1180
1181func gimmejonk(xid string) ([]byte, bool) {
1182	var j []byte
1183	ok := oldjonks.Get(xid, &j)
1184	return j, ok
1185}
1186
1187func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1188	rcpts := make(map[string]bool)
1189	for _, a := range addresses {
1190		if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1191			continue
1192		}
1193		if a[0] == '%' {
1194			rcpts[a] = true
1195			continue
1196		}
1197		var box *Box
1198		ok := boxofboxes.Get(a, &box)
1199		if ok && useshared && box.Shared != "" {
1200			rcpts["%"+box.Shared] = true
1201		} else {
1202			rcpts[a] = true
1203		}
1204	}
1205	return rcpts
1206}
1207
1208func honkworldwide(user *WhatAbout, honk *Honk) {
1209	jonk, _ := jonkjonk(user, honk)
1210	jonk["@context"] = itiswhatitis
1211	msg := jonk.ToBytes()
1212
1213	rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1214
1215	if honk.Public {
1216		for _, h := range getdubs(user.ID) {
1217			if h.XID == user.URL {
1218				continue
1219			}
1220			var box *Box
1221			ok := boxofboxes.Get(h.XID, &box)
1222			if ok && box.Shared != "" {
1223				rcpts["%"+box.Shared] = true
1224			} else {
1225				rcpts[h.XID] = true
1226			}
1227		}
1228		for _, f := range getbacktracks(honk.XID) {
1229			rcpts[f] = true
1230		}
1231	}
1232	for a := range rcpts {
1233		go deliverate(0, user.ID, a, msg)
1234	}
1235	if honk.Public && len(honk.Onts) > 0 {
1236		collectiveaction(honk)
1237	}
1238}
1239
1240func collectiveaction(honk *Honk) {
1241	user := getserveruser()
1242	for _, ont := range honk.Onts {
1243		dubs := getnameddubs(serverUID, ont)
1244		if len(dubs) == 0 {
1245			continue
1246		}
1247		j := junk.New()
1248		j["@context"] = itiswhatitis
1249		j["type"] = "Add"
1250		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1251		j["actor"] = user.URL
1252		j["object"] = honk.XID
1253		j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1254		rcpts := make(map[string]bool)
1255		for _, dub := range dubs {
1256			var box *Box
1257			ok := boxofboxes.Get(dub.XID, &box)
1258			if ok && box.Shared != "" {
1259				rcpts["%"+box.Shared] = true
1260			} else {
1261				rcpts[dub.XID] = true
1262			}
1263		}
1264		msg := j.ToBytes()
1265		for a := range rcpts {
1266			go deliverate(0, user.ID, a, msg)
1267		}
1268	}
1269}
1270
1271func junkuser(user *WhatAbout) []byte {
1272	about := markitzero(user.About)
1273
1274	j := junk.New()
1275	j["@context"] = itiswhatitis
1276	j["id"] = user.URL
1277	j["inbox"] = user.URL + "/inbox"
1278	j["outbox"] = user.URL + "/outbox"
1279	j["name"] = user.Display
1280	j["preferredUsername"] = user.Name
1281	j["summary"] = about
1282	if user.ID > 0 {
1283		j["type"] = "Person"
1284		j["url"] = user.URL
1285		j["followers"] = user.URL + "/followers"
1286		j["following"] = user.URL + "/following"
1287		a := junk.New()
1288		a["type"] = "Image"
1289		a["mediaType"] = "image/png"
1290		if ava := user.Options.Avatar; ava != "" {
1291			a["url"] = ava
1292		} else {
1293			a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1294		}
1295		j["icon"] = a
1296	} else {
1297		j["type"] = "Service"
1298	}
1299	k := junk.New()
1300	k["id"] = user.URL + "#key"
1301	k["owner"] = user.URL
1302	k["publicKeyPem"] = user.Key
1303	j["publicKey"] = k
1304
1305	return j.ToBytes()
1306}
1307
1308var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1309	user, err := butwhatabout(name)
1310	if err != nil {
1311		return nil, false
1312	}
1313	return junkuser(user), true
1314}, Duration: 1 * time.Minute})
1315
1316func asjonker(name string) ([]byte, bool) {
1317	var j []byte
1318	ok := oldjonkers.Get(name, &j)
1319	return j, ok
1320}
1321
1322var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1323	m := strings.Split(name, "@")
1324	if len(m) != 2 {
1325		log.Printf("bad fish name: %s", name)
1326		return "", true
1327	}
1328	var href string
1329	row := stmtGetXonker.QueryRow(name, "fishname")
1330	err := row.Scan(&href)
1331	if err == nil {
1332		return href, true
1333	}
1334	log.Printf("fishing for %s", name)
1335	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1336	if err != nil {
1337		log.Printf("failed to go fish %s: %s", name, err)
1338		return "", true
1339	}
1340	links, _ := j.GetArray("links")
1341	for _, li := range links {
1342		l, ok := li.(junk.Junk)
1343		if !ok {
1344			continue
1345		}
1346		href, _ := l.GetString("href")
1347		rel, _ := l.GetString("rel")
1348		t, _ := l.GetString("type")
1349		if rel == "self" && friendorfoe(t) {
1350			when := time.Now().UTC().Format(dbtimeformat)
1351			_, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1352			if err != nil {
1353				log.Printf("error saving fishname: %s", err)
1354			}
1355			return href, true
1356		}
1357	}
1358	return href, true
1359}})
1360
1361func gofish(name string) string {
1362	if name[0] == '@' {
1363		name = name[1:]
1364	}
1365	var href string
1366	handfull.Get(name, &href)
1367	return href
1368}
1369
1370func investigate(name string) (*SomeThing, error) {
1371	if name == "" {
1372		return nil, fmt.Errorf("no name")
1373	}
1374	if name[0] == '@' {
1375		name = gofish(name)
1376	}
1377	if name == "" {
1378		return nil, fmt.Errorf("no name")
1379	}
1380	obj, err := GetJunkFast(name)
1381	if err != nil {
1382		return nil, err
1383	}
1384	allinjest(originate(name), obj)
1385	return somethingabout(obj)
1386}
1387
1388func somethingabout(obj junk.Junk) (*SomeThing, error) {
1389	info := new(SomeThing)
1390	t, _ := obj.GetString("type")
1391	switch t {
1392	case "Person":
1393		fallthrough
1394	case "Organization":
1395		fallthrough
1396	case "Application":
1397		fallthrough
1398	case "Service":
1399		info.What = SomeActor
1400	case "OrderedCollection":
1401		fallthrough
1402	case "Collection":
1403		info.What = SomeCollection
1404	default:
1405		return nil, fmt.Errorf("unknown object type")
1406	}
1407	info.XID, _ = obj.GetString("id")
1408	info.Name, _ = obj.GetString("preferredUsername")
1409	if info.Name == "" {
1410		info.Name, _ = obj.GetString("name")
1411	}
1412	info.Owner, _ = obj.GetString("attributedTo")
1413	if info.Owner == "" {
1414		info.Owner = info.XID
1415	}
1416	return info, nil
1417}
1418
1419func allinjest(origin string, obj junk.Junk) {
1420	keyobj, ok := obj.GetMap("publicKey")
1421	if ok {
1422		ingestpubkey(origin, keyobj)
1423	}
1424	ingestboxes(origin, obj)
1425	ingesthandle(origin, obj)
1426}
1427
1428func ingestpubkey(origin string, obj junk.Junk) {
1429	keyobj, ok := obj.GetMap("publicKey")
1430	if ok {
1431		obj = keyobj
1432	}
1433	keyname, ok := obj.GetString("id")
1434	var data string
1435	row := stmtGetXonker.QueryRow(keyname, "pubkey")
1436	err := row.Scan(&data)
1437	if err == nil {
1438		return
1439	}
1440	if !ok || origin != originate(keyname) {
1441		log.Printf("bad key origin %s <> %s", origin, keyname)
1442		return
1443	}
1444	log.Printf("ingesting a needed pubkey: %s", keyname)
1445	owner, ok := obj.GetString("owner")
1446	if !ok {
1447		log.Printf("error finding %s pubkey owner", keyname)
1448		return
1449	}
1450	data, ok = obj.GetString("publicKeyPem")
1451	if !ok {
1452		log.Printf("error finding %s pubkey", keyname)
1453		return
1454	}
1455	if originate(owner) != origin {
1456		log.Printf("bad key owner: %s <> %s", owner, origin)
1457		return
1458	}
1459	_, _, err = httpsig.DecodeKey(data)
1460	if err != nil {
1461		log.Printf("error decoding %s pubkey: %s", keyname, err)
1462		return
1463	}
1464	when := time.Now().UTC().Format(dbtimeformat)
1465	_, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1466	if err != nil {
1467		log.Printf("error saving key: %s", err)
1468	}
1469}
1470
1471func ingestboxes(origin string, obj junk.Junk) {
1472	ident, _ := obj.GetString("id")
1473	if ident == "" {
1474		return
1475	}
1476	if originate(ident) != origin {
1477		return
1478	}
1479	var info string
1480	row := stmtGetXonker.QueryRow(ident, "boxes")
1481	err := row.Scan(&info)
1482	if err == nil {
1483		return
1484	}
1485	log.Printf("ingesting boxes: %s", ident)
1486	inbox, _ := obj.GetString("inbox")
1487	outbox, _ := obj.GetString("outbox")
1488	sbox, _ := obj.GetString("endpoints", "sharedInbox")
1489	if inbox != "" {
1490		when := time.Now().UTC().Format(dbtimeformat)
1491		m := strings.Join([]string{inbox, outbox, sbox}, " ")
1492		_, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1493		if err != nil {
1494			log.Printf("error saving boxes: %s", err)
1495		}
1496	}
1497}
1498
1499func ingesthandle(origin string, obj junk.Junk) {
1500	xid, _ := obj.GetString("id")
1501	if xid == "" {
1502		return
1503	}
1504	if originate(xid) != origin {
1505		return
1506	}
1507	var handle string
1508	row := stmtGetXonker.QueryRow(xid, "handle")
1509	err := row.Scan(&handle)
1510	if err == nil {
1511		return
1512	}
1513	handle, _ = obj.GetString("preferredUsername")
1514	if handle != "" {
1515		when := time.Now().UTC().Format(dbtimeformat)
1516		_, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1517		if err != nil {
1518			log.Printf("error saving handle: %s", err)
1519		}
1520	}
1521}