all repos — honk @ fc48669ed0423b72bbb2500e785ef4f8f266c5ee

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