all repos — honk @ 7cd26e01a909fe93055be476117fe745f3aa72db

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