all repos — honk @ a9738224f00c936d1fe358b7f07ed0ab721684b5

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