all repos — honk @ caa15d152605dadcb21036f5d2251b69124ee7cc

my fork of honk

activity.go (view raw)

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