all repos — honk @ 1714fe90b52de5a2597957cafa609f46c4acaf31

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