all repos — honk @ 3f4e4a9dd65439abb761e7412b890d8faa7a5a1a

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