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