all repos — honk @ af18b76516cfa7060753899fcd909381ab75c059

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