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