all repos — honk @ 039a5c36fa004f3096599b3b6f45a72e2ea3ed9d

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