all repos — honk @ 659e5fc38c5c816493d228039e8f265f6bdba00f

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			if _, ok := obj.GetString("diaspora:guid"); ok {
 608				// friendica does the silliest bonks
 609				if c, ok := obj.GetString("source", "content"); ok {
 610					re_link := regexp.MustCompile(`link='([^']*)'`)
 611					if m := re_link.FindStringSubmatch(c); len(m) > 1 {
 612						xid := m[1]
 613						log.Printf("getting friendica flavored bonk: %s", xid)
 614						if !needxonkid(user, xid) {
 615							return nil
 616						}
 617						if newobj, err := GetJunkHardMode(xid); err == nil {
 618							obj = newobj
 619							origin = originate(xid)
 620							what = "bonk"
 621						} else {
 622							log.Printf("error getting bonk: %s: %s", xid, err)
 623						}
 624					}
 625				}
 626			}
 627		}
 628
 629		var xonk Honk
 630		// early init
 631		xonk.UserID = user.ID
 632		xonk.Honker, _ = item.GetString("actor")
 633		if xonk.Honker == "" {
 634			xonk.Honker, _ = item.GetString("attributedTo")
 635		}
 636		if obj != nil {
 637			if xonk.Honker == "" {
 638				xonk.Honker = extractattrto(obj)
 639			}
 640			xonk.Oonker = extractattrto(obj)
 641			if xonk.Oonker == xonk.Honker {
 642				xonk.Oonker = ""
 643			}
 644			xonk.Audience = newphone(nil, obj)
 645		}
 646		xonk.Audience = append(xonk.Audience, xonk.Honker)
 647		xonk.Audience = oneofakind(xonk.Audience)
 648
 649		var mentions []Mention
 650		if obj != nil {
 651			ot, _ := obj.GetString("type")
 652			url, _ = obj.GetString("url")
 653			if dt2, ok := obj.GetString("published"); ok {
 654				dt = dt2
 655			}
 656			xid, _ = obj.GetString("id")
 657			precis, _ = obj.GetString("summary")
 658			if name, ok := obj.GetString("name"); ok {
 659				if precis != "" {
 660					precis = "\n" + precis
 661				}
 662				precis = name + precis
 663			}
 664			content, _ = obj.GetString("content")
 665			if !strings.HasPrefix(content, "<p>") {
 666				content = "<p>" + content
 667			}
 668			if sens, _ := obj["sensitive"].(bool); sens && precis == "" {
 669				precis = "unspecified horror"
 670			}
 671			rid, ok = obj.GetString("inReplyTo")
 672			if !ok {
 673				if robj, ok := obj.GetMap("inReplyTo"); ok {
 674					rid, _ = robj.GetString("id")
 675				}
 676			}
 677			convoy, _ = obj.GetString("context")
 678			if convoy == "" {
 679				convoy, _ = obj.GetString("conversation")
 680			}
 681			if ot == "Question" {
 682				if what == "honk" {
 683					what = "qonk"
 684				}
 685				content += "<ul>"
 686				ans, _ := obj.GetArray("oneOf")
 687				for _, ai := range ans {
 688					a, ok := ai.(junk.Junk)
 689					if !ok {
 690						continue
 691					}
 692					as, _ := a.GetString("name")
 693					content += "<li>" + as
 694				}
 695				ans, _ = obj.GetArray("anyOf")
 696				for _, ai := range ans {
 697					a, ok := ai.(junk.Junk)
 698					if !ok {
 699						continue
 700					}
 701					as, _ := a.GetString("name")
 702					content += "<li>" + as
 703				}
 704				content += "</ul>"
 705			}
 706			if ot == "Move" {
 707				targ, _ := obj.GetString("target")
 708				content += string(templates.Sprintf(`<p>Moved to <a href="%s">%s</a>`, targ, targ))
 709			}
 710			if what == "honk" && rid != "" {
 711				what = "tonk"
 712			}
 713			atts, _ := obj.GetArray("attachment")
 714			for i, atti := range atts {
 715				att, ok := atti.(junk.Junk)
 716				if !ok {
 717					continue
 718				}
 719				at, _ := att.GetString("type")
 720				mt, _ := att.GetString("mediaType")
 721				u, _ := att.GetString("url")
 722				name, _ := att.GetString("name")
 723				desc, _ := att.GetString("summary")
 724				if desc == "" {
 725					desc = name
 726				}
 727				localize := false
 728				if i > 4 {
 729					log.Printf("excessive attachment: %s", at)
 730				} else if at == "Document" || at == "Image" {
 731					mt = strings.ToLower(mt)
 732					log.Printf("attachment: %s %s", mt, u)
 733					if mt == "text/plain" || mt == "application/pdf" ||
 734						strings.HasPrefix(mt, "image") {
 735						localize = true
 736					}
 737				} else {
 738					log.Printf("unknown attachment: %s", at)
 739				}
 740				if skipMedia(&xonk) {
 741					localize = false
 742				}
 743				donk := savedonk(u, name, desc, mt, localize)
 744				if donk != nil {
 745					xonk.Donks = append(xonk.Donks, donk)
 746				}
 747			}
 748			tags, _ := obj.GetArray("tag")
 749			for _, tagi := range tags {
 750				tag, ok := tagi.(junk.Junk)
 751				if !ok {
 752					continue
 753				}
 754				tt, _ := tag.GetString("type")
 755				name, _ := tag.GetString("name")
 756				desc, _ := tag.GetString("summary")
 757				if desc == "" {
 758					desc = name
 759				}
 760				if tt == "Emoji" {
 761					icon, _ := tag.GetMap("icon")
 762					mt, _ := icon.GetString("mediaType")
 763					if mt == "" {
 764						mt = "image/png"
 765					}
 766					u, _ := icon.GetString("url")
 767					donk := savedonk(u, name, desc, mt, true)
 768					if donk != nil {
 769						xonk.Donks = append(xonk.Donks, donk)
 770					}
 771				}
 772				if tt == "Hashtag" {
 773					if name == "" || name == "#" {
 774						// skip it
 775					} else {
 776						if name[0] != '#' {
 777							name = "#" + name
 778						}
 779						xonk.Onts = append(xonk.Onts, name)
 780					}
 781				}
 782				if tt == "Place" {
 783					p := new(Place)
 784					p.Name = name
 785					p.Latitude, _ = tag["latitude"].(float64)
 786					p.Longitude, _ = tag["longitude"].(float64)
 787					p.Url, _ = tag.GetString("url")
 788					xonk.Place = p
 789				}
 790				if tt == "Mention" {
 791					var m Mention
 792					m.Who, _ = tag.GetString("name")
 793					m.Where, _ = tag.GetString("href")
 794					mentions = append(mentions, m)
 795				}
 796			}
 797			if starttime, ok := obj.GetString("startTime"); ok {
 798				if start, err := time.Parse(time.RFC3339, starttime); err == nil {
 799					t := new(Time)
 800					t.StartTime = start
 801					endtime, _ := obj.GetString("endTime")
 802					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
 803					dura, _ := obj.GetString("duration")
 804					if strings.HasPrefix(dura, "PT") {
 805						dura = strings.ToLower(dura[2:])
 806						d, _ := time.ParseDuration(dura)
 807						t.Duration = Duration(d)
 808					}
 809					xonk.Time = t
 810				}
 811			}
 812			if loca, ok := obj.GetMap("location"); ok {
 813				if tt, _ := loca.GetString("type"); tt == "Place" {
 814					p := new(Place)
 815					p.Name, _ = loca.GetString("name")
 816					p.Latitude, _ = loca["latitude"].(float64)
 817					p.Longitude, _ = loca["longitude"].(float64)
 818					p.Url, _ = loca.GetString("url")
 819					xonk.Place = p
 820				}
 821			}
 822
 823			xonk.Onts = oneofakind(xonk.Onts)
 824			replyobj, ok := obj.GetMap("replies")
 825			if ok {
 826				items, ok := replyobj.GetArray("items")
 827				if !ok {
 828					first, ok := replyobj.GetMap("first")
 829					if ok {
 830						items, _ = first.GetArray("items")
 831					}
 832				}
 833				for _, repl := range items {
 834					s, ok := repl.(string)
 835					if ok {
 836						replies = append(replies, s)
 837					}
 838				}
 839			}
 840
 841		}
 842		if originate(xid) != origin {
 843			log.Printf("original sin: %s <> %s", xid, origin)
 844			item.Write(os.Stdout)
 845			return nil
 846		}
 847
 848		if currenttid == "" {
 849			currenttid = convoy
 850		}
 851
 852		if len(content) > 90001 {
 853			log.Printf("content too long. truncating")
 854			content = content[:90001]
 855		}
 856
 857		// init xonk
 858		xonk.What = what
 859		xonk.XID = xid
 860		xonk.RID = rid
 861		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 862		xonk.URL = url
 863		xonk.Noise = content
 864		xonk.Precis = precis
 865		xonk.Format = "html"
 866		xonk.Convoy = convoy
 867		xonk.Mentions = mentions
 868		for _, m := range mentions {
 869			if m.Where == user.URL {
 870				xonk.Whofore = 1
 871			}
 872		}
 873		imaginate(&xonk)
 874
 875		if isUpdate {
 876			log.Printf("something has changed! %s", xonk.XID)
 877			prev := getxonk(user.ID, xonk.XID)
 878			if prev == nil {
 879				log.Printf("didn't find old version for update: %s", xonk.XID)
 880				isUpdate = false
 881			} else {
 882				xonk.ID = prev.ID
 883				updatehonk(&xonk)
 884			}
 885		}
 886		if !isUpdate && needxonk(user, &xonk) {
 887			if strings.HasSuffix(convoy, "#context") {
 888				// friendica...
 889				if rid != "" {
 890					convoy = ""
 891				} else {
 892					convoy = url
 893				}
 894			}
 895			if rid != "" {
 896				if needxonkid(user, rid) {
 897					goingup++
 898					saveonemore(rid)
 899					goingup--
 900				}
 901				if convoy == "" {
 902					xx := getxonk(user.ID, rid)
 903					if xx != nil {
 904						convoy = xx.Convoy
 905					}
 906				}
 907			}
 908			if convoy == "" {
 909				convoy = currenttid
 910			}
 911			if convoy == "" {
 912				convoy = "data:,missing-" + xfiltrate()
 913				currenttid = convoy
 914			}
 915			xonk.Convoy = convoy
 916			savexonk(&xonk)
 917		}
 918		if goingup == 0 {
 919			for _, replid := range replies {
 920				if needxonkid(user, replid) {
 921					log.Printf("missing a reply: %s", replid)
 922					saveonemore(replid)
 923				}
 924			}
 925		}
 926		return &xonk
 927	}
 928
 929	return xonkxonkfn(item, origin)
 930}
 931
 932func rubadubdub(user *WhatAbout, req junk.Junk) {
 933	xid, _ := req.GetString("id")
 934	actor, _ := req.GetString("actor")
 935	j := junk.New()
 936	j["@context"] = itiswhatitis
 937	j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
 938	j["type"] = "Accept"
 939	j["actor"] = user.URL
 940	j["to"] = actor
 941	j["published"] = time.Now().UTC().Format(time.RFC3339)
 942	j["object"] = req
 943
 944	deliverate(0, user.ID, actor, j.ToBytes())
 945}
 946
 947func itakeitallback(user *WhatAbout, xid string) {
 948	j := junk.New()
 949	j["@context"] = itiswhatitis
 950	j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
 951	j["type"] = "Undo"
 952	j["actor"] = user.URL
 953	j["to"] = xid
 954	f := junk.New()
 955	f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 956	f["type"] = "Follow"
 957	f["actor"] = user.URL
 958	f["to"] = xid
 959	f["object"] = xid
 960	j["object"] = f
 961	j["published"] = time.Now().UTC().Format(time.RFC3339)
 962
 963	deliverate(0, user.ID, xid, j.ToBytes())
 964}
 965
 966func subsub(user *WhatAbout, xid string, owner string) {
 967	if xid == "" {
 968		log.Printf("can't subscribe to empty")
 969		return
 970	}
 971	j := junk.New()
 972	j["@context"] = itiswhatitis
 973	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 974	j["type"] = "Follow"
 975	j["actor"] = user.URL
 976	j["to"] = owner
 977	j["object"] = xid
 978	j["published"] = time.Now().UTC().Format(time.RFC3339)
 979
 980	deliverate(0, user.ID, owner, j.ToBytes())
 981}
 982
 983// returns activity, object
 984func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 985	dt := h.Date.Format(time.RFC3339)
 986	var jo junk.Junk
 987	j := junk.New()
 988	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 989	j["actor"] = user.URL
 990	j["published"] = dt
 991	if h.Public {
 992		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
 993	} else {
 994		j["to"] = h.Audience[0]
 995	}
 996	if len(h.Audience) > 1 {
 997		j["cc"] = h.Audience[1:]
 998	}
 999
1000	switch h.What {
1001	case "update":
1002		fallthrough
1003	case "tonk":
1004		fallthrough
1005	case "event":
1006		fallthrough
1007	case "honk":
1008		j["type"] = "Create"
1009		if h.What == "update" {
1010			j["type"] = "Update"
1011		}
1012
1013		jo = junk.New()
1014		jo["id"] = h.XID
1015		jo["type"] = "Note"
1016		if h.What == "event" {
1017			jo["type"] = "Event"
1018		}
1019		jo["published"] = dt
1020		jo["url"] = h.XID
1021		jo["attributedTo"] = user.URL
1022		if h.RID != "" {
1023			jo["inReplyTo"] = h.RID
1024		}
1025		if h.Convoy != "" {
1026			jo["context"] = h.Convoy
1027			jo["conversation"] = h.Convoy
1028		}
1029		jo["to"] = h.Audience[0]
1030		if len(h.Audience) > 1 {
1031			jo["cc"] = h.Audience[1:]
1032		}
1033		if !h.Public {
1034			jo["directMessage"] = true
1035		}
1036		mentions := bunchofgrapes(h.Noise)
1037		translate(h)
1038		redoimages(h)
1039		jo["summary"] = html.EscapeString(h.Precis)
1040		jo["content"] = h.Noise
1041		if h.Precis != "" {
1042			jo["sensitive"] = true
1043		}
1044
1045		var replies []string
1046		for _, reply := range h.Replies {
1047			replies = append(replies, reply.XID)
1048		}
1049		if len(replies) > 0 {
1050			jr := junk.New()
1051			jr["type"] = "Collection"
1052			jr["totalItems"] = len(replies)
1053			jr["items"] = replies
1054			jo["replies"] = jr
1055		}
1056
1057		var tags []junk.Junk
1058		for _, m := range mentions {
1059			t := junk.New()
1060			t["type"] = "Mention"
1061			t["name"] = m.Who
1062			t["href"] = m.Where
1063			tags = append(tags, t)
1064		}
1065		for _, o := range h.Onts {
1066			t := junk.New()
1067			t["type"] = "Hashtag"
1068			o = strings.ToLower(o)
1069			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1070			t["name"] = o
1071			tags = append(tags, t)
1072		}
1073		for _, e := range herdofemus(h.Noise) {
1074			t := junk.New()
1075			t["id"] = e.ID
1076			t["type"] = "Emoji"
1077			t["name"] = e.Name
1078			i := junk.New()
1079			i["type"] = "Image"
1080			i["mediaType"] = "image/png"
1081			i["url"] = e.ID
1082			t["icon"] = i
1083			tags = append(tags, t)
1084		}
1085		if len(tags) > 0 {
1086			jo["tag"] = tags
1087		}
1088		if p := h.Place; p != nil {
1089			t := junk.New()
1090			t["type"] = "Place"
1091			if p.Name != "" {
1092				t["name"] = p.Name
1093			}
1094			if p.Latitude != 0 {
1095				t["latitude"] = p.Latitude
1096			}
1097			if p.Longitude != 0 {
1098				t["longitude"] = p.Longitude
1099			}
1100			if p.Url != "" {
1101				t["url"] = p.Url
1102			}
1103			jo["location"] = t
1104		}
1105		if t := h.Time; t != nil {
1106			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1107			if t.Duration != 0 {
1108				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1109			}
1110		}
1111		var atts []junk.Junk
1112		for _, d := range h.Donks {
1113			if re_emus.MatchString(d.Name) {
1114				continue
1115			}
1116			jd := junk.New()
1117			jd["mediaType"] = d.Media
1118			jd["name"] = d.Name
1119			jd["summary"] = html.EscapeString(d.Desc)
1120			jd["type"] = "Document"
1121			jd["url"] = d.URL
1122			atts = append(atts, jd)
1123		}
1124		if len(atts) > 0 {
1125			jo["attachment"] = atts
1126		}
1127		j["object"] = jo
1128	case "bonk":
1129		j["type"] = "Announce"
1130		if h.Convoy != "" {
1131			j["context"] = h.Convoy
1132		}
1133		j["object"] = h.XID
1134	case "unbonk":
1135		b := junk.New()
1136		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1137		b["type"] = "Announce"
1138		b["actor"] = user.URL
1139		if h.Convoy != "" {
1140			b["context"] = h.Convoy
1141		}
1142		b["object"] = h.XID
1143		j["type"] = "Undo"
1144		j["object"] = b
1145	case "zonk":
1146		j["type"] = "Delete"
1147		j["object"] = h.XID
1148	case "ack":
1149		j["type"] = "Read"
1150		j["object"] = h.XID
1151		if h.Convoy != "" {
1152			j["context"] = h.Convoy
1153		}
1154	case "deack":
1155		b := junk.New()
1156		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1157		b["type"] = "Read"
1158		b["actor"] = user.URL
1159		b["object"] = h.XID
1160		if h.Convoy != "" {
1161			b["context"] = h.Convoy
1162		}
1163		j["type"] = "Undo"
1164		j["object"] = b
1165	}
1166
1167	return j, jo
1168}
1169
1170var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1171	row := stmtAnyXonk.QueryRow(xid)
1172	honk := scanhonk(row)
1173	if honk == nil || !honk.Public {
1174		return nil, true
1175	}
1176	user, _ := butwhatabout(honk.Username)
1177	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1178	reversehonks(rawhonks)
1179	for _, h := range rawhonks {
1180		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1181			honk.Replies = append(honk.Replies, h)
1182		}
1183	}
1184	donksforhonks([]*Honk{honk})
1185	_, j := jonkjonk(user, honk)
1186	j["@context"] = itiswhatitis
1187
1188	return j.ToBytes(), true
1189}, Limit: 128})
1190
1191func gimmejonk(xid string) ([]byte, bool) {
1192	var j []byte
1193	ok := oldjonks.Get(xid, &j)
1194	return j, ok
1195}
1196
1197func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1198	rcpts := make(map[string]bool)
1199	for _, a := range addresses {
1200		if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1201			continue
1202		}
1203		if a[0] == '%' {
1204			rcpts[a] = true
1205			continue
1206		}
1207		var box *Box
1208		ok := boxofboxes.Get(a, &box)
1209		if ok && useshared && box.Shared != "" {
1210			rcpts["%"+box.Shared] = true
1211		} else {
1212			rcpts[a] = true
1213		}
1214	}
1215	return rcpts
1216}
1217
1218func honkworldwide(user *WhatAbout, honk *Honk) {
1219	jonk, _ := jonkjonk(user, honk)
1220	jonk["@context"] = itiswhatitis
1221	msg := jonk.ToBytes()
1222
1223	rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1224
1225	if honk.Public {
1226		for _, h := range getdubs(user.ID) {
1227			if h.XID == user.URL {
1228				continue
1229			}
1230			var box *Box
1231			ok := boxofboxes.Get(h.XID, &box)
1232			if ok && box.Shared != "" {
1233				rcpts["%"+box.Shared] = true
1234			} else {
1235				rcpts[h.XID] = true
1236			}
1237		}
1238		for _, f := range getbacktracks(honk.XID) {
1239			rcpts[f] = true
1240		}
1241	}
1242	for a := range rcpts {
1243		go deliverate(0, user.ID, a, msg)
1244	}
1245	if honk.Public && len(honk.Onts) > 0 {
1246		collectiveaction(honk)
1247	}
1248}
1249
1250func collectiveaction(honk *Honk) {
1251	user := getserveruser()
1252	for _, ont := range honk.Onts {
1253		dubs := getnameddubs(serverUID, ont)
1254		if len(dubs) == 0 {
1255			continue
1256		}
1257		j := junk.New()
1258		j["@context"] = itiswhatitis
1259		j["type"] = "Add"
1260		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1261		j["actor"] = user.URL
1262		j["object"] = honk.XID
1263		j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1264		rcpts := make(map[string]bool)
1265		for _, dub := range dubs {
1266			var box *Box
1267			ok := boxofboxes.Get(dub.XID, &box)
1268			if ok && box.Shared != "" {
1269				rcpts["%"+box.Shared] = true
1270			} else {
1271				rcpts[dub.XID] = true
1272			}
1273		}
1274		msg := j.ToBytes()
1275		for a := range rcpts {
1276			go deliverate(0, user.ID, a, msg)
1277		}
1278	}
1279}
1280
1281func junkuser(user *WhatAbout) []byte {
1282	about := markitzero(user.About)
1283
1284	j := junk.New()
1285	j["@context"] = itiswhatitis
1286	j["id"] = user.URL
1287	j["inbox"] = user.URL + "/inbox"
1288	j["outbox"] = user.URL + "/outbox"
1289	j["name"] = user.Display
1290	j["preferredUsername"] = user.Name
1291	j["summary"] = about
1292	if user.ID > 0 {
1293		j["type"] = "Person"
1294		j["url"] = user.URL
1295		j["followers"] = user.URL + "/followers"
1296		j["following"] = user.URL + "/following"
1297		a := junk.New()
1298		a["type"] = "Image"
1299		a["mediaType"] = "image/png"
1300		if ava := user.Options.Avatar; ava != "" {
1301			a["url"] = ava
1302		} else {
1303			a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1304		}
1305		j["icon"] = a
1306	} else {
1307		j["type"] = "Service"
1308	}
1309	k := junk.New()
1310	k["id"] = user.URL + "#key"
1311	k["owner"] = user.URL
1312	k["publicKeyPem"] = user.Key
1313	j["publicKey"] = k
1314
1315	return j.ToBytes()
1316}
1317
1318var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1319	user, err := butwhatabout(name)
1320	if err != nil {
1321		return nil, false
1322	}
1323	return junkuser(user), true
1324}, Duration: 1 * time.Minute})
1325
1326func asjonker(name string) ([]byte, bool) {
1327	var j []byte
1328	ok := oldjonkers.Get(name, &j)
1329	return j, ok
1330}
1331
1332var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1333	m := strings.Split(name, "@")
1334	if len(m) != 2 {
1335		log.Printf("bad fish name: %s", name)
1336		return "", true
1337	}
1338	var href string
1339	row := stmtGetXonker.QueryRow(name, "fishname")
1340	err := row.Scan(&href)
1341	if err == nil {
1342		return href, true
1343	}
1344	log.Printf("fishing for %s", name)
1345	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1346	if err != nil {
1347		log.Printf("failed to go fish %s: %s", name, err)
1348		return "", true
1349	}
1350	links, _ := j.GetArray("links")
1351	for _, li := range links {
1352		l, ok := li.(junk.Junk)
1353		if !ok {
1354			continue
1355		}
1356		href, _ := l.GetString("href")
1357		rel, _ := l.GetString("rel")
1358		t, _ := l.GetString("type")
1359		if rel == "self" && friendorfoe(t) {
1360			when := time.Now().UTC().Format(dbtimeformat)
1361			_, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1362			if err != nil {
1363				log.Printf("error saving fishname: %s", err)
1364			}
1365			return href, true
1366		}
1367	}
1368	return href, true
1369}})
1370
1371func gofish(name string) string {
1372	if name[0] == '@' {
1373		name = name[1:]
1374	}
1375	var href string
1376	handfull.Get(name, &href)
1377	return href
1378}
1379
1380func investigate(name string) (*SomeThing, error) {
1381	if name == "" {
1382		return nil, fmt.Errorf("no name")
1383	}
1384	if name[0] == '@' {
1385		name = gofish(name)
1386	}
1387	if name == "" {
1388		return nil, fmt.Errorf("no name")
1389	}
1390	obj, err := GetJunkFast(name)
1391	if err != nil {
1392		return nil, err
1393	}
1394	allinjest(originate(name), obj)
1395	return somethingabout(obj)
1396}
1397
1398func somethingabout(obj junk.Junk) (*SomeThing, error) {
1399	info := new(SomeThing)
1400	t, _ := obj.GetString("type")
1401	switch t {
1402	case "Person":
1403		fallthrough
1404	case "Organization":
1405		fallthrough
1406	case "Application":
1407		fallthrough
1408	case "Service":
1409		info.What = SomeActor
1410	case "OrderedCollection":
1411		fallthrough
1412	case "Collection":
1413		info.What = SomeCollection
1414	default:
1415		return nil, fmt.Errorf("unknown object type")
1416	}
1417	info.XID, _ = obj.GetString("id")
1418	info.Name, _ = obj.GetString("preferredUsername")
1419	if info.Name == "" {
1420		info.Name, _ = obj.GetString("name")
1421	}
1422	info.Owner, _ = obj.GetString("attributedTo")
1423	if info.Owner == "" {
1424		info.Owner = info.XID
1425	}
1426	return info, nil
1427}
1428
1429func allinjest(origin string, obj junk.Junk) {
1430	keyobj, ok := obj.GetMap("publicKey")
1431	if ok {
1432		ingestpubkey(origin, keyobj)
1433	}
1434	ingestboxes(origin, obj)
1435	ingesthandle(origin, obj)
1436}
1437
1438func ingestpubkey(origin string, obj junk.Junk) {
1439	keyobj, ok := obj.GetMap("publicKey")
1440	if ok {
1441		obj = keyobj
1442	}
1443	keyname, ok := obj.GetString("id")
1444	var data string
1445	row := stmtGetXonker.QueryRow(keyname, "pubkey")
1446	err := row.Scan(&data)
1447	if err == nil {
1448		return
1449	}
1450	if !ok || origin != originate(keyname) {
1451		log.Printf("bad key origin %s <> %s", origin, keyname)
1452		return
1453	}
1454	log.Printf("ingesting a needed pubkey: %s", keyname)
1455	owner, ok := obj.GetString("owner")
1456	if !ok {
1457		log.Printf("error finding %s pubkey owner", keyname)
1458		return
1459	}
1460	data, ok = obj.GetString("publicKeyPem")
1461	if !ok {
1462		log.Printf("error finding %s pubkey", keyname)
1463		return
1464	}
1465	if originate(owner) != origin {
1466		log.Printf("bad key owner: %s <> %s", owner, origin)
1467		return
1468	}
1469	_, _, err = httpsig.DecodeKey(data)
1470	if err != nil {
1471		log.Printf("error decoding %s pubkey: %s", keyname, err)
1472		return
1473	}
1474	when := time.Now().UTC().Format(dbtimeformat)
1475	_, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1476	if err != nil {
1477		log.Printf("error saving key: %s", err)
1478	}
1479}
1480
1481func ingestboxes(origin string, obj junk.Junk) {
1482	ident, _ := obj.GetString("id")
1483	if ident == "" {
1484		return
1485	}
1486	if originate(ident) != origin {
1487		return
1488	}
1489	var info string
1490	row := stmtGetXonker.QueryRow(ident, "boxes")
1491	err := row.Scan(&info)
1492	if err == nil {
1493		return
1494	}
1495	log.Printf("ingesting boxes: %s", ident)
1496	inbox, _ := obj.GetString("inbox")
1497	outbox, _ := obj.GetString("outbox")
1498	sbox, _ := obj.GetString("endpoints", "sharedInbox")
1499	if inbox != "" {
1500		when := time.Now().UTC().Format(dbtimeformat)
1501		m := strings.Join([]string{inbox, outbox, sbox}, " ")
1502		_, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1503		if err != nil {
1504			log.Printf("error saving boxes: %s", err)
1505		}
1506	}
1507}
1508
1509func ingesthandle(origin string, obj junk.Junk) {
1510	xid, _ := obj.GetString("id")
1511	if xid == "" {
1512		return
1513	}
1514	if originate(xid) != origin {
1515		return
1516	}
1517	var handle string
1518	row := stmtGetXonker.QueryRow(xid, "handle")
1519	err := row.Scan(&handle)
1520	if err == nil {
1521		return
1522	}
1523	handle, _ = obj.GetString("preferredUsername")
1524	if handle != "" {
1525		when := time.Now().UTC().Format(dbtimeformat)
1526		_, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1527		if err != nil {
1528			log.Printf("error saving handle: %s", err)
1529		}
1530	}
1531}