all repos — honk @ f96162d5d557259ff944716fac12dfb6183a33c2

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