all repos — honk @ 8935c6ad3c41d3cb4e9910ebe71aab076075ebaa

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