all repos — honk @ v0.8.4

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				updatehonk(prev)
 857			}
 858		}
 859		if !isUpdate && needxonk(user, &xonk) {
 860			if strings.HasSuffix(convoy, "#context") {
 861				// friendica...
 862				if rid != "" {
 863					convoy = ""
 864				} else {
 865					convoy = url
 866				}
 867			}
 868			if rid != "" {
 869				if needxonkid(user, rid) {
 870					goingup++
 871					saveonemore(rid)
 872					goingup--
 873				}
 874				if convoy == "" {
 875					xx := getxonk(user.ID, rid)
 876					if xx != nil {
 877						convoy = xx.Convoy
 878					}
 879				}
 880			}
 881			if convoy == "" {
 882				convoy = currenttid
 883			}
 884			if convoy == "" {
 885				convoy = "missing-" + xfiltrate()
 886				currenttid = convoy
 887			}
 888			xonk.Convoy = convoy
 889			savexonk(&xonk)
 890		}
 891		if goingup == 0 {
 892			for _, replid := range replies {
 893				if needxonkid(user, replid) {
 894					log.Printf("missing a reply: %s", replid)
 895					saveonemore(replid)
 896				}
 897			}
 898		}
 899		return &xonk
 900	}
 901
 902	return xonkxonkfn(item, origin)
 903}
 904
 905func rubadubdub(user *WhatAbout, req junk.Junk) {
 906	xid, _ := req.GetString("id")
 907	actor, _ := req.GetString("actor")
 908	j := junk.New()
 909	j["@context"] = itiswhatitis
 910	j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
 911	j["type"] = "Accept"
 912	j["actor"] = user.URL
 913	j["to"] = actor
 914	j["published"] = time.Now().UTC().Format(time.RFC3339)
 915	j["object"] = req
 916
 917	deliverate(0, user.ID, actor, j.ToBytes())
 918}
 919
 920func itakeitallback(user *WhatAbout, xid string) {
 921	j := junk.New()
 922	j["@context"] = itiswhatitis
 923	j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
 924	j["type"] = "Undo"
 925	j["actor"] = user.URL
 926	j["to"] = xid
 927	f := junk.New()
 928	f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 929	f["type"] = "Follow"
 930	f["actor"] = user.URL
 931	f["to"] = xid
 932	f["object"] = xid
 933	j["object"] = f
 934	j["published"] = time.Now().UTC().Format(time.RFC3339)
 935
 936	deliverate(0, user.ID, xid, j.ToBytes())
 937}
 938
 939func subsub(user *WhatAbout, xid string, owner string) {
 940	if xid == "" {
 941		log.Printf("can't subscribe to empty")
 942		return
 943	}
 944	j := junk.New()
 945	j["@context"] = itiswhatitis
 946	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 947	j["type"] = "Follow"
 948	j["actor"] = user.URL
 949	j["to"] = owner
 950	j["object"] = xid
 951	j["published"] = time.Now().UTC().Format(time.RFC3339)
 952
 953	deliverate(0, user.ID, owner, j.ToBytes())
 954}
 955
 956// returns activity, object
 957func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 958	dt := h.Date.Format(time.RFC3339)
 959	var jo junk.Junk
 960	j := junk.New()
 961	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 962	j["actor"] = user.URL
 963	j["published"] = dt
 964	if h.Public {
 965		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
 966	} else {
 967		j["to"] = h.Audience[0]
 968	}
 969	if len(h.Audience) > 1 {
 970		j["cc"] = h.Audience[1:]
 971	}
 972
 973	switch h.What {
 974	case "update":
 975		fallthrough
 976	case "tonk":
 977		fallthrough
 978	case "event":
 979		fallthrough
 980	case "honk":
 981		j["type"] = "Create"
 982		if h.What == "update" {
 983			j["type"] = "Update"
 984		}
 985
 986		jo = junk.New()
 987		jo["id"] = h.XID
 988		jo["type"] = "Note"
 989		if h.What == "event" {
 990			jo["type"] = "Event"
 991		}
 992		jo["published"] = dt
 993		jo["url"] = h.XID
 994		jo["attributedTo"] = user.URL
 995		if h.RID != "" {
 996			jo["inReplyTo"] = h.RID
 997		}
 998		if h.Convoy != "" {
 999			jo["context"] = h.Convoy
1000			jo["conversation"] = h.Convoy
1001		}
1002		jo["to"] = h.Audience[0]
1003		if len(h.Audience) > 1 {
1004			jo["cc"] = h.Audience[1:]
1005		}
1006		if !h.Public {
1007			jo["directMessage"] = true
1008		}
1009		mentions := bunchofgrapes(h.Noise)
1010		translate(h, true)
1011		jo["summary"] = html.EscapeString(h.Precis)
1012		jo["content"] = h.Noise
1013		if strings.HasPrefix(h.Precis, "DZ:") {
1014			jo["sensitive"] = true
1015		}
1016
1017		var replies []string
1018		for _, reply := range h.Replies {
1019			replies = append(replies, reply.XID)
1020		}
1021		if len(replies) > 0 {
1022			jr := junk.New()
1023			jr["type"] = "Collection"
1024			jr["totalItems"] = len(replies)
1025			jr["items"] = replies
1026			jo["replies"] = jr
1027		}
1028
1029		var tags []junk.Junk
1030		for _, m := range mentions {
1031			t := junk.New()
1032			t["type"] = "Mention"
1033			t["name"] = m.who
1034			t["href"] = m.where
1035			tags = append(tags, t)
1036		}
1037		for _, o := range h.Onts {
1038			t := junk.New()
1039			t["type"] = "Hashtag"
1040			o = strings.ToLower(o)
1041			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1042			t["name"] = o
1043			tags = append(tags, t)
1044		}
1045		for _, e := range herdofemus(h.Noise) {
1046			t := junk.New()
1047			t["id"] = e.ID
1048			t["type"] = "Emoji"
1049			t["name"] = e.Name
1050			i := junk.New()
1051			i["type"] = "Image"
1052			i["mediaType"] = "image/png"
1053			i["url"] = e.ID
1054			t["icon"] = i
1055			tags = append(tags, t)
1056		}
1057		if len(tags) > 0 {
1058			jo["tag"] = tags
1059		}
1060		if p := h.Place; p != nil {
1061			t := junk.New()
1062			t["type"] = "Place"
1063			if p.Name != "" {
1064				t["name"] = p.Name
1065			}
1066			if p.Latitude != 0 {
1067				t["latitude"] = p.Latitude
1068			}
1069			if p.Longitude != 0 {
1070				t["longitude"] = p.Longitude
1071			}
1072			if p.Url != "" {
1073				t["url"] = p.Url
1074			}
1075			jo["location"] = t
1076		}
1077		if t := h.Time; t != nil {
1078			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1079			if t.Duration != 0 {
1080				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1081			}
1082		}
1083		var atts []junk.Junk
1084		for _, d := range h.Donks {
1085			if re_emus.MatchString(d.Name) {
1086				continue
1087			}
1088			jd := junk.New()
1089			jd["mediaType"] = d.Media
1090			jd["name"] = d.Name
1091			jd["summary"] = html.EscapeString(d.Desc)
1092			jd["type"] = "Document"
1093			jd["url"] = d.URL
1094			atts = append(atts, jd)
1095		}
1096		if len(atts) > 0 {
1097			jo["attachment"] = atts
1098		}
1099		j["object"] = jo
1100	case "bonk":
1101		j["type"] = "Announce"
1102		if h.Convoy != "" {
1103			j["context"] = h.Convoy
1104		}
1105		j["object"] = h.XID
1106	case "unbonk":
1107		b := junk.New()
1108		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1109		b["type"] = "Announce"
1110		b["actor"] = user.URL
1111		if h.Convoy != "" {
1112			b["context"] = h.Convoy
1113		}
1114		b["object"] = h.XID
1115		j["type"] = "Undo"
1116		j["object"] = b
1117	case "zonk":
1118		j["type"] = "Delete"
1119		j["object"] = h.XID
1120	case "ack":
1121		j["type"] = "Read"
1122		j["object"] = h.XID
1123		if h.Convoy != "" {
1124			j["context"] = h.Convoy
1125		}
1126	case "deack":
1127		b := junk.New()
1128		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1129		b["type"] = "Read"
1130		b["actor"] = user.URL
1131		b["object"] = h.XID
1132		if h.Convoy != "" {
1133			b["context"] = h.Convoy
1134		}
1135		j["type"] = "Undo"
1136		j["object"] = b
1137	}
1138
1139	return j, jo
1140}
1141
1142var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1143	row := stmtAnyXonk.QueryRow(xid)
1144	honk := scanhonk(row)
1145	if honk == nil || !honk.Public {
1146		return nil, true
1147	}
1148	user, _ := butwhatabout(honk.Username)
1149	rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1150	reversehonks(rawhonks)
1151	for _, h := range rawhonks {
1152		if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1153			honk.Replies = append(honk.Replies, h)
1154		}
1155	}
1156	donksforhonks([]*Honk{honk})
1157	_, j := jonkjonk(user, honk)
1158	j["@context"] = itiswhatitis
1159
1160	return j.ToBytes(), true
1161}, Limit: 128})
1162
1163func gimmejonk(xid string) ([]byte, bool) {
1164	var j []byte
1165	ok := oldjonks.Get(xid, &j)
1166	return j, ok
1167}
1168
1169func honkworldwide(user *WhatAbout, honk *Honk) {
1170	jonk, _ := jonkjonk(user, honk)
1171	jonk["@context"] = itiswhatitis
1172	msg := jonk.ToBytes()
1173
1174	rcpts := make(map[string]bool)
1175	for _, a := range honk.Audience {
1176		if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1177			continue
1178		}
1179		var box *Box
1180		ok := boxofboxes.Get(a, &box)
1181		if ok && honk.Public && box.Shared != "" {
1182			rcpts["%"+box.Shared] = true
1183		} else {
1184			rcpts[a] = true
1185		}
1186	}
1187	if honk.Public {
1188		for _, h := range getdubs(user.ID) {
1189			if h.XID == user.URL {
1190				continue
1191			}
1192			var box *Box
1193			ok := boxofboxes.Get(h.XID, &box)
1194			if ok && box.Shared != "" {
1195				rcpts["%"+box.Shared] = true
1196			} else {
1197				rcpts[h.XID] = true
1198			}
1199		}
1200	}
1201	for a := range rcpts {
1202		go deliverate(0, user.ID, a, msg)
1203	}
1204	if honk.Public && len(honk.Onts) > 0 {
1205		collectiveaction(honk)
1206	}
1207}
1208
1209func collectiveaction(honk *Honk) {
1210	user := getserveruser()
1211	for _, ont := range honk.Onts {
1212		dubs := getnameddubs(serverUID, ont)
1213		if len(dubs) == 0 {
1214			continue
1215		}
1216		j := junk.New()
1217		j["@context"] = itiswhatitis
1218		j["type"] = "Add"
1219		j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1220		j["actor"] = user.URL
1221		j["object"] = honk.XID
1222		j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1223		rcpts := make(map[string]bool)
1224		for _, dub := range dubs {
1225			var box *Box
1226			ok := boxofboxes.Get(dub.XID, &box)
1227			if ok && box.Shared != "" {
1228				rcpts["%"+box.Shared] = true
1229			} else {
1230				rcpts[dub.XID] = true
1231			}
1232		}
1233		msg := j.ToBytes()
1234		for a := range rcpts {
1235			go deliverate(0, user.ID, a, msg)
1236		}
1237	}
1238}
1239
1240func junkuser(user *WhatAbout) []byte {
1241	about := markitzero(user.About)
1242
1243	j := junk.New()
1244	j["@context"] = itiswhatitis
1245	j["id"] = user.URL
1246	j["inbox"] = user.URL + "/inbox"
1247	j["outbox"] = user.URL + "/outbox"
1248	j["name"] = user.Display
1249	j["preferredUsername"] = user.Name
1250	j["summary"] = about
1251	if user.ID > 0 {
1252		j["type"] = "Person"
1253		j["url"] = user.URL
1254		j["followers"] = user.URL + "/followers"
1255		j["following"] = user.URL + "/following"
1256		a := junk.New()
1257		a["type"] = "Image"
1258		a["mediaType"] = "image/png"
1259		if ava := user.Options.Avatar; ava != "" {
1260			a["url"] = ava
1261		} else {
1262			a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1263		}
1264		j["icon"] = a
1265	} else {
1266		j["type"] = "Service"
1267	}
1268	k := junk.New()
1269	k["id"] = user.URL + "#key"
1270	k["owner"] = user.URL
1271	k["publicKeyPem"] = user.Key
1272	j["publicKey"] = k
1273
1274	return j.ToBytes()
1275}
1276
1277var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1278	user, err := butwhatabout(name)
1279	if err != nil {
1280		return nil, false
1281	}
1282	return junkuser(user), true
1283}, Duration: 1 * time.Minute})
1284
1285func asjonker(name string) ([]byte, bool) {
1286	var j []byte
1287	ok := oldjonkers.Get(name, &j)
1288	return j, ok
1289}
1290
1291var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1292	m := strings.Split(name, "@")
1293	if len(m) != 2 {
1294		log.Printf("bad fish name: %s", name)
1295		return "", true
1296	}
1297	var href string
1298	row := stmtGetXonker.QueryRow(name, "fishname")
1299	err := row.Scan(&href)
1300	if err == nil {
1301		return href, true
1302	}
1303	log.Printf("fishing for %s", name)
1304	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1305	if err != nil {
1306		log.Printf("failed to go fish %s: %s", name, err)
1307		return "", true
1308	}
1309	links, _ := j.GetArray("links")
1310	for _, li := range links {
1311		l, ok := li.(junk.Junk)
1312		if !ok {
1313			continue
1314		}
1315		href, _ := l.GetString("href")
1316		rel, _ := l.GetString("rel")
1317		t, _ := l.GetString("type")
1318		if rel == "self" && friendorfoe(t) {
1319			_, err := stmtSaveXonker.Exec(name, href, "fishname")
1320			if err != nil {
1321				log.Printf("error saving fishname: %s", err)
1322			}
1323			return href, true
1324		}
1325	}
1326	return href, true
1327}})
1328
1329func gofish(name string) string {
1330	if name[0] == '@' {
1331		name = name[1:]
1332	}
1333	var href string
1334	handfull.Get(name, &href)
1335	return href
1336}
1337
1338func investigate(name string) (*SomeThing, error) {
1339	if name == "" {
1340		return nil, fmt.Errorf("no name")
1341	}
1342	if name[0] == '@' {
1343		name = gofish(name)
1344	}
1345	if name == "" {
1346		return nil, fmt.Errorf("no name")
1347	}
1348	obj, err := GetJunkFast(name)
1349	if err != nil {
1350		return nil, err
1351	}
1352	allinjest(originate(name), obj)
1353	return somethingabout(obj)
1354}
1355
1356func somethingabout(obj junk.Junk) (*SomeThing, error) {
1357	info := new(SomeThing)
1358	t, _ := obj.GetString("type")
1359	switch t {
1360	case "Person":
1361		fallthrough
1362	case "Organization":
1363		fallthrough
1364	case "Application":
1365		fallthrough
1366	case "Service":
1367		info.What = SomeActor
1368	case "OrderedCollection":
1369		fallthrough
1370	case "Collection":
1371		info.What = SomeCollection
1372	default:
1373		return nil, fmt.Errorf("unknown object type")
1374	}
1375	info.XID, _ = obj.GetString("id")
1376	info.Name, _ = obj.GetString("preferredUsername")
1377	if info.Name == "" {
1378		info.Name, _ = obj.GetString("name")
1379	}
1380	info.Owner, _ = obj.GetString("attributedTo")
1381	if info.Owner == "" {
1382		info.Owner = info.XID
1383	}
1384	return info, nil
1385}
1386
1387func allinjest(origin string, obj junk.Junk) {
1388	keyobj, ok := obj.GetMap("publicKey")
1389	if ok {
1390		ingestpubkey(origin, keyobj)
1391	}
1392	ingestboxes(origin, obj)
1393	ingesthandle(origin, obj)
1394}
1395
1396func ingestpubkey(origin string, obj junk.Junk) {
1397	keyobj, ok := obj.GetMap("publicKey")
1398	if ok {
1399		obj = keyobj
1400	}
1401	keyname, ok := obj.GetString("id")
1402	var data string
1403	row := stmtGetXonker.QueryRow(keyname, "pubkey")
1404	err := row.Scan(&data)
1405	if err == nil {
1406		return
1407	}
1408	if !ok || origin != originate(keyname) {
1409		log.Printf("bad key origin %s <> %s", origin, keyname)
1410		return
1411	}
1412	log.Printf("ingesting a needed pubkey: %s", keyname)
1413	owner, ok := obj.GetString("owner")
1414	if !ok {
1415		log.Printf("error finding %s pubkey owner", keyname)
1416		return
1417	}
1418	data, ok = obj.GetString("publicKeyPem")
1419	if !ok {
1420		log.Printf("error finding %s pubkey", keyname)
1421		return
1422	}
1423	if originate(owner) != origin {
1424		log.Printf("bad key owner: %s <> %s", owner, origin)
1425		return
1426	}
1427	_, _, err = httpsig.DecodeKey(data)
1428	if err != nil {
1429		log.Printf("error decoding %s pubkey: %s", keyname, err)
1430		return
1431	}
1432	_, err = stmtSaveXonker.Exec(keyname, data, "pubkey")
1433	if err != nil {
1434		log.Printf("error saving key: %s", err)
1435	}
1436}
1437
1438func ingestboxes(origin string, obj junk.Junk) {
1439	ident, _ := obj.GetString("id")
1440	if ident == "" {
1441		return
1442	}
1443	if originate(ident) != origin {
1444		return
1445	}
1446	var info string
1447	row := stmtGetXonker.QueryRow(ident, "boxes")
1448	err := row.Scan(&info)
1449	if err == nil {
1450		return
1451	}
1452	log.Printf("ingesting boxes: %s", ident)
1453	inbox, _ := obj.GetString("inbox")
1454	outbox, _ := obj.GetString("outbox")
1455	sbox, _ := obj.GetString("endpoints", "sharedInbox")
1456	if inbox != "" {
1457		m := strings.Join([]string{inbox, outbox, sbox}, " ")
1458		_, err = stmtSaveXonker.Exec(ident, m, "boxes")
1459		if err != nil {
1460			log.Printf("error saving boxes: %s", err)
1461		}
1462	}
1463}
1464
1465func ingesthandle(origin string, obj junk.Junk) {
1466	xid, _ := obj.GetString("id")
1467	if xid == "" {
1468		return
1469	}
1470	if originate(xid) != origin {
1471		return
1472	}
1473	var handle string
1474	row := stmtGetXonker.QueryRow(xid, "handle")
1475	err := row.Scan(&handle)
1476	if err == nil {
1477		return
1478	}
1479	handle, _ = obj.GetString("preferredUsername")
1480	if handle != "" {
1481		_, err = stmtSaveXonker.Exec(xid, handle, "handle")
1482		if err != nil {
1483			log.Printf("error saving handle: %s", err)
1484		}
1485	}
1486}