all repos — honk @ 06ff96f72420c419871a3d85c951a0c29d6c0013

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