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 arr, _ := obj.GetArray("attributedTo")
450 for _, a := range arr {
451 o, ok := a.(junk.Junk)
452 if ok {
453 t, _ := o.GetString("type")
454 id, _ := o.GetString("id")
455 if t == "Person" || t == "" {
456 return id
457 }
458 }
459 }
460 return ""
461}
462
463func consumeactivity(user *WhatAbout, j junk.Junk, origin string) {
464 xonk := xonkxonk(user, j, origin)
465 if xonk != nil {
466 savexonk(user, xonk)
467 }
468}
469
470func xonkxonk(user *WhatAbout, item junk.Junk, origin string) *Honk {
471 depth := 0
472 maxdepth := 4
473 currenttid := ""
474 var xonkxonkfn func(item junk.Junk, origin string) *Honk
475
476 saveoneup := func(xid string) {
477 log.Printf("getting oneup: %s", xid)
478 if depth >= maxdepth {
479 log.Printf("in too deep")
480 return
481 }
482 obj, err := GetJunk(xid)
483 if err != nil {
484 log.Printf("error getting oneup: %s", err)
485 return
486 }
487 depth++
488 xonk := xonkxonkfn(obj, originate(xid))
489 if xonk != nil {
490 savexonk(user, xonk)
491 }
492 depth--
493 }
494
495 xonkxonkfn = func(item junk.Junk, origin string) *Honk {
496 // id, _ := item.GetString( "id")
497 what, _ := item.GetString("type")
498 dt, _ := item.GetString("published")
499
500 var audience []string
501 var err error
502 var xid, rid, url, content, precis, convoy, oonker string
503 var obj junk.Junk
504 var ok bool
505 switch what {
506 case "Announce":
507 obj, ok = item.GetMap("object")
508 if ok {
509 xid, _ = obj.GetString("id")
510 } else {
511 xid, _ = item.GetString("object")
512 }
513 if !needxonkid(user, xid) {
514 return nil
515 }
516 log.Printf("getting bonk: %s", xid)
517 obj, err = GetJunk(xid)
518 if err != nil {
519 log.Printf("error regetting: %s", err)
520 }
521 origin = originate(xid)
522 what = "bonk"
523 case "Create":
524 obj, _ = item.GetMap("object")
525 what = "honk"
526 case "Delete":
527 obj, _ = item.GetMap("object")
528 xid, _ = item.GetString("object")
529 what = "eradicate"
530 case "Video":
531 fallthrough
532 case "Question":
533 fallthrough
534 case "Note":
535 fallthrough
536 case "Article":
537 fallthrough
538 case "Page":
539 obj = item
540 what = "honk"
541 default:
542 log.Printf("unknown activity: %s", what)
543 fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
544 item.Write(fd)
545 io.WriteString(fd, "\n")
546 fd.Close()
547 return nil
548 }
549
550 var xonk Honk
551 who, _ := item.GetString("actor")
552 if obj != nil {
553 if who == "" {
554 who = extractattrto(obj)
555 }
556 oonker = extractattrto(obj)
557 ot, _ := obj.GetString("type")
558 url, _ = obj.GetString("url")
559 if ot == "Tombstone" {
560 xid, _ = obj.GetString("id")
561 } else {
562 audience = newphone(audience, obj)
563 xid, _ = obj.GetString("id")
564 precis, _ = obj.GetString("summary")
565 if precis == "" {
566 precis, _ = obj.GetString("name")
567 }
568 content, _ = obj.GetString("content")
569 if !strings.HasPrefix(content, "<p>") {
570 content = "<p>" + content
571 }
572 sens, _ := obj["sensitive"].(bool)
573 if sens && precis == "" {
574 precis = "unspecified horror"
575 }
576 rid, _ = obj.GetString("inReplyTo")
577 convoy, _ = obj.GetString("context")
578 if convoy == "" {
579 convoy, _ = obj.GetString("conversation")
580 }
581 if ot == "Question" {
582 if what == "honk" {
583 what = "qonk"
584 }
585 content += "<ul>"
586 ans, _ := obj.GetArray("oneOf")
587 for _, ai := range ans {
588 a, ok := ai.(junk.Junk)
589 if !ok {
590 continue
591 }
592 as, _ := a.GetString("name")
593 content += "<li>" + as
594 }
595 ans, _ = obj.GetArray("anyOf")
596 for _, ai := range ans {
597 a, ok := ai.(junk.Junk)
598 if !ok {
599 continue
600 }
601 as, _ := a.GetString("name")
602 content += "<li>" + as
603 }
604 content += "</ul>"
605 }
606 if what == "honk" && rid != "" {
607 what = "tonk"
608 }
609 }
610 atts, _ := obj.GetArray("attachment")
611 for i, atti := range atts {
612 att, ok := atti.(junk.Junk)
613 if !ok {
614 continue
615 }
616 at, _ := att.GetString("type")
617 mt, _ := att.GetString("mediaType")
618 u, _ := att.GetString("url")
619 name, _ := att.GetString("name")
620 localize := false
621 if i > 4 {
622 log.Printf("excessive attachment: %s", at)
623 } else if at == "Document" || at == "Image" {
624 mt = strings.ToLower(mt)
625 log.Printf("attachment: %s %s", mt, u)
626 if mt == "text/plain" || strings.HasPrefix(mt, "image") {
627 localize = true
628 }
629 } else {
630 log.Printf("unknown attachment: %s", at)
631 }
632 donk := savedonk(u, name, mt, localize)
633 if donk != nil {
634 xonk.Donks = append(xonk.Donks, donk)
635 }
636 }
637 tags, _ := obj.GetArray("tag")
638 for _, tagi := range tags {
639 tag, ok := tagi.(junk.Junk)
640 if !ok {
641 continue
642 }
643 tt, _ := tag.GetString("type")
644 name, _ := tag.GetString("name")
645 if tt == "Emoji" {
646 icon, _ := tag.GetMap("icon")
647 mt, _ := icon.GetString("mediaType")
648 if mt == "" {
649 mt = "image/png"
650 }
651 u, _ := icon.GetString("url")
652 donk := savedonk(u, name, mt, true)
653 if donk != nil {
654 xonk.Donks = append(xonk.Donks, donk)
655 }
656 }
657 }
658 }
659 if originate(xid) != origin {
660 log.Printf("original sin: %s <> %s", xid, origin)
661 item.Write(os.Stdout)
662 return nil
663 }
664 audience = append(audience, who)
665
666 audience = oneofakind(audience)
667
668 if currenttid == "" {
669 currenttid = convoy
670 }
671
672 if oonker == who {
673 oonker = ""
674 }
675 xonk.UserID = user.ID
676 xonk.What = what
677 xonk.Honker = who
678 xonk.XID = xid
679 xonk.RID = rid
680 xonk.Date, _ = time.Parse(time.RFC3339, dt)
681 xonk.URL = url
682 xonk.Noise = content
683 xonk.Precis = precis
684 xonk.Audience = audience
685 xonk.Oonker = oonker
686
687 if needxonk(user, &xonk) {
688 if rid != "" {
689 if needxonkid(user, rid) {
690 saveoneup(rid)
691 }
692 }
693 if convoy == "" {
694 convoy = currenttid
695 }
696 xonk.Convoy = convoy
697 return &xonk
698 }
699 return nil
700 }
701
702 return xonkxonkfn(item, origin)
703}
704
705func rubadubdub(user *WhatAbout, req junk.Junk) {
706 xid, _ := req.GetString("id")
707 actor, _ := req.GetString("actor")
708 j := junk.New()
709 j["@context"] = itiswhatitis
710 j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
711 j["type"] = "Accept"
712 j["actor"] = user.URL
713 j["to"] = actor
714 j["published"] = time.Now().UTC().Format(time.RFC3339)
715 j["object"] = req
716
717 var buf bytes.Buffer
718 j.Write(&buf)
719 msg := buf.Bytes()
720
721 deliverate(0, user.Name, actor, msg)
722}
723
724func itakeitallback(user *WhatAbout, xid string) {
725 j := junk.New()
726 j["@context"] = itiswhatitis
727 j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
728 j["type"] = "Undo"
729 j["actor"] = user.URL
730 j["to"] = xid
731 f := junk.New()
732 f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
733 f["type"] = "Follow"
734 f["actor"] = user.URL
735 f["to"] = xid
736 f["object"] = xid
737 j["object"] = f
738 j["published"] = time.Now().UTC().Format(time.RFC3339)
739
740 var buf bytes.Buffer
741 j.Write(&buf)
742 msg := buf.Bytes()
743
744 deliverate(0, user.Name, xid, msg)
745}
746
747func subsub(user *WhatAbout, xid string) {
748 j := junk.New()
749 j["@context"] = itiswhatitis
750 j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
751 j["type"] = "Follow"
752 j["actor"] = user.URL
753 j["to"] = xid
754 j["object"] = xid
755 j["published"] = time.Now().UTC().Format(time.RFC3339)
756
757 var buf bytes.Buffer
758 j.Write(&buf)
759 msg := buf.Bytes()
760
761 deliverate(0, user.Name, xid, msg)
762}
763
764var re_spicy = regexp.MustCompile("^(\U0001f336\ufe0f?){3,}")
765
766func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
767 dt := h.Date.Format(time.RFC3339)
768 var jo junk.Junk
769 j := junk.New()
770 j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
771 j["actor"] = user.URL
772 j["published"] = dt
773 if h.Public {
774 j["to"] = []string{h.Audience[0], user.URL + "/followers"}
775 } else {
776 j["to"] = h.Audience[0]
777 }
778 if len(h.Audience) > 1 {
779 j["cc"] = h.Audience[1:]
780 }
781
782 switch h.What {
783 case "tonk":
784 fallthrough
785 case "honk":
786 j["type"] = "Create"
787
788 jo = junk.New()
789 jo["id"] = h.XID
790 jo["type"] = "Note"
791 jo["published"] = dt
792 jo["url"] = h.XID
793 jo["attributedTo"] = user.URL
794 if h.RID != "" {
795 jo["inReplyTo"] = h.RID
796 }
797 if h.Convoy != "" {
798 jo["context"] = h.Convoy
799 jo["conversation"] = h.Convoy
800 }
801 jo["to"] = h.Audience[0]
802 if len(h.Audience) > 1 {
803 jo["cc"] = h.Audience[1:]
804 }
805 if !h.Public {
806 jo["directMessage"] = true
807 }
808 jo["summary"] = h.Precis
809 jo["content"] = mentionize(h.Noise)
810 if strings.HasPrefix(h.Precis, "DZ:") {
811 jo["sensitive"] = true
812 } else if peppers := re_spicy.FindString(h.Noise); peppers != "" {
813 jo["summary"] = peppers
814 jo["sensitive"] = true
815 }
816
817 var tags []interface{}
818 g := bunchofgrapes(h.Noise)
819 for _, m := range g {
820 t := junk.New()
821 t["type"] = "Mention"
822 t["name"] = m.who
823 t["href"] = m.where
824 tags = append(tags, t)
825 }
826 ooo := ontologies(h.Noise)
827 for _, o := range ooo {
828 t := junk.New()
829 t["type"] = "Hashtag"
830 t["name"] = o
831 tags = append(tags, t)
832 }
833 herd := herdofemus(h.Noise)
834 for _, e := range herd {
835 t := junk.New()
836 t["id"] = e.ID
837 t["type"] = "Emoji"
838 t["name"] = e.Name
839 i := junk.New()
840 i["type"] = "Image"
841 i["mediaType"] = "image/png"
842 i["url"] = e.ID
843 t["icon"] = i
844 tags = append(tags, t)
845 }
846 if len(tags) > 0 {
847 jo["tag"] = tags
848 }
849 var atts []interface{}
850 for _, d := range h.Donks {
851 if re_emus.MatchString(d.Name) {
852 continue
853 }
854 jd := junk.New()
855 jd["mediaType"] = d.Media
856 jd["name"] = d.Name
857 jd["type"] = "Document"
858 jd["url"] = d.URL
859 atts = append(atts, jd)
860 }
861 if len(atts) > 0 {
862 jo["attachment"] = atts
863 }
864 j["object"] = jo
865 case "bonk":
866 j["type"] = "Announce"
867 if h.Convoy != "" {
868 j["context"] = h.Convoy
869 }
870 j["object"] = h.XID
871 case "zonk":
872 j["type"] = "Delete"
873 j["object"] = h.XID
874 }
875
876 return j, jo
877}
878
879func honkworldwide(user *WhatAbout, honk *Honk) {
880 jonk, _ := jonkjonk(user, honk)
881 jonk["@context"] = itiswhatitis
882 var buf bytes.Buffer
883 jonk.Write(&buf)
884 msg := buf.Bytes()
885
886 rcpts := make(map[string]bool)
887 for _, a := range honk.Audience {
888 if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
889 box, _ := getboxes(a)
890 if box != nil {
891 if honk.Public && box.Shared != "" {
892 rcpts["%"+box.Shared] = true
893 } else {
894 rcpts["%"+box.In] = true
895 }
896 } else {
897 rcpts[a] = true
898 }
899 }
900 }
901 if honk.Public {
902 for _, f := range getdubs(user.ID) {
903 box, _ := getboxes(f.XID)
904 if box != nil && box.Shared != "" {
905 rcpts["%"+box.Shared] = true
906 } else {
907 rcpts[f.XID] = true
908 }
909 }
910 }
911 for a := range rcpts {
912 go deliverate(0, user.Name, a, msg)
913 }
914}
915
916func asjonker(user *WhatAbout) junk.Junk {
917 about := obfusbreak(user.About)
918
919 j := junk.New()
920 j["@context"] = itiswhatitis
921 j["id"] = user.URL
922 j["type"] = "Person"
923 j["inbox"] = user.URL + "/inbox"
924 j["outbox"] = user.URL + "/outbox"
925 j["followers"] = user.URL + "/followers"
926 j["following"] = user.URL + "/following"
927 j["name"] = user.Display
928 j["preferredUsername"] = user.Name
929 j["summary"] = about
930 j["url"] = user.URL
931 a := junk.New()
932 a["type"] = "Image"
933 a["mediaType"] = "image/png"
934 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
935 j["icon"] = a
936 k := junk.New()
937 k["id"] = user.URL + "#key"
938 k["owner"] = user.URL
939 k["publicKeyPem"] = user.Key
940 j["publicKey"] = k
941
942 return j
943}
944
945var handfull = make(map[string]string)
946var handlock sync.Mutex
947
948func gofish(name string) string {
949 if name[0] == '@' {
950 name = name[1:]
951 }
952 m := strings.Split(name, "@")
953 if len(m) != 2 {
954 log.Printf("bad fish name: %s", name)
955 return ""
956 }
957 handlock.Lock()
958 ref, ok := handfull[name]
959 handlock.Unlock()
960 if ok {
961 return ref
962 }
963 row := stmtGetXonker.QueryRow(name, "fishname")
964 var href string
965 err := row.Scan(&href)
966 if err == nil {
967 handlock.Lock()
968 handfull[name] = href
969 handlock.Unlock()
970 return href
971 }
972 log.Printf("fishing for %s", name)
973 j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
974 if err != nil {
975 log.Printf("failed to go fish %s: %s", name, err)
976 handlock.Lock()
977 handfull[name] = ""
978 handlock.Unlock()
979 return ""
980 }
981 links, _ := j.GetArray("links")
982 for _, li := range links {
983 l, ok := li.(junk.Junk)
984 if !ok {
985 continue
986 }
987 href, _ := l.GetString("href")
988 rel, _ := l.GetString("rel")
989 t, _ := l.GetString("type")
990 if rel == "self" && friendorfoe(t) {
991 stmtSaveXonker.Exec(name, href, "fishname")
992 handlock.Lock()
993 handfull[name] = href
994 handlock.Unlock()
995 return href
996 }
997 }
998 handlock.Lock()
999 handfull[name] = ""
1000 handlock.Unlock()
1001 return ""
1002}
1003
1004func isactor(t string) bool {
1005 switch t {
1006 case "Person":
1007 case "Application":
1008 case "Service":
1009 default:
1010 return false
1011 }
1012 return true
1013}
1014
1015func investigate(name string) string {
1016 if name == "" {
1017 return ""
1018 }
1019 if name[0] == '@' {
1020 name = gofish(name)
1021 }
1022 if name == "" {
1023 return ""
1024 }
1025 obj, err := GetJunkFast(name)
1026 if err != nil {
1027 log.Printf("error investigating honker: %s", err)
1028 return ""
1029 }
1030 t, _ := obj.GetString("type")
1031 if !isactor(t) {
1032 log.Printf("it's not a person! %s", name)
1033 return ""
1034 }
1035 id, _ := obj.GetString("id")
1036 return id
1037}