all repos — honk @ fb9695ebc3dff7aacc1681e932d98cb300f4f0eb

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