all repos — honk @ 57efc76f2d9e84f5c8033990c314bc4ebe2bf391

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