all repos — honk @ db582287736dac7593852ab064267de1d2d37b55

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