all repos — honk @ b5482facb8c28fb1fd14fb30ac3f18e734da0fe7

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