all repos — honk @ 7d1e2617a8f139ab7c225d01d673b354a34ecdda

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