all repos — honk @ 5036d46acc40279489fba5156682addfed218121

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