all repos — honk @ 018b6c68c9e2b8659008b80fed7c9b984c0f9a38

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