all repos — honk @ c008f7b2513b77d4674570190cc81dd9d9e2d20a

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