all repos — honk @ eccd76a3b4ce0046e5c0242b9d2a7baf59db0222

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