all repos — honk @ 724f98d69d0ae219f4f656b97376658360474e49

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