all repos — honk @ 5cacee23cdde3009ac4304827b4e52b6c8c5d476

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