all repos — honk @ 28ead20c47da900447c5b49e00429eca2a12919d

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