all repos — honk @ b830c0123af40f69d945d8418f1ec9fd5af72e59

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