all repos — honk @ 0974e669a03327ccd4192421272bdc227ba46ed3

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