all repos — honk @ 764308c6bd46e984cee267f517e3f2f224d1f198

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	"context"
  21	"crypto/tls"
  22	"database/sql"
  23	"fmt"
  24	"html"
  25	"io"
  26	notrand "math/rand"
  27	"net/http"
  28	"net/url"
  29	"os"
  30	"regexp"
  31	"strings"
  32	"time"
  33
  34	"humungus.tedunangst.com/r/webs/cache"
  35	"humungus.tedunangst.com/r/webs/gate"
  36	"humungus.tedunangst.com/r/webs/httpsig"
  37	"humungus.tedunangst.com/r/webs/junk"
  38	"humungus.tedunangst.com/r/webs/templates"
  39)
  40
  41var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
  42var thefakename = `application/activity+json`
  43var falsenames = []string{
  44	`application/ld+json`,
  45	`application/activity+json`,
  46}
  47var itiswhatitis = "https://www.w3.org/ns/activitystreams"
  48var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
  49
  50var fastTimeout time.Duration = 5
  51var slowTimeout time.Duration = 30
  52
  53func friendorfoe(ct string) bool {
  54	ct = strings.ToLower(ct)
  55	for _, at := range falsenames {
  56		if strings.HasPrefix(ct, at) {
  57			return true
  58		}
  59	}
  60	return false
  61}
  62
  63var develClient = &http.Client{
  64	Transport: &http.Transport{
  65		TLSClientConfig: &tls.Config{
  66			InsecureSkipVerify: true,
  67		},
  68	},
  69}
  70
  71func PostJunk(keyname string, key httpsig.PrivateKey, url string, j junk.Junk) error {
  72	return PostMsg(keyname, key, url, j.ToBytes())
  73}
  74
  75func PostMsg(keyname string, key httpsig.PrivateKey, url string, msg []byte) error {
  76	client := http.DefaultClient
  77	if develMode {
  78		client = develClient
  79	}
  80	req, err := http.NewRequest("POST", url, bytes.NewReader(msg))
  81	if err != nil {
  82		return err
  83	}
  84	req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName)
  85	req.Header.Set("Content-Type", theonetruename)
  86	httpsig.SignRequest(keyname, key, req, msg)
  87	ctx, cancel := context.WithTimeout(context.Background(), 2*slowTimeout*time.Second)
  88	defer cancel()
  89	req = req.WithContext(ctx)
  90	resp, err := client.Do(req)
  91	if err != nil {
  92		return err
  93	}
  94	resp.Body.Close()
  95	switch resp.StatusCode {
  96	case 200:
  97	case 201:
  98	case 202:
  99	default:
 100		return fmt.Errorf("http post status: %d", resp.StatusCode)
 101	}
 102	ilog.Printf("successful post: %s %d", url, resp.StatusCode)
 103	return nil
 104}
 105
 106func GetJunk(userid int64, url string) (junk.Junk, error) {
 107	return GetJunkTimeout(userid, url, slowTimeout*time.Second)
 108}
 109
 110func GetJunkFast(userid int64, url string) (junk.Junk, error) {
 111	return GetJunkTimeout(userid, url, fastTimeout*time.Second)
 112}
 113
 114func GetJunkHardMode(userid int64, url string) (junk.Junk, error) {
 115	j, err := GetJunk(userid, url)
 116	if err != nil {
 117		emsg := err.Error()
 118		if emsg == "http get status: 502" || strings.Contains(emsg, "timeout") {
 119			ilog.Printf("trying again after error: %s", emsg)
 120			time.Sleep(time.Duration(60+notrand.Int63n(60)) * time.Second)
 121			j, err = GetJunk(userid, url)
 122			if err != nil {
 123				ilog.Printf("still couldn't get it")
 124			} else {
 125				ilog.Printf("retry success!")
 126			}
 127		}
 128	}
 129	return j, err
 130}
 131
 132var flightdeck = gate.NewSerializer()
 133
 134var signGets = true
 135
 136func junkGet(userid int64, url string, args junk.GetArgs) (junk.Junk, error) {
 137	client := http.DefaultClient
 138	if args.Client != nil {
 139		client = args.Client
 140	}
 141	req, err := http.NewRequest("GET", url, nil)
 142	if err != nil {
 143		return nil, err
 144	}
 145	if args.Accept != "" {
 146		req.Header.Set("Accept", args.Accept)
 147	}
 148	if args.Agent != "" {
 149		req.Header.Set("User-Agent", args.Agent)
 150	}
 151	if signGets {
 152		var ki *KeyInfo
 153		ok := ziggies.Get(userid, &ki)
 154		if ok {
 155			httpsig.SignRequest(ki.keyname, ki.seckey, req, nil)
 156		}
 157	}
 158	if args.Timeout != 0 {
 159		ctx, cancel := context.WithTimeout(context.Background(), args.Timeout)
 160		defer cancel()
 161		req = req.WithContext(ctx)
 162	}
 163	resp, err := client.Do(req)
 164	if err != nil {
 165		return nil, err
 166	}
 167	defer resp.Body.Close()
 168
 169	if resp.StatusCode != 200 {
 170		return nil, fmt.Errorf("http get status: %d", resp.StatusCode)
 171	}
 172	return junk.Read(resp.Body)
 173}
 174
 175func GetJunkTimeout(userid int64, url string, timeout time.Duration) (junk.Junk, error) {
 176	client := http.DefaultClient
 177	if develMode {
 178		client = develClient
 179	}
 180	fn := func() (interface{}, error) {
 181		at := thefakename
 182		if strings.Contains(url, ".well-known/webfinger?resource") {
 183			at = "application/jrd+json"
 184		}
 185		j, err := junkGet(userid, url, junk.GetArgs{
 186			Accept:  at,
 187			Agent:   "honksnonk/5.0; " + serverName,
 188			Timeout: timeout,
 189			Client:  client,
 190		})
 191		return j, err
 192	}
 193
 194	ji, err := flightdeck.Call(url, fn)
 195	if err != nil {
 196		return nil, err
 197	}
 198	j := ji.(junk.Junk)
 199	return j, nil
 200}
 201
 202func fetchsome(url string) ([]byte, error) {
 203	client := http.DefaultClient
 204	if develMode {
 205		client = develClient
 206	}
 207	req, err := http.NewRequest("GET", url, nil)
 208	if err != nil {
 209		ilog.Printf("error fetching %s: %s", url, err)
 210		return nil, err
 211	}
 212	req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName)
 213	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
 214	defer cancel()
 215	req = req.WithContext(ctx)
 216	resp, err := client.Do(req)
 217	if err != nil {
 218		ilog.Printf("error fetching %s: %s", url, err)
 219		return nil, err
 220	}
 221	defer resp.Body.Close()
 222	switch resp.StatusCode {
 223	case 200:
 224	case 201:
 225	case 202:
 226	default:
 227		return nil, fmt.Errorf("http get not 200: %d %s", resp.StatusCode, url)
 228	}
 229	var buf bytes.Buffer
 230	limiter := io.LimitReader(resp.Body, 10*1024*1024)
 231	io.Copy(&buf, limiter)
 232	return buf.Bytes(), nil
 233}
 234
 235func savedonk(url string, name, desc, media string, localize bool) *Donk {
 236	if url == "" {
 237		return nil
 238	}
 239	if donk := finddonk(url); donk != nil {
 240		return donk
 241	}
 242	ilog.Printf("saving donk: %s", url)
 243	data := []byte{}
 244	if localize {
 245		fn := func() (interface{}, error) {
 246			return fetchsome(url)
 247		}
 248		ii, err := flightdeck.Call(url, fn)
 249		if err != nil {
 250			ilog.Printf("error fetching donk: %s", err)
 251			localize = false
 252			goto saveit
 253		}
 254		data = ii.([]byte)
 255
 256		if len(data) == 10*1024*1024 {
 257			ilog.Printf("truncation likely")
 258		}
 259		if strings.HasPrefix(media, "image") {
 260			img, err := shrinkit(data)
 261			if err != nil {
 262				ilog.Printf("unable to decode image: %s", err)
 263				localize = false
 264				data = []byte{}
 265				goto saveit
 266			}
 267			data = img.Data
 268			media = "image/" + img.Format
 269		} else if media == "application/pdf" {
 270			if len(data) > 1000000 {
 271				ilog.Printf("not saving large pdf")
 272				localize = false
 273				data = []byte{}
 274			}
 275		} else if len(data) > 100000 {
 276			ilog.Printf("not saving large attachment")
 277			localize = false
 278			data = []byte{}
 279		}
 280	}
 281saveit:
 282	fileid, err := savefile(name, desc, url, media, localize, data)
 283	if err != nil {
 284		elog.Printf("error saving file %s: %s", url, err)
 285		return nil
 286	}
 287	donk := new(Donk)
 288	donk.FileID = fileid
 289	return donk
 290}
 291
 292func iszonked(userid int64, xid string) bool {
 293	var id int64
 294	row := stmtFindZonk.QueryRow(userid, xid)
 295	err := row.Scan(&id)
 296	if err == nil {
 297		return true
 298	}
 299	if err != sql.ErrNoRows {
 300		ilog.Printf("error querying zonk: %s", err)
 301	}
 302	return false
 303}
 304
 305func needxonk(user *WhatAbout, x *Honk) bool {
 306	if rejectxonk(x) {
 307		return false
 308	}
 309	return needxonkid(user, x.XID)
 310}
 311func needbonkid(user *WhatAbout, xid string) bool {
 312	return needxonkidX(user, xid, true)
 313}
 314func needxonkid(user *WhatAbout, xid string) bool {
 315	return needxonkidX(user, xid, false)
 316}
 317func needxonkidX(user *WhatAbout, xid string, isannounce bool) bool {
 318	if !strings.HasPrefix(xid, "https://") {
 319		return false
 320	}
 321	if strings.HasPrefix(xid, user.URL+"/") {
 322		return false
 323	}
 324	if rejectorigin(user.ID, xid, isannounce) {
 325		ilog.Printf("rejecting origin: %s", xid)
 326		return false
 327	}
 328	if iszonked(user.ID, xid) {
 329		ilog.Printf("already zonked: %s", xid)
 330		return false
 331	}
 332	var id int64
 333	row := stmtFindXonk.QueryRow(user.ID, xid)
 334	err := row.Scan(&id)
 335	if err == nil {
 336		return false
 337	}
 338	if err != sql.ErrNoRows {
 339		ilog.Printf("error querying xonk: %s", err)
 340	}
 341	return true
 342}
 343
 344func eradicatexonk(userid int64, xid string) {
 345	xonk := getxonk(userid, xid)
 346	if xonk != nil {
 347		deletehonk(xonk.ID)
 348	}
 349	_, err := stmtSaveZonker.Exec(userid, xid, "zonk")
 350	if err != nil {
 351		elog.Printf("error eradicating: %s", err)
 352	}
 353}
 354
 355func savexonk(x *Honk) {
 356	ilog.Printf("saving xonk: %s", x.XID)
 357	go handles(x.Honker)
 358	go handles(x.Oonker)
 359	savehonk(x)
 360}
 361
 362type Box struct {
 363	In     string
 364	Out    string
 365	Shared string
 366}
 367
 368var boxofboxes = cache.New(cache.Options{Filler: func(ident string) (*Box, bool) {
 369	var info string
 370	row := stmtGetXonker.QueryRow(ident, "boxes")
 371	err := row.Scan(&info)
 372	if err != nil {
 373		dlog.Printf("need to get boxes for %s", ident)
 374		var j junk.Junk
 375		j, err = GetJunk(readyLuserOne, ident)
 376		if err != nil {
 377			dlog.Printf("error getting boxes: %s", err)
 378			return nil, false
 379		}
 380		allinjest(originate(ident), j)
 381		row = stmtGetXonker.QueryRow(ident, "boxes")
 382		err = row.Scan(&info)
 383	}
 384	if err == nil {
 385		m := strings.Split(info, " ")
 386		b := &Box{In: m[0], Out: m[1], Shared: m[2]}
 387		return b, true
 388	}
 389	return nil, false
 390}})
 391
 392func gimmexonks(user *WhatAbout, outbox string) {
 393	dlog.Printf("getting outbox: %s", outbox)
 394	j, err := GetJunk(user.ID, outbox)
 395	if err != nil {
 396		ilog.Printf("error getting outbox: %s", err)
 397		return
 398	}
 399	t, _ := j.GetString("type")
 400	origin := originate(outbox)
 401	if t == "OrderedCollection" {
 402		items, _ := j.GetArray("orderedItems")
 403		if items == nil {
 404			items, _ = j.GetArray("items")
 405		}
 406		if items == nil {
 407			obj, ok := j.GetMap("first")
 408			if ok {
 409				items, _ = obj.GetArray("orderedItems")
 410			} else {
 411				page1, ok := j.GetString("first")
 412				if ok {
 413					j, err = GetJunk(user.ID, page1)
 414					if err != nil {
 415						ilog.Printf("error getting page1: %s", err)
 416						return
 417					}
 418					items, _ = j.GetArray("orderedItems")
 419				}
 420			}
 421		}
 422		if len(items) > 20 {
 423			items = items[0:20]
 424		}
 425		for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
 426			items[i], items[j] = items[j], items[i]
 427		}
 428		for _, item := range items {
 429			obj, ok := item.(junk.Junk)
 430			if ok {
 431				xonksaver(user, obj, origin)
 432				continue
 433			}
 434			xid, ok := item.(string)
 435			if ok {
 436				if !needxonkid(user, xid) {
 437					continue
 438				}
 439				obj, err = GetJunk(user.ID, xid)
 440				if err != nil {
 441					ilog.Printf("error getting item: %s", err)
 442					continue
 443				}
 444				xonksaver(user, obj, originate(xid))
 445			}
 446		}
 447	}
 448}
 449
 450func newphone(a []string, obj junk.Junk) []string {
 451	for _, addr := range []string{"to", "cc", "attributedTo"} {
 452		who, _ := obj.GetString(addr)
 453		if who != "" {
 454			a = append(a, who)
 455		}
 456		whos, _ := obj.GetArray(addr)
 457		for _, w := range whos {
 458			who, _ := w.(string)
 459			if who != "" {
 460				a = append(a, who)
 461			}
 462		}
 463	}
 464	return a
 465}
 466
 467func extractattrto(obj junk.Junk) string {
 468	who, _ := obj.GetString("attributedTo")
 469	if who != "" {
 470		return who
 471	}
 472	o, ok := obj.GetMap("attributedTo")
 473	if ok {
 474		id, ok := o.GetString("id")
 475		if ok {
 476			return id
 477		}
 478	}
 479	arr, _ := obj.GetArray("attributedTo")
 480	for _, a := range arr {
 481		o, ok := a.(junk.Junk)
 482		if ok {
 483			t, _ := o.GetString("type")
 484			id, _ := o.GetString("id")
 485			if t == "Person" || t == "" {
 486				return id
 487			}
 488		}
 489		s, ok := a.(string)
 490		if ok {
 491			return s
 492		}
 493	}
 494	return ""
 495}
 496
 497func firstofmany(obj junk.Junk, key string) string {
 498	if val, _ := obj.GetString(key); val != "" {
 499		return val
 500	}
 501	if arr, _ := obj.GetArray(key); len(arr) > 0 {
 502		val, ok := arr[0].(string)
 503		if ok {
 504			return val
 505		}
 506	}
 507	return ""
 508}
 509
 510var re_mast0link = regexp.MustCompile(`https://[[:alnum:].]+/users/[[:alnum:]]+/statuses/[[:digit:]]+`)
 511var re_masto1ink = regexp.MustCompile(`https://[[:alnum:].]+/@[[:alnum:]]+/[[:digit:]]+`)
 512var re_misslink = regexp.MustCompile(`https://[[:alnum:].]+/notes/[[:alnum:]]+`)
 513var re_honklink = regexp.MustCompile(`https://[[:alnum:].]+/u/[[:alnum:]]+/h/[[:alnum:]]+`)
 514var re_r0malink = regexp.MustCompile(`https://[[:alnum:].]+/objects/[[:alnum:]-]+`)
 515var re_roma1ink = regexp.MustCompile(`https://[[:alnum:].]+/notice/[[:alnum:]]+`)
 516var re_qtlinks = regexp.MustCompile(`>https://[^\s<]+<`)
 517
 518func qutify(user *WhatAbout, content string) string {
 519	// well this is gross
 520	malcontent := strings.ReplaceAll(content, `</span><span class="ellipsis">`, "")
 521	malcontent = strings.ReplaceAll(malcontent, `</span><span class="invisible">`, "")
 522	mlinks := re_qtlinks.FindAllString(malcontent, -1)
 523	for _, m := range mlinks {
 524		m = m[1 : len(m)-1]
 525		if re_mast0link.MatchString(m) || re_masto1ink.MatchString(m) ||
 526			re_misslink.MatchString(m) ||
 527			re_honklink.MatchString(m) ||
 528			re_r0malink.MatchString(m) || re_roma1ink.MatchString(m) {
 529			j, err := GetJunk(user.ID, m)
 530			if err == nil {
 531				q, ok := j.GetString("content")
 532				if ok {
 533					content = fmt.Sprintf("%s<blockquote>%s</blockquote>", content, q)
 534				}
 535			}
 536		}
 537	}
 538	return content
 539}
 540
 541func xonksaver(user *WhatAbout, item junk.Junk, origin string) *Honk {
 542	depth := 0
 543	maxdepth := 10
 544	currenttid := ""
 545	goingup := 0
 546	var xonkxonkfn func(item junk.Junk, origin string, isUpdate bool) *Honk
 547
 548	saveonemore := func(xid string) {
 549		dlog.Printf("getting onemore: %s", xid)
 550		if depth >= maxdepth {
 551			ilog.Printf("in too deep")
 552			return
 553		}
 554		obj, err := GetJunkHardMode(user.ID, xid)
 555		if err != nil {
 556			ilog.Printf("error getting onemore: %s: %s", xid, err)
 557			return
 558		}
 559		depth++
 560		xonkxonkfn(obj, originate(xid), false)
 561		depth--
 562	}
 563
 564	xonkxonkfn = func(item junk.Junk, origin string, isUpdate bool) *Honk {
 565		id, _ := item.GetString("id")
 566		what := firstofmany(item, "type")
 567		dt, ok := item.GetString("published")
 568		if !ok {
 569			dt = time.Now().Format(time.RFC3339)
 570		}
 571
 572		var err error
 573		var xid, rid, url, convoy string
 574		var replies []string
 575		var obj junk.Junk
 576		waspage := false
 577		preferorig := false
 578		switch what {
 579		case "Delete":
 580			obj, ok = item.GetMap("object")
 581			if ok {
 582				xid, _ = obj.GetString("id")
 583			} else {
 584				xid, _ = item.GetString("object")
 585			}
 586			if xid == "" {
 587				return nil
 588			}
 589			if originate(xid) != origin {
 590				ilog.Printf("forged delete: %s", xid)
 591				return nil
 592			}
 593			ilog.Printf("eradicating %s", xid)
 594			eradicatexonk(user.ID, xid)
 595			return nil
 596		case "Remove":
 597			xid, _ = item.GetString("object")
 598			targ, _ := obj.GetString("target")
 599			ilog.Printf("remove %s from %s", obj, targ)
 600			return nil
 601		case "Tombstone":
 602			xid, _ = item.GetString("id")
 603			if xid == "" {
 604				return nil
 605			}
 606			if originate(xid) != origin {
 607				ilog.Printf("forged delete: %s", xid)
 608				return nil
 609			}
 610			ilog.Printf("eradicating %s", xid)
 611			eradicatexonk(user.ID, xid)
 612			return nil
 613		case "Announce":
 614			obj, ok = item.GetMap("object")
 615			if ok {
 616				xid, _ = obj.GetString("id")
 617			} else {
 618				xid, _ = item.GetString("object")
 619			}
 620			if !needbonkid(user, xid) {
 621				return nil
 622			}
 623			dlog.Printf("getting bonk: %s", xid)
 624			obj, err = GetJunkHardMode(user.ID, xid)
 625			if err != nil {
 626				ilog.Printf("error getting bonk: %s: %s", xid, err)
 627			}
 628			origin = originate(xid)
 629			what = "bonk"
 630		case "Update":
 631			isUpdate = true
 632			fallthrough
 633		case "Create":
 634			obj, ok = item.GetMap("object")
 635			if !ok {
 636				xid, _ = item.GetString("object")
 637				dlog.Printf("getting created honk: %s", xid)
 638				if originate(xid) != origin {
 639					ilog.Printf("out of bounds %s not from %s", xid, origin)
 640					return nil
 641				}
 642				obj, err = GetJunkHardMode(user.ID, xid)
 643				if err != nil {
 644					ilog.Printf("error getting creation: %s", err)
 645				}
 646			}
 647			if obj == nil {
 648				ilog.Printf("no object for creation %s", id)
 649				return nil
 650			}
 651			return xonkxonkfn(obj, origin, isUpdate)
 652		case "Read":
 653			xid, ok = item.GetString("object")
 654			if ok {
 655				if !needxonkid(user, xid) {
 656					dlog.Printf("don't need read obj: %s", xid)
 657					return nil
 658				}
 659				obj, err = GetJunkHardMode(user.ID, xid)
 660				if err != nil {
 661					ilog.Printf("error getting read: %s", err)
 662					return nil
 663				}
 664				return xonkxonkfn(obj, originate(xid), false)
 665			}
 666			return nil
 667		case "Add":
 668			xid, ok = item.GetString("object")
 669			if ok {
 670				// check target...
 671				if !needxonkid(user, xid) {
 672					dlog.Printf("don't need added obj: %s", xid)
 673					return nil
 674				}
 675				obj, err = GetJunkHardMode(user.ID, xid)
 676				if err != nil {
 677					ilog.Printf("error getting add: %s", err)
 678					return nil
 679				}
 680				return xonkxonkfn(obj, originate(xid), false)
 681			}
 682			return nil
 683		case "Move":
 684			obj = item
 685			what = "move"
 686		case "Page":
 687			waspage = true
 688			fallthrough
 689		case "Audio":
 690			fallthrough
 691		case "Image":
 692			preferorig = true
 693			fallthrough
 694		case "Video":
 695			fallthrough
 696		case "Question":
 697			fallthrough
 698		case "Note":
 699			fallthrough
 700		case "Article":
 701			obj = item
 702			what = "honk"
 703		case "Event":
 704			obj = item
 705			what = "event"
 706		case "ChatMessage":
 707			obj = item
 708			what = "chonk"
 709		default:
 710			ilog.Printf("unknown activity: %s", what)
 711			dumpactivity(item)
 712			return nil
 713		}
 714
 715		if obj != nil {
 716			xid, _ = obj.GetString("id")
 717		}
 718
 719		if xid == "" {
 720			ilog.Printf("don't know what xid is")
 721			item.Write(ilog.Writer())
 722			return nil
 723		}
 724		if originate(xid) != origin {
 725			if !develMode && origin != "" {
 726				ilog.Printf("original sin: %s not from %s", xid, origin)
 727				item.Write(ilog.Writer())
 728				return nil
 729			}
 730		}
 731
 732		var xonk Honk
 733		// early init
 734		xonk.XID = xid
 735		xonk.UserID = user.ID
 736		xonk.Honker, _ = item.GetString("actor")
 737		if xonk.Honker == "" {
 738			xonk.Honker, _ = item.GetString("attributedTo")
 739		}
 740		if obj != nil {
 741			if xonk.Honker == "" {
 742				xonk.Honker = extractattrto(obj)
 743			}
 744			xonk.Oonker = extractattrto(obj)
 745			if xonk.Oonker == xonk.Honker {
 746				xonk.Oonker = ""
 747			}
 748			xonk.Audience = newphone(nil, obj)
 749		}
 750		xonk.Audience = append(xonk.Audience, xonk.Honker)
 751		xonk.Audience = oneofakind(xonk.Audience)
 752		xonk.Public = loudandproud(xonk.Audience)
 753
 754		var mentions []Mention
 755		if obj != nil {
 756			ot, _ := obj.GetString("type")
 757			url, _ = obj.GetString("url")
 758			if dt2, ok := obj.GetString("published"); ok {
 759				dt = dt2
 760			}
 761			content, _ := obj.GetString("content")
 762			if !strings.HasPrefix(content, "<p>") {
 763				content = "<p>" + content
 764			}
 765			precis, _ := obj.GetString("summary")
 766			if name, ok := obj.GetString("name"); ok {
 767				if precis != "" {
 768					content = precis + "<p>" + content
 769				}
 770				precis = html.EscapeString(name)
 771			}
 772			if sens, _ := obj["sensitive"].(bool); sens && precis == "" {
 773				precis = "unspecified horror"
 774			}
 775			if waspage {
 776				content += fmt.Sprintf(`<p><a href="%s">%s</a>`, url, url)
 777				url = xid
 778			}
 779			if user.Options.InlineQuotes {
 780				content = qutify(user, content)
 781			}
 782			rid, ok = obj.GetString("inReplyTo")
 783			if !ok {
 784				if robj, ok := obj.GetMap("inReplyTo"); ok {
 785					rid, _ = robj.GetString("id")
 786				}
 787			}
 788			convoy, _ = obj.GetString("context")
 789			if convoy == "" {
 790				convoy, _ = obj.GetString("conversation")
 791			}
 792			if ot == "Question" {
 793				if what == "honk" {
 794					what = "qonk"
 795				}
 796				content += "<ul>"
 797				ans, _ := obj.GetArray("oneOf")
 798				for _, ai := range ans {
 799					a, ok := ai.(junk.Junk)
 800					if !ok {
 801						continue
 802					}
 803					as, _ := a.GetString("name")
 804					content += "<li>" + as
 805				}
 806				ans, _ = obj.GetArray("anyOf")
 807				for _, ai := range ans {
 808					a, ok := ai.(junk.Junk)
 809					if !ok {
 810						continue
 811					}
 812					as, _ := a.GetString("name")
 813					content += "<li>" + as
 814				}
 815				content += "</ul>"
 816			}
 817			if ot == "Move" {
 818				targ, _ := obj.GetString("target")
 819				content += string(templates.Sprintf(`<p>Moved to <a href="%s">%s</a>`, targ, targ))
 820			}
 821			if what == "honk" && rid != "" {
 822				what = "tonk"
 823			}
 824			if len(content) > 90001 {
 825				ilog.Printf("content too long. truncating")
 826				content = content[:90001]
 827			}
 828
 829			xonk.Noise = content
 830			xonk.Precis = precis
 831			if rejectxonk(&xonk) {
 832				dlog.Printf("fast reject: %s", xid)
 833				return nil
 834			}
 835
 836			numatts := 0
 837			procatt := func(att junk.Junk) {
 838				at, _ := att.GetString("type")
 839				mt, _ := att.GetString("mediaType")
 840				u, ok := att.GetString("url")
 841				if !ok {
 842					u, ok = att.GetString("href")
 843				}
 844				if !ok {
 845					if ua, ok := att.GetArray("url"); ok && len(ua) > 0 {
 846						u, ok = ua[0].(string)
 847						if !ok {
 848							if uu, ok := ua[0].(junk.Junk); ok {
 849								u, _ = uu.GetString("href")
 850								if mt == "" {
 851									mt, _ = uu.GetString("mediaType")
 852								}
 853							}
 854						}
 855					} else if uu, ok := att.GetMap("url"); ok {
 856						u, _ = uu.GetString("href")
 857						if mt == "" {
 858							mt, _ = uu.GetString("mediaType")
 859						}
 860					}
 861				}
 862				name, _ := att.GetString("name")
 863				desc, _ := att.GetString("summary")
 864				desc = html.UnescapeString(desc)
 865				if desc == "" {
 866					desc = name
 867				}
 868				localize := false
 869				if numatts > 4 {
 870					ilog.Printf("excessive attachment: %s", at)
 871				} else if at == "Document" || at == "Image" || (preferorig && at == "Link") {
 872					mt = strings.ToLower(mt)
 873					dlog.Printf("attachment: %s %s", mt, u)
 874					if mt == "text/plain" || mt == "application/pdf" ||
 875						strings.HasPrefix(mt, "image") {
 876						localize = true
 877					}
 878				} else {
 879					ilog.Printf("unknown attachment: %s", at)
 880				}
 881				if skipMedia(&xonk) {
 882					localize = false
 883				}
 884				if preferorig && !localize {
 885					return
 886				}
 887				donk := savedonk(u, name, desc, mt, localize)
 888				if donk != nil {
 889					xonk.Donks = append(xonk.Donks, donk)
 890				}
 891				numatts++
 892			}
 893			if preferorig {
 894				atts, _ := obj.GetArray("url")
 895				for _, atti := range atts {
 896					att, ok := atti.(junk.Junk)
 897					if !ok {
 898						ilog.Printf("attachment that wasn't map?")
 899						continue
 900					}
 901					procatt(att)
 902				}
 903				if numatts == 0 {
 904					preferorig = false
 905				}
 906			}
 907			if !preferorig {
 908				atts, _ := obj.GetArray("attachment")
 909				for _, atti := range atts {
 910					att, ok := atti.(junk.Junk)
 911					if !ok {
 912						ilog.Printf("attachment that wasn't map?")
 913						continue
 914					}
 915					procatt(att)
 916				}
 917				if att, ok := obj.GetMap("attachment"); ok {
 918					procatt(att)
 919				}
 920			}
 921			tags, _ := obj.GetArray("tag")
 922			for _, tagi := range tags {
 923				tag, ok := tagi.(junk.Junk)
 924				if !ok {
 925					continue
 926				}
 927				tt, _ := tag.GetString("type")
 928				name, _ := tag.GetString("name")
 929				desc, _ := tag.GetString("summary")
 930				desc = html.UnescapeString(desc)
 931				if desc == "" {
 932					desc = name
 933				}
 934				if tt == "Emoji" {
 935					icon, _ := tag.GetMap("icon")
 936					mt, _ := icon.GetString("mediaType")
 937					if mt == "" {
 938						mt = "image/png"
 939					}
 940					u, _ := icon.GetString("url")
 941					donk := savedonk(u, name, desc, mt, true)
 942					if donk != nil {
 943						xonk.Donks = append(xonk.Donks, donk)
 944					}
 945				}
 946				if tt == "Hashtag" {
 947					if name == "" || name == "#" {
 948						// skip it
 949					} else {
 950						if name[0] != '#' {
 951							name = "#" + name
 952						}
 953						xonk.Onts = append(xonk.Onts, name)
 954					}
 955				}
 956				if tt == "Place" {
 957					p := new(Place)
 958					p.Name = name
 959					p.Latitude, _ = tag.GetNumber("latitude")
 960					p.Longitude, _ = tag.GetNumber("longitude")
 961					p.Url, _ = tag.GetString("url")
 962					xonk.Place = p
 963				}
 964				if tt == "Mention" {
 965					var m Mention
 966					m.Who, _ = tag.GetString("name")
 967					m.Where, _ = tag.GetString("href")
 968					mentions = append(mentions, m)
 969				}
 970			}
 971			if starttime, ok := obj.GetString("startTime"); ok {
 972				if start, err := time.Parse(time.RFC3339, starttime); err == nil {
 973					t := new(Time)
 974					t.StartTime = start
 975					endtime, _ := obj.GetString("endTime")
 976					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
 977					dura, _ := obj.GetString("duration")
 978					if strings.HasPrefix(dura, "PT") {
 979						dura = strings.ToLower(dura[2:])
 980						d, _ := time.ParseDuration(dura)
 981						t.Duration = Duration(d)
 982					}
 983					xonk.Time = t
 984				}
 985			}
 986			if loca, ok := obj.GetMap("location"); ok {
 987				if tt, _ := loca.GetString("type"); tt == "Place" {
 988					p := new(Place)
 989					p.Name, _ = loca.GetString("name")
 990					p.Latitude, _ = loca.GetNumber("latitude")
 991					p.Longitude, _ = loca.GetNumber("longitude")
 992					p.Url, _ = loca.GetString("url")
 993					xonk.Place = p
 994				}
 995			}
 996
 997			xonk.Onts = oneofakind(xonk.Onts)
 998			replyobj, ok := obj.GetMap("replies")
 999			if ok {
1000				items, ok := replyobj.GetArray("items")
1001				if !ok {
1002					first, ok := replyobj.GetMap("first")
1003					if ok {
1004						items, _ = first.GetArray("items")
1005					}
1006				}
1007				for _, repl := range items {
1008					s, ok := repl.(string)
1009					if ok {
1010						replies = append(replies, s)
1011					}
1012				}
1013			}
1014
1015		}
1016
1017		if currenttid == "" {
1018			currenttid = convoy
1019		}
1020
1021		// init xonk
1022		xonk.What = what
1023		xonk.RID = rid
1024		xonk.Date, _ = time.Parse(time.RFC3339, dt)
1025		xonk.URL = url
1026		xonk.Format = "html"
1027		xonk.Convoy = convoy
1028		xonk.Mentions = mentions
1029		for _, m := range mentions {
1030			if m.Where == user.URL {
1031				xonk.Whofore = 1
1032			}
1033		}
1034		imaginate(&xonk)
1035
1036		if what == "chonk" {
1037			ch := Chonk{
1038				UserID: xonk.UserID,
1039				XID:    xid,
1040				Who:    xonk.Honker,
1041				Target: xonk.Honker,
1042				Date:   xonk.Date,
1043				Noise:  xonk.Noise,
1044				Format: xonk.Format,
1045				Donks:  xonk.Donks,
1046			}
1047			savechonk(&ch)
1048			return nil
1049		}
1050
1051		if isUpdate {
1052			dlog.Printf("something has changed! %s", xonk.XID)
1053			prev := getxonk(user.ID, xonk.XID)
1054			if prev == nil {
1055				ilog.Printf("didn't find old version for update: %s", xonk.XID)
1056				isUpdate = false
1057			} else {
1058				xonk.ID = prev.ID
1059				updatehonk(&xonk)
1060			}
1061		}
1062		if !isUpdate && needxonk(user, &xonk) {
1063			if rid != "" && xonk.Public {
1064				if needxonkid(user, rid) {
1065					goingup++
1066					saveonemore(rid)
1067					goingup--
1068				}
1069				if convoy == "" {
1070					xx := getxonk(user.ID, rid)
1071					if xx != nil {
1072						convoy = xx.Convoy
1073					}
1074				}
1075			}
1076			if convoy == "" {
1077				convoy = currenttid
1078			}
1079			if convoy == "" {
1080				convoy = "data:,missing-" + xfiltrate()
1081				currenttid = convoy
1082			}
1083			xonk.Convoy = convoy
1084			savexonk(&xonk)
1085		}
1086		if goingup == 0 {
1087			for _, replid := range replies {
1088				if needxonkid(user, replid) {
1089					dlog.Printf("missing a reply: %s", replid)
1090					saveonemore(replid)
1091				}
1092			}
1093		}
1094		return &xonk
1095	}
1096
1097	return xonkxonkfn(item, origin, false)
1098}
1099
1100func dumpactivity(item junk.Junk) {
1101	fd, err := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
1102	if err != nil {
1103		elog.Printf("error opening inbox! %s", err)
1104		return
1105	}
1106	defer fd.Close()
1107	item.Write(fd)
1108	io.WriteString(fd, "\n")
1109}
1110
1111func rubadubdub(user *WhatAbout, req junk.Junk) {
1112	actor, _ := req.GetString("actor")
1113	j := junk.New()
1114	j["@context"] = itiswhatitis
1115	j["id"] = user.URL + "/dub/" + xfiltrate()
1116	j["type"] = "Accept"
1117	j["actor"] = user.URL
1118	j["to"] = actor
1119	j["published"] = time.Now().UTC().Format(time.RFC3339)
1120	j["object"] = req
1121
1122	deliverate(0, user.ID, actor, j.ToBytes(), true)
1123}
1124
1125func itakeitallback(user *WhatAbout, xid string, owner string, folxid string) {
1126	j := junk.New()
1127	j["@context"] = itiswhatitis
1128	j["id"] = user.URL + "/unsub/" + folxid
1129	j["type"] = "Undo"
1130	j["actor"] = user.URL
1131	j["to"] = owner
1132	f := junk.New()
1133	f["id"] = user.URL + "/sub/" + folxid
1134	f["type"] = "Follow"
1135	f["actor"] = user.URL
1136	f["to"] = owner
1137	f["object"] = xid
1138	j["object"] = f
1139	j["published"] = time.Now().UTC().Format(time.RFC3339)
1140
1141	deliverate(0, user.ID, owner, j.ToBytes(), true)
1142}
1143
1144func subsub(user *WhatAbout, xid string, owner string, folxid string) {
1145	if xid == "" {
1146		ilog.Printf("can't subscribe to empty")
1147		return
1148	}
1149	j := junk.New()
1150	j["@context"] = itiswhatitis
1151	j["id"] = user.URL + "/sub/" + folxid
1152	j["type"] = "Follow"
1153	j["actor"] = user.URL
1154	j["to"] = owner
1155	j["object"] = xid
1156	j["published"] = time.Now().UTC().Format(time.RFC3339)
1157
1158	deliverate(0, user.ID, owner, j.ToBytes(), true)
1159}
1160
1161func activatedonks(donks []*Donk) []junk.Junk {
1162	var atts []junk.Junk
1163	for _, d := range donks {
1164		if re_emus.MatchString(d.Name) {
1165			continue
1166		}
1167		jd := junk.New()
1168		jd["mediaType"] = d.Media
1169		jd["name"] = d.Name
1170		jd["summary"] = html.EscapeString(d.Desc)
1171		jd["type"] = "Document"
1172		jd["url"] = d.URL
1173		atts = append(atts, jd)
1174	}
1175	return atts
1176}
1177
1178// returns activity, object
1179func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
1180	dt := h.Date.Format(time.RFC3339)
1181	var jo junk.Junk
1182	j := junk.New()
1183	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
1184	j["actor"] = user.URL
1185	j["published"] = dt
1186	j["to"] = h.Audience[0]
1187	if len(h.Audience) > 1 {
1188		j["cc"] = h.Audience[1:]
1189	}
1190
1191	switch h.What {
1192	case "update":
1193		fallthrough
1194	case "tonk":
1195		fallthrough
1196	case "event":
1197		fallthrough
1198	case "honk":
1199		j["type"] = "Create"
1200		jo = junk.New()
1201		jo["id"] = h.XID
1202		jo["type"] = "Note"
1203		if h.What == "event" {
1204			jo["type"] = "Event"
1205		}
1206		if h.What == "update" {
1207			j["type"] = "Update"
1208			jo["updated"] = dt
1209		}
1210		jo["published"] = dt
1211		jo["url"] = h.XID
1212		jo["attributedTo"] = user.URL
1213		if h.RID != "" {
1214			jo["inReplyTo"] = h.RID
1215		}
1216		if h.Convoy != "" {
1217			jo["context"] = h.Convoy
1218			jo["conversation"] = h.Convoy
1219		}
1220		jo["to"] = h.Audience[0]
1221		if len(h.Audience) > 1 {
1222			jo["cc"] = h.Audience[1:]
1223		}
1224		if !h.Public {
1225			jo["directMessage"] = true
1226		}
1227		translate(h)
1228		redoimages(h)
1229		if h.Precis != "" {
1230			jo["sensitive"] = true
1231		}
1232
1233		var replies []string
1234		for _, reply := range h.Replies {
1235			replies = append(replies, reply.XID)
1236		}
1237		if len(replies) > 0 {
1238			jr := junk.New()
1239			jr["type"] = "Collection"
1240			jr["totalItems"] = len(replies)
1241			jr["items"] = replies
1242			jo["replies"] = jr
1243		}
1244
1245		var tags []junk.Junk
1246		for _, m := range h.Mentions {
1247			t := junk.New()
1248			t["type"] = "Mention"
1249			t["name"] = m.Who
1250			t["href"] = m.Where
1251			tags = append(tags, t)
1252		}
1253		for _, o := range h.Onts {
1254			t := junk.New()
1255			t["type"] = "Hashtag"
1256			o = strings.ToLower(o)
1257			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1258			t["name"] = o
1259			tags = append(tags, t)
1260		}
1261		for _, e := range herdofemus(h.Noise) {
1262			t := junk.New()
1263			t["id"] = e.ID
1264			t["type"] = "Emoji"
1265			t["name"] = e.Name
1266			i := junk.New()
1267			i["type"] = "Image"
1268			i["mediaType"] = e.Type
1269			i["url"] = e.ID
1270			t["icon"] = i
1271			tags = append(tags, t)
1272		}
1273		for _, e := range fixupflags(h) {
1274			t := junk.New()
1275			t["id"] = e.ID
1276			t["type"] = "Emoji"
1277			t["name"] = e.Name
1278			i := junk.New()
1279			i["type"] = "Image"
1280			i["mediaType"] = "image/png"
1281			i["url"] = e.ID
1282			t["icon"] = i
1283			tags = append(tags, t)
1284		}
1285		if len(tags) > 0 {
1286			jo["tag"] = tags
1287		}
1288		if p := h.Place; p != nil {
1289			t := junk.New()
1290			t["type"] = "Place"
1291			if p.Name != "" {
1292				t["name"] = p.Name
1293			}
1294			if p.Latitude != 0 {
1295				t["latitude"] = p.Latitude
1296			}
1297			if p.Longitude != 0 {
1298				t["longitude"] = p.Longitude
1299			}
1300			if p.Url != "" {
1301				t["url"] = p.Url
1302			}
1303			jo["location"] = t
1304		}
1305		if t := h.Time; t != nil {
1306			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1307			if t.Duration != 0 {
1308				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1309			}
1310		}
1311		atts := activatedonks(h.Donks)
1312		if len(atts) > 0 {
1313			jo["attachment"] = atts
1314		}
1315		jo["summary"] = h.Precis
1316		jo["content"] = h.Noise
1317		j["object"] = jo
1318	case "bonk":
1319		j["type"] = "Announce"
1320		if h.Convoy != "" {
1321			j["context"] = h.Convoy
1322		}
1323		j["object"] = h.XID
1324	case "unbonk":
1325		b := junk.New()
1326		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1327		b["type"] = "Announce"
1328		b["actor"] = user.URL
1329		if h.Convoy != "" {
1330			b["context"] = h.Convoy
1331		}
1332		b["object"] = h.XID
1333		j["type"] = "Undo"
1334		j["object"] = b
1335	case "zonk":
1336		j["type"] = "Delete"
1337		j["object"] = h.XID
1338	case "ack":
1339		j["type"] = "Read"
1340		j["object"] = h.XID
1341		if h.Convoy != "" {
1342			j["context"] = h.Convoy
1343		}
1344	case "react":
1345		j["type"] = "EmojiReact"
1346		j["object"] = h.XID
1347		if h.Convoy != "" {
1348			j["context"] = h.Convoy
1349		}
1350		j["content"] = h.Noise
1351	case "deack":
1352		b := junk.New()
1353		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1354		b["type"] = "Read"
1355		b["actor"] = user.URL
1356		b["object"] = h.XID
1357		if h.Convoy != "" {
1358			b["context"] = h.Convoy
1359		}
1360		j["type"] = "Undo"
1361		j["object"] = b
1362	}
1363
1364	return j, jo
1365}
1366
1367var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1368	row := stmtAnyXonk.QueryRow(xid)
1369	honk := scanhonk(row)
1370	if honk == nil || !honk.Public {
1371		return nil, true
1372	}
1373	user, _ := butwhatabout(honk.Username)
1374	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1375	reversehonks(rawhonks)
1376	for _, h := range rawhonks {
1377		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1378			honk.Replies = append(honk.Replies, h)
1379		}
1380	}
1381	donksforhonks([]*Honk{honk})
1382	_, j := jonkjonk(user, honk)
1383	if j == nil {
1384		elog.Fatalf("what just happened? %v", honk)
1385	}
1386	j["@context"] = itiswhatitis
1387
1388	return j.ToBytes(), true
1389}, Limit: 128})
1390
1391func gimmejonk(xid string) ([]byte, bool) {
1392	var j []byte
1393	ok := oldjonks.Get(xid, &j)
1394	return j, ok
1395}
1396
1397func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1398	rcpts := make(map[string]bool)
1399	for _, a := range addresses {
1400		if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1401			continue
1402		}
1403		if a[0] == '%' {
1404			rcpts[a] = true
1405			continue
1406		}
1407		var box *Box
1408		ok := boxofboxes.Get(a, &box)
1409		if ok && useshared && box.Shared != "" {
1410			rcpts["%"+box.Shared] = true
1411		} else {
1412			rcpts[a] = true
1413		}
1414	}
1415	return rcpts
1416}
1417
1418func chonkifymsg(user *WhatAbout, ch *Chonk) []byte {
1419	dt := ch.Date.Format(time.RFC3339)
1420	aud := []string{ch.Target}
1421
1422	jo := junk.New()
1423	jo["id"] = ch.XID
1424	jo["type"] = "ChatMessage"
1425	jo["published"] = dt
1426	jo["attributedTo"] = user.URL
1427	jo["to"] = aud
1428	jo["content"] = ch.HTML
1429	atts := activatedonks(ch.Donks)
1430	if len(atts) > 0 {
1431		jo["attachment"] = atts
1432	}
1433	var tags []junk.Junk
1434	for _, e := range herdofemus(ch.Noise) {
1435		t := junk.New()
1436		t["id"] = e.ID
1437		t["type"] = "Emoji"
1438		t["name"] = e.Name
1439		i := junk.New()
1440		i["type"] = "Image"
1441		i["mediaType"] = e.Type
1442		i["url"] = e.ID
1443		t["icon"] = i
1444		tags = append(tags, t)
1445	}
1446	if len(tags) > 0 {
1447		jo["tag"] = tags
1448	}
1449
1450	j := junk.New()
1451	j["@context"] = itiswhatitis
1452	j["id"] = user.URL + "/" + "honk" + "/" + shortxid(ch.XID)
1453	j["type"] = "Create"
1454	j["actor"] = user.URL
1455	j["published"] = dt
1456	j["to"] = aud
1457	j["object"] = jo
1458
1459	return j.ToBytes()
1460}
1461
1462func sendchonk(user *WhatAbout, ch *Chonk) {
1463	msg := chonkifymsg(user, ch)
1464
1465	rcpts := make(map[string]bool)
1466	rcpts[ch.Target] = true
1467	for a := range rcpts {
1468		go deliverate(0, user.ID, a, msg, true)
1469	}
1470}
1471
1472func honkworldwide(user *WhatAbout, honk *Honk) {
1473	jonk, _ := jonkjonk(user, honk)
1474	jonk["@context"] = itiswhatitis
1475	msg := jonk.ToBytes()
1476
1477	rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1478
1479	if honk.Public {
1480		for _, h := range getdubs(user.ID) {
1481			if h.XID == user.URL {
1482				continue
1483			}
1484			var box *Box
1485			ok := boxofboxes.Get(h.XID, &box)
1486			if ok && box.Shared != "" {
1487				rcpts["%"+box.Shared] = true
1488			} else {
1489				rcpts[h.XID] = true
1490			}
1491		}
1492		for _, f := range getbacktracks(honk.XID) {
1493			if f[0] == '%' {
1494				rcpts[f] = true
1495			} else {
1496				var box *Box
1497				ok := boxofboxes.Get(f, &box)
1498				if ok && box.Shared != "" {
1499					rcpts["%"+box.Shared] = true
1500				} else {
1501					rcpts[f] = true
1502				}
1503			}
1504		}
1505	}
1506	for a := range rcpts {
1507		go deliverate(0, user.ID, a, msg, doesitmatter(honk.What))
1508	}
1509	if honk.Public && len(honk.Onts) > 0 {
1510		collectiveaction(honk)
1511	}
1512}
1513
1514func doesitmatter(what string) bool {
1515	switch what {
1516	case "ack":
1517		return false
1518	case "react":
1519		return false
1520	case "deack":
1521		return false
1522	}
1523	return true
1524}
1525
1526func collectiveaction(honk *Honk) {
1527	user := getserveruser()
1528	for _, ont := range honk.Onts {
1529		dubs := getnameddubs(readyLuserOne, ont)
1530		if len(dubs) == 0 {
1531			continue
1532		}
1533		j := junk.New()
1534		j["@context"] = itiswhatitis
1535		j["type"] = "Add"
1536		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1537		j["actor"] = user.URL
1538		j["object"] = honk.XID
1539		j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1540		rcpts := make(map[string]bool)
1541		for _, dub := range dubs {
1542			var box *Box
1543			ok := boxofboxes.Get(dub.XID, &box)
1544			if ok && box.Shared != "" {
1545				rcpts["%"+box.Shared] = true
1546			} else {
1547				rcpts[dub.XID] = true
1548			}
1549		}
1550		msg := j.ToBytes()
1551		for a := range rcpts {
1552			go deliverate(0, user.ID, a, msg, false)
1553		}
1554	}
1555}
1556
1557func junkuser(user *WhatAbout) junk.Junk {
1558	j := junk.New()
1559	j["@context"] = itiswhatitis
1560	j["id"] = user.URL
1561	j["inbox"] = user.URL + "/inbox"
1562	j["outbox"] = user.URL + "/outbox"
1563	j["name"] = user.Display
1564	j["preferredUsername"] = user.Name
1565	j["summary"] = user.HTAbout
1566	var tags []junk.Junk
1567	for _, o := range user.Onts {
1568		t := junk.New()
1569		t["type"] = "Hashtag"
1570		o = strings.ToLower(o)
1571		t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1572		t["name"] = o
1573		tags = append(tags, t)
1574	}
1575	if len(tags) > 0 {
1576		j["tag"] = tags
1577	}
1578
1579	if user.ID > 0 {
1580		j["type"] = "Person"
1581		j["url"] = user.URL
1582		j["followers"] = user.URL + "/followers"
1583		j["following"] = user.URL + "/following"
1584		a := junk.New()
1585		a["type"] = "Image"
1586		a["mediaType"] = "image/png"
1587		if ava := user.Options.Avatar; ava != "" {
1588			a["url"] = ava
1589		} else {
1590			u := fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1591			a["url"] = u
1592		}
1593		j["icon"] = a
1594		if ban := user.Options.Banner; ban != "" {
1595			a := junk.New()
1596			a["type"] = "Image"
1597			a["mediaType"] = "image/jpg"
1598			a["url"] = ban
1599			j["image"] = a
1600		}
1601	} else {
1602		j["type"] = "Service"
1603	}
1604	k := junk.New()
1605	k["id"] = user.URL + "#key"
1606	k["owner"] = user.URL
1607	k["publicKeyPem"] = user.Key
1608	j["publicKey"] = k
1609
1610	return j
1611}
1612
1613var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1614	user, err := butwhatabout(name)
1615	if err != nil {
1616		return nil, false
1617	}
1618	var buf bytes.Buffer
1619	j := junkuser(user)
1620	j.Write(&buf)
1621	return buf.Bytes(), true
1622}, Duration: 1 * time.Minute})
1623
1624func asjonker(name string) ([]byte, bool) {
1625	var j []byte
1626	ok := oldjonkers.Get(name, &j)
1627	return j, ok
1628}
1629
1630var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1631	m := strings.Split(name, "@")
1632	if len(m) != 2 {
1633		dlog.Printf("bad fish name: %s", name)
1634		return "", true
1635	}
1636	var href string
1637	row := stmtGetXonker.QueryRow(name, "fishname")
1638	err := row.Scan(&href)
1639	if err == nil {
1640		return href, true
1641	}
1642	dlog.Printf("fishing for %s", name)
1643	j, err := GetJunkFast(readyLuserOne, fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1644	if err != nil {
1645		ilog.Printf("failed to go fish %s: %s", name, err)
1646		return "", true
1647	}
1648	links, _ := j.GetArray("links")
1649	for _, li := range links {
1650		l, ok := li.(junk.Junk)
1651		if !ok {
1652			continue
1653		}
1654		href, _ := l.GetString("href")
1655		rel, _ := l.GetString("rel")
1656		t, _ := l.GetString("type")
1657		if rel == "self" && friendorfoe(t) {
1658			when := time.Now().UTC().Format(dbtimeformat)
1659			_, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1660			if err != nil {
1661				elog.Printf("error saving fishname: %s", err)
1662			}
1663			return href, true
1664		}
1665	}
1666	return href, true
1667}, Duration: 1 * time.Minute})
1668
1669func gofish(name string) string {
1670	if name[0] == '@' {
1671		name = name[1:]
1672	}
1673	var href string
1674	handfull.Get(name, &href)
1675	return href
1676}
1677
1678func investigate(name string) (*SomeThing, error) {
1679	if name == "" {
1680		return nil, fmt.Errorf("no name")
1681	}
1682	if name[0] == '@' {
1683		name = gofish(name)
1684	}
1685	if name == "" {
1686		return nil, fmt.Errorf("no name")
1687	}
1688	obj, err := GetJunkFast(readyLuserOne, name)
1689	if err != nil {
1690		return nil, err
1691	}
1692	allinjest(originate(name), obj)
1693	return somethingabout(obj)
1694}
1695
1696func somethingabout(obj junk.Junk) (*SomeThing, error) {
1697	info := new(SomeThing)
1698	t, _ := obj.GetString("type")
1699	switch t {
1700	case "Person":
1701		fallthrough
1702	case "Organization":
1703		fallthrough
1704	case "Application":
1705		fallthrough
1706	case "Service":
1707		info.What = SomeActor
1708	case "OrderedCollection":
1709		fallthrough
1710	case "Collection":
1711		info.What = SomeCollection
1712	default:
1713		return nil, fmt.Errorf("unknown object type")
1714	}
1715	info.XID, _ = obj.GetString("id")
1716	info.Name, _ = obj.GetString("preferredUsername")
1717	if info.Name == "" {
1718		info.Name, _ = obj.GetString("name")
1719	}
1720	info.Owner, _ = obj.GetString("attributedTo")
1721	if info.Owner == "" {
1722		info.Owner = info.XID
1723	}
1724	return info, nil
1725}
1726
1727func allinjest(origin string, obj junk.Junk) {
1728	keyobj, ok := obj.GetMap("publicKey")
1729	if ok {
1730		ingestpubkey(origin, keyobj)
1731	}
1732	ingestboxes(origin, obj)
1733	ingesthandle(origin, obj)
1734}
1735
1736func ingestpubkey(origin string, obj junk.Junk) {
1737	keyobj, ok := obj.GetMap("publicKey")
1738	if ok {
1739		obj = keyobj
1740	}
1741	keyname, ok := obj.GetString("id")
1742	var data string
1743	row := stmtGetXonker.QueryRow(keyname, "pubkey")
1744	err := row.Scan(&data)
1745	if err == nil {
1746		return
1747	}
1748	if !ok || origin != originate(keyname) {
1749		ilog.Printf("bad key origin %s <> %s", origin, keyname)
1750		return
1751	}
1752	dlog.Printf("ingesting a needed pubkey: %s", keyname)
1753	owner, ok := obj.GetString("owner")
1754	if !ok {
1755		ilog.Printf("error finding %s pubkey owner", keyname)
1756		return
1757	}
1758	data, ok = obj.GetString("publicKeyPem")
1759	if !ok {
1760		ilog.Printf("error finding %s pubkey", keyname)
1761		return
1762	}
1763	if originate(owner) != origin {
1764		ilog.Printf("bad key owner: %s <> %s", owner, origin)
1765		return
1766	}
1767	_, _, err = httpsig.DecodeKey(data)
1768	if err != nil {
1769		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
1770		return
1771	}
1772	when := time.Now().UTC().Format(dbtimeformat)
1773	_, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1774	if err != nil {
1775		elog.Printf("error saving key: %s", err)
1776	}
1777}
1778
1779func ingestboxes(origin string, obj junk.Junk) {
1780	ident, _ := obj.GetString("id")
1781	if ident == "" {
1782		return
1783	}
1784	if originate(ident) != origin {
1785		return
1786	}
1787	var info string
1788	row := stmtGetXonker.QueryRow(ident, "boxes")
1789	err := row.Scan(&info)
1790	if err == nil {
1791		return
1792	}
1793	dlog.Printf("ingesting boxes: %s", ident)
1794	inbox, _ := obj.GetString("inbox")
1795	outbox, _ := obj.GetString("outbox")
1796	sbox, _ := obj.GetString("endpoints", "sharedInbox")
1797	if inbox != "" {
1798		when := time.Now().UTC().Format(dbtimeformat)
1799		m := strings.Join([]string{inbox, outbox, sbox}, " ")
1800		_, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1801		if err != nil {
1802			elog.Printf("error saving boxes: %s", err)
1803		}
1804	}
1805}
1806
1807func ingesthandle(origin string, obj junk.Junk) {
1808	xid, _ := obj.GetString("id")
1809	if xid == "" {
1810		return
1811	}
1812	if originate(xid) != origin {
1813		return
1814	}
1815	var handle string
1816	row := stmtGetXonker.QueryRow(xid, "handle")
1817	err := row.Scan(&handle)
1818	if err == nil {
1819		return
1820	}
1821	handle, _ = obj.GetString("preferredUsername")
1822	if handle != "" {
1823		when := time.Now().UTC().Format(dbtimeformat)
1824		_, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1825		if err != nil {
1826			elog.Printf("error saving handle: %s", err)
1827		}
1828	}
1829}
1830
1831func updateMe(username string) {
1832	var user *WhatAbout
1833	somenamedusers.Get(username, &user)
1834	dt := time.Now().UTC().Format(time.RFC3339)
1835	j := junk.New()
1836	j["@context"] = itiswhatitis
1837	j["id"] = fmt.Sprintf("%s/upme/%s/%d", user.URL, user.Name, time.Now().Unix())
1838	j["actor"] = user.URL
1839	j["published"] = dt
1840	j["to"] = thewholeworld
1841	j["type"] = "Update"
1842	j["object"] = junkuser(user)
1843
1844	msg := j.ToBytes()
1845
1846	rcpts := make(map[string]bool)
1847	for _, f := range getdubs(user.ID) {
1848		if f.XID == user.URL {
1849			continue
1850		}
1851		var box *Box
1852		boxofboxes.Get(f.XID, &box)
1853		if box != nil && box.Shared != "" {
1854			rcpts["%"+box.Shared] = true
1855		} else {
1856			rcpts[f.XID] = true
1857		}
1858	}
1859	for a := range rcpts {
1860		go deliverate(0, user.ID, a, msg, false)
1861	}
1862}
1863
1864func followme(user *WhatAbout, who string, name string, j junk.Junk) {
1865	folxid, _ := j.GetString("id")
1866
1867	ilog.Printf("updating honker follow: %s %s", who, folxid)
1868
1869	var x string
1870	db := opendatabase()
1871	row := db.QueryRow("select xid from honkers where name = ? and xid = ? and userid = ? and flavor in ('dub', 'undub')", name, who, user.ID)
1872	err := row.Scan(&x)
1873	if err != sql.ErrNoRows {
1874		ilog.Printf("duplicate follow request: %s", who)
1875		_, err = stmtUpdateFlavor.Exec("dub", folxid, user.ID, name, who, "undub")
1876		if err != nil {
1877			elog.Printf("error updating honker: %s", err)
1878		}
1879	} else {
1880		stmtSaveDub.Exec(user.ID, name, who, "dub", folxid)
1881	}
1882	go rubadubdub(user, j)
1883}
1884
1885func unfollowme(user *WhatAbout, who string, name string, j junk.Junk) {
1886	var folxid string
1887	if who == "" {
1888		folxid, _ = j.GetString("object")
1889
1890		db := opendatabase()
1891		row := db.QueryRow("select xid, name from honkers where userid = ? and folxid = ? and flavor in ('dub', 'undub')", user.ID, folxid)
1892		err := row.Scan(&who, &name)
1893		if err != nil {
1894			if err != sql.ErrNoRows {
1895				elog.Printf("error scanning honker: %s", err)
1896			}
1897			return
1898		}
1899	}
1900
1901	ilog.Printf("updating honker undo: %s %s", who, folxid)
1902	_, err := stmtUpdateFlavor.Exec("undub", folxid, user.ID, name, who, "dub")
1903	if err != nil {
1904		elog.Printf("error updating honker: %s", err)
1905		return
1906	}
1907}
1908
1909func followyou(user *WhatAbout, honkerid int64, sync bool) {
1910	var url, owner string
1911	db := opendatabase()
1912	row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1913		honkerid, user.ID)
1914	err := row.Scan(&url, &owner)
1915	if err != nil {
1916		elog.Printf("can't get honker xid: %s", err)
1917		return
1918	}
1919	folxid := xfiltrate()
1920	ilog.Printf("subscribing to %s", url)
1921	_, err = db.Exec("update honkers set flavor = ?, folxid = ? where honkerid = ?", "presub", folxid, honkerid)
1922	if err != nil {
1923		elog.Printf("error updating honker: %s", err)
1924		return
1925	}
1926	if sync {
1927		subsub(user, url, owner, folxid)
1928	} else {
1929		go subsub(user, url, owner, folxid)
1930	}
1931
1932}
1933func unfollowyou(user *WhatAbout, honkerid int64, sync bool) {
1934	db := opendatabase()
1935	row := db.QueryRow("select xid, owner, folxid, flavor from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1936		honkerid, user.ID)
1937	var url, owner, folxid, flavor string
1938	err := row.Scan(&url, &owner, &folxid, &flavor)
1939	if err != nil {
1940		elog.Printf("can't get honker xid: %s", err)
1941		return
1942	}
1943	if flavor == "peep" {
1944		return
1945	}
1946	ilog.Printf("unsubscribing from %s", url)
1947	_, err = db.Exec("update honkers set flavor = ? where honkerid = ?", "unsub", honkerid)
1948	if err != nil {
1949		elog.Printf("error updating honker: %s", err)
1950		return
1951	}
1952	if sync {
1953		itakeitallback(user, url, owner, folxid)
1954	} else {
1955		go itakeitallback(user, url, owner, folxid)
1956	}
1957}
1958
1959func followyou2(user *WhatAbout, j junk.Junk) {
1960	who, _ := j.GetString("actor")
1961
1962	ilog.Printf("updating honker accept: %s", who)
1963	db := opendatabase()
1964	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
1965		user.ID, who)
1966	var name, folxid string
1967	err := row.Scan(&name, &folxid)
1968	if err != nil {
1969		elog.Printf("can't get honker name: %s", err)
1970		return
1971	}
1972	_, err = stmtUpdateFlavor.Exec("sub", folxid, user.ID, name, who, "presub")
1973	if err != nil {
1974		elog.Printf("error updating honker: %s", err)
1975		return
1976	}
1977}
1978
1979func nofollowyou2(user *WhatAbout, j junk.Junk) {
1980	who, _ := j.GetString("actor")
1981
1982	ilog.Printf("updating honker reject: %s", who)
1983	db := opendatabase()
1984	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
1985		user.ID, who)
1986	var name, folxid string
1987	err := row.Scan(&name, &folxid)
1988	if err != nil {
1989		elog.Printf("can't get honker name: %s", err)
1990		return
1991	}
1992	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "presub")
1993	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "sub")
1994	if err != nil {
1995		elog.Printf("error updating honker: %s", err)
1996		return
1997	}
1998}