all repos — honk @ 9c7f3569ee2cfcd7848912430f150f30c97f375c

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