all repos — honk @ 75da70289f898fba3d3f9f1be38546277d78b9be

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