all repos — honk @ 91a633c46ca0cf1e1a7629b1b5b8de2236f1322f

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