all repos — honk @ 39eb566738fc186d2a68dcb88f9c1a43bb5b1625

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