all repos — honk @ 4627a7cb216839a224d5b55b9f18031dbbb12599

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