all repos — honk @ ff67fc32e5ac9213e7ff1e7324be06f5642b5e69

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 len(tags) > 0 {
1065			jo["tag"] = tags
1066		}
1067		if p := h.Place; p != nil {
1068			t := junk.New()
1069			t["type"] = "Place"
1070			if p.Name != "" {
1071				t["name"] = p.Name
1072			}
1073			if p.Latitude != 0 {
1074				t["latitude"] = p.Latitude
1075			}
1076			if p.Longitude != 0 {
1077				t["longitude"] = p.Longitude
1078			}
1079			if p.Url != "" {
1080				t["url"] = p.Url
1081			}
1082			jo["location"] = t
1083		}
1084		if t := h.Time; t != nil {
1085			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1086			if t.Duration != 0 {
1087				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1088			}
1089		}
1090		var atts []junk.Junk
1091		for _, d := range h.Donks {
1092			if re_emus.MatchString(d.Name) {
1093				continue
1094			}
1095			jd := junk.New()
1096			jd["mediaType"] = d.Media
1097			jd["name"] = d.Name
1098			jd["summary"] = html.EscapeString(d.Desc)
1099			jd["type"] = "Document"
1100			jd["url"] = d.URL
1101			atts = append(atts, jd)
1102		}
1103		if len(atts) > 0 {
1104			jo["attachment"] = atts
1105		}
1106		j["object"] = jo
1107	case "bonk":
1108		j["type"] = "Announce"
1109		if h.Convoy != "" {
1110			j["context"] = h.Convoy
1111		}
1112		j["object"] = h.XID
1113	case "unbonk":
1114		b := junk.New()
1115		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1116		b["type"] = "Announce"
1117		b["actor"] = user.URL
1118		if h.Convoy != "" {
1119			b["context"] = h.Convoy
1120		}
1121		b["object"] = h.XID
1122		j["type"] = "Undo"
1123		j["object"] = b
1124	case "zonk":
1125		j["type"] = "Delete"
1126		j["object"] = h.XID
1127	case "ack":
1128		j["type"] = "Read"
1129		j["object"] = h.XID
1130		if h.Convoy != "" {
1131			j["context"] = h.Convoy
1132		}
1133	case "deack":
1134		b := junk.New()
1135		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1136		b["type"] = "Read"
1137		b["actor"] = user.URL
1138		b["object"] = h.XID
1139		if h.Convoy != "" {
1140			b["context"] = h.Convoy
1141		}
1142		j["type"] = "Undo"
1143		j["object"] = b
1144	}
1145
1146	return j, jo
1147}
1148
1149var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1150	row := stmtAnyXonk.QueryRow(xid)
1151	honk := scanhonk(row)
1152	if honk == nil || !honk.Public {
1153		return nil, true
1154	}
1155	user, _ := butwhatabout(honk.Username)
1156	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1157	reversehonks(rawhonks)
1158	for _, h := range rawhonks {
1159		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1160			honk.Replies = append(honk.Replies, h)
1161		}
1162	}
1163	donksforhonks([]*Honk{honk})
1164	_, j := jonkjonk(user, honk)
1165	j["@context"] = itiswhatitis
1166
1167	return j.ToBytes(), true
1168}})
1169
1170func gimmejonk(xid string) ([]byte, bool) {
1171	var j []byte
1172	ok := oldjonks.Get(xid, &j)
1173	return j, ok
1174}
1175
1176func honkworldwide(user *WhatAbout, honk *Honk) {
1177	jonk, _ := jonkjonk(user, honk)
1178	jonk["@context"] = itiswhatitis
1179	msg := jonk.ToBytes()
1180
1181	rcpts := make(map[string]bool)
1182	for _, a := range honk.Audience {
1183		if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1184			continue
1185		}
1186		var box *Box
1187		ok := boxofboxes.Get(a, &box)
1188		if ok && honk.Public && box.Shared != "" {
1189			rcpts["%"+box.Shared] = true
1190		} else {
1191			rcpts[a] = true
1192		}
1193	}
1194	if honk.Public {
1195		for _, h := range getdubs(user.ID) {
1196			if h.XID == user.URL {
1197				continue
1198			}
1199			var box *Box
1200			ok := boxofboxes.Get(h.XID, &box)
1201			if ok && box.Shared != "" {
1202				rcpts["%"+box.Shared] = true
1203			} else {
1204				rcpts[h.XID] = true
1205			}
1206		}
1207	}
1208	for a := range rcpts {
1209		go deliverate(0, user.ID, a, msg)
1210	}
1211	if honk.Public && len(honk.Onts) > 0 {
1212		collectiveaction(honk)
1213	}
1214}
1215
1216func collectiveaction(honk *Honk) {
1217	user := getserveruser()
1218	for _, ont := range honk.Onts {
1219		dubs := getnameddubs(serverUID, ont)
1220		if len(dubs) == 0 {
1221			continue
1222		}
1223		j := junk.New()
1224		j["@context"] = itiswhatitis
1225		j["type"] = "Add"
1226		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1227		j["actor"] = user.URL
1228		j["object"] = honk.XID
1229		j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1230		rcpts := make(map[string]bool)
1231		for _, dub := range dubs {
1232			var box *Box
1233			ok := boxofboxes.Get(dub.XID, &box)
1234			if ok && box.Shared != "" {
1235				rcpts["%"+box.Shared] = true
1236			} else {
1237				rcpts[dub.XID] = true
1238			}
1239		}
1240		msg := j.ToBytes()
1241		for a := range rcpts {
1242			go deliverate(0, user.ID, a, msg)
1243		}
1244	}
1245}
1246
1247func junkuser(user *WhatAbout) []byte {
1248	about := markitzero(user.About)
1249
1250	j := junk.New()
1251	j["@context"] = itiswhatitis
1252	j["id"] = user.URL
1253	j["inbox"] = user.URL + "/inbox"
1254	j["outbox"] = user.URL + "/outbox"
1255	j["name"] = user.Display
1256	j["preferredUsername"] = user.Name
1257	j["summary"] = about
1258	if user.ID > 0 {
1259		j["type"] = "Person"
1260		j["url"] = user.URL
1261		j["followers"] = user.URL + "/followers"
1262		j["following"] = user.URL + "/following"
1263		a := junk.New()
1264		a["type"] = "Image"
1265		a["mediaType"] = "image/png"
1266		if ava := user.Options.Avatar; ava != "" {
1267			a["url"] = ava
1268		} else {
1269			a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1270		}
1271		j["icon"] = a
1272	} else {
1273		j["type"] = "Service"
1274	}
1275	k := junk.New()
1276	k["id"] = user.URL + "#key"
1277	k["owner"] = user.URL
1278	k["publicKeyPem"] = user.Key
1279	j["publicKey"] = k
1280
1281	return j.ToBytes()
1282}
1283
1284var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1285	user, err := butwhatabout(name)
1286	if err != nil {
1287		return nil, false
1288	}
1289	return junkuser(user), true
1290}, Duration: 1 * time.Minute})
1291
1292func asjonker(name string) ([]byte, bool) {
1293	var j []byte
1294	ok := oldjonkers.Get(name, &j)
1295	return j, ok
1296}
1297
1298var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1299	m := strings.Split(name, "@")
1300	if len(m) != 2 {
1301		log.Printf("bad fish name: %s", name)
1302		return "", true
1303	}
1304	row := stmtGetXonker.QueryRow(name, "fishname")
1305	var href string
1306	err := row.Scan(&href)
1307	if err == nil {
1308		return href, true
1309	}
1310	log.Printf("fishing for %s", name)
1311	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1312	if err != nil {
1313		log.Printf("failed to go fish %s: %s", name, err)
1314		return "", true
1315	}
1316	links, _ := j.GetArray("links")
1317	for _, li := range links {
1318		l, ok := li.(junk.Junk)
1319		if !ok {
1320			continue
1321		}
1322		href, _ := l.GetString("href")
1323		rel, _ := l.GetString("rel")
1324		t, _ := l.GetString("type")
1325		if rel == "self" && friendorfoe(t) {
1326			_, err := stmtSaveXonker.Exec(name, href, "fishname")
1327			if err != nil {
1328				log.Printf("error saving fishname: %s", err)
1329			}
1330			return href, true
1331		}
1332	}
1333	return href, true
1334}})
1335
1336func gofish(name string) string {
1337	if name[0] == '@' {
1338		name = name[1:]
1339	}
1340	var href string
1341	handfull.Get(name, &href)
1342	return href
1343}
1344
1345func investigate(name string) (*SomeThing, error) {
1346	if name == "" {
1347		return nil, fmt.Errorf("no name")
1348	}
1349	if name[0] == '@' {
1350		name = gofish(name)
1351	}
1352	if name == "" {
1353		return nil, fmt.Errorf("no name")
1354	}
1355	obj, err := GetJunkFast(name)
1356	if err != nil {
1357		return nil, err
1358	}
1359	return somethingabout(obj)
1360}
1361
1362func somethingabout(obj junk.Junk) (*SomeThing, error) {
1363	info := new(SomeThing)
1364	t, _ := obj.GetString("type")
1365	switch t {
1366	case "Person":
1367		fallthrough
1368	case "Organization":
1369		fallthrough
1370	case "Application":
1371		fallthrough
1372	case "Service":
1373		info.What = SomeActor
1374	case "OrderedCollection":
1375		fallthrough
1376	case "Collection":
1377		info.What = SomeCollection
1378	default:
1379		return nil, fmt.Errorf("unknown object type")
1380	}
1381	info.XID, _ = obj.GetString("id")
1382	info.Name, _ = obj.GetString("preferredUsername")
1383	if info.Name == "" {
1384		info.Name, _ = obj.GetString("name")
1385	}
1386	info.Owner, _ = obj.GetString("attributedTo")
1387	if info.Owner == "" {
1388		info.Owner = info.XID
1389	}
1390	return info, nil
1391}