all repos — honk @ 4486057adcd0805c66e1e1a29f06c466508be110

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