all repos — honk @ ea41aa826129d270640dd3bd8856507ae52f8ed3

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, isUpdate bool) *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), false)
 474		depth--
 475	}
 476
 477	xonkxonkfn = func(item junk.Junk, origin string, isUpdate bool) *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		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, isUpdate)
 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), false)
 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), false)
 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			if len(content) > 90001 {
 719				log.Printf("content too long. truncating")
 720				content = content[:90001]
 721			}
 722
 723			xonk.Noise = content
 724			xonk.Precis = precis
 725			if rejectxonk(&xonk) {
 726				log.Printf("fast reject: %s", xid)
 727				return nil
 728			}
 729
 730			numatts := 0
 731			procatt := func(att junk.Junk) {
 732				at, _ := att.GetString("type")
 733				mt, _ := att.GetString("mediaType")
 734				u, ok := att.GetString("url")
 735				if !ok {
 736					if ua, ok := att.GetArray("url"); ok && len(ua) > 0 {
 737						u, ok = ua[0].(string)
 738						if !ok {
 739							if uu, ok := ua[0].(junk.Junk); ok {
 740								u, _ = uu.GetString("href")
 741								if mt == "" {
 742									mt, _ = uu.GetString("mediaType")
 743								}
 744							}
 745						}
 746					} else if uu, ok := att.GetMap("url"); ok {
 747						u, _ = uu.GetString("href")
 748						if mt == "" {
 749							mt, _ = uu.GetString("mediaType")
 750						}
 751					}
 752				}
 753				name, _ := att.GetString("name")
 754				desc, _ := att.GetString("summary")
 755				if desc == "" {
 756					desc = name
 757				}
 758				localize := false
 759				if numatts > 4 {
 760					log.Printf("excessive attachment: %s", at)
 761				} else if at == "Document" || at == "Image" {
 762					mt = strings.ToLower(mt)
 763					log.Printf("attachment: %s %s", mt, u)
 764					if mt == "text/plain" || mt == "application/pdf" ||
 765						strings.HasPrefix(mt, "image") {
 766						localize = true
 767					}
 768				} else {
 769					log.Printf("unknown attachment: %s", at)
 770				}
 771				if skipMedia(&xonk) {
 772					localize = false
 773				}
 774				donk := savedonk(u, name, desc, mt, localize)
 775				if donk != nil {
 776					xonk.Donks = append(xonk.Donks, donk)
 777				}
 778				numatts++
 779			}
 780			atts, _ := obj.GetArray("attachment")
 781			for _, atti := range atts {
 782				att, ok := atti.(junk.Junk)
 783				if !ok {
 784					log.Printf("attachment that wasn't map?")
 785					continue
 786				}
 787				procatt(att)
 788			}
 789			if att, ok := obj.GetMap("attachment"); ok {
 790				procatt(att)
 791			}
 792			tags, _ := obj.GetArray("tag")
 793			for _, tagi := range tags {
 794				tag, ok := tagi.(junk.Junk)
 795				if !ok {
 796					continue
 797				}
 798				tt, _ := tag.GetString("type")
 799				name, _ := tag.GetString("name")
 800				desc, _ := tag.GetString("summary")
 801				if desc == "" {
 802					desc = name
 803				}
 804				if tt == "Emoji" {
 805					icon, _ := tag.GetMap("icon")
 806					mt, _ := icon.GetString("mediaType")
 807					if mt == "" {
 808						mt = "image/png"
 809					}
 810					u, _ := icon.GetString("url")
 811					donk := savedonk(u, name, desc, mt, true)
 812					if donk != nil {
 813						xonk.Donks = append(xonk.Donks, donk)
 814					}
 815				}
 816				if tt == "Hashtag" {
 817					if name == "" || name == "#" {
 818						// skip it
 819					} else {
 820						if name[0] != '#' {
 821							name = "#" + name
 822						}
 823						xonk.Onts = append(xonk.Onts, name)
 824					}
 825				}
 826				if tt == "Place" {
 827					p := new(Place)
 828					p.Name = name
 829					p.Latitude, _ = tag.GetNumber("latitude")
 830					p.Longitude, _ = tag.GetNumber("longitude")
 831					p.Url, _ = tag.GetString("url")
 832					xonk.Place = p
 833				}
 834				if tt == "Mention" {
 835					var m Mention
 836					m.Who, _ = tag.GetString("name")
 837					m.Where, _ = tag.GetString("href")
 838					mentions = append(mentions, m)
 839				}
 840			}
 841			if starttime, ok := obj.GetString("startTime"); ok {
 842				if start, err := time.Parse(time.RFC3339, starttime); err == nil {
 843					t := new(Time)
 844					t.StartTime = start
 845					endtime, _ := obj.GetString("endTime")
 846					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
 847					dura, _ := obj.GetString("duration")
 848					if strings.HasPrefix(dura, "PT") {
 849						dura = strings.ToLower(dura[2:])
 850						d, _ := time.ParseDuration(dura)
 851						t.Duration = Duration(d)
 852					}
 853					xonk.Time = t
 854				}
 855			}
 856			if loca, ok := obj.GetMap("location"); ok {
 857				if tt, _ := loca.GetString("type"); tt == "Place" {
 858					p := new(Place)
 859					p.Name, _ = loca.GetString("name")
 860					p.Latitude, _ = loca.GetNumber("latitude")
 861					p.Longitude, _ = loca.GetNumber("longitude")
 862					p.Url, _ = loca.GetString("url")
 863					xonk.Place = p
 864				}
 865			}
 866
 867			xonk.Onts = oneofakind(xonk.Onts)
 868			replyobj, ok := obj.GetMap("replies")
 869			if ok {
 870				items, ok := replyobj.GetArray("items")
 871				if !ok {
 872					first, ok := replyobj.GetMap("first")
 873					if ok {
 874						items, _ = first.GetArray("items")
 875					}
 876				}
 877				for _, repl := range items {
 878					s, ok := repl.(string)
 879					if ok {
 880						replies = append(replies, s)
 881					}
 882				}
 883			}
 884
 885		}
 886
 887		if currenttid == "" {
 888			currenttid = convoy
 889		}
 890
 891		// init xonk
 892		xonk.What = what
 893		xonk.RID = rid
 894		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 895		xonk.URL = url
 896		xonk.Format = "html"
 897		xonk.Convoy = convoy
 898		xonk.Mentions = mentions
 899		for _, m := range mentions {
 900			if m.Where == user.URL {
 901				xonk.Whofore = 1
 902			}
 903		}
 904		imaginate(&xonk)
 905
 906		if what == "chonk" {
 907			ch := Chonk{
 908				UserID: xonk.UserID,
 909				XID:    xid,
 910				Who:    xonk.Honker,
 911				Target: xonk.Honker,
 912				Date:   xonk.Date,
 913				Noise:  xonk.Noise,
 914				Format: xonk.Format,
 915				Donks:  xonk.Donks,
 916			}
 917			savechonk(&ch)
 918			return nil
 919		}
 920
 921		if isUpdate {
 922			log.Printf("something has changed! %s", xonk.XID)
 923			prev := getxonk(user.ID, xonk.XID)
 924			if prev == nil {
 925				log.Printf("didn't find old version for update: %s", xonk.XID)
 926				isUpdate = false
 927			} else {
 928				xonk.ID = prev.ID
 929				updatehonk(&xonk)
 930			}
 931		}
 932		if !isUpdate && needxonk(user, &xonk) {
 933			if rid != "" {
 934				if needxonkid(user, rid) {
 935					goingup++
 936					saveonemore(rid)
 937					goingup--
 938				}
 939				if convoy == "" {
 940					xx := getxonk(user.ID, rid)
 941					if xx != nil {
 942						convoy = xx.Convoy
 943					}
 944				}
 945			}
 946			if convoy == "" {
 947				convoy = currenttid
 948			}
 949			if convoy == "" {
 950				convoy = "data:,missing-" + xfiltrate()
 951				currenttid = convoy
 952			}
 953			xonk.Convoy = convoy
 954			savexonk(&xonk)
 955		}
 956		if goingup == 0 {
 957			for _, replid := range replies {
 958				if needxonkid(user, replid) {
 959					log.Printf("missing a reply: %s", replid)
 960					saveonemore(replid)
 961				}
 962			}
 963		}
 964		return &xonk
 965	}
 966
 967	return xonkxonkfn(item, origin, false)
 968}
 969
 970func dumpactivity(item junk.Junk) {
 971	fd, err := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 972	if err != nil {
 973		log.Printf("error opening inbox! %s", err)
 974		return
 975	}
 976	defer fd.Close()
 977	item.Write(fd)
 978	io.WriteString(fd, "\n")
 979}
 980
 981func rubadubdub(user *WhatAbout, req junk.Junk) {
 982	actor, _ := req.GetString("actor")
 983	j := junk.New()
 984	j["@context"] = itiswhatitis
 985	j["id"] = user.URL + "/dub/" + xfiltrate()
 986	j["type"] = "Accept"
 987	j["actor"] = user.URL
 988	j["to"] = actor
 989	j["published"] = time.Now().UTC().Format(time.RFC3339)
 990	j["object"] = req
 991
 992	deliverate(0, user.ID, actor, j.ToBytes(), true)
 993}
 994
 995func itakeitallback(user *WhatAbout, xid string, owner string, folxid string) {
 996	j := junk.New()
 997	j["@context"] = itiswhatitis
 998	j["id"] = user.URL + "/unsub/" + folxid
 999	j["type"] = "Undo"
1000	j["actor"] = user.URL
1001	j["to"] = owner
1002	f := junk.New()
1003	f["id"] = user.URL + "/sub/" + folxid
1004	f["type"] = "Follow"
1005	f["actor"] = user.URL
1006	f["to"] = owner
1007	f["object"] = xid
1008	j["object"] = f
1009	j["published"] = time.Now().UTC().Format(time.RFC3339)
1010
1011	deliverate(0, user.ID, owner, j.ToBytes(), true)
1012}
1013
1014func subsub(user *WhatAbout, xid string, owner string, folxid string) {
1015	if xid == "" {
1016		log.Printf("can't subscribe to empty")
1017		return
1018	}
1019	j := junk.New()
1020	j["@context"] = itiswhatitis
1021	j["id"] = user.URL + "/sub/" + folxid
1022	j["type"] = "Follow"
1023	j["actor"] = user.URL
1024	j["to"] = owner
1025	j["object"] = xid
1026	j["published"] = time.Now().UTC().Format(time.RFC3339)
1027
1028	deliverate(0, user.ID, owner, j.ToBytes(), true)
1029}
1030
1031func activatedonks(donks []*Donk) []junk.Junk {
1032	var atts []junk.Junk
1033	for _, d := range donks {
1034		if re_emus.MatchString(d.Name) {
1035			continue
1036		}
1037		jd := junk.New()
1038		jd["mediaType"] = d.Media
1039		jd["name"] = d.Name
1040		jd["summary"] = html.EscapeString(d.Desc)
1041		jd["type"] = "Document"
1042		jd["url"] = d.URL
1043		atts = append(atts, jd)
1044	}
1045	return atts
1046}
1047
1048// returns activity, object
1049func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
1050	dt := h.Date.Format(time.RFC3339)
1051	var jo junk.Junk
1052	j := junk.New()
1053	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
1054	j["actor"] = user.URL
1055	j["published"] = dt
1056	j["to"] = h.Audience[0]
1057	if len(h.Audience) > 1 {
1058		j["cc"] = h.Audience[1:]
1059	}
1060
1061	switch h.What {
1062	case "update":
1063		fallthrough
1064	case "tonk":
1065		fallthrough
1066	case "event":
1067		fallthrough
1068	case "honk":
1069		j["type"] = "Create"
1070		if h.What == "update" {
1071			j["type"] = "Update"
1072		}
1073
1074		jo = junk.New()
1075		jo["id"] = h.XID
1076		jo["type"] = "Note"
1077		if h.What == "event" {
1078			jo["type"] = "Event"
1079		}
1080		jo["published"] = dt
1081		jo["url"] = h.XID
1082		jo["attributedTo"] = user.URL
1083		if h.RID != "" {
1084			jo["inReplyTo"] = h.RID
1085		}
1086		if h.Convoy != "" {
1087			jo["context"] = h.Convoy
1088			jo["conversation"] = h.Convoy
1089		}
1090		jo["to"] = h.Audience[0]
1091		if len(h.Audience) > 1 {
1092			jo["cc"] = h.Audience[1:]
1093		}
1094		if !h.Public {
1095			jo["directMessage"] = true
1096		}
1097		translate(h)
1098		redoimages(h)
1099		if h.Precis != "" {
1100			jo["sensitive"] = true
1101		}
1102
1103		var replies []string
1104		for _, reply := range h.Replies {
1105			replies = append(replies, reply.XID)
1106		}
1107		if len(replies) > 0 {
1108			jr := junk.New()
1109			jr["type"] = "Collection"
1110			jr["totalItems"] = len(replies)
1111			jr["items"] = replies
1112			jo["replies"] = jr
1113		}
1114
1115		var tags []junk.Junk
1116		for _, m := range h.Mentions {
1117			t := junk.New()
1118			t["type"] = "Mention"
1119			t["name"] = m.Who
1120			t["href"] = m.Where
1121			tags = append(tags, t)
1122		}
1123		for _, o := range h.Onts {
1124			t := junk.New()
1125			t["type"] = "Hashtag"
1126			o = strings.ToLower(o)
1127			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1128			t["name"] = o
1129			tags = append(tags, t)
1130		}
1131		for _, e := range herdofemus(h.Noise) {
1132			t := junk.New()
1133			t["id"] = e.ID
1134			t["type"] = "Emoji"
1135			t["name"] = e.Name
1136			i := junk.New()
1137			i["type"] = "Image"
1138			i["mediaType"] = "image/png"
1139			i["url"] = e.ID
1140			t["icon"] = i
1141			tags = append(tags, t)
1142		}
1143		for _, e := range fixupflags(h) {
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		if len(tags) > 0 {
1156			jo["tag"] = tags
1157		}
1158		if p := h.Place; p != nil {
1159			t := junk.New()
1160			t["type"] = "Place"
1161			if p.Name != "" {
1162				t["name"] = p.Name
1163			}
1164			if p.Latitude != 0 {
1165				t["latitude"] = p.Latitude
1166			}
1167			if p.Longitude != 0 {
1168				t["longitude"] = p.Longitude
1169			}
1170			if p.Url != "" {
1171				t["url"] = p.Url
1172			}
1173			jo["location"] = t
1174		}
1175		if t := h.Time; t != nil {
1176			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1177			if t.Duration != 0 {
1178				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1179			}
1180		}
1181		atts := activatedonks(h.Donks)
1182		if len(atts) > 0 {
1183			jo["attachment"] = atts
1184		}
1185		jo["summary"] = html.EscapeString(h.Precis)
1186		jo["content"] = h.Noise
1187		j["object"] = jo
1188	case "bonk":
1189		j["type"] = "Announce"
1190		if h.Convoy != "" {
1191			j["context"] = h.Convoy
1192		}
1193		j["object"] = h.XID
1194	case "unbonk":
1195		b := junk.New()
1196		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1197		b["type"] = "Announce"
1198		b["actor"] = user.URL
1199		if h.Convoy != "" {
1200			b["context"] = h.Convoy
1201		}
1202		b["object"] = h.XID
1203		j["type"] = "Undo"
1204		j["object"] = b
1205	case "zonk":
1206		j["type"] = "Delete"
1207		j["object"] = h.XID
1208	case "ack":
1209		j["type"] = "Read"
1210		j["object"] = h.XID
1211		if h.Convoy != "" {
1212			j["context"] = h.Convoy
1213		}
1214	case "react":
1215		j["type"] = "EmojiReact"
1216		j["object"] = h.XID
1217		if h.Convoy != "" {
1218			j["context"] = h.Convoy
1219		}
1220		j["content"] = h.Noise
1221	case "deack":
1222		b := junk.New()
1223		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1224		b["type"] = "Read"
1225		b["actor"] = user.URL
1226		b["object"] = h.XID
1227		if h.Convoy != "" {
1228			b["context"] = h.Convoy
1229		}
1230		j["type"] = "Undo"
1231		j["object"] = b
1232	}
1233
1234	return j, jo
1235}
1236
1237var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1238	row := stmtAnyXonk.QueryRow(xid)
1239	honk := scanhonk(row)
1240	if honk == nil || !honk.Public {
1241		return nil, true
1242	}
1243	user, _ := butwhatabout(honk.Username)
1244	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1245	reversehonks(rawhonks)
1246	for _, h := range rawhonks {
1247		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1248			honk.Replies = append(honk.Replies, h)
1249		}
1250	}
1251	donksforhonks([]*Honk{honk})
1252	_, j := jonkjonk(user, honk)
1253	j["@context"] = itiswhatitis
1254
1255	return j.ToBytes(), true
1256}, Limit: 128})
1257
1258func gimmejonk(xid string) ([]byte, bool) {
1259	var j []byte
1260	ok := oldjonks.Get(xid, &j)
1261	return j, ok
1262}
1263
1264func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1265	rcpts := make(map[string]bool)
1266	for _, a := range addresses {
1267		if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1268			continue
1269		}
1270		if a[0] == '%' {
1271			rcpts[a] = true
1272			continue
1273		}
1274		var box *Box
1275		ok := boxofboxes.Get(a, &box)
1276		if ok && useshared && box.Shared != "" {
1277			rcpts["%"+box.Shared] = true
1278		} else {
1279			rcpts[a] = true
1280		}
1281	}
1282	return rcpts
1283}
1284
1285func chonkifymsg(user *WhatAbout, ch *Chonk) []byte {
1286	dt := ch.Date.Format(time.RFC3339)
1287	aud := []string{ch.Target}
1288
1289	jo := junk.New()
1290	jo["id"] = ch.XID
1291	jo["type"] = "ChatMessage"
1292	jo["published"] = dt
1293	jo["attributedTo"] = user.URL
1294	jo["to"] = aud
1295	jo["content"] = ch.HTML
1296	atts := activatedonks(ch.Donks)
1297	if len(atts) > 0 {
1298		jo["attachment"] = atts
1299	}
1300	var tags []junk.Junk
1301	for _, e := range herdofemus(ch.Noise) {
1302		t := junk.New()
1303		t["id"] = e.ID
1304		t["type"] = "Emoji"
1305		t["name"] = e.Name
1306		i := junk.New()
1307		i["type"] = "Image"
1308		i["mediaType"] = "image/png"
1309		i["url"] = e.ID
1310		t["icon"] = i
1311		tags = append(tags, t)
1312	}
1313	if len(tags) > 0 {
1314		jo["tag"] = tags
1315	}
1316
1317	j := junk.New()
1318	j["@context"] = itiswhatitis
1319	j["id"] = user.URL + "/" + "honk" + "/" + shortxid(ch.XID)
1320	j["type"] = "Create"
1321	j["actor"] = user.URL
1322	j["published"] = dt
1323	j["to"] = aud
1324	j["object"] = jo
1325
1326	return j.ToBytes()
1327}
1328
1329func sendchonk(user *WhatAbout, ch *Chonk) {
1330	msg := chonkifymsg(user, ch)
1331
1332	rcpts := make(map[string]bool)
1333	rcpts[ch.Target] = true
1334	for a := range rcpts {
1335		go deliverate(0, user.ID, a, msg, true)
1336	}
1337}
1338
1339func honkworldwide(user *WhatAbout, honk *Honk) {
1340	jonk, _ := jonkjonk(user, honk)
1341	jonk["@context"] = itiswhatitis
1342	msg := jonk.ToBytes()
1343
1344	rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1345
1346	if honk.Public {
1347		for _, h := range getdubs(user.ID) {
1348			if h.XID == user.URL {
1349				continue
1350			}
1351			var box *Box
1352			ok := boxofboxes.Get(h.XID, &box)
1353			if ok && box.Shared != "" {
1354				rcpts["%"+box.Shared] = true
1355			} else {
1356				rcpts[h.XID] = true
1357			}
1358		}
1359		for _, f := range getbacktracks(honk.XID) {
1360			var box *Box
1361			ok := boxofboxes.Get(f, &box)
1362			if ok && box.Shared != "" {
1363				rcpts["%"+box.Shared] = true
1364			} else {
1365				rcpts[f] = true
1366			}
1367		}
1368	}
1369	for a := range rcpts {
1370		go deliverate(0, user.ID, a, msg, doesitmatter(honk.What))
1371	}
1372	if honk.Public && len(honk.Onts) > 0 {
1373		collectiveaction(honk)
1374	}
1375}
1376
1377func doesitmatter(what string) bool {
1378	switch what {
1379	case "ack":
1380		return false
1381	case "react":
1382		return false
1383	case "deack":
1384		return false
1385	}
1386	return true
1387}
1388
1389func collectiveaction(honk *Honk) {
1390	user := getserveruser()
1391	for _, ont := range honk.Onts {
1392		dubs := getnameddubs(serverUID, ont)
1393		if len(dubs) == 0 {
1394			continue
1395		}
1396		j := junk.New()
1397		j["@context"] = itiswhatitis
1398		j["type"] = "Add"
1399		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1400		j["actor"] = user.URL
1401		j["object"] = honk.XID
1402		j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1403		rcpts := make(map[string]bool)
1404		for _, dub := range dubs {
1405			var box *Box
1406			ok := boxofboxes.Get(dub.XID, &box)
1407			if ok && box.Shared != "" {
1408				rcpts["%"+box.Shared] = true
1409			} else {
1410				rcpts[dub.XID] = true
1411			}
1412		}
1413		msg := j.ToBytes()
1414		for a := range rcpts {
1415			go deliverate(0, user.ID, a, msg, false)
1416		}
1417	}
1418}
1419
1420func junkuser(user *WhatAbout) junk.Junk {
1421	j := junk.New()
1422	j["@context"] = itiswhatitis
1423	j["id"] = user.URL
1424	j["inbox"] = user.URL + "/inbox"
1425	j["outbox"] = user.URL + "/outbox"
1426	j["name"] = user.Display
1427	j["preferredUsername"] = user.Name
1428	j["summary"] = user.HTAbout
1429	var tags []junk.Junk
1430	for _, o := range user.Onts {
1431		t := junk.New()
1432		t["type"] = "Hashtag"
1433		o = strings.ToLower(o)
1434		t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1435		t["name"] = o
1436		tags = append(tags, t)
1437	}
1438	if len(tags) > 0 {
1439		j["tag"] = tags
1440	}
1441
1442	if user.ID > 0 {
1443		j["type"] = "Person"
1444		j["url"] = user.URL
1445		j["followers"] = user.URL + "/followers"
1446		j["following"] = user.URL + "/following"
1447		a := junk.New()
1448		a["type"] = "Image"
1449		a["mediaType"] = "image/png"
1450		if ava := user.Options.Avatar; ava != "" {
1451			a["url"] = ava
1452		} else {
1453			a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1454		}
1455		j["icon"] = a
1456	} else {
1457		j["type"] = "Service"
1458	}
1459	k := junk.New()
1460	k["id"] = user.URL + "#key"
1461	k["owner"] = user.URL
1462	k["publicKeyPem"] = user.Key
1463	j["publicKey"] = k
1464
1465	return j
1466}
1467
1468var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1469	user, err := butwhatabout(name)
1470	if err != nil {
1471		return nil, false
1472	}
1473	var buf bytes.Buffer
1474	j := junkuser(user)
1475	j.Write(&buf)
1476	return buf.Bytes(), true
1477}, Duration: 1 * time.Minute})
1478
1479func asjonker(name string) ([]byte, bool) {
1480	var j []byte
1481	ok := oldjonkers.Get(name, &j)
1482	return j, ok
1483}
1484
1485var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1486	m := strings.Split(name, "@")
1487	if len(m) != 2 {
1488		log.Printf("bad fish name: %s", name)
1489		return "", true
1490	}
1491	var href string
1492	row := stmtGetXonker.QueryRow(name, "fishname")
1493	err := row.Scan(&href)
1494	if err == nil {
1495		return href, true
1496	}
1497	log.Printf("fishing for %s", name)
1498	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1499	if err != nil {
1500		log.Printf("failed to go fish %s: %s", name, err)
1501		return "", true
1502	}
1503	links, _ := j.GetArray("links")
1504	for _, li := range links {
1505		l, ok := li.(junk.Junk)
1506		if !ok {
1507			continue
1508		}
1509		href, _ := l.GetString("href")
1510		rel, _ := l.GetString("rel")
1511		t, _ := l.GetString("type")
1512		if rel == "self" && friendorfoe(t) {
1513			when := time.Now().UTC().Format(dbtimeformat)
1514			_, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1515			if err != nil {
1516				log.Printf("error saving fishname: %s", err)
1517			}
1518			return href, true
1519		}
1520	}
1521	return href, true
1522}, Duration: 1 * time.Minute})
1523
1524func gofish(name string) string {
1525	if name[0] == '@' {
1526		name = name[1:]
1527	}
1528	var href string
1529	handfull.Get(name, &href)
1530	return href
1531}
1532
1533func investigate(name string) (*SomeThing, error) {
1534	if name == "" {
1535		return nil, fmt.Errorf("no name")
1536	}
1537	if name[0] == '@' {
1538		name = gofish(name)
1539	}
1540	if name == "" {
1541		return nil, fmt.Errorf("no name")
1542	}
1543	obj, err := GetJunkFast(name)
1544	if err != nil {
1545		return nil, err
1546	}
1547	allinjest(originate(name), obj)
1548	return somethingabout(obj)
1549}
1550
1551func somethingabout(obj junk.Junk) (*SomeThing, error) {
1552	info := new(SomeThing)
1553	t, _ := obj.GetString("type")
1554	switch t {
1555	case "Person":
1556		fallthrough
1557	case "Organization":
1558		fallthrough
1559	case "Application":
1560		fallthrough
1561	case "Service":
1562		info.What = SomeActor
1563	case "OrderedCollection":
1564		fallthrough
1565	case "Collection":
1566		info.What = SomeCollection
1567	default:
1568		return nil, fmt.Errorf("unknown object type")
1569	}
1570	info.XID, _ = obj.GetString("id")
1571	info.Name, _ = obj.GetString("preferredUsername")
1572	if info.Name == "" {
1573		info.Name, _ = obj.GetString("name")
1574	}
1575	info.Owner, _ = obj.GetString("attributedTo")
1576	if info.Owner == "" {
1577		info.Owner = info.XID
1578	}
1579	return info, nil
1580}
1581
1582func allinjest(origin string, obj junk.Junk) {
1583	keyobj, ok := obj.GetMap("publicKey")
1584	if ok {
1585		ingestpubkey(origin, keyobj)
1586	}
1587	ingestboxes(origin, obj)
1588	ingesthandle(origin, obj)
1589}
1590
1591func ingestpubkey(origin string, obj junk.Junk) {
1592	keyobj, ok := obj.GetMap("publicKey")
1593	if ok {
1594		obj = keyobj
1595	}
1596	keyname, ok := obj.GetString("id")
1597	var data string
1598	row := stmtGetXonker.QueryRow(keyname, "pubkey")
1599	err := row.Scan(&data)
1600	if err == nil {
1601		return
1602	}
1603	if !ok || origin != originate(keyname) {
1604		log.Printf("bad key origin %s <> %s", origin, keyname)
1605		return
1606	}
1607	log.Printf("ingesting a needed pubkey: %s", keyname)
1608	owner, ok := obj.GetString("owner")
1609	if !ok {
1610		log.Printf("error finding %s pubkey owner", keyname)
1611		return
1612	}
1613	data, ok = obj.GetString("publicKeyPem")
1614	if !ok {
1615		log.Printf("error finding %s pubkey", keyname)
1616		return
1617	}
1618	if originate(owner) != origin {
1619		log.Printf("bad key owner: %s <> %s", owner, origin)
1620		return
1621	}
1622	_, _, err = httpsig.DecodeKey(data)
1623	if err != nil {
1624		log.Printf("error decoding %s pubkey: %s", keyname, err)
1625		return
1626	}
1627	when := time.Now().UTC().Format(dbtimeformat)
1628	_, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1629	if err != nil {
1630		log.Printf("error saving key: %s", err)
1631	}
1632}
1633
1634func ingestboxes(origin string, obj junk.Junk) {
1635	ident, _ := obj.GetString("id")
1636	if ident == "" {
1637		return
1638	}
1639	if originate(ident) != origin {
1640		return
1641	}
1642	var info string
1643	row := stmtGetXonker.QueryRow(ident, "boxes")
1644	err := row.Scan(&info)
1645	if err == nil {
1646		return
1647	}
1648	log.Printf("ingesting boxes: %s", ident)
1649	inbox, _ := obj.GetString("inbox")
1650	outbox, _ := obj.GetString("outbox")
1651	sbox, _ := obj.GetString("endpoints", "sharedInbox")
1652	if inbox != "" {
1653		when := time.Now().UTC().Format(dbtimeformat)
1654		m := strings.Join([]string{inbox, outbox, sbox}, " ")
1655		_, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1656		if err != nil {
1657			log.Printf("error saving boxes: %s", err)
1658		}
1659	}
1660}
1661
1662func ingesthandle(origin string, obj junk.Junk) {
1663	xid, _ := obj.GetString("id")
1664	if xid == "" {
1665		return
1666	}
1667	if originate(xid) != origin {
1668		return
1669	}
1670	var handle string
1671	row := stmtGetXonker.QueryRow(xid, "handle")
1672	err := row.Scan(&handle)
1673	if err == nil {
1674		return
1675	}
1676	handle, _ = obj.GetString("preferredUsername")
1677	if handle != "" {
1678		when := time.Now().UTC().Format(dbtimeformat)
1679		_, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1680		if err != nil {
1681			log.Printf("error saving handle: %s", err)
1682		}
1683	}
1684}
1685
1686func updateMe(username string) {
1687	var user *WhatAbout
1688	somenamedusers.Get(username, &user)
1689	dt := time.Now().UTC().Format(time.RFC3339)
1690	j := junk.New()
1691	j["@context"] = itiswhatitis
1692	j["id"] = fmt.Sprintf("%s/upme/%s/%d", user.URL, user.Name, time.Now().Unix())
1693	j["actor"] = user.URL
1694	j["published"] = dt
1695	j["to"] = thewholeworld
1696	j["type"] = "Update"
1697	j["object"] = junkuser(user)
1698
1699	msg := j.ToBytes()
1700
1701	rcpts := make(map[string]bool)
1702	for _, f := range getdubs(user.ID) {
1703		if f.XID == user.URL {
1704			continue
1705		}
1706		var box *Box
1707		boxofboxes.Get(f.XID, &box)
1708		if box != nil && box.Shared != "" {
1709			rcpts["%"+box.Shared] = true
1710		} else {
1711			rcpts[f.XID] = true
1712		}
1713	}
1714	for a := range rcpts {
1715		go deliverate(0, user.ID, a, msg, false)
1716	}
1717}
1718
1719func followme(user *WhatAbout, who string, name string, j junk.Junk) {
1720	folxid, _ := j.GetString("id")
1721
1722	log.Printf("updating honker follow: %s %s", who, folxid)
1723
1724	var x string
1725	db := opendatabase()
1726	row := db.QueryRow("select xid from honkers where name = ? and xid = ? and userid = ? and flavor in ('dub', 'undub')", name, who, user.ID)
1727	err := row.Scan(&x)
1728	if err != sql.ErrNoRows {
1729		log.Printf("duplicate follow request: %s", who)
1730		_, err = stmtUpdateFlavor.Exec("dub", folxid, user.ID, name, who, "undub")
1731		if err != nil {
1732			log.Printf("error updating honker: %s", err)
1733		}
1734	} else {
1735		stmtSaveDub.Exec(user.ID, name, who, "dub", folxid)
1736	}
1737	go rubadubdub(user, j)
1738}
1739
1740func unfollowme(user *WhatAbout, who string, name string, j junk.Junk) {
1741	var folxid string
1742	if who == "" {
1743		folxid, _ = j.GetString("object")
1744
1745		db := opendatabase()
1746		row := db.QueryRow("select xid, name from honkers where userid = ? and folxid = ? and flavor in ('dub', 'undub')", user.ID, folxid)
1747		err := row.Scan(&who, &name)
1748		if err != nil {
1749			if err != sql.ErrNoRows {
1750				log.Printf("error scanning honker: %s", err)
1751			}
1752			return
1753		}
1754	}
1755
1756	log.Printf("updating honker undo: %s %s", who, folxid)
1757	_, err := stmtUpdateFlavor.Exec("undub", folxid, user.ID, name, who, "dub")
1758	if err != nil {
1759		log.Printf("error updating honker: %s", err)
1760		return
1761	}
1762}
1763
1764func followyou(user *WhatAbout, honkerid int64) {
1765	var url, owner string
1766	db := opendatabase()
1767	row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1768		honkerid, user.ID)
1769	err := row.Scan(&url, &owner)
1770	if err != nil {
1771		log.Printf("can't get honker xid: %s", err)
1772		return
1773	}
1774	folxid := xfiltrate()
1775	log.Printf("subscribing to %s", url)
1776	_, err = db.Exec("update honkers set flavor = ?, folxid = ? where honkerid = ?", "presub", folxid, honkerid)
1777	if err != nil {
1778		log.Printf("error updating honker: %s", err)
1779		return
1780	}
1781	go subsub(user, url, owner, folxid)
1782
1783}
1784func unfollowyou(user *WhatAbout, honkerid int64) {
1785	db := opendatabase()
1786	row := db.QueryRow("select xid, owner, folxid from honkers where honkerid = ? and userid = ? and flavor in ('sub')",
1787		honkerid, user.ID)
1788	var url, owner, folxid string
1789	err := row.Scan(&url, &owner, &folxid)
1790	if err != nil {
1791		log.Printf("can't get honker xid: %s", err)
1792		return
1793	}
1794	log.Printf("unsubscribing from %s", url)
1795	_, err = db.Exec("update honkers set flavor = ? where honkerid = ?", "unsub", honkerid)
1796	if err != nil {
1797		log.Printf("error updating honker: %s", err)
1798		return
1799	}
1800	go itakeitallback(user, url, owner, folxid)
1801}
1802
1803func followyou2(user *WhatAbout, j junk.Junk) {
1804	who, _ := j.GetString("actor")
1805
1806	log.Printf("updating honker accept: %s", who)
1807	db := opendatabase()
1808	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub')",
1809		user.ID, who)
1810	var name, folxid string
1811	err := row.Scan(&name, &folxid)
1812	if err != nil {
1813		log.Printf("can't get honker name: %s", err)
1814		return
1815	}
1816	_, err = stmtUpdateFlavor.Exec("sub", folxid, user.ID, name, who, "presub")
1817	if err != nil {
1818		log.Printf("error updating honker: %s", err)
1819		return
1820	}
1821}
1822
1823func nofollowyou2(user *WhatAbout, j junk.Junk) {
1824	who, _ := j.GetString("actor")
1825
1826	log.Printf("updating honker reject: %s", who)
1827	db := opendatabase()
1828	row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
1829		user.ID, who)
1830	var name, folxid string
1831	err := row.Scan(&name, &folxid)
1832	if err != nil {
1833		log.Printf("can't get honker name: %s", err)
1834		return
1835	}
1836	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "presub")
1837	_, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "sub")
1838	if err != nil {
1839		log.Printf("error updating honker: %s", err)
1840		return
1841	}
1842}