all repos — honk @ f37b30f081397e6e0ad92b7e23861e70870e0f87

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