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