all repos — honk @ 6bf279da3fee4ef0493baef7bc454529e290a51c

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