all repos — honk @ 49ad928c264cf40032f00e8572116586d5e6cc19

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