all repos — honk @ f39d99994461c4f0b350b29b38008a98b674c8af

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			obj, ok := j.GetMap("first")
 300			if ok {
 301				items, _ = obj.GetArray("orderedItems")
 302			} else {
 303				page1, _ := j.GetString("first")
 304				j, err = GetJunk(page1)
 305				if err != nil {
 306					log.Printf("error gettings page1: %s", err)
 307					return
 308				}
 309				items, _ = j.GetArray("orderedItems")
 310			}
 311		}
 312		if len(items) > 20 {
 313			items = items[0:20]
 314		}
 315		for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
 316			items[i], items[j] = items[j], items[i]
 317		}
 318		for _, item := range items {
 319			obj, ok := item.(junk.Junk)
 320			if !ok {
 321				continue
 322			}
 323			xonksaver(user, obj, origin)
 324		}
 325	}
 326}
 327
 328func peeppeep() {
 329	user, _ := butwhatabout("htest")
 330	honkers := gethonkers(user.ID)
 331	for _, f := range honkers {
 332		if f.Flavor != "peep" {
 333			continue
 334		}
 335		log.Printf("getting updates: %s", f.XID)
 336		var box *Box
 337		ok := boxofboxes.Get(f.XID, &box)
 338		if !ok {
 339			log.Printf("error getting outbox")
 340			continue
 341		}
 342		gimmexonks(user, box.Out)
 343	}
 344}
 345func whosthere(xid string) ([]string, string) {
 346	obj, err := GetJunk(xid)
 347	if err != nil {
 348		log.Printf("error getting remote xonk: %s", err)
 349		return nil, ""
 350	}
 351	convoy, _ := obj.GetString("context")
 352	if convoy == "" {
 353		convoy, _ = obj.GetString("conversation")
 354	}
 355	return newphone(nil, obj), convoy
 356}
 357
 358func newphone(a []string, obj junk.Junk) []string {
 359	for _, addr := range []string{"to", "cc", "attributedTo"} {
 360		who, _ := obj.GetString(addr)
 361		if who != "" {
 362			a = append(a, who)
 363		}
 364		whos, _ := obj.GetArray(addr)
 365		for _, w := range whos {
 366			who, _ := w.(string)
 367			if who != "" {
 368				a = append(a, who)
 369			}
 370		}
 371	}
 372	return a
 373}
 374
 375func extractattrto(obj junk.Junk) string {
 376	who, _ := obj.GetString("attributedTo")
 377	if who != "" {
 378		return who
 379	}
 380	o, ok := obj.GetMap("attributedTo")
 381	if ok {
 382		id, ok := o.GetString("id")
 383		if ok {
 384			return id
 385		}
 386	}
 387	arr, _ := obj.GetArray("attributedTo")
 388	for _, a := range arr {
 389		o, ok := a.(junk.Junk)
 390		if ok {
 391			t, _ := o.GetString("type")
 392			id, _ := o.GetString("id")
 393			if t == "Person" || t == "" {
 394				return id
 395			}
 396		}
 397		s, ok := a.(string)
 398		if ok {
 399			return s
 400		}
 401	}
 402	return ""
 403}
 404
 405func xonksaver(user *WhatAbout, item junk.Junk, origin string) *Honk {
 406	depth := 0
 407	maxdepth := 10
 408	currenttid := ""
 409	goingup := 0
 410	var xonkxonkfn func(item junk.Junk, origin string) *Honk
 411
 412	saveonemore := func(xid string) {
 413		log.Printf("getting onemore: %s", xid)
 414		if depth >= maxdepth {
 415			log.Printf("in too deep")
 416			return
 417		}
 418		obj, err := GetJunkHardMode(xid)
 419		if err != nil {
 420			log.Printf("error getting onemore: %s: %s", xid, err)
 421			return
 422		}
 423		depth++
 424		xonkxonkfn(obj, originate(xid))
 425		depth--
 426	}
 427
 428	xonkxonkfn = func(item junk.Junk, origin string) *Honk {
 429		// id, _ := item.GetString( "id")
 430		what, _ := item.GetString("type")
 431		dt, _ := item.GetString("published")
 432
 433		var err error
 434		var xid, rid, url, content, precis, convoy string
 435		var replies []string
 436		var obj junk.Junk
 437		var ok bool
 438		isUpdate := false
 439		switch what {
 440		case "Delete":
 441			obj, ok = item.GetMap("object")
 442			if ok {
 443				xid, _ = obj.GetString("id")
 444			} else {
 445				xid, _ = item.GetString("object")
 446			}
 447			if xid == "" {
 448				return nil
 449			}
 450			if originate(xid) != origin {
 451				log.Printf("forged delete: %s", xid)
 452				return nil
 453			}
 454			log.Printf("eradicating %s", xid)
 455			eradicatexonk(user.ID, xid)
 456			return nil
 457		case "Tombstone":
 458			xid, _ = item.GetString("id")
 459			if xid == "" {
 460				return nil
 461			}
 462			if originate(xid) != origin {
 463				log.Printf("forged delete: %s", xid)
 464				return nil
 465			}
 466			log.Printf("eradicating %s", xid)
 467			eradicatexonk(user.ID, xid)
 468			return nil
 469		case "Announce":
 470			obj, ok = item.GetMap("object")
 471			if ok {
 472				xid, _ = obj.GetString("id")
 473			} else {
 474				xid, _ = item.GetString("object")
 475			}
 476			if !needxonkid(user, xid) {
 477				return nil
 478			}
 479			log.Printf("getting bonk: %s", xid)
 480			obj, err = GetJunkHardMode(xid)
 481			if err != nil {
 482				log.Printf("error getting bonk: %s: %s", xid, err)
 483			}
 484			origin = originate(xid)
 485			what = "bonk"
 486		case "Update":
 487			isUpdate = true
 488			fallthrough
 489		case "Create":
 490			obj, ok = item.GetMap("object")
 491			if !ok {
 492				xid, _ = item.GetString("object")
 493				log.Printf("getting created honk: %s", xid)
 494				obj, err = GetJunkHardMode(xid)
 495				if err != nil {
 496					log.Printf("error getting creation: %s", err)
 497				}
 498			}
 499			what = "honk"
 500		case "Read":
 501			xid, ok = item.GetString("object")
 502			if ok {
 503				if !needxonkid(user, xid) {
 504					log.Printf("don't need read obj: %s", xid)
 505					return nil
 506				}
 507				obj, err = GetJunkHardMode(xid)
 508				if err != nil {
 509					log.Printf("error getting read: %s", err)
 510					return nil
 511				}
 512				return xonkxonkfn(obj, originate(xid))
 513			}
 514			return nil
 515		case "Audio":
 516			fallthrough
 517		case "Video":
 518			fallthrough
 519		case "Question":
 520			fallthrough
 521		case "Note":
 522			fallthrough
 523		case "Article":
 524			fallthrough
 525		case "Page":
 526			obj = item
 527			what = "honk"
 528		case "Event":
 529			obj = item
 530			what = "event"
 531		default:
 532			log.Printf("unknown activity: %s", what)
 533			fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 534			item.Write(fd)
 535			io.WriteString(fd, "\n")
 536			fd.Close()
 537			return nil
 538		}
 539
 540		if obj != nil {
 541			_, ok := obj.GetString("diaspora:guid")
 542			if ok {
 543				log.Printf("looks like friendica")
 544				// friendica does the silliest bonks
 545				c, ok := obj.FindString([]string{"source", "content"})
 546				if ok {
 547					log.Printf("got content")
 548					re_link := regexp.MustCompile(`link='([^']*)'`)
 549					m := re_link.FindStringSubmatch(c)
 550					if len(m) > 1 {
 551						xid := m[1]
 552						log.Printf("getting friendica flavored bonk: %s", xid)
 553						if !needxonkid(user, xid) {
 554							return nil
 555						}
 556						newobj, err := GetJunkHardMode(xid)
 557						if err != nil {
 558							log.Printf("error getting bonk: %s: %s", xid, err)
 559						} else {
 560							obj = newobj
 561							origin = originate(xid)
 562							what = "bonk"
 563						}
 564					} else {
 565						log.Printf("can't find link")
 566					}
 567				} else {
 568					log.Printf("no source content")
 569				}
 570			}
 571		}
 572
 573		var xonk Honk
 574		// early init
 575		xonk.UserID = user.ID
 576		xonk.Honker, _ = item.GetString("actor")
 577		if xonk.Honker == "" {
 578			xonk.Honker, _ = item.GetString("attributedTo")
 579		}
 580		if obj != nil {
 581			if xonk.Honker == "" {
 582				xonk.Honker = extractattrto(obj)
 583			}
 584			xonk.Oonker = extractattrto(obj)
 585			if xonk.Oonker == xonk.Honker {
 586				xonk.Oonker = ""
 587			}
 588			xonk.Audience = newphone(nil, obj)
 589		}
 590		xonk.Audience = append(xonk.Audience, xonk.Honker)
 591		xonk.Audience = oneofakind(xonk.Audience)
 592		for _, a := range xonk.Audience {
 593			if a == user.URL {
 594				xonk.Whofore = 1
 595			}
 596		}
 597
 598		if obj != nil {
 599			ot, _ := obj.GetString("type")
 600			url, _ = obj.GetString("url")
 601			dt2, ok := obj.GetString("published")
 602			if ok {
 603				dt = dt2
 604			}
 605			xid, _ = obj.GetString("id")
 606			precis, _ = obj.GetString("summary")
 607			if precis == "" {
 608				precis, _ = obj.GetString("name")
 609			}
 610			content, _ = obj.GetString("content")
 611			if !strings.HasPrefix(content, "<p>") {
 612				content = "<p>" + content
 613			}
 614			sens, _ := obj["sensitive"].(bool)
 615			if sens && precis == "" {
 616				precis = "unspecified horror"
 617			}
 618			rid, ok = obj.GetString("inReplyTo")
 619			if !ok {
 620				robj, ok := obj.GetMap("inReplyTo")
 621				if ok {
 622					rid, _ = robj.GetString("id")
 623				}
 624			}
 625			convoy, _ = obj.GetString("context")
 626			if strings.HasSuffix(convoy, "#context") &&
 627				originate(convoy) != originate(xid) {
 628				// friendica...
 629				convoy = ""
 630			}
 631			if convoy == "" {
 632				convoy, _ = obj.GetString("conversation")
 633			}
 634			if ot == "Question" {
 635				if what == "honk" {
 636					what = "qonk"
 637				}
 638				content += "<ul>"
 639				ans, _ := obj.GetArray("oneOf")
 640				for _, ai := range ans {
 641					a, ok := ai.(junk.Junk)
 642					if !ok {
 643						continue
 644					}
 645					as, _ := a.GetString("name")
 646					content += "<li>" + as
 647				}
 648				ans, _ = obj.GetArray("anyOf")
 649				for _, ai := range ans {
 650					a, ok := ai.(junk.Junk)
 651					if !ok {
 652						continue
 653					}
 654					as, _ := a.GetString("name")
 655					content += "<li>" + as
 656				}
 657				content += "</ul>"
 658			}
 659			if what == "honk" && rid != "" {
 660				what = "tonk"
 661			}
 662			atts, _ := obj.GetArray("attachment")
 663			for i, atti := range atts {
 664				att, ok := atti.(junk.Junk)
 665				if !ok {
 666					continue
 667				}
 668				at, _ := att.GetString("type")
 669				mt, _ := att.GetString("mediaType")
 670				u, _ := att.GetString("url")
 671				name, _ := att.GetString("name")
 672				desc, _ := att.GetString("summary")
 673				if desc == "" {
 674					desc = name
 675				}
 676				localize := false
 677				if i > 4 {
 678					log.Printf("excessive attachment: %s", at)
 679				} else if at == "Document" || at == "Image" {
 680					mt = strings.ToLower(mt)
 681					log.Printf("attachment: %s %s", mt, u)
 682					if mt == "text/plain" || strings.HasPrefix(mt, "image") {
 683						localize = true
 684					}
 685				} else {
 686					log.Printf("unknown attachment: %s", at)
 687				}
 688				if skipMedia(&xonk) {
 689					localize = false
 690				}
 691				donk := savedonk(u, name, desc, mt, localize)
 692				if donk != nil {
 693					xonk.Donks = append(xonk.Donks, donk)
 694				}
 695			}
 696			tags, _ := obj.GetArray("tag")
 697			for _, tagi := range tags {
 698				tag, ok := tagi.(junk.Junk)
 699				if !ok {
 700					continue
 701				}
 702				tt, _ := tag.GetString("type")
 703				name, _ := tag.GetString("name")
 704				desc, _ := tag.GetString("summary")
 705				if desc == "" {
 706					desc = name
 707				}
 708				if tt == "Emoji" {
 709					icon, _ := tag.GetMap("icon")
 710					mt, _ := icon.GetString("mediaType")
 711					if mt == "" {
 712						mt = "image/png"
 713					}
 714					u, _ := icon.GetString("url")
 715					donk := savedonk(u, name, desc, mt, true)
 716					if donk != nil {
 717						xonk.Donks = append(xonk.Donks, donk)
 718					}
 719				}
 720				if tt == "Hashtag" {
 721					if name == "" || name == "#" {
 722						// skip it
 723					} else {
 724						if name[0] != '#' {
 725							name = "#" + name
 726						}
 727						xonk.Onts = append(xonk.Onts, name)
 728					}
 729				}
 730				if tt == "Place" {
 731					p := new(Place)
 732					p.Name = name
 733					p.Latitude, _ = tag["latitude"].(float64)
 734					p.Longitude, _ = tag["longitude"].(float64)
 735					p.Url, _ = tag.GetString("url")
 736					xonk.Place = p
 737				}
 738			}
 739			starttime, ok := obj.GetString("startTime")
 740			if ok {
 741				start, err := time.Parse(time.RFC3339, starttime)
 742				if err == nil {
 743					t := new(Time)
 744					t.StartTime = start
 745					endtime, _ := obj.GetString("endTime")
 746					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
 747					dura, _ := obj.GetString("duration")
 748					if strings.HasPrefix(dura, "PT") {
 749						dura = strings.ToLower(dura[2:])
 750						d, _ := time.ParseDuration(dura)
 751						t.Duration = Duration(d)
 752					}
 753					xonk.Time = t
 754				}
 755			}
 756			loca, ok := obj.GetMap("location")
 757			if ok {
 758				tt, _ := loca.GetString("type")
 759				name, _ := loca.GetString("name")
 760				if tt == "Place" {
 761					p := new(Place)
 762					p.Name = name
 763					p.Latitude, _ = loca["latitude"].(float64)
 764					p.Longitude, _ = loca["longitude"].(float64)
 765					p.Url, _ = loca.GetString("url")
 766					xonk.Place = p
 767				}
 768			}
 769
 770			xonk.Onts = oneofakind(xonk.Onts)
 771			replyobj, ok := obj.GetMap("replies")
 772			if ok {
 773				items, ok := replyobj.GetArray("items")
 774				if !ok {
 775					first, ok := replyobj.GetMap("first")
 776					if ok {
 777						items, _ = first.GetArray("items")
 778					}
 779				}
 780				for _, repl := range items {
 781					s, ok := repl.(string)
 782					if ok {
 783						replies = append(replies, s)
 784					}
 785				}
 786			}
 787
 788		}
 789		if originate(xid) != origin {
 790			log.Printf("original sin: %s <> %s", xid, origin)
 791			item.Write(os.Stdout)
 792			return nil
 793		}
 794
 795		if currenttid == "" {
 796			currenttid = convoy
 797		}
 798
 799		if len(content) > 90001 {
 800			log.Printf("content too long. truncating")
 801			content = content[:90001]
 802		}
 803
 804		// grab any inline imgs
 805		imgfilt := htfilter.New()
 806		imgfilt.Imager = inlineimgs
 807		imgfilt.String(content)
 808
 809		// init xonk
 810		xonk.What = what
 811		xonk.XID = xid
 812		xonk.RID = rid
 813		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 814		xonk.URL = url
 815		xonk.Noise = content
 816		xonk.Precis = precis
 817		xonk.Format = "html"
 818		xonk.Convoy = convoy
 819
 820		if isUpdate {
 821			log.Printf("something has changed! %s", xonk.XID)
 822			prev := getxonk(user.ID, xonk.XID)
 823			if prev == nil {
 824				log.Printf("didn't find old version for update: %s", xonk.XID)
 825				return nil
 826			}
 827			prev.Noise = xonk.Noise
 828			prev.Precis = xonk.Precis
 829			prev.Date = xonk.Date
 830			prev.Donks = xonk.Donks
 831			prev.Onts = xonk.Onts
 832			prev.Place = xonk.Place
 833			updatehonk(prev)
 834		} else if needxonk(user, &xonk) {
 835			if rid != "" {
 836				if needxonkid(user, rid) {
 837					goingup++
 838					saveonemore(rid)
 839					goingup--
 840				}
 841				if convoy == "" {
 842					xx := getxonk(user.ID, rid)
 843					if xx != nil {
 844						convoy = xx.Convoy
 845					}
 846				}
 847			}
 848			if convoy == "" {
 849				convoy = currenttid
 850			}
 851			if convoy == "" {
 852				convoy = "missing-" + xfiltrate()
 853				currenttid = convoy
 854			}
 855			xonk.Convoy = convoy
 856			savexonk(&xonk)
 857		}
 858		if goingup == 0 {
 859			for _, replid := range replies {
 860				if needxonkid(user, replid) {
 861					log.Printf("missing a reply: %s", replid)
 862					saveonemore(replid)
 863				}
 864			}
 865		}
 866		return &xonk
 867	}
 868
 869	return xonkxonkfn(item, origin)
 870}
 871
 872func rubadubdub(user *WhatAbout, req junk.Junk) {
 873	xid, _ := req.GetString("id")
 874	actor, _ := req.GetString("actor")
 875	j := junk.New()
 876	j["@context"] = itiswhatitis
 877	j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
 878	j["type"] = "Accept"
 879	j["actor"] = user.URL
 880	j["to"] = actor
 881	j["published"] = time.Now().UTC().Format(time.RFC3339)
 882	j["object"] = req
 883
 884	var buf bytes.Buffer
 885	j.Write(&buf)
 886	msg := buf.Bytes()
 887
 888	deliverate(0, user.Name, actor, msg)
 889}
 890
 891func itakeitallback(user *WhatAbout, xid string) {
 892	j := junk.New()
 893	j["@context"] = itiswhatitis
 894	j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
 895	j["type"] = "Undo"
 896	j["actor"] = user.URL
 897	j["to"] = xid
 898	f := junk.New()
 899	f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 900	f["type"] = "Follow"
 901	f["actor"] = user.URL
 902	f["to"] = xid
 903	f["object"] = xid
 904	j["object"] = f
 905	j["published"] = time.Now().UTC().Format(time.RFC3339)
 906
 907	var buf bytes.Buffer
 908	j.Write(&buf)
 909	msg := buf.Bytes()
 910
 911	deliverate(0, user.Name, xid, msg)
 912}
 913
 914func subsub(user *WhatAbout, xid string) {
 915	if xid == "" {
 916		log.Printf("can't subscribe to empty")
 917		return
 918	}
 919	j := junk.New()
 920	j["@context"] = itiswhatitis
 921	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 922	j["type"] = "Follow"
 923	j["actor"] = user.URL
 924	j["to"] = xid
 925	j["object"] = xid
 926	j["published"] = time.Now().UTC().Format(time.RFC3339)
 927
 928	var buf bytes.Buffer
 929	j.Write(&buf)
 930	msg := buf.Bytes()
 931
 932	deliverate(0, user.Name, xid, msg)
 933}
 934
 935// returns activity, object
 936func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 937	dt := h.Date.Format(time.RFC3339)
 938	var jo junk.Junk
 939	j := junk.New()
 940	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 941	j["actor"] = user.URL
 942	j["published"] = dt
 943	if h.Public {
 944		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
 945	} else {
 946		j["to"] = h.Audience[0]
 947	}
 948	if len(h.Audience) > 1 {
 949		j["cc"] = h.Audience[1:]
 950	}
 951
 952	switch h.What {
 953	case "update":
 954		fallthrough
 955	case "tonk":
 956		fallthrough
 957	case "event":
 958		fallthrough
 959	case "honk":
 960		j["type"] = "Create"
 961		if h.What == "update" {
 962			j["type"] = "Update"
 963		}
 964
 965		jo = junk.New()
 966		jo["id"] = h.XID
 967		jo["type"] = "Note"
 968		if h.What == "event" {
 969			jo["type"] = "Event"
 970		}
 971		jo["published"] = dt
 972		jo["url"] = h.XID
 973		jo["attributedTo"] = user.URL
 974		if h.RID != "" {
 975			jo["inReplyTo"] = h.RID
 976		}
 977		if h.Convoy != "" {
 978			jo["context"] = h.Convoy
 979			jo["conversation"] = h.Convoy
 980		}
 981		jo["to"] = h.Audience[0]
 982		if len(h.Audience) > 1 {
 983			jo["cc"] = h.Audience[1:]
 984		}
 985		if !h.Public {
 986			jo["directMessage"] = true
 987		}
 988		translate(h)
 989		h.Noise = re_memes.ReplaceAllString(h.Noise, "")
 990		jo["summary"] = html.EscapeString(h.Precis)
 991		jo["content"] = ontologize(mentionize(h.Noise))
 992		if strings.HasPrefix(h.Precis, "DZ:") {
 993			jo["sensitive"] = true
 994		}
 995
 996		var replies []string
 997		for _, reply := range h.Replies {
 998			replies = append(replies, reply.XID)
 999		}
1000		if len(replies) > 0 {
1001			jr := junk.New()
1002			jr["type"] = "Collection"
1003			jr["totalItems"] = len(replies)
1004			jr["items"] = replies
1005			jo["replies"] = jr
1006		}
1007
1008		var tags []junk.Junk
1009		g := bunchofgrapes(h.Noise)
1010		for _, m := range g {
1011			t := junk.New()
1012			t["type"] = "Mention"
1013			t["name"] = m.who
1014			t["href"] = m.where
1015			tags = append(tags, t)
1016		}
1017		for _, o := range h.Onts {
1018			t := junk.New()
1019			t["type"] = "Hashtag"
1020			o = strings.ToLower(o)
1021			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1022			t["name"] = o
1023			tags = append(tags, t)
1024		}
1025		herd := herdofemus(h.Noise)
1026		for _, e := range herd {
1027			t := junk.New()
1028			t["id"] = e.ID
1029			t["type"] = "Emoji"
1030			t["name"] = e.Name
1031			i := junk.New()
1032			i["type"] = "Image"
1033			i["mediaType"] = "image/png"
1034			i["url"] = e.ID
1035			t["icon"] = i
1036			tags = append(tags, t)
1037		}
1038		if p := h.Place; p != nil {
1039			t := junk.New()
1040			t["type"] = "Place"
1041			t["name"] = p.Name
1042			t["latitude"] = p.Latitude
1043			t["longitude"] = p.Longitude
1044			t["url"] = p.Url
1045			if h.What == "event" {
1046				jo["location"] = t
1047			} else {
1048				tags = append(tags, t)
1049			}
1050		}
1051		if len(tags) > 0 {
1052			jo["tag"] = tags
1053		}
1054		if t := h.Time; t != nil {
1055			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1056			if t.Duration != 0 {
1057				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1058			}
1059		}
1060		var atts []junk.Junk
1061		for _, d := range h.Donks {
1062			if re_emus.MatchString(d.Name) {
1063				continue
1064			}
1065			jd := junk.New()
1066			jd["mediaType"] = d.Media
1067			jd["name"] = d.Name
1068			jd["summary"] = html.EscapeString(d.Desc)
1069			jd["type"] = "Document"
1070			jd["url"] = d.URL
1071			atts = append(atts, jd)
1072		}
1073		if len(atts) > 0 {
1074			jo["attachment"] = atts
1075		}
1076		j["object"] = jo
1077	case "bonk":
1078		j["type"] = "Announce"
1079		if h.Convoy != "" {
1080			j["context"] = h.Convoy
1081		}
1082		j["object"] = h.XID
1083	case "unbonk":
1084		b := junk.New()
1085		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1086		b["type"] = "Announce"
1087		b["actor"] = user.URL
1088		if h.Convoy != "" {
1089			b["context"] = h.Convoy
1090		}
1091		b["object"] = h.XID
1092		j["type"] = "Undo"
1093		j["object"] = b
1094	case "zonk":
1095		j["type"] = "Delete"
1096		j["object"] = h.XID
1097	case "ack":
1098		j["type"] = "Read"
1099		j["object"] = h.XID
1100	case "deack":
1101		b := junk.New()
1102		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1103		b["type"] = "Read"
1104		b["actor"] = user.URL
1105		b["object"] = h.XID
1106		j["type"] = "Undo"
1107		j["object"] = b
1108	}
1109
1110	return j, jo
1111}
1112
1113var oldjonks = cacheNew(cacheOptions{Filler: func(xid string) ([]byte, bool) {
1114	row := stmtAnyXonk.QueryRow(xid)
1115	honk := scanhonk(row)
1116	if honk == nil || !honk.Public {
1117		return nil, true
1118	}
1119	user, _ := butwhatabout(honk.Username)
1120	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
1121	reversehonks(rawhonks)
1122	for _, h := range rawhonks {
1123		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1124			honk.Replies = append(honk.Replies, h)
1125		}
1126	}
1127	donksforhonks([]*Honk{honk})
1128	_, j := jonkjonk(user, honk)
1129	j["@context"] = itiswhatitis
1130	var buf bytes.Buffer
1131	j.Write(&buf)
1132	return buf.Bytes(), true
1133}})
1134
1135func gimmejonk(xid string) ([]byte, bool) {
1136	var j []byte
1137	ok := oldjonks.Get(xid, &j)
1138	return j, ok
1139}
1140
1141func honkworldwide(user *WhatAbout, honk *Honk) {
1142	jonk, _ := jonkjonk(user, honk)
1143	jonk["@context"] = itiswhatitis
1144	var buf bytes.Buffer
1145	jonk.Write(&buf)
1146	msg := buf.Bytes()
1147
1148	rcpts := make(map[string]bool)
1149	for _, a := range honk.Audience {
1150		if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1151			continue
1152		}
1153		var box *Box
1154		ok := boxofboxes.Get(a, &box)
1155		if ok && honk.Public && box.Shared != "" {
1156			rcpts["%"+box.Shared] = true
1157		} else {
1158			rcpts[a] = true
1159		}
1160	}
1161	if honk.Public {
1162		for _, f := range getdubs(user.ID) {
1163			if f.XID == user.URL {
1164				continue
1165			}
1166			var box *Box
1167			ok := boxofboxes.Get(f.XID, &box)
1168			if ok && box.Shared != "" {
1169				rcpts["%"+box.Shared] = true
1170			} else {
1171				rcpts[f.XID] = true
1172			}
1173		}
1174	}
1175	for a := range rcpts {
1176		go deliverate(0, user.Name, a, msg)
1177	}
1178}
1179
1180var oldjonkers = cacheNew(cacheOptions{Filler: func(name string) ([]byte, bool) {
1181	user, err := butwhatabout(name)
1182	if err != nil {
1183		return nil, false
1184	}
1185	about := markitzero(user.About)
1186
1187	j := junk.New()
1188	j["@context"] = itiswhatitis
1189	j["id"] = user.URL
1190	j["type"] = "Person"
1191	j["inbox"] = user.URL + "/inbox"
1192	j["outbox"] = user.URL + "/outbox"
1193	j["followers"] = user.URL + "/followers"
1194	j["following"] = user.URL + "/following"
1195	j["name"] = user.Display
1196	j["preferredUsername"] = user.Name
1197	j["summary"] = about
1198	j["url"] = user.URL
1199	a := junk.New()
1200	a["type"] = "Image"
1201	a["mediaType"] = "image/png"
1202	a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1203	j["icon"] = a
1204	k := junk.New()
1205	k["id"] = user.URL + "#key"
1206	k["owner"] = user.URL
1207	k["publicKeyPem"] = user.Key
1208	j["publicKey"] = k
1209
1210	var buf bytes.Buffer
1211	j.Write(&buf)
1212	return buf.Bytes(), true
1213}, Duration: 1 * time.Minute})
1214
1215func asjonker(name string) ([]byte, bool) {
1216	var j []byte
1217	ok := oldjonkers.Get(name, &j)
1218	return j, ok
1219}
1220
1221var handfull = cacheNew(cacheOptions{Filler: func(name string) (string, bool) {
1222	m := strings.Split(name, "@")
1223	if len(m) != 2 {
1224		log.Printf("bad fish name: %s", name)
1225		return "", true
1226	}
1227	row := stmtGetXonker.QueryRow(name, "fishname")
1228	var href string
1229	err := row.Scan(&href)
1230	if err == nil {
1231		return href, true
1232	}
1233	log.Printf("fishing for %s", name)
1234	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1235	if err != nil {
1236		log.Printf("failed to go fish %s: %s", name, err)
1237		return "", true
1238	}
1239	links, _ := j.GetArray("links")
1240	for _, li := range links {
1241		l, ok := li.(junk.Junk)
1242		if !ok {
1243			continue
1244		}
1245		href, _ := l.GetString("href")
1246		rel, _ := l.GetString("rel")
1247		t, _ := l.GetString("type")
1248		if rel == "self" && friendorfoe(t) {
1249			_, err := stmtSaveXonker.Exec(name, href, "fishname")
1250			if err != nil {
1251				log.Printf("error saving fishname: %s", err)
1252			}
1253			return href, true
1254		}
1255	}
1256	return href, true
1257}})
1258
1259func gofish(name string) string {
1260	if name[0] == '@' {
1261		name = name[1:]
1262	}
1263	var href string
1264	handfull.Get(name, &href)
1265	return href
1266}
1267
1268func isactor(t string) bool {
1269	switch t {
1270	case "Person":
1271	case "Organization":
1272	case "Application":
1273	case "Service":
1274	default:
1275		return false
1276	}
1277	return true
1278}
1279
1280func investigate(name string) (*Honker, error) {
1281	if name == "" {
1282		return nil, fmt.Errorf("no name")
1283	}
1284	if name[0] == '@' {
1285		name = gofish(name)
1286	}
1287	if name == "" {
1288		return nil, fmt.Errorf("no name")
1289	}
1290	log.Printf("digging up some info on %s", name)
1291	obj, err := GetJunkFast(name)
1292	if err != nil {
1293		log.Printf("error investigating honker: %s", err)
1294		return nil, err
1295	}
1296	t, _ := obj.GetString("type")
1297	if !isactor(t) {
1298		log.Printf("it's not a person! %s", name)
1299		return nil, err
1300	}
1301	xid, _ := obj.GetString("id")
1302	handle, _ := obj.GetString("preferredUsername")
1303	return &Honker{XID: xid, Handle: handle}, nil
1304}