all repos — honk @ 547426b21e4e95308d435ed42d85758a97182908

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					endtime, _ := obj.GetString("endTime")
 755					t.EndTime, _ = time.Parse(time.RFC3339, endtime)
 756					dura, _ := obj.GetString("duration")
 757					if strings.HasPrefix(dura, "PT") {
 758						dura = strings.ToLower(dura[2:])
 759						d, _ := time.ParseDuration(dura)
 760						t.Duration = Duration(d)
 761					}
 762					xonk.Time = t
 763				}
 764			}
 765			loca, ok := obj.GetMap("location")
 766			if ok {
 767				tt, _ := loca.GetString("type")
 768				name, _ := loca.GetString("name")
 769				if tt == "Place" {
 770					p := new(Place)
 771					p.Name = name
 772					p.Latitude, _ = loca["latitude"].(float64)
 773					p.Longitude, _ = loca["longitude"].(float64)
 774					p.Url, _ = loca.GetString("url")
 775					xonk.Place = p
 776				}
 777			}
 778
 779			xonk.Onts = oneofakind(xonk.Onts)
 780			replyobj, ok := obj.GetMap("replies")
 781			if ok {
 782				items, ok := replyobj.GetArray("items")
 783				if !ok {
 784					first, ok := replyobj.GetMap("first")
 785					if ok {
 786						items, _ = first.GetArray("items")
 787					}
 788				}
 789				for _, repl := range items {
 790					s, ok := repl.(string)
 791					if ok {
 792						replies = append(replies, s)
 793					}
 794				}
 795			}
 796
 797		}
 798		if originate(xid) != origin {
 799			log.Printf("original sin: %s <> %s", xid, origin)
 800			item.Write(os.Stdout)
 801			return nil
 802		}
 803
 804		if currenttid == "" {
 805			currenttid = convoy
 806		}
 807
 808		if len(content) > 90001 {
 809			log.Printf("content too long. truncating")
 810			content = content[:90001]
 811		}
 812
 813		// grab any inline imgs
 814		imgfilt := htfilter.New()
 815		imgfilt.Imager = inlineimgs
 816		imgfilt.String(content)
 817
 818		// init xonk
 819		xonk.What = what
 820		xonk.XID = xid
 821		xonk.RID = rid
 822		xonk.Date, _ = time.Parse(time.RFC3339, dt)
 823		xonk.URL = url
 824		xonk.Noise = content
 825		xonk.Precis = precis
 826		xonk.Format = "html"
 827		xonk.Convoy = convoy
 828
 829		if isUpdate {
 830			log.Printf("something has changed! %s", xonk.XID)
 831			prev := getxonk(user.ID, xonk.XID)
 832			if prev == nil {
 833				log.Printf("didn't find old version for update: %s", xonk.XID)
 834				return nil
 835			}
 836			prev.Noise = xonk.Noise
 837			prev.Precis = xonk.Precis
 838			prev.Date = xonk.Date
 839			prev.Donks = xonk.Donks
 840			prev.Onts = xonk.Onts
 841			prev.Place = xonk.Place
 842			updatehonk(prev)
 843		} else if 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	j := junk.New()
 925	j["@context"] = itiswhatitis
 926	j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
 927	j["type"] = "Follow"
 928	j["actor"] = user.URL
 929	j["to"] = xid
 930	j["object"] = xid
 931	j["published"] = time.Now().UTC().Format(time.RFC3339)
 932
 933	var buf bytes.Buffer
 934	j.Write(&buf)
 935	msg := buf.Bytes()
 936
 937	deliverate(0, user.Name, xid, msg)
 938}
 939
 940// returns activity, object
 941func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
 942	dt := h.Date.Format(time.RFC3339)
 943	var jo junk.Junk
 944	j := junk.New()
 945	j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
 946	j["actor"] = user.URL
 947	j["published"] = dt
 948	if h.Public {
 949		j["to"] = []string{h.Audience[0], user.URL + "/followers"}
 950	} else {
 951		j["to"] = h.Audience[0]
 952	}
 953	if len(h.Audience) > 1 {
 954		j["cc"] = h.Audience[1:]
 955	}
 956
 957	switch h.What {
 958	case "update":
 959		fallthrough
 960	case "tonk":
 961		fallthrough
 962	case "event":
 963		fallthrough
 964	case "honk":
 965		j["type"] = "Create"
 966		if h.What == "update" {
 967			j["type"] = "Update"
 968		}
 969
 970		jo = junk.New()
 971		jo["id"] = h.XID
 972		jo["type"] = "Note"
 973		if h.What == "event" {
 974			jo["type"] = "Event"
 975		}
 976		jo["published"] = dt
 977		jo["url"] = h.XID
 978		jo["attributedTo"] = user.URL
 979		if h.RID != "" {
 980			jo["inReplyTo"] = h.RID
 981		}
 982		if h.Convoy != "" {
 983			jo["context"] = h.Convoy
 984			jo["conversation"] = h.Convoy
 985		}
 986		jo["to"] = h.Audience[0]
 987		if len(h.Audience) > 1 {
 988			jo["cc"] = h.Audience[1:]
 989		}
 990		if !h.Public {
 991			jo["directMessage"] = true
 992		}
 993		translate(h)
 994		h.Noise = re_memes.ReplaceAllString(h.Noise, "")
 995		jo["summary"] = h.Precis
 996		jo["content"] = ontologize(mentionize(h.Noise))
 997		if strings.HasPrefix(h.Precis, "DZ:") {
 998			jo["sensitive"] = true
 999		}
1000
1001		var replies []string
1002		for _, reply := range h.Replies {
1003			replies = append(replies, reply.XID)
1004		}
1005		if len(replies) > 0 {
1006			jr := junk.New()
1007			jr["type"] = "Collection"
1008			jr["totalItems"] = len(replies)
1009			jr["items"] = replies
1010			jo["replies"] = jr
1011		}
1012
1013		var tags []junk.Junk
1014		g := bunchofgrapes(h.Noise)
1015		for _, m := range g {
1016			t := junk.New()
1017			t["type"] = "Mention"
1018			t["name"] = m.who
1019			t["href"] = m.where
1020			tags = append(tags, t)
1021		}
1022		for _, o := range h.Onts {
1023			t := junk.New()
1024			t["type"] = "Hashtag"
1025			o = strings.ToLower(o)
1026			t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1027			t["name"] = o
1028			tags = append(tags, t)
1029		}
1030		herd := herdofemus(h.Noise)
1031		for _, e := range herd {
1032			t := junk.New()
1033			t["id"] = e.ID
1034			t["type"] = "Emoji"
1035			t["name"] = e.Name
1036			i := junk.New()
1037			i["type"] = "Image"
1038			i["mediaType"] = "image/png"
1039			i["url"] = e.ID
1040			t["icon"] = i
1041			tags = append(tags, t)
1042		}
1043		if p := h.Place; p != nil {
1044			t := junk.New()
1045			t["type"] = "Place"
1046			t["name"] = p.Name
1047			t["latitude"] = p.Latitude
1048			t["longitude"] = p.Longitude
1049			t["url"] = p.Url
1050			if h.What == "event" {
1051				jo["location"] = t
1052			} else {
1053				tags = append(tags, t)
1054			}
1055		}
1056		if len(tags) > 0 {
1057			jo["tag"] = tags
1058		}
1059		if t := h.Time; t != nil {
1060			jo["startTime"] = t.StartTime.Format(time.RFC3339)
1061			if t.Duration != 0 {
1062				jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1063			}
1064		}
1065		var atts []junk.Junk
1066		for _, d := range h.Donks {
1067			if re_emus.MatchString(d.Name) {
1068				continue
1069			}
1070			jd := junk.New()
1071			jd["mediaType"] = d.Media
1072			jd["name"] = d.Name
1073			jd["summary"] = d.Desc
1074			jd["type"] = "Document"
1075			jd["url"] = d.URL
1076			atts = append(atts, jd)
1077		}
1078		if len(atts) > 0 {
1079			jo["attachment"] = atts
1080		}
1081		j["object"] = jo
1082	case "bonk":
1083		j["type"] = "Announce"
1084		if h.Convoy != "" {
1085			j["context"] = h.Convoy
1086		}
1087		j["object"] = h.XID
1088	case "unbonk":
1089		b := junk.New()
1090		b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1091		b["type"] = "Announce"
1092		b["actor"] = user.URL
1093		if h.Convoy != "" {
1094			b["context"] = h.Convoy
1095		}
1096		b["object"] = h.XID
1097		j["type"] = "Undo"
1098		j["object"] = b
1099	case "zonk":
1100		j["type"] = "Delete"
1101		j["object"] = h.XID
1102	case "ack":
1103		j["type"] = "Read"
1104		j["object"] = h.XID
1105	case "deack":
1106		b := junk.New()
1107		b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1108		b["type"] = "Read"
1109		b["actor"] = user.URL
1110		b["object"] = h.XID
1111		j["type"] = "Undo"
1112		j["object"] = b
1113	}
1114
1115	return j, jo
1116}
1117
1118func honkworldwide(user *WhatAbout, honk *Honk) {
1119	jonk, _ := jonkjonk(user, honk)
1120	jonk["@context"] = itiswhatitis
1121	var buf bytes.Buffer
1122	jonk.Write(&buf)
1123	msg := buf.Bytes()
1124
1125	rcpts := make(map[string]bool)
1126	for _, a := range honk.Audience {
1127		if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1128			continue
1129		}
1130		box, _ := getboxes(a)
1131		if box != nil && honk.Public && box.Shared != "" {
1132			rcpts["%"+box.Shared] = true
1133		} else {
1134			rcpts[a] = true
1135		}
1136	}
1137	if honk.Public {
1138		for _, f := range getdubs(user.ID) {
1139			if f.XID == user.URL {
1140				continue
1141			}
1142			box, _ := getboxes(f.XID)
1143			if box != nil && box.Shared != "" {
1144				rcpts["%"+box.Shared] = true
1145			} else {
1146				rcpts[f.XID] = true
1147			}
1148		}
1149	}
1150	for a := range rcpts {
1151		go deliverate(0, user.Name, a, msg)
1152	}
1153}
1154
1155func asjonker(user *WhatAbout) junk.Junk {
1156	about := obfusbreak(user.About)
1157
1158	j := junk.New()
1159	j["@context"] = itiswhatitis
1160	j["id"] = user.URL
1161	j["type"] = "Person"
1162	j["inbox"] = user.URL + "/inbox"
1163	j["outbox"] = user.URL + "/outbox"
1164	j["followers"] = user.URL + "/followers"
1165	j["following"] = user.URL + "/following"
1166	j["name"] = user.Display
1167	j["preferredUsername"] = user.Name
1168	j["summary"] = about
1169	j["url"] = user.URL
1170	a := junk.New()
1171	a["type"] = "Image"
1172	a["mediaType"] = "image/png"
1173	a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1174	j["icon"] = a
1175	k := junk.New()
1176	k["id"] = user.URL + "#key"
1177	k["owner"] = user.URL
1178	k["publicKeyPem"] = user.Key
1179	j["publicKey"] = k
1180
1181	return j
1182}
1183
1184var handfull = make(map[string]string)
1185var handlock sync.Mutex
1186
1187func gofish(name string) string {
1188	if name[0] == '@' {
1189		name = name[1:]
1190	}
1191	m := strings.Split(name, "@")
1192	if len(m) != 2 {
1193		log.Printf("bad fish name: %s", name)
1194		return ""
1195	}
1196	handlock.Lock()
1197	ref, ok := handfull[name]
1198	handlock.Unlock()
1199	if ok {
1200		return ref
1201	}
1202	row := stmtGetXonker.QueryRow(name, "fishname")
1203	var href string
1204	err := row.Scan(&href)
1205	if err == nil {
1206		handlock.Lock()
1207		handfull[name] = href
1208		handlock.Unlock()
1209		return href
1210	}
1211	log.Printf("fishing for %s", name)
1212	j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1213	if err != nil {
1214		log.Printf("failed to go fish %s: %s", name, err)
1215		handlock.Lock()
1216		handfull[name] = ""
1217		handlock.Unlock()
1218		return ""
1219	}
1220	links, _ := j.GetArray("links")
1221	for _, li := range links {
1222		l, ok := li.(junk.Junk)
1223		if !ok {
1224			continue
1225		}
1226		href, _ := l.GetString("href")
1227		rel, _ := l.GetString("rel")
1228		t, _ := l.GetString("type")
1229		if rel == "self" && friendorfoe(t) {
1230			_, err := stmtSaveXonker.Exec(name, href, "fishname")
1231			if err != nil {
1232				log.Printf("error saving fishname: %s", err)
1233			}
1234			handlock.Lock()
1235			handfull[name] = href
1236			handlock.Unlock()
1237			return href
1238		}
1239	}
1240	handlock.Lock()
1241	handfull[name] = ""
1242	handlock.Unlock()
1243	return ""
1244}
1245
1246func isactor(t string) bool {
1247	switch t {
1248	case "Person":
1249	case "Organization":
1250	case "Application":
1251	case "Service":
1252	default:
1253		return false
1254	}
1255	return true
1256}
1257
1258func investigate(name string) (*Honker, error) {
1259	if name == "" {
1260		return nil, fmt.Errorf("no name")
1261	}
1262	if name[0] == '@' {
1263		name = gofish(name)
1264	}
1265	if name == "" {
1266		return nil, fmt.Errorf("no name")
1267	}
1268	log.Printf("digging up some info on %s", name)
1269	obj, err := GetJunkFast(name)
1270	if err != nil {
1271		log.Printf("error investigating honker: %s", err)
1272		return nil, err
1273	}
1274	t, _ := obj.GetString("type")
1275	if !isactor(t) {
1276		log.Printf("it's not a person! %s", name)
1277		return nil, err
1278	}
1279	xid, _ := obj.GetString("id")
1280	handle, _ := obj.GetString("preferredUsername")
1281	return &Honker{XID: xid, Handle: handle}, nil
1282}