all repos — honk @ fcde0c7e9374af8d7b6027a3d440771ae823ac0e

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