all repos — honk @ a774192626249641eb7fad08ccfe075046f74396

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_romalink = regexp.MustCompile(`https://[[:alnum:].]+/objects/[[:alnum:]-]+`)
 515var re_qtlinks = regexp.MustCompile(`>https://[^\s<]+<`)
 516
 517func qutify(user *WhatAbout, content string) string {
 518	// well this is gross
 519	malcontent := strings.ReplaceAll(content, `</span><span class="ellipsis">`, "")
 520	malcontent = strings.ReplaceAll(malcontent, `</span><span class="invisible">`, "")
 521	mlinks := re_qtlinks.FindAllString(malcontent, -1)
 522	for _, m := range mlinks {
 523		m = m[1 : len(m)-1]
 524		dlog.Printf("consider qt: %s", m)
 525		if re_mast0link.MatchString(m) ||
 526			re_masto1ink.MatchString(m) ||
 527			re_misslink.MatchString(m) ||
 528			re_honklink.MatchString(m) ||
 529			re_romalink.MatchString(m) {
 530			j, err := GetJunk(user.ID, m)
 531			dlog.Printf("fetched %s: %s", m, err)
 532			if err == nil {
 533				q, ok := j.GetString("content")
 534				if ok {
 535					content = fmt.Sprintf("%s<blockquote>%s</blockquote>", content, q)
 536				}
 537			}
 538		}
 539	}
 540	return content
 541}
 542
 543func xonksaver(user *WhatAbout, item junk.Junk, origin string) *Honk {
 544	depth := 0
 545	maxdepth := 10
 546	currenttid := ""
 547	goingup := 0
 548	var xonkxonkfn func(item junk.Junk, origin string, isUpdate bool) *Honk
 549
 550	saveonemore := func(xid string) {
 551		dlog.Printf("getting onemore: %s", xid)
 552		if depth >= maxdepth {
 553			ilog.Printf("in too deep")
 554			return
 555		}
 556		obj, err := GetJunkHardMode(user.ID, xid)
 557		if err != nil {
 558			ilog.Printf("error getting onemore: %s: %s", xid, err)
 559			return
 560		}
 561		depth++
 562		xonkxonkfn(obj, originate(xid), false)
 563		depth--
 564	}
 565
 566	xonkxonkfn = func(item junk.Junk, origin string, isUpdate bool) *Honk {
 567		id, _ := item.GetString("id")
 568		what := firstofmany(item, "type")
 569		dt, ok := item.GetString("published")
 570		if !ok {
 571			dt = time.Now().Format(time.RFC3339)
 572		}
 573
 574		var err error
 575		var xid, rid, url, convoy string
 576		var replies []string
 577		var obj junk.Junk
 578		waspage := false
 579		switch what {
 580		case "Delete":
 581			obj, ok = item.GetMap("object")
 582			if ok {
 583				xid, _ = obj.GetString("id")
 584			} else {
 585				xid, _ = item.GetString("object")
 586			}
 587			if xid == "" {
 588				return nil
 589			}
 590			if originate(xid) != origin {
 591				ilog.Printf("forged delete: %s", xid)
 592				return nil
 593			}
 594			ilog.Printf("eradicating %s", xid)
 595			eradicatexonk(user.ID, xid)
 596			return nil
 597		case "Remove":
 598			xid, _ = item.GetString("object")
 599			targ, _ := obj.GetString("target")
 600			ilog.Printf("remove %s from %s", obj, targ)
 601			return nil
 602		case "Tombstone":
 603			xid, _ = item.GetString("id")
 604			if xid == "" {
 605				return nil
 606			}
 607			if originate(xid) != origin {
 608				ilog.Printf("forged delete: %s", xid)
 609				return nil
 610			}
 611			ilog.Printf("eradicating %s", xid)
 612			eradicatexonk(user.ID, xid)
 613			return nil
 614		case "Announce":
 615			obj, ok = item.GetMap("object")
 616			if ok {
 617				xid, _ = obj.GetString("id")
 618			} else {
 619				xid, _ = item.GetString("object")
 620			}
 621			if !needbonkid(user, xid) {
 622				return nil
 623			}
 624			dlog.Printf("getting bonk: %s", xid)
 625			obj, err = GetJunkHardMode(user.ID, xid)
 626			if err != nil {
 627				ilog.Printf("error getting bonk: %s: %s", xid, err)
 628			}
 629			origin = originate(xid)
 630			what = "bonk"
 631		case "Update":
 632			isUpdate = true
 633			fallthrough
 634		case "Create":
 635			obj, ok = item.GetMap("object")
 636			if !ok {
 637				xid, _ = item.GetString("object")
 638				dlog.Printf("getting created honk: %s", xid)
 639				if originate(xid) != origin {
 640					ilog.Printf("out of bounds %s not from %s", xid, origin)
 641					return nil
 642				}
 643				obj, err = GetJunkHardMode(user.ID, xid)
 644				if err != nil {
 645					ilog.Printf("error getting creation: %s", err)
 646				}
 647			}
 648			if obj == nil {
 649				ilog.Printf("no object for creation %s", id)
 650				return nil
 651			}
 652			return xonkxonkfn(obj, origin, isUpdate)
 653		case "Read":
 654			xid, ok = item.GetString("object")
 655			if ok {
 656				if !needxonkid(user, xid) {
 657					dlog.Printf("don't need read obj: %s", xid)
 658					return nil
 659				}
 660				obj, err = GetJunkHardMode(user.ID, xid)
 661				if err != nil {
 662					ilog.Printf("error getting read: %s", err)
 663					return nil
 664				}
 665				return xonkxonkfn(obj, originate(xid), false)
 666			}
 667			return nil
 668		case "Add":
 669			xid, ok = item.GetString("object")
 670			if ok {
 671				// check target...
 672				if !needxonkid(user, xid) {
 673					dlog.Printf("don't need added obj: %s", xid)
 674					return nil
 675				}
 676				obj, err = GetJunkHardMode(user.ID, xid)
 677				if err != nil {
 678					ilog.Printf("error getting add: %s", err)
 679					return nil
 680				}
 681				return xonkxonkfn(obj, originate(xid), false)
 682			}
 683			return nil
 684		case "Move":
 685			obj = item
 686			what = "move"
 687		case "Page":
 688			waspage = true
 689			fallthrough
 690		case "GuessWord": // dealt with below
 691			fallthrough
 692		case "Audio":
 693			fallthrough
 694		case "Image":
 695			fallthrough
 696		case "Video":
 697			fallthrough
 698		case "Question":
 699			fallthrough
 700		case "Note":
 701			fallthrough
 702		case "Article":
 703			obj = item
 704			what = "honk"
 705		case "Event":
 706			obj = item
 707			what = "event"
 708		case "ChatMessage":
 709			obj = item
 710			what = "chonk"
 711		default:
 712			ilog.Printf("unknown activity: %s", what)
 713			dumpactivity(item)
 714			return nil
 715		}
 716
 717		if obj != nil {
 718			xid, _ = obj.GetString("id")
 719		}
 720
 721		if xid == "" {
 722			ilog.Printf("don't know what xid is")
 723			item.Write(ilog.Writer())
 724			return nil
 725		}
 726		if originate(xid) != origin {
 727			if !develMode && origin != "" {
 728				ilog.Printf("original sin: %s not from %s", xid, origin)
 729				item.Write(ilog.Writer())
 730				return nil
 731			}
 732		}
 733
 734		var xonk Honk
 735		// early init
 736		xonk.XID = xid
 737		xonk.UserID = user.ID
 738		xonk.Honker, _ = item.GetString("actor")
 739		if xonk.Honker == "" {
 740			xonk.Honker, _ = item.GetString("attributedTo")
 741		}
 742		if obj != nil {
 743			if xonk.Honker == "" {
 744				xonk.Honker = extractattrto(obj)
 745			}
 746			xonk.Oonker = extractattrto(obj)
 747			if xonk.Oonker == xonk.Honker {
 748				xonk.Oonker = ""
 749			}
 750			xonk.Audience = newphone(nil, obj)
 751		}
 752		xonk.Audience = append(xonk.Audience, xonk.Honker)
 753		xonk.Audience = oneofakind(xonk.Audience)
 754		xonk.Public = loudandproud(xonk.Audience)
 755
 756		var mentions []Mention
 757		if obj != nil {
 758			ot, _ := obj.GetString("type")
 759			url, _ = obj.GetString("url")
 760			if dt2, ok := obj.GetString("published"); ok {
 761				dt = dt2
 762			}
 763			content, _ := obj.GetString("content")
 764			if !strings.HasPrefix(content, "<p>") {
 765				content = "<p>" + content
 766			}
 767			precis, _ := obj.GetString("summary")
 768			if name, ok := obj.GetString("name"); ok {
 769				if precis != "" {
 770					content = precis + "<p>" + content
 771				}
 772				precis = html.EscapeString(name)
 773			}
 774			if sens, _ := obj["sensitive"].(bool); sens && precis == "" {
 775				precis = "unspecified horror"
 776			}
 777			if waspage {
 778				content += fmt.Sprintf(`<p><a href="%s">%s</a>`, url, url)
 779				url = xid
 780			}
 781			if user.Options.InlineQuotes {
 782				content = qutify(user, content)
 783			}
 784			rid, ok = obj.GetString("inReplyTo")
 785			if !ok {
 786				if robj, ok := obj.GetMap("inReplyTo"); ok {
 787					rid, _ = robj.GetString("id")
 788				}
 789			}
 790			convoy, _ = obj.GetString("context")
 791			if convoy == "" {
 792				convoy, _ = obj.GetString("conversation")
 793			}
 794			if ot == "Question" {
 795				if what == "honk" {
 796					what = "qonk"
 797				}
 798				content += "<ul>"
 799				ans, _ := obj.GetArray("oneOf")
 800				for _, ai := range ans {
 801					a, ok := ai.(junk.Junk)
 802					if !ok {
 803						continue
 804					}
 805					as, _ := a.GetString("name")
 806					content += "<li>" + as
 807				}
 808				ans, _ = obj.GetArray("anyOf")
 809				for _, ai := range ans {
 810					a, ok := ai.(junk.Junk)
 811					if !ok {
 812						continue
 813					}
 814					as, _ := a.GetString("name")
 815					content += "<li>" + as
 816				}
 817				content += "</ul>"
 818			}
 819			if ot == "Move" {
 820				targ, _ := obj.GetString("target")
 821				content += string(templates.Sprintf(`<p>Moved to <a href="%s">%s</a>`, targ, targ))
 822			}
 823			if ot == "GuessWord" {
 824				what = "wonk"
 825				content, _ = obj.GetString("content")
 826				xonk.Wonkles, _ = obj.GetString("wordlist")
 827				go savewonkles(xonk.Wonkles)
 828			}
 829			if what == "honk" && rid != "" {
 830				what = "tonk"
 831			}
 832			if len(content) > 90001 {
 833				ilog.Printf("content too long. truncating")
 834				content = content[:90001]
 835			}
 836
 837			xonk.Noise = content
 838			xonk.Precis = precis
 839			if rejectxonk(&xonk) {
 840				dlog.Printf("fast reject: %s", xid)
 841				return nil
 842			}
 843
 844			numatts := 0
 845			procatt := func(att junk.Junk) {
 846				at, _ := att.GetString("type")
 847				mt, _ := att.GetString("mediaType")
 848				u, ok := att.GetString("url")
 849				if !ok {
 850					if ua, ok := att.GetArray("url"); ok && len(ua) > 0 {
 851						u, ok = ua[0].(string)
 852						if !ok {
 853							if uu, ok := ua[0].(junk.Junk); ok {
 854								u, _ = uu.GetString("href")
 855								if mt == "" {
 856									mt, _ = uu.GetString("mediaType")
 857								}
 858							}
 859						}
 860					} else if uu, ok := att.GetMap("url"); ok {
 861						u, _ = uu.GetString("href")
 862						if mt == "" {
 863							mt, _ = uu.GetString("mediaType")
 864						}
 865					}
 866				}
 867				name, _ := att.GetString("name")
 868				desc, _ := att.GetString("summary")
 869				desc = html.UnescapeString(desc)
 870				if desc == "" {
 871					desc = name
 872				}
 873				localize := false
 874				if numatts > 4 {
 875					ilog.Printf("excessive attachment: %s", at)
 876				} else if at == "Document" || at == "Image" {
 877					mt = strings.ToLower(mt)
 878					dlog.Printf("attachment: %s %s", mt, u)
 879					if mt == "text/plain" || mt == "application/pdf" ||
 880						strings.HasPrefix(mt, "image") {
 881						localize = true
 882					}
 883				} else {
 884					ilog.Printf("unknown attachment: %s", at)
 885				}
 886				if skipMedia(&xonk) {
 887					localize = false
 888				}
 889				donk := savedonk(u, name, desc, mt, localize)
 890				if donk != nil {
 891					xonk.Donks = append(xonk.Donks, donk)
 892				}
 893				numatts++
 894			}
 895			atts, _ := obj.GetArray("attachment")
 896			for _, atti := range atts {
 897				att, ok := atti.(junk.Junk)
 898				if !ok {
 899					ilog.Printf("attachment that wasn't map?")
 900					continue
 901				}
 902				procatt(att)
 903			}
 904			if att, ok := obj.GetMap("attachment"); ok {
 905				procatt(att)
 906			}
 907			tags, _ := obj.GetArray("tag")
 908			for _, tagi := range tags {
 909				tag, ok := tagi.(junk.Junk)
 910				if !ok {
 911					continue
 912				}
 913				tt, _ := tag.GetString("type")
 914				name, _ := tag.GetString("name")
 915				desc, _ := tag.GetString("summary")
 916				desc = html.UnescapeString(desc)
 917				if desc == "" {
 918					desc = name
 919				}
 920				if tt == "Emoji" {
 921					icon, _ := tag.GetMap("icon")
 922					mt, _ := icon.GetString("mediaType")
 923					if mt == "" {
 924						mt = "image/png"
 925					}
 926					u, _ := icon.GetString("url")
 927					donk := savedonk(u, name, desc, mt, true)
 928					if donk != nil {
 929						xonk.Donks = append(xonk.Donks, donk)
 930					}
 931				}
 932				if tt == "Hashtag" {
 933					if name == "" || name == "#" {
 934						// skip it
 935					} else {
 936						if name[0] != '#' {
 937							name = "#" + name
 938						}
 939						xonk.Onts = append(xonk.Onts, name)
 940					}
 941				}
 942				if tt == "Place" {
 943					p := new(Place)
 944					p.Name = name
 945					p.Latitude, _ = tag.GetNumber("latitude")
 946					p.Longitude, _ = tag.GetNumber("longitude")
 947					p.Url, _ = tag.GetString("url")
 948					xonk.Place = p
 949				}
 950				if tt == "Mention" {
 951					var m Mention
 952					m.Who, _ = tag.GetString("name")
 953					m.Where, _ = tag.GetString("href")
 954					mentions = append(mentions, m)
 955				}
 956			}
 957			if starttime, ok := obj.GetString("startTime"); ok {
 958				if start, err := time.Parse(time.RFC3339, starttime); err == nil {
 959					t := new(Time)
 960					t.StartTime = start
 961					endtime, _ := obj.GetString("endTime")
 962					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
 963					dura, _ := obj.GetString("duration")
 964					if strings.HasPrefix(dura, "PT") {
 965						dura = strings.ToLower(dura[2:])
 966						d, _ := time.ParseDuration(dura)
 967						t.Duration = Duration(d)
 968					}
 969					xonk.Time = t
 970				}
 971			}
 972			if loca, ok := obj.GetMap("location"); ok {
 973				if tt, _ := loca.GetString("type"); tt == "Place" {
 974					p := new(Place)
 975					p.Name, _ = loca.GetString("name")
 976					p.Latitude, _ = loca.GetNumber("latitude")
 977					p.Longitude, _ = loca.GetNumber("longitude")
 978					p.Url, _ = loca.GetString("url")
 979					xonk.Place = p
 980				}
 981			}
 982
 983			xonk.Onts = oneofakind(xonk.Onts)
 984			replyobj, ok := obj.GetMap("replies")
 985			if ok {
 986				items, ok := replyobj.GetArray("items")
 987				if !ok {
 988					first, ok := replyobj.GetMap("first")
 989					if ok {
 990						items, _ = first.GetArray("items")
 991					}
 992				}
 993				for _, repl := range items {
 994					s, ok := repl.(string)
 995					if ok {
 996						replies = append(replies, s)
 997					}
 998				}
 999			}
1000
1001		}
1002
1003		if currenttid == "" {
1004			currenttid = convoy
1005		}
1006
1007		// init xonk
1008		xonk.What = what
1009		xonk.RID = rid
1010		xonk.Date, _ = time.Parse(time.RFC3339, dt)
1011		xonk.URL = url
1012		xonk.Format = "html"
1013		xonk.Convoy = convoy
1014		xonk.Mentions = mentions
1015		for _, m := range mentions {
1016			if m.Where == user.URL {
1017				xonk.Whofore = 1
1018			}
1019		}
1020		imaginate(&xonk)
1021
1022		if what == "chonk" {
1023			ch := Chonk{
1024				UserID: xonk.UserID,
1025				XID:    xid,
1026				Who:    xonk.Honker,
1027				Target: xonk.Honker,
1028				Date:   xonk.Date,
1029				Noise:  xonk.Noise,
1030				Format: xonk.Format,
1031				Donks:  xonk.Donks,
1032			}
1033			savechonk(&ch)
1034			return nil
1035		}
1036
1037		if isUpdate {
1038			dlog.Printf("something has changed! %s", xonk.XID)
1039			prev := getxonk(user.ID, xonk.XID)
1040			if prev == nil {
1041				ilog.Printf("didn't find old version for update: %s", xonk.XID)
1042				isUpdate = false
1043			} else {
1044				xonk.ID = prev.ID
1045				updatehonk(&xonk)
1046			}
1047		}
1048		if !isUpdate && needxonk(user, &xonk) {
1049			if rid != "" && xonk.Public {
1050				if needxonkid(user, rid) {
1051					goingup++
1052					saveonemore(rid)
1053					goingup--
1054				}
1055				if convoy == "" {
1056					xx := getxonk(user.ID, rid)
1057					if xx != nil {
1058						convoy = xx.Convoy
1059					}
1060				}
1061			}
1062			if convoy == "" {
1063				convoy = currenttid
1064			}
1065			if convoy == "" {
1066				convoy = "data:,missing-" + xfiltrate()
1067				currenttid = convoy
1068			}
1069			xonk.Convoy = convoy
1070			savexonk(&xonk)
1071		}
1072		if goingup == 0 {
1073			for _, replid := range replies {
1074				if needxonkid(user, replid) {
1075					dlog.Printf("missing a reply: %s", replid)
1076					saveonemore(replid)
1077				}
1078			}
1079		}
1080		return &xonk
1081	}
1082
1083	return xonkxonkfn(item, origin, false)
1084}
1085
1086func dumpactivity(item junk.Junk) {
1087	fd, err := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
1088	if err != nil {
1089		elog.Printf("error opening inbox! %s", err)
1090		return
1091	}
1092	defer fd.Close()
1093	item.Write(fd)
1094	io.WriteString(fd, "\n")
1095}
1096
1097func rubadubdub(user *WhatAbout, req junk.Junk) {
1098	actor, _ := req.GetString("actor")
1099	j := junk.New()
1100	j["@context"] = itiswhatitis
1101	j["id"] = user.URL + "/dub/" + xfiltrate()
1102	j["type"] = "Accept"
1103	j["actor"] = user.URL
1104	j["to"] = actor
1105	j["published"] = time.Now().UTC().Format(time.RFC3339)
1106	j["object"] = req
1107
1108	deliverate(0, user.ID, actor, j.ToBytes(), true)
1109}
1110
1111func itakeitallback(user *WhatAbout, xid string, owner string, folxid string) {
1112	j := junk.New()
1113	j["@context"] = itiswhatitis
1114	j["id"] = user.URL + "/unsub/" + folxid
1115	j["type"] = "Undo"
1116	j["actor"] = user.URL
1117	j["to"] = owner
1118	f := junk.New()
1119	f["id"] = user.URL + "/sub/" + folxid
1120	f["type"] = "Follow"
1121	f["actor"] = user.URL
1122	f["to"] = owner
1123	f["object"] = xid
1124	j["object"] = f
1125	j["published"] = time.Now().UTC().Format(time.RFC3339)
1126
1127	deliverate(0, user.ID, owner, j.ToBytes(), true)
1128}
1129
1130func subsub(user *WhatAbout, xid string, owner string, folxid string) {
1131	if xid == "" {
1132		ilog.Printf("can't subscribe to empty")
1133		return
1134	}
1135	j := junk.New()
1136	j["@context"] = itiswhatitis
1137	j["id"] = user.URL + "/sub/" + folxid
1138	j["type"] = "Follow"
1139	j["actor"] = user.URL
1140	j["to"] = owner
1141	j["object"] = xid
1142	j["published"] = time.Now().UTC().Format(time.RFC3339)
1143
1144	deliverate(0, user.ID, owner, j.ToBytes(), true)
1145}
1146
1147func activatedonks(donks []*Donk) []junk.Junk {
1148	var atts []junk.Junk
1149	for _, d := range donks {
1150		if re_emus.MatchString(d.Name) {
1151			continue
1152		}
1153		jd := junk.New()
1154		jd["mediaType"] = d.Media
1155		jd["name"] = d.Name
1156		jd["summary"] = html.EscapeString(d.Desc)
1157		jd["type"] = "Document"
1158		jd["url"] = d.URL
1159		atts = append(atts, jd)
1160	}
1161	return atts
1162}
1163
1164// returns activity, object
1165func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
1166	dt := h.Date.Format(time.RFC3339)
1167	var jo junk.Junk
1168	j := junk.New()
1169	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
1170	j["actor"] = user.URL
1171	j["published"] = dt
1172	j["to"] = h.Audience[0]
1173	if len(h.Audience) > 1 {
1174		j["cc"] = h.Audience[1:]
1175	}
1176
1177	switch h.What {
1178	case "update":
1179		fallthrough
1180	case "tonk":
1181		fallthrough
1182	case "event":
1183		fallthrough
1184	case "wonk":
1185		fallthrough
1186	case "honk":
1187		j["type"] = "Create"
1188		jo = junk.New()
1189		jo["id"] = h.XID
1190		jo["type"] = "Note"
1191		if h.What == "event" {
1192			jo["type"] = "Event"
1193		} else if h.What == "wonk" {
1194			jo["type"] = "GuessWord"
1195		}
1196		if h.What == "update" {
1197			j["type"] = "Update"
1198			jo["updated"] = dt
1199		}
1200		jo["published"] = dt
1201		jo["url"] = h.XID
1202		jo["attributedTo"] = user.URL
1203		if h.RID != "" {
1204			jo["inReplyTo"] = h.RID
1205		}
1206		if h.Convoy != "" {
1207			jo["context"] = h.Convoy
1208			jo["conversation"] = h.Convoy
1209		}
1210		jo["to"] = h.Audience[0]
1211		if len(h.Audience) > 1 {
1212			jo["cc"] = h.Audience[1:]
1213		}
1214		if !h.Public {
1215			jo["directMessage"] = true
1216		}
1217		translate(h)
1218		redoimages(h)
1219		if h.Precis != "" {
1220			jo["sensitive"] = true
1221		}
1222
1223		var replies []string
1224		for _, reply := range h.Replies {
1225			replies = append(replies, reply.XID)
1226		}
1227		if len(replies) > 0 {
1228			jr := junk.New()
1229			jr["type"] = "Collection"
1230			jr["totalItems"] = len(replies)
1231			jr["items"] = replies
1232			jo["replies"] = jr
1233		}
1234
1235		var tags []junk.Junk
1236		for _, m := range h.Mentions {
1237			t := junk.New()
1238			t["type"] = "Mention"
1239			t["name"] = m.Who
1240			t["href"] = m.Where
1241			tags = append(tags, t)
1242		}
1243		for _, o := range h.Onts {
1244			t := junk.New()
1245			t["type"] = "Hashtag"
1246			o = strings.ToLower(o)
1247			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1248			t["name"] = o
1249			tags = append(tags, t)
1250		}
1251		for _, e := range herdofemus(h.Noise) {
1252			t := junk.New()
1253			t["id"] = e.ID
1254			t["type"] = "Emoji"
1255			t["name"] = e.Name
1256			i := junk.New()
1257			i["type"] = "Image"
1258			i["mediaType"] = e.Type
1259			i["url"] = e.ID
1260			t["icon"] = i
1261			tags = append(tags, t)
1262		}
1263		for _, e := range fixupflags(h) {
1264			t := junk.New()
1265			t["id"] = e.ID
1266			t["type"] = "Emoji"
1267			t["name"] = e.Name
1268			i := junk.New()
1269			i["type"] = "Image"
1270			i["mediaType"] = "image/png"
1271			i["url"] = e.ID
1272			t["icon"] = i
1273			tags = append(tags, t)
1274		}
1275		if len(tags) > 0 {
1276			jo["tag"] = tags
1277		}
1278		if p := h.Place; p != nil {
1279			t := junk.New()
1280			t["type"] = "Place"
1281			if p.Name != "" {
1282				t["name"] = p.Name
1283			}
1284			if p.Latitude != 0 {
1285				t["latitude"] = p.Latitude
1286			}
1287			if p.Longitude != 0 {
1288				t["longitude"] = p.Longitude
1289			}
1290			if p.Url != "" {
1291				t["url"] = p.Url
1292			}
1293			jo["location"] = t
1294		}
1295		if t := h.Time; t != nil {
1296			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1297			if t.Duration != 0 {
1298				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1299			}
1300		}
1301		if w := h.Wonkles; w != "" {
1302			jo["wordlist"] = w
1303		}
1304		atts := activatedonks(h.Donks)
1305		if len(atts) > 0 {
1306			jo["attachment"] = atts
1307		}
1308		jo["summary"] = html.EscapeString(h.Precis)
1309		jo["content"] = h.Noise
1310		j["object"] = jo
1311	case "bonk":
1312		j["type"] = "Announce"
1313		if h.Convoy != "" {
1314			j["context"] = h.Convoy
1315		}
1316		j["object"] = h.XID
1317	case "unbonk":
1318		b := junk.New()
1319		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1320		b["type"] = "Announce"
1321		b["actor"] = user.URL
1322		if h.Convoy != "" {
1323			b["context"] = h.Convoy
1324		}
1325		b["object"] = h.XID
1326		j["type"] = "Undo"
1327		j["object"] = b
1328	case "zonk":
1329		j["type"] = "Delete"
1330		j["object"] = h.XID
1331	case "ack":
1332		j["type"] = "Read"
1333		j["object"] = h.XID
1334		if h.Convoy != "" {
1335			j["context"] = h.Convoy
1336		}
1337	case "react":
1338		j["type"] = "EmojiReact"
1339		j["object"] = h.XID
1340		if h.Convoy != "" {
1341			j["context"] = h.Convoy
1342		}
1343		j["content"] = h.Noise
1344	case "deack":
1345		b := junk.New()
1346		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1347		b["type"] = "Read"
1348		b["actor"] = user.URL
1349		b["object"] = h.XID
1350		if h.Convoy != "" {
1351			b["context"] = h.Convoy
1352		}
1353		j["type"] = "Undo"
1354		j["object"] = b
1355	}
1356
1357	return j, jo
1358}
1359
1360var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1361	row := stmtAnyXonk.QueryRow(xid)
1362	honk := scanhonk(row)
1363	if honk == nil || !honk.Public {
1364		return nil, true
1365	}
1366	user, _ := butwhatabout(honk.Username)
1367	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1368	reversehonks(rawhonks)
1369	for _, h := range rawhonks {
1370		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1371			honk.Replies = append(honk.Replies, h)
1372		}
1373	}
1374	donksforhonks([]*Honk{honk})
1375	_, j := jonkjonk(user, honk)
1376	if j == nil {
1377		elog.Fatalf("what just happened? %v", honk)
1378	}
1379	j["@context"] = itiswhatitis
1380
1381	return j.ToBytes(), true
1382}, Limit: 128})
1383
1384func gimmejonk(xid string) ([]byte, bool) {
1385	var j []byte
1386	ok := oldjonks.Get(xid, &j)
1387	return j, ok
1388}
1389
1390func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1391	rcpts := make(map[string]bool)
1392	for _, a := range addresses {
1393		if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1394			continue
1395		}
1396		if a[0] == '%' {
1397			rcpts[a] = true
1398			continue
1399		}
1400		var box *Box
1401		ok := boxofboxes.Get(a, &box)
1402		if ok && useshared && box.Shared != "" {
1403			rcpts["%"+box.Shared] = true
1404		} else {
1405			rcpts[a] = true
1406		}
1407	}
1408	return rcpts
1409}
1410
1411func chonkifymsg(user *WhatAbout, ch *Chonk) []byte {
1412	dt := ch.Date.Format(time.RFC3339)
1413	aud := []string{ch.Target}
1414
1415	jo := junk.New()
1416	jo["id"] = ch.XID
1417	jo["type"] = "ChatMessage"
1418	jo["published"] = dt
1419	jo["attributedTo"] = user.URL
1420	jo["to"] = aud
1421	jo["content"] = ch.HTML
1422	atts := activatedonks(ch.Donks)
1423	if len(atts) > 0 {
1424		jo["attachment"] = atts
1425	}
1426	var tags []junk.Junk
1427	for _, e := range herdofemus(ch.Noise) {
1428		t := junk.New()
1429		t["id"] = e.ID
1430		t["type"] = "Emoji"
1431		t["name"] = e.Name
1432		i := junk.New()
1433		i["type"] = "Image"
1434		i["mediaType"] = e.Type
1435		i["url"] = e.ID
1436		t["icon"] = i
1437		tags = append(tags, t)
1438	}
1439	if len(tags) > 0 {
1440		jo["tag"] = tags
1441	}
1442
1443	j := junk.New()
1444	j["@context"] = itiswhatitis
1445	j["id"] = user.URL + "/" + "honk" + "/" + shortxid(ch.XID)
1446	j["type"] = "Create"
1447	j["actor"] = user.URL
1448	j["published"] = dt
1449	j["to"] = aud
1450	j["object"] = jo
1451
1452	return j.ToBytes()
1453}
1454
1455func sendchonk(user *WhatAbout, ch *Chonk) {
1456	msg := chonkifymsg(user, ch)
1457
1458	rcpts := make(map[string]bool)
1459	rcpts[ch.Target] = true
1460	for a := range rcpts {
1461		go deliverate(0, user.ID, a, msg, true)
1462	}
1463}
1464
1465func honkworldwide(user *WhatAbout, honk *Honk) {
1466	jonk, _ := jonkjonk(user, honk)
1467	jonk["@context"] = itiswhatitis
1468	msg := jonk.ToBytes()
1469
1470	rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1471
1472	if honk.Public {
1473		for _, h := range getdubs(user.ID) {
1474			if h.XID == user.URL {
1475				continue
1476			}
1477			var box *Box
1478			ok := boxofboxes.Get(h.XID, &box)
1479			if ok && box.Shared != "" {
1480				rcpts["%"+box.Shared] = true
1481			} else {
1482				rcpts[h.XID] = true
1483			}
1484		}
1485		for _, f := range getbacktracks(honk.XID) {
1486			if f[0] == '%' {
1487				rcpts[f] = true
1488			} else {
1489				var box *Box
1490				ok := boxofboxes.Get(f, &box)
1491				if ok && box.Shared != "" {
1492					rcpts["%"+box.Shared] = true
1493				} else {
1494					rcpts[f] = true
1495				}
1496			}
1497		}
1498	}
1499	for a := range rcpts {
1500		go deliverate(0, user.ID, a, msg, doesitmatter(honk.What))
1501	}
1502	if honk.Public && len(honk.Onts) > 0 {
1503		collectiveaction(honk)
1504	}
1505}
1506
1507func doesitmatter(what string) bool {
1508	switch what {
1509	case "ack":
1510		return false
1511	case "react":
1512		return false
1513	case "deack":
1514		return false
1515	}
1516	return true
1517}
1518
1519func collectiveaction(honk *Honk) {
1520	user := getserveruser()
1521	for _, ont := range honk.Onts {
1522		dubs := getnameddubs(readyLuserOne, ont)
1523		if len(dubs) == 0 {
1524			continue
1525		}
1526		j := junk.New()
1527		j["@context"] = itiswhatitis
1528		j["type"] = "Add"
1529		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1530		j["actor"] = user.URL
1531		j["object"] = honk.XID
1532		j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1533		rcpts := make(map[string]bool)
1534		for _, dub := range dubs {
1535			var box *Box
1536			ok := boxofboxes.Get(dub.XID, &box)
1537			if ok && box.Shared != "" {
1538				rcpts["%"+box.Shared] = true
1539			} else {
1540				rcpts[dub.XID] = true
1541			}
1542		}
1543		msg := j.ToBytes()
1544		for a := range rcpts {
1545			go deliverate(0, user.ID, a, msg, false)
1546		}
1547	}
1548}
1549
1550func junkuser(user *WhatAbout) junk.Junk {
1551	j := junk.New()
1552	j["@context"] = itiswhatitis
1553	j["id"] = user.URL
1554	j["inbox"] = user.URL + "/inbox"
1555	j["outbox"] = user.URL + "/outbox"
1556	j["name"] = user.Display
1557	j["preferredUsername"] = user.Name
1558	j["summary"] = user.HTAbout
1559	var tags []junk.Junk
1560	for _, o := range user.Onts {
1561		t := junk.New()
1562		t["type"] = "Hashtag"
1563		o = strings.ToLower(o)
1564		t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1565		t["name"] = o
1566		tags = append(tags, t)
1567	}
1568	if len(tags) > 0 {
1569		j["tag"] = tags
1570	}
1571
1572	if user.ID > 0 {
1573		j["type"] = "Person"
1574		j["url"] = user.URL
1575		j["followers"] = user.URL + "/followers"
1576		j["following"] = user.URL + "/following"
1577		a := junk.New()
1578		a["type"] = "Image"
1579		a["mediaType"] = "image/png"
1580		if ava := user.Options.Avatar; ava != "" {
1581			a["url"] = ava
1582		} else {
1583			u := fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1584			a["url"] = u
1585		}
1586		j["icon"] = a
1587		if ban := user.Options.Banner; ban != "" {
1588			a := junk.New()
1589			a["type"] = "Image"
1590			a["mediaType"] = "image/jpg"
1591			a["url"] = ban
1592			j["image"] = a
1593		}
1594	} else {
1595		j["type"] = "Service"
1596	}
1597	k := junk.New()
1598	k["id"] = user.URL + "#key"
1599	k["owner"] = user.URL
1600	k["publicKeyPem"] = user.Key
1601	j["publicKey"] = k
1602
1603	return j
1604}
1605
1606var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1607	user, err := butwhatabout(name)
1608	if err != nil {
1609		return nil, false
1610	}
1611	var buf bytes.Buffer
1612	j := junkuser(user)
1613	j.Write(&buf)
1614	return buf.Bytes(), true
1615}, Duration: 1 * time.Minute})
1616
1617func asjonker(name string) ([]byte, bool) {
1618	var j []byte
1619	ok := oldjonkers.Get(name, &j)
1620	return j, ok
1621}
1622
1623var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1624	m := strings.Split(name, "@")
1625	if len(m) != 2 {
1626		dlog.Printf("bad fish name: %s", name)
1627		return "", true
1628	}
1629	var href string
1630	row := stmtGetXonker.QueryRow(name, "fishname")
1631	err := row.Scan(&href)
1632	if err == nil {
1633		return href, true
1634	}
1635	dlog.Printf("fishing for %s", name)
1636	j, err := GetJunkFast(readyLuserOne, fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1637	if err != nil {
1638		ilog.Printf("failed to go fish %s: %s", name, err)
1639		return "", true
1640	}
1641	links, _ := j.GetArray("links")
1642	for _, li := range links {
1643		l, ok := li.(junk.Junk)
1644		if !ok {
1645			continue
1646		}
1647		href, _ := l.GetString("href")
1648		rel, _ := l.GetString("rel")
1649		t, _ := l.GetString("type")
1650		if rel == "self" && friendorfoe(t) {
1651			when := time.Now().UTC().Format(dbtimeformat)
1652			_, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1653			if err != nil {
1654				elog.Printf("error saving fishname: %s", err)
1655			}
1656			return href, true
1657		}
1658	}
1659	return href, true
1660}, Duration: 1 * time.Minute})
1661
1662func gofish(name string) string {
1663	if name[0] == '@' {
1664		name = name[1:]
1665	}
1666	var href string
1667	handfull.Get(name, &href)
1668	return href
1669}
1670
1671func investigate(name string) (*SomeThing, error) {
1672	if name == "" {
1673		return nil, fmt.Errorf("no name")
1674	}
1675	if name[0] == '@' {
1676		name = gofish(name)
1677	}
1678	if name == "" {
1679		return nil, fmt.Errorf("no name")
1680	}
1681	obj, err := GetJunkFast(readyLuserOne, name)
1682	if err != nil {
1683		return nil, err
1684	}
1685	allinjest(originate(name), obj)
1686	return somethingabout(obj)
1687}
1688
1689func somethingabout(obj junk.Junk) (*SomeThing, error) {
1690	info := new(SomeThing)
1691	t, _ := obj.GetString("type")
1692	switch t {
1693	case "Person":
1694		fallthrough
1695	case "Organization":
1696		fallthrough
1697	case "Application":
1698		fallthrough
1699	case "Service":
1700		info.What = SomeActor
1701	case "OrderedCollection":
1702		fallthrough
1703	case "Collection":
1704		info.What = SomeCollection
1705	default:
1706		return nil, fmt.Errorf("unknown object type")
1707	}
1708	info.XID, _ = obj.GetString("id")
1709	info.Name, _ = obj.GetString("preferredUsername")
1710	if info.Name == "" {
1711		info.Name, _ = obj.GetString("name")
1712	}
1713	info.Owner, _ = obj.GetString("attributedTo")
1714	if info.Owner == "" {
1715		info.Owner = info.XID
1716	}
1717	return info, nil
1718}
1719
1720func allinjest(origin string, obj junk.Junk) {
1721	keyobj, ok := obj.GetMap("publicKey")
1722	if ok {
1723		ingestpubkey(origin, keyobj)
1724	}
1725	ingestboxes(origin, obj)
1726	ingesthandle(origin, obj)
1727}
1728
1729func ingestpubkey(origin string, obj junk.Junk) {
1730	keyobj, ok := obj.GetMap("publicKey")
1731	if ok {
1732		obj = keyobj
1733	}
1734	keyname, ok := obj.GetString("id")
1735	var data string
1736	row := stmtGetXonker.QueryRow(keyname, "pubkey")
1737	err := row.Scan(&data)
1738	if err == nil {
1739		return
1740	}
1741	if !ok || origin != originate(keyname) {
1742		ilog.Printf("bad key origin %s <> %s", origin, keyname)
1743		return
1744	}
1745	dlog.Printf("ingesting a needed pubkey: %s", keyname)
1746	owner, ok := obj.GetString("owner")
1747	if !ok {
1748		ilog.Printf("error finding %s pubkey owner", keyname)
1749		return
1750	}
1751	data, ok = obj.GetString("publicKeyPem")
1752	if !ok {
1753		ilog.Printf("error finding %s pubkey", keyname)
1754		return
1755	}
1756	if originate(owner) != origin {
1757		ilog.Printf("bad key owner: %s <> %s", owner, origin)
1758		return
1759	}
1760	_, _, err = httpsig.DecodeKey(data)
1761	if err != nil {
1762		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
1763		return
1764	}
1765	when := time.Now().UTC().Format(dbtimeformat)
1766	_, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1767	if err != nil {
1768		elog.Printf("error saving key: %s", err)
1769	}
1770}
1771
1772func ingestboxes(origin string, obj junk.Junk) {
1773	ident, _ := obj.GetString("id")
1774	if ident == "" {
1775		return
1776	}
1777	if originate(ident) != origin {
1778		return
1779	}
1780	var info string
1781	row := stmtGetXonker.QueryRow(ident, "boxes")
1782	err := row.Scan(&info)
1783	if err == nil {
1784		return
1785	}
1786	dlog.Printf("ingesting boxes: %s", ident)
1787	inbox, _ := obj.GetString("inbox")
1788	outbox, _ := obj.GetString("outbox")
1789	sbox, _ := obj.GetString("endpoints", "sharedInbox")
1790	if inbox != "" {
1791		when := time.Now().UTC().Format(dbtimeformat)
1792		m := strings.Join([]string{inbox, outbox, sbox}, " ")
1793		_, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1794		if err != nil {
1795			elog.Printf("error saving boxes: %s", err)
1796		}
1797	}
1798}
1799
1800func ingesthandle(origin string, obj junk.Junk) {
1801	xid, _ := obj.GetString("id")
1802	if xid == "" {
1803		return
1804	}
1805	if originate(xid) != origin {
1806		return
1807	}
1808	var handle string
1809	row := stmtGetXonker.QueryRow(xid, "handle")
1810	err := row.Scan(&handle)
1811	if err == nil {
1812		return
1813	}
1814	handle, _ = obj.GetString("preferredUsername")
1815	if handle != "" {
1816		when := time.Now().UTC().Format(dbtimeformat)
1817		_, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1818		if err != nil {
1819			elog.Printf("error saving handle: %s", err)
1820		}
1821	}
1822}
1823
1824func updateMe(username string) {
1825	var user *WhatAbout
1826	somenamedusers.Get(username, &user)
1827	dt := time.Now().UTC().Format(time.RFC3339)
1828	j := junk.New()
1829	j["@context"] = itiswhatitis
1830	j["id"] = fmt.Sprintf("%s/upme/%s/%d", user.URL, user.Name, time.Now().Unix())
1831	j["actor"] = user.URL
1832	j["published"] = dt
1833	j["to"] = thewholeworld
1834	j["type"] = "Update"
1835	j["object"] = junkuser(user)
1836
1837	msg := j.ToBytes()
1838
1839	rcpts := make(map[string]bool)
1840	for _, f := range getdubs(user.ID) {
1841		if f.XID == user.URL {
1842			continue
1843		}
1844		var box *Box
1845		boxofboxes.Get(f.XID, &box)
1846		if box != nil && box.Shared != "" {
1847			rcpts["%"+box.Shared] = true
1848		} else {
1849			rcpts[f.XID] = true
1850		}
1851	}
1852	for a := range rcpts {
1853		go deliverate(0, user.ID, a, msg, false)
1854	}
1855}
1856
1857func followme(user *WhatAbout, who string, name string, j junk.Junk) {
1858	folxid, _ := j.GetString("id")
1859
1860	ilog.Printf("updating honker follow: %s %s", who, folxid)
1861
1862	var x string
1863	db := opendatabase()
1864	row := db.QueryRow("select xid from honkers where name = ? and xid = ? and userid = ? and flavor in ('dub', 'undub')", name, who, user.ID)
1865	err := row.Scan(&x)
1866	if err != sql.ErrNoRows {
1867		ilog.Printf("duplicate follow request: %s", who)
1868		_, err = stmtUpdateFlavor.Exec("dub", folxid, user.ID, name, who, "undub")
1869		if err != nil {
1870			elog.Printf("error updating honker: %s", err)
1871		}
1872	} else {
1873		stmtSaveDub.Exec(user.ID, name, who, "dub", folxid)
1874	}
1875	go rubadubdub(user, j)
1876}
1877
1878func unfollowme(user *WhatAbout, who string, name string, j junk.Junk) {
1879	var folxid string
1880	if who == "" {
1881		folxid, _ = j.GetString("object")
1882
1883		db := opendatabase()
1884		row := db.QueryRow("select xid, name from honkers where userid = ? and folxid = ? and flavor in ('dub', 'undub')", user.ID, folxid)
1885		err := row.Scan(&who, &name)
1886		if err != nil {
1887			if err != sql.ErrNoRows {
1888				elog.Printf("error scanning honker: %s", err)
1889			}
1890			return
1891		}
1892	}
1893
1894	ilog.Printf("updating honker undo: %s %s", who, folxid)
1895	_, err := stmtUpdateFlavor.Exec("undub", folxid, user.ID, name, who, "dub")
1896	if err != nil {
1897		elog.Printf("error updating honker: %s", err)
1898		return
1899	}
1900}
1901
1902func followyou(user *WhatAbout, honkerid int64) {
1903	var url, owner string
1904	db := opendatabase()
1905	row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1906		honkerid, user.ID)
1907	err := row.Scan(&url, &owner)
1908	if err != nil {
1909		elog.Printf("can't get honker xid: %s", err)
1910		return
1911	}
1912	folxid := xfiltrate()
1913	ilog.Printf("subscribing to %s", url)
1914	_, err = db.Exec("update honkers set flavor = ?, folxid = ? where honkerid = ?", "presub", folxid, honkerid)
1915	if err != nil {
1916		elog.Printf("error updating honker: %s", err)
1917		return
1918	}
1919	go subsub(user, url, owner, folxid)
1920
1921}
1922func unfollowyou(user *WhatAbout, honkerid int64) {
1923	db := opendatabase()
1924	row := db.QueryRow("select xid, owner, folxid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1925		honkerid, user.ID)
1926	var url, owner, folxid string
1927	err := row.Scan(&url, &owner, &folxid)
1928	if err != nil {
1929		elog.Printf("can't get honker xid: %s", err)
1930		return
1931	}
1932	ilog.Printf("unsubscribing from %s", url)
1933	_, err = db.Exec("update honkers set flavor = ? where honkerid = ?", "unsub", honkerid)
1934	if err != nil {
1935		elog.Printf("error updating honker: %s", err)
1936		return
1937	}
1938	go itakeitallback(user, url, owner, folxid)
1939}
1940
1941func followyou2(user *WhatAbout, j junk.Junk) {
1942	who, _ := j.GetString("actor")
1943
1944	ilog.Printf("updating honker accept: %s", who)
1945	db := opendatabase()
1946	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
1947		user.ID, who)
1948	var name, folxid string
1949	err := row.Scan(&name, &folxid)
1950	if err != nil {
1951		elog.Printf("can't get honker name: %s", err)
1952		return
1953	}
1954	_, err = stmtUpdateFlavor.Exec("sub", folxid, user.ID, name, who, "presub")
1955	if err != nil {
1956		elog.Printf("error updating honker: %s", err)
1957		return
1958	}
1959}
1960
1961func nofollowyou2(user *WhatAbout, j junk.Junk) {
1962	who, _ := j.GetString("actor")
1963
1964	ilog.Printf("updating honker reject: %s", who)
1965	db := opendatabase()
1966	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
1967		user.ID, who)
1968	var name, folxid string
1969	err := row.Scan(&name, &folxid)
1970	if err != nil {
1971		elog.Printf("can't get honker name: %s", err)
1972		return
1973	}
1974	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "presub")
1975	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "sub")
1976	if err != nil {
1977		elog.Printf("error updating honker: %s", err)
1978		return
1979	}
1980}