all repos — honk @ 60166f362b42a3ce1f89df5cab4275b6f5f558b4

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)
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, convoy 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 "Note":
489			obj = item.(map[string]interface{})
490			what = "honk"
491		case "Delete":
492			obj, _ = jsongetmap(item, "object")
493			rid, _ = jsongetstring(item, "object")
494			what = "eradicate"
495		default:
496			log.Printf("unknown activity: %s", what)
497			fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
498			WriteJunk(fd, item.(map[string]interface{}))
499			io.WriteString(fd, "\n")
500			fd.Close()
501			return nil
502		}
503
504		var xonk Honk
505		who, _ := jsongetstring(item, "actor")
506		if obj != nil {
507			if who == "" {
508				who, _ = jsongetstring(obj, "attributedTo")
509			}
510			ot, _ := jsongetstring(obj, "type")
511			url, _ = jsongetstring(obj, "url")
512			if ot == "Note" || ot == "Article" {
513				audience = newphone(audience, obj)
514				xid, _ = jsongetstring(obj, "id")
515				content, _ = jsongetstring(obj, "content")
516				summary, _ := jsongetstring(obj, "summary")
517				if !strings.HasPrefix(content, "<p>") {
518					content = "<p>" + content
519				}
520				if summary != "" {
521					content = "<p>summary: " + summary + content
522				}
523				rid, _ = jsongetstring(obj, "inReplyTo")
524				convoy, _ = jsongetstring(obj, "context")
525				if convoy == "" {
526					convoy, _ = jsongetstring(obj, "conversation")
527				}
528				if what == "honk" && rid != "" {
529					what = "tonk"
530				}
531			}
532			if ot == "Tombstone" {
533				rid, _ = jsongetstring(obj, "id")
534			}
535			atts, _ := jsongetarray(obj, "attachment")
536			for i, att := range atts {
537				at, _ := jsongetstring(att, "type")
538				mt, _ := jsongetstring(att, "mediaType")
539				u, _ := jsongetstring(att, "url")
540				name, _ := jsongetstring(att, "name")
541				if i < 4 && (at == "Document" || at == "Image") {
542					mt = strings.ToLower(mt)
543					log.Printf("attachment: %s %s", mt, u)
544					if mt == "image/jpeg" || mt == "image/png" ||
545						mt == "text/plain" {
546						donk := savedonk(u, name, mt)
547						if donk != nil {
548							xonk.Donks = append(xonk.Donks, donk)
549						}
550					} else {
551						u = html.EscapeString(u)
552						content += fmt.Sprintf(
553							`<p>External attachment: <a href="%s" rel=noreferrer>%s</a>`, u, u)
554					}
555				} else {
556					log.Printf("unknown attachment: %s", at)
557				}
558			}
559			tags, _ := jsongetarray(obj, "tag")
560			for _, tag := range tags {
561				tt, _ := jsongetstring(tag, "type")
562				name, _ := jsongetstring(tag, "name")
563				if tt == "Emoji" {
564					icon, _ := jsongetmap(tag, "icon")
565					mt, _ := jsongetstring(icon, "mediaType")
566					if mt == "" {
567						mt = "image/png"
568					}
569					u, _ := jsongetstring(icon, "url")
570					donk := savedonk(u, name, mt)
571					if donk != nil {
572						xonk.Donks = append(xonk.Donks, donk)
573					}
574				}
575			}
576		}
577		audience = append(audience, who)
578
579		audience = oneofakind(audience)
580
581		xonk.UserID = user.ID
582		xonk.What = what
583		xonk.Honker = who
584		xonk.XID = xid
585		xonk.RID = rid
586		xonk.Date, _ = time.Parse(time.RFC3339, dt)
587		xonk.URL = url
588		xonk.Noise = content
589		xonk.Audience = audience
590		xonk.Convoy = convoy
591
592		if needxonk(user, &xonk) {
593			if what == "tonk" {
594				if needxonkid(user, rid) {
595					saveoneup(rid)
596				}
597			}
598			return &xonk
599		}
600		return nil
601	}
602
603	return xonkxonkfn(item)
604}
605
606func rubadubdub(user *WhatAbout, req map[string]interface{}) {
607	xid, _ := jsongetstring(req, "id")
608	reqactor, _ := jsongetstring(req, "actor")
609	j := NewJunk()
610	j["@context"] = itiswhatitis
611	j["id"] = user.URL + "/dub/" + xid
612	j["type"] = "Accept"
613	j["actor"] = user.URL
614	j["to"] = reqactor
615	j["published"] = time.Now().UTC().Format(time.RFC3339)
616	j["object"] = req
617
618	WriteJunk(os.Stdout, j)
619
620	actor, _ := jsongetstring(req, "actor")
621	box, err := getboxes(actor)
622	if err != nil {
623		log.Printf("can't get dub box: %s", err)
624		return
625	}
626	keyname, key := ziggy(user.Name)
627	err = PostJunk(keyname, key, box.In, j)
628	if err != nil {
629		log.Printf("can't rub a dub: %s", err)
630		return
631	}
632	stmtSaveDub.Exec(user.ID, actor, actor, "dub")
633}
634
635func itakeitallback(user *WhatAbout, xid string) error {
636	j := NewJunk()
637	j["@context"] = itiswhatitis
638	j["id"] = user.URL + "/unsub/" + xid
639	j["type"] = "Undo"
640	j["actor"] = user.URL
641	j["to"] = xid
642	f := NewJunk()
643	f["id"] = user.URL + "/sub/" + xid
644	f["type"] = "Follow"
645	f["actor"] = user.URL
646	f["to"] = xid
647	j["object"] = f
648	j["published"] = time.Now().UTC().Format(time.RFC3339)
649
650	box, err := getboxes(xid)
651	if err != nil {
652		return err
653	}
654	keyname, key := ziggy(user.Name)
655	err = PostJunk(keyname, key, box.In, j)
656	if err != nil {
657		return err
658	}
659	return nil
660}
661
662func subsub(user *WhatAbout, xid string) {
663	j := NewJunk()
664	j["@context"] = itiswhatitis
665	j["id"] = user.URL + "/sub/" + xid
666	j["type"] = "Follow"
667	j["actor"] = user.URL
668	j["to"] = xid
669	j["object"] = xid
670	j["published"] = time.Now().UTC().Format(time.RFC3339)
671
672	box, err := getboxes(xid)
673	if err != nil {
674		log.Printf("can't send follow: %s", err)
675		return
676	}
677	WriteJunk(os.Stdout, j)
678	keyname, key := ziggy(user.Name)
679	err = PostJunk(keyname, key, box.In, j)
680	if err != nil {
681		log.Printf("failed to subsub: %s", err)
682	}
683}
684
685func jonkjonk(user *WhatAbout, h *Honk) (map[string]interface{}, map[string]interface{}) {
686	dt := h.Date.Format(time.RFC3339)
687	var jo map[string]interface{}
688	j := NewJunk()
689	j["id"] = user.URL + "/" + h.What + "/" + h.XID
690	j["actor"] = user.URL
691	j["published"] = dt
692	j["to"] = h.Audience[0]
693	if len(h.Audience) > 1 {
694		j["cc"] = h.Audience[1:]
695	}
696
697	switch h.What {
698	case "tonk":
699		fallthrough
700	case "honk":
701		j["type"] = "Create"
702
703		jo = NewJunk()
704		jo["id"] = user.URL + "/h/" + h.XID
705		jo["type"] = "Note"
706		jo["published"] = dt
707		jo["url"] = user.URL + "/h/" + h.XID
708		jo["attributedTo"] = user.URL
709		if h.RID != "" {
710			jo["inReplyTo"] = h.RID
711		}
712		if h.Convoy != "" {
713			jo["context"] = h.Convoy
714			jo["conversation"] = h.Convoy
715		}
716		jo["to"] = h.Audience[0]
717		if len(h.Audience) > 1 {
718			jo["cc"] = h.Audience[1:]
719		}
720		if strings.HasPrefix(h.Noise, "DZ:") {
721			// alas, it's already been turned into html
722			idx := strings.Index(h.Noise, "<br>")
723			if idx == -1 {
724				jo["summary"] = h.Noise
725				jo["content"] = ""
726			} else {
727				jo["summary"] = h.Noise[:idx]
728				if strings.HasPrefix(h.Noise[idx+4:], "<br>") {
729					idx += 4
730				}
731				jo["content"] = mentionize(h.Noise[idx+4:])
732			}
733			jo["sensitive"] = true
734		} else {
735			jo["content"] = mentionize(h.Noise)
736		}
737		var tags []interface{}
738		g := bunchofgrapes(h.Noise)
739		for _, m := range g {
740			t := NewJunk()
741			t["type"] = "Mention"
742			t["name"] = m.who
743			t["href"] = m.where
744			tags = append(tags, t)
745		}
746		herd := herdofemus(h.Noise)
747		for _, e := range herd {
748			t := NewJunk()
749			t["id"] = e.ID
750			t["type"] = "Emoji"
751			t["name"] = e.Name
752			i := NewJunk()
753			i["type"] = "Image"
754			i["mediaType"] = "image/png"
755			i["url"] = e.ID
756			t["icon"] = i
757			tags = append(tags, t)
758		}
759		if len(tags) > 0 {
760			jo["tag"] = tags
761		}
762		var atts []interface{}
763		for _, d := range h.Donks {
764			if re_emus.MatchString(d.Name) {
765				continue
766			}
767			jd := NewJunk()
768			jd["mediaType"] = d.Media
769			jd["name"] = d.Name
770			jd["type"] = "Document"
771			jd["url"] = d.URL
772			atts = append(atts, jd)
773		}
774		if len(atts) > 0 {
775			jo["attachment"] = atts
776		}
777		j["object"] = jo
778	case "bonk":
779		j["type"] = "Announce"
780		j["object"] = h.XID
781	case "zonk":
782		j["type"] = "Delete"
783		j["object"] = user.URL + "/h/" + h.XID
784	}
785
786	return j, jo
787}
788
789func honkworldwide(user *WhatAbout, honk *Honk) {
790	jonk, _ := jonkjonk(user, honk)
791	jonk["@context"] = itiswhatitis
792	var buf bytes.Buffer
793	WriteJunk(&buf, jonk)
794	msg := buf.Bytes()
795
796	rcpts := make(map[string]bool)
797	for _, a := range honk.Audience {
798		if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
799			box, _ := getboxes(a)
800			if box != nil && box.Shared != "" {
801				rcpts["%"+box.Shared] = true
802			} else {
803				rcpts[a] = true
804			}
805		}
806	}
807	for _, f := range getdubs(user.ID) {
808		box, _ := getboxes(f.XID)
809		if box != nil && box.Shared != "" {
810			rcpts["%"+box.Shared] = true
811		} else {
812			rcpts[f.XID] = true
813		}
814	}
815	for a := range rcpts {
816		go deliverate(0, user.Name, a, msg)
817	}
818}
819
820func asjonker(user *WhatAbout) map[string]interface{} {
821	about := obfusbreak(user.About)
822
823	j := NewJunk()
824	j["@context"] = itiswhatitis
825	j["id"] = user.URL
826	j["type"] = "Person"
827	j["inbox"] = user.URL + "/inbox"
828	j["outbox"] = user.URL + "/outbox"
829	j["followers"] = user.URL + "/followers"
830	j["following"] = user.URL + "/following"
831	j["name"] = user.Display
832	j["preferredUsername"] = user.Name
833	j["summary"] = about
834	j["url"] = user.URL
835	a := NewJunk()
836	a["type"] = "icon"
837	a["mediaType"] = "image/png"
838	a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
839	j["icon"] = a
840	k := NewJunk()
841	k["id"] = user.URL + "#key"
842	k["owner"] = user.URL
843	k["publicKeyPem"] = user.Key
844	j["publicKey"] = k
845
846	return j
847}
848
849var handfull = make(map[string]string)
850var handlock sync.Mutex
851
852func gofish(name string) string {
853	if name[0] == '@' {
854		name = name[1:]
855	}
856	m := strings.Split(name, "@")
857	if len(m) != 2 {
858		log.Printf("bad fish name: %s", name)
859		return ""
860	}
861	handlock.Lock()
862	ref, ok := handfull[name]
863	handlock.Unlock()
864	if ok {
865		return ref
866	}
867	db := opendatabase()
868	row := db.QueryRow("select ibox from xonkers where xid = ?", name)
869	var href string
870	err := row.Scan(&href)
871	if err == nil {
872		handlock.Lock()
873		handfull[name] = href
874		handlock.Unlock()
875		return href
876	}
877	log.Printf("fishing for %s", name)
878	j, err := GetJunk(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
879	if err != nil {
880		log.Printf("failed to go fish %s: %s", name, err)
881		handlock.Lock()
882		handfull[name] = ""
883		handlock.Unlock()
884		return ""
885	}
886	links, _ := jsongetarray(j, "links")
887	for _, l := range links {
888		href, _ := jsongetstring(l, "href")
889		rel, _ := jsongetstring(l, "rel")
890		t, _ := jsongetstring(l, "type")
891		if rel == "self" && friendorfoe(t) {
892			db.Exec("insert into xonkers (xid, ibox, obox, sbox, pubkey) values (?, ?, ?, ?, ?)",
893			name, href, "", "", "")
894			handlock.Lock()
895			handfull[name] = href
896			handlock.Unlock()
897			return href
898		}
899	}
900	handlock.Lock()
901	handfull[name] = ""
902	handlock.Unlock()
903	return ""
904}
905