all repos — honk @ 36f3f3f5a152e856e2f495155825a1e05e0522cc

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 convoy == "" {
 668				convoy, _ = obj.GetString("conversation")
 669			}
 670			if ot == "Question" {
 671				if what == "honk" {
 672					what = "qonk"
 673				}
 674				content += "<ul>"
 675				ans, _ := obj.GetArray("oneOf")
 676				for _, ai := range ans {
 677					a, ok := ai.(junk.Junk)
 678					if !ok {
 679						continue
 680					}
 681					as, _ := a.GetString("name")
 682					content += "<li>" + as
 683				}
 684				ans, _ = obj.GetArray("anyOf")
 685				for _, ai := range ans {
 686					a, ok := ai.(junk.Junk)
 687					if !ok {
 688						continue
 689					}
 690					as, _ := a.GetString("name")
 691					content += "<li>" + as
 692				}
 693				content += "</ul>"
 694			}
 695			if what == "honk" && rid != "" {
 696				what = "tonk"
 697			}
 698			atts, _ := obj.GetArray("attachment")
 699			for i, atti := range atts {
 700				att, ok := atti.(junk.Junk)
 701				if !ok {
 702					continue
 703				}
 704				at, _ := att.GetString("type")
 705				mt, _ := att.GetString("mediaType")
 706				u, _ := att.GetString("url")
 707				name, _ := att.GetString("name")
 708				desc, _ := att.GetString("summary")
 709				if desc == "" {
 710					desc = name
 711				}
 712				localize := false
 713				if i > 4 {
 714					log.Printf("excessive attachment: %s", at)
 715				} else if at == "Document" || at == "Image" {
 716					mt = strings.ToLower(mt)
 717					log.Printf("attachment: %s %s", mt, u)
 718					if mt == "text/plain" || strings.HasPrefix(mt, "image") {
 719						localize = true
 720					}
 721				} else {
 722					log.Printf("unknown attachment: %s", at)
 723				}
 724				if skipMedia(&xonk) {
 725					localize = false
 726				}
 727				donk := savedonk(u, name, desc, mt, localize)
 728				if donk != nil {
 729					xonk.Donks = append(xonk.Donks, donk)
 730				}
 731			}
 732			tags, _ := obj.GetArray("tag")
 733			for _, tagi := range tags {
 734				tag, ok := tagi.(junk.Junk)
 735				if !ok {
 736					continue
 737				}
 738				tt, _ := tag.GetString("type")
 739				name, _ := tag.GetString("name")
 740				desc, _ := tag.GetString("summary")
 741				if desc == "" {
 742					desc = name
 743				}
 744				if tt == "Emoji" {
 745					icon, _ := tag.GetMap("icon")
 746					mt, _ := icon.GetString("mediaType")
 747					if mt == "" {
 748						mt = "image/png"
 749					}
 750					u, _ := icon.GetString("url")
 751					donk := savedonk(u, name, desc, mt, true)
 752					if donk != nil {
 753						xonk.Donks = append(xonk.Donks, donk)
 754					}
 755				}
 756				if tt == "Hashtag" {
 757					if name == "" || name == "#" {
 758						// skip it
 759					} else {
 760						if name[0] != '#' {
 761							name = "#" + name
 762						}
 763						xonk.Onts = append(xonk.Onts, name)
 764					}
 765				}
 766				if tt == "Place" {
 767					p := new(Place)
 768					p.Name = name
 769					p.Latitude, _ = tag["latitude"].(float64)
 770					p.Longitude, _ = tag["longitude"].(float64)
 771					p.Url, _ = tag.GetString("url")
 772					xonk.Place = p
 773				}
 774				if tt == "Mention" {
 775					m, _ := tag.GetString("href")
 776					mentions = append(mentions, m)
 777				}
 778			}
 779			starttime, ok := obj.GetString("startTime")
 780			if ok {
 781				start, err := time.Parse(time.RFC3339, starttime)
 782				if err == nil {
 783					t := new(Time)
 784					t.StartTime = start
 785					endtime, _ := obj.GetString("endTime")
 786					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
 787					dura, _ := obj.GetString("duration")
 788					if strings.HasPrefix(dura, "PT") {
 789						dura = strings.ToLower(dura[2:])
 790						d, _ := time.ParseDuration(dura)
 791						t.Duration = Duration(d)
 792					}
 793					xonk.Time = t
 794				}
 795			}
 796			loca, ok := obj.GetMap("location")
 797			if ok {
 798				tt, _ := loca.GetString("type")
 799				name, _ := loca.GetString("name")
 800				if tt == "Place" {
 801					p := new(Place)
 802					p.Name = name
 803					p.Latitude, _ = loca["latitude"].(float64)
 804					p.Longitude, _ = loca["longitude"].(float64)
 805					p.Url, _ = loca.GetString("url")
 806					xonk.Place = p
 807				}
 808			}
 809
 810			xonk.Onts = oneofakind(xonk.Onts)
 811			replyobj, ok := obj.GetMap("replies")
 812			if ok {
 813				items, ok := replyobj.GetArray("items")
 814				if !ok {
 815					first, ok := replyobj.GetMap("first")
 816					if ok {
 817						items, _ = first.GetArray("items")
 818					}
 819				}
 820				for _, repl := range items {
 821					s, ok := repl.(string)
 822					if ok {
 823						replies = append(replies, s)
 824					}
 825				}
 826			}
 827
 828		}
 829		if originate(xid) != origin {
 830			log.Printf("original sin: %s <> %s", xid, origin)
 831			item.Write(os.Stdout)
 832			return nil
 833		}
 834
 835		if currenttid == "" {
 836			currenttid = convoy
 837		}
 838
 839		if len(content) > 90001 {
 840			log.Printf("content too long. truncating")
 841			content = content[:90001]
 842		}
 843
 844		// grab any inline imgs
 845		imgfilt := htfilter.New()
 846		imgfilt.Imager = inlineimgs
 847		imgfilt.String(content)
 848
 849		// init xonk
 850		xonk.What = what
 851		xonk.XID = xid
 852		xonk.RID = rid
 853		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 854		xonk.URL = url
 855		xonk.Noise = content
 856		xonk.Precis = precis
 857		xonk.Format = "html"
 858		xonk.Convoy = convoy
 859		for _, m := range mentions {
 860			if m == user.URL {
 861				xonk.Whofore = 1
 862			}
 863		}
 864
 865		if isUpdate {
 866			log.Printf("something has changed! %s", xonk.XID)
 867			prev := getxonk(user.ID, xonk.XID)
 868			if prev == nil {
 869				log.Printf("didn't find old version for update: %s", xonk.XID)
 870				isUpdate = false
 871			} else {
 872				prev.Noise = xonk.Noise
 873				prev.Precis = xonk.Precis
 874				prev.Date = xonk.Date
 875				prev.Donks = xonk.Donks
 876				prev.Onts = xonk.Onts
 877				prev.Place = xonk.Place
 878				updatehonk(prev)
 879			}
 880		}
 881		if !isUpdate && needxonk(user, &xonk) {
 882			if strings.HasSuffix(convoy, "#context") {
 883				// friendica...
 884				if rid != "" {
 885					convoy = ""
 886				} else {
 887					convoy = url
 888				}
 889			}
 890			if rid != "" {
 891				if needxonkid(user, rid) {
 892					goingup++
 893					saveonemore(rid)
 894					goingup--
 895				}
 896				if convoy == "" {
 897					xx := getxonk(user.ID, rid)
 898					if xx != nil {
 899						convoy = xx.Convoy
 900					}
 901				}
 902			}
 903			if convoy == "" {
 904				convoy = currenttid
 905			}
 906			if convoy == "" {
 907				convoy = "missing-" + xfiltrate()
 908				currenttid = convoy
 909			}
 910			xonk.Convoy = convoy
 911			savexonk(&xonk)
 912		}
 913		if goingup == 0 {
 914			for _, replid := range replies {
 915				if needxonkid(user, replid) {
 916					log.Printf("missing a reply: %s", replid)
 917					saveonemore(replid)
 918				}
 919			}
 920		}
 921		return &xonk
 922	}
 923
 924	return xonkxonkfn(item, origin)
 925}
 926
 927func rubadubdub(user *WhatAbout, req junk.Junk) {
 928	xid, _ := req.GetString("id")
 929	actor, _ := req.GetString("actor")
 930	j := junk.New()
 931	j["@context"] = itiswhatitis
 932	j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
 933	j["type"] = "Accept"
 934	j["actor"] = user.URL
 935	j["to"] = actor
 936	j["published"] = time.Now().UTC().Format(time.RFC3339)
 937	j["object"] = req
 938
 939	var buf bytes.Buffer
 940	j.Write(&buf)
 941	msg := buf.Bytes()
 942
 943	deliverate(0, user.Name, actor, msg)
 944}
 945
 946func itakeitallback(user *WhatAbout, xid string) {
 947	j := junk.New()
 948	j["@context"] = itiswhatitis
 949	j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
 950	j["type"] = "Undo"
 951	j["actor"] = user.URL
 952	j["to"] = xid
 953	f := junk.New()
 954	f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 955	f["type"] = "Follow"
 956	f["actor"] = user.URL
 957	f["to"] = xid
 958	f["object"] = xid
 959	j["object"] = f
 960	j["published"] = time.Now().UTC().Format(time.RFC3339)
 961
 962	var buf bytes.Buffer
 963	j.Write(&buf)
 964	msg := buf.Bytes()
 965
 966	deliverate(0, user.Name, xid, msg)
 967}
 968
 969func subsub(user *WhatAbout, xid string) {
 970	if xid == "" {
 971		log.Printf("can't subscribe to empty")
 972		return
 973	}
 974	j := junk.New()
 975	j["@context"] = itiswhatitis
 976	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 977	j["type"] = "Follow"
 978	j["actor"] = user.URL
 979	j["to"] = xid
 980	j["object"] = xid
 981	j["published"] = time.Now().UTC().Format(time.RFC3339)
 982
 983	var buf bytes.Buffer
 984	j.Write(&buf)
 985	msg := buf.Bytes()
 986
 987	deliverate(0, user.Name, xid, msg)
 988}
 989
 990// returns activity, object
 991func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 992	dt := h.Date.Format(time.RFC3339)
 993	var jo junk.Junk
 994	j := junk.New()
 995	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 996	j["actor"] = user.URL
 997	j["published"] = dt
 998	if h.Public {
 999		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
1000	} else {
1001		j["to"] = h.Audience[0]
1002	}
1003	if len(h.Audience) > 1 {
1004		j["cc"] = h.Audience[1:]
1005	}
1006
1007	switch h.What {
1008	case "update":
1009		fallthrough
1010	case "tonk":
1011		fallthrough
1012	case "event":
1013		fallthrough
1014	case "honk":
1015		j["type"] = "Create"
1016		if h.What == "update" {
1017			j["type"] = "Update"
1018		}
1019
1020		jo = junk.New()
1021		jo["id"] = h.XID
1022		jo["type"] = "Note"
1023		if h.What == "event" {
1024			jo["type"] = "Event"
1025		}
1026		jo["published"] = dt
1027		jo["url"] = h.XID
1028		jo["attributedTo"] = user.URL
1029		if h.RID != "" {
1030			jo["inReplyTo"] = h.RID
1031		}
1032		if h.Convoy != "" {
1033			jo["context"] = h.Convoy
1034			jo["conversation"] = h.Convoy
1035		}
1036		jo["to"] = h.Audience[0]
1037		if len(h.Audience) > 1 {
1038			jo["cc"] = h.Audience[1:]
1039		}
1040		if !h.Public {
1041			jo["directMessage"] = true
1042		}
1043		translate(h)
1044		h.Noise = re_memes.ReplaceAllString(h.Noise, "")
1045		jo["summary"] = html.EscapeString(h.Precis)
1046		jo["content"] = ontologize(mentionize(h.Noise))
1047		if strings.HasPrefix(h.Precis, "DZ:") {
1048			jo["sensitive"] = true
1049		}
1050
1051		var replies []string
1052		for _, reply := range h.Replies {
1053			replies = append(replies, reply.XID)
1054		}
1055		if len(replies) > 0 {
1056			jr := junk.New()
1057			jr["type"] = "Collection"
1058			jr["totalItems"] = len(replies)
1059			jr["items"] = replies
1060			jo["replies"] = jr
1061		}
1062
1063		var tags []junk.Junk
1064		for _, m := range bunchofgrapes(h.Noise) {
1065			t := junk.New()
1066			t["type"] = "Mention"
1067			t["name"] = m.who
1068			t["href"] = m.where
1069			tags = append(tags, t)
1070		}
1071		for _, o := range h.Onts {
1072			t := junk.New()
1073			t["type"] = "Hashtag"
1074			o = strings.ToLower(o)
1075			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1076			t["name"] = o
1077			tags = append(tags, t)
1078		}
1079		for _, e := range herdofemus(h.Noise) {
1080			t := junk.New()
1081			t["id"] = e.ID
1082			t["type"] = "Emoji"
1083			t["name"] = e.Name
1084			i := junk.New()
1085			i["type"] = "Image"
1086			i["mediaType"] = "image/png"
1087			i["url"] = e.ID
1088			t["icon"] = i
1089			tags = append(tags, t)
1090		}
1091		if p := h.Place; p != nil {
1092			t := junk.New()
1093			t["type"] = "Place"
1094			t["name"] = p.Name
1095			t["latitude"] = p.Latitude
1096			t["longitude"] = p.Longitude
1097			t["url"] = p.Url
1098			if h.What == "event" {
1099				jo["location"] = t
1100			} else {
1101				tags = append(tags, t)
1102			}
1103		}
1104		if len(tags) > 0 {
1105			jo["tag"] = tags
1106		}
1107		if t := h.Time; t != nil {
1108			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1109			if t.Duration != 0 {
1110				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1111			}
1112		}
1113		var atts []junk.Junk
1114		for _, d := range h.Donks {
1115			if re_emus.MatchString(d.Name) {
1116				continue
1117			}
1118			jd := junk.New()
1119			jd["mediaType"] = d.Media
1120			jd["name"] = d.Name
1121			jd["summary"] = html.EscapeString(d.Desc)
1122			jd["type"] = "Document"
1123			jd["url"] = d.URL
1124			atts = append(atts, jd)
1125		}
1126		if len(atts) > 0 {
1127			jo["attachment"] = atts
1128		}
1129		j["object"] = jo
1130	case "bonk":
1131		j["type"] = "Announce"
1132		if h.Convoy != "" {
1133			j["context"] = h.Convoy
1134		}
1135		j["object"] = h.XID
1136	case "unbonk":
1137		b := junk.New()
1138		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1139		b["type"] = "Announce"
1140		b["actor"] = user.URL
1141		if h.Convoy != "" {
1142			b["context"] = h.Convoy
1143		}
1144		b["object"] = h.XID
1145		j["type"] = "Undo"
1146		j["object"] = b
1147	case "zonk":
1148		j["type"] = "Delete"
1149		j["object"] = h.XID
1150	case "ack":
1151		j["type"] = "Read"
1152		j["object"] = h.XID
1153	case "deack":
1154		b := junk.New()
1155		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1156		b["type"] = "Read"
1157		b["actor"] = user.URL
1158		b["object"] = h.XID
1159		j["type"] = "Undo"
1160		j["object"] = b
1161	}
1162
1163	return j, jo
1164}
1165
1166var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1167	row := stmtAnyXonk.QueryRow(xid)
1168	honk := scanhonk(row)
1169	if honk == nil || !honk.Public {
1170		return nil, true
1171	}
1172	user, _ := butwhatabout(honk.Username)
1173	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy)
1174	reversehonks(rawhonks)
1175	for _, h := range rawhonks {
1176		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1177			honk.Replies = append(honk.Replies, h)
1178		}
1179	}
1180	donksforhonks([]*Honk{honk})
1181	_, j := jonkjonk(user, honk)
1182	j["@context"] = itiswhatitis
1183	var buf bytes.Buffer
1184	j.Write(&buf)
1185	return buf.Bytes(), true
1186}})
1187
1188func gimmejonk(xid string) ([]byte, bool) {
1189	var j []byte
1190	ok := oldjonks.Get(xid, &j)
1191	return j, ok
1192}
1193
1194func honkworldwide(user *WhatAbout, honk *Honk) {
1195	jonk, _ := jonkjonk(user, honk)
1196	jonk["@context"] = itiswhatitis
1197	var buf bytes.Buffer
1198	jonk.Write(&buf)
1199	msg := buf.Bytes()
1200
1201	rcpts := make(map[string]bool)
1202	for _, a := range honk.Audience {
1203		if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1204			continue
1205		}
1206		var box *Box
1207		ok := boxofboxes.Get(a, &box)
1208		if ok && honk.Public && box.Shared != "" {
1209			rcpts["%"+box.Shared] = true
1210		} else {
1211			rcpts[a] = true
1212		}
1213	}
1214	if honk.Public {
1215		for _, f := range getdubs(user.ID) {
1216			if f.XID == user.URL {
1217				continue
1218			}
1219			var box *Box
1220			ok := boxofboxes.Get(f.XID, &box)
1221			if ok && box.Shared != "" {
1222				rcpts["%"+box.Shared] = true
1223			} else {
1224				rcpts[f.XID] = true
1225			}
1226		}
1227	}
1228	for a := range rcpts {
1229		go deliverate(0, user.Name, a, msg)
1230	}
1231}
1232
1233var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1234	user, err := butwhatabout(name)
1235	if err != nil {
1236		return nil, false
1237	}
1238	about := markitzero(user.About)
1239
1240	j := junk.New()
1241	j["@context"] = itiswhatitis
1242	j["id"] = user.URL
1243	j["type"] = "Person"
1244	j["inbox"] = user.URL + "/inbox"
1245	j["outbox"] = user.URL + "/outbox"
1246	j["followers"] = user.URL + "/followers"
1247	j["following"] = user.URL + "/following"
1248	j["name"] = user.Display
1249	j["preferredUsername"] = user.Name
1250	j["summary"] = about
1251	j["url"] = user.URL
1252	a := junk.New()
1253	a["type"] = "Image"
1254	a["mediaType"] = "image/png"
1255	a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1256	j["icon"] = a
1257	k := junk.New()
1258	k["id"] = user.URL + "#key"
1259	k["owner"] = user.URL
1260	k["publicKeyPem"] = user.Key
1261	j["publicKey"] = k
1262
1263	var buf bytes.Buffer
1264	j.Write(&buf)
1265	return buf.Bytes(), true
1266}, Duration: 1 * time.Minute})
1267
1268func asjonker(name string) ([]byte, bool) {
1269	var j []byte
1270	ok := oldjonkers.Get(name, &j)
1271	return j, ok
1272}
1273
1274var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1275	m := strings.Split(name, "@")
1276	if len(m) != 2 {
1277		log.Printf("bad fish name: %s", name)
1278		return "", true
1279	}
1280	row := stmtGetXonker.QueryRow(name, "fishname")
1281	var href string
1282	err := row.Scan(&href)
1283	if err == nil {
1284		return href, true
1285	}
1286	log.Printf("fishing for %s", name)
1287	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1288	if err != nil {
1289		log.Printf("failed to go fish %s: %s", name, err)
1290		return "", true
1291	}
1292	links, _ := j.GetArray("links")
1293	for _, li := range links {
1294		l, ok := li.(junk.Junk)
1295		if !ok {
1296			continue
1297		}
1298		href, _ := l.GetString("href")
1299		rel, _ := l.GetString("rel")
1300		t, _ := l.GetString("type")
1301		if rel == "self" && friendorfoe(t) {
1302			_, err := stmtSaveXonker.Exec(name, href, "fishname")
1303			if err != nil {
1304				log.Printf("error saving fishname: %s", err)
1305			}
1306			return href, true
1307		}
1308	}
1309	return href, true
1310}})
1311
1312func gofish(name string) string {
1313	if name[0] == '@' {
1314		name = name[1:]
1315	}
1316	var href string
1317	handfull.Get(name, &href)
1318	return href
1319}
1320
1321func isactor(t string) bool {
1322	switch t {
1323	case "Person":
1324	case "Organization":
1325	case "Application":
1326	case "Service":
1327	default:
1328		return false
1329	}
1330	return true
1331}
1332
1333func investigate(name string) (*Honker, error) {
1334	if name == "" {
1335		return nil, fmt.Errorf("no name")
1336	}
1337	if name[0] == '@' {
1338		name = gofish(name)
1339	}
1340	if name == "" {
1341		return nil, fmt.Errorf("no name")
1342	}
1343	obj, err := GetJunkFast(name)
1344	if err != nil {
1345		return nil, err
1346	}
1347	t, _ := obj.GetString("type")
1348	if !isactor(t) {
1349		return nil, fmt.Errorf("not a person")
1350	}
1351	xid, _ := obj.GetString("id")
1352	handle, _ := obj.GetString("preferredUsername")
1353	return &Honker{XID: xid, Handle: handle}, nil
1354}