all repos — honk @ d9043d898ed2654a70442ed584ed76c8a236b5df

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