all repos — honk @ 9ecbd57f09a044972ef5ee5772d5df1808343171

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