all repos — honk @ 2bb87a7cff4cd5c6fcae45f8cd40dfbd85bd456b

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