all repos — honk @ b60b88b850ecd6aa480df78600855bc79d634347

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