1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
|
package pub
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/superseriousbusiness/activity/streams"
"github.com/superseriousbusiness/activity/streams/vocab"
)
// sideEffectActor must satisfy the DelegateActor interface.
var _ DelegateActor = &SideEffectActor{}
// SideEffectActor is a DelegateActor that handles the ActivityPub
// implementation side effects, but requires a more opinionated application to
// be written.
//
// Note that when using the SideEffectActor with an application that good-faith
// implements its required interfaces, the ActivityPub specification is
// guaranteed to be correctly followed.
type SideEffectActor struct {
common CommonBehavior
s2s FederatingProtocol
c2s SocialProtocol
db Database
clock Clock
}
// NewSideEffectActor returns a new SideEffectActor, which satisfies the
// DelegateActor interface. Most of the time you will not need to call this
// function, and should instead rely on the NewSocialActor, NewFederatingActor,
// and NewActor functions, all of which use a SideEffectActor under the hood.
// Nevertheless, this function is exposed in case application developers need
// a SideEffectActor for some other reason (tests, monkey patches, etc).
//
// If you are using the returned SideEffectActor for federation, ensure that s2s
// is not nil. Likewise, if you are using it for the social protocol, ensure
// that c2s is not nil.
func NewSideEffectActor(c CommonBehavior,
s2s FederatingProtocol,
c2s SocialProtocol,
db Database,
clock Clock) *SideEffectActor {
return &SideEffectActor{
common: c,
s2s: s2s,
c2s: c2s,
db: db,
clock: clock,
}
}
// PostInboxRequestBodyHook defers to the delegate.
func (a *SideEffectActor) PostInboxRequestBodyHook(c context.Context, r *http.Request, activity Activity) (context.Context, error) {
return a.s2s.PostInboxRequestBodyHook(c, r, activity)
}
// PostOutboxRequestBodyHook defers to the delegate.
func (a *SideEffectActor) PostOutboxRequestBodyHook(c context.Context, r *http.Request, data vocab.Type) (context.Context, error) {
return a.c2s.PostOutboxRequestBodyHook(c, r, data)
}
// AuthenticatePostInbox defers to the delegate to authenticate the request.
func (a *SideEffectActor) AuthenticatePostInbox(c context.Context, w http.ResponseWriter, r *http.Request) (out context.Context, authenticated bool, err error) {
return a.s2s.AuthenticatePostInbox(c, w, r)
}
// AuthenticateGetInbox defers to the delegate to authenticate the request.
func (a *SideEffectActor) AuthenticateGetInbox(c context.Context, w http.ResponseWriter, r *http.Request) (out context.Context, authenticated bool, err error) {
return a.common.AuthenticateGetInbox(c, w, r)
}
// AuthenticatePostOutbox defers to the delegate to authenticate the request.
func (a *SideEffectActor) AuthenticatePostOutbox(c context.Context, w http.ResponseWriter, r *http.Request) (out context.Context, authenticated bool, err error) {
return a.c2s.AuthenticatePostOutbox(c, w, r)
}
// AuthenticateGetOutbox defers to the delegate to authenticate the request.
func (a *SideEffectActor) AuthenticateGetOutbox(c context.Context, w http.ResponseWriter, r *http.Request) (out context.Context, authenticated bool, err error) {
return a.common.AuthenticateGetOutbox(c, w, r)
}
// GetOutbox delegates to the SocialProtocol.
func (a *SideEffectActor) GetOutbox(c context.Context, r *http.Request) (vocab.ActivityStreamsOrderedCollectionPage, error) {
return a.common.GetOutbox(c, r)
}
// GetInbox delegates to the FederatingProtocol.
func (a *SideEffectActor) GetInbox(c context.Context, r *http.Request) (vocab.ActivityStreamsOrderedCollectionPage, error) {
return a.s2s.GetInbox(c, r)
}
// AuthorizePostInbox defers to the federating protocol whether the peer request
// is authorized based on the actors' ids.
func (a *SideEffectActor) AuthorizePostInbox(c context.Context, w http.ResponseWriter, activity Activity) (authorized bool, err error) {
authorized = false
actor := activity.GetActivityStreamsActor()
if actor == nil {
err = fmt.Errorf("no actors in post to inbox")
return
}
var iris []*url.URL
for i := 0; i < actor.Len(); i++ {
iter := actor.At(i)
if iter.IsIRI() {
iris = append(iris, iter.GetIRI())
} else if t := iter.GetType(); t != nil {
iris = append(iris, activity.GetJSONLDId().Get())
} else {
err = fmt.Errorf("actor at index %d is missing an id", i)
return
}
}
// Determine if the actor(s) sending this request are blocked.
var blocked bool
if blocked, err = a.s2s.Blocked(c, iris); err != nil {
return
} else if blocked {
w.WriteHeader(http.StatusForbidden)
return
}
authorized = true
return
}
// PostInbox handles the side effects of determining whether to block the peer's
// request, adding the activity to the actor's inbox, and triggering side
// effects based on the activity's type.
func (a *SideEffectActor) PostInbox(c context.Context, inboxIRI *url.URL, activity Activity) error {
isNew, err := a.addToInboxIfNew(c, inboxIRI, activity)
if err != nil {
return err
}
if isNew {
wrapped, other, err := a.s2s.FederatingCallbacks(c)
if err != nil {
return err
}
// Populate side channels.
wrapped.db = a.db
wrapped.inboxIRI = inboxIRI
wrapped.newTransport = a.common.NewTransport
wrapped.deliver = a.Deliver
wrapped.addNewIds = a.AddNewIDs
res, err := streams.NewTypeResolver(wrapped.callbacks(other)...)
if err != nil {
return err
}
if err = res.Resolve(c, activity); err != nil && !streams.IsUnmatchedErr(err) {
return err
} else if streams.IsUnmatchedErr(err) {
err = a.s2s.DefaultCallback(c, activity)
if err != nil {
return err
}
}
}
return nil
}
// InboxForwarding implements the 3-part inbox forwarding algorithm specified in
// the ActivityPub specification. Does not modify the Activity, but may send
// outbound requests as a side effect.
//
// InboxForwarding sets the federated data in the database.
func (a *SideEffectActor) InboxForwarding(c context.Context, inboxIRI *url.URL, activity Activity) error {
// 1. Must be first time we have seen this Activity.
//
// Obtain the id of the activity
id := activity.GetJSONLDId()
// Acquire a lock for the id. To be held for the rest of execution.
unlock, err := a.db.Lock(c, id.Get())
if err != nil {
return err
}
// WARNING: Unlock is not deferred
//
// If the database already contains the activity, exit early.
exists, err := a.db.Exists(c, id.Get())
if err != nil {
unlock()
return err
} else if exists {
unlock()
return nil
}
// Attempt to create the activity entry.
err = a.db.Create(c, activity)
unlock() // unlock even on error return
if err != nil {
return err
}
// Unlock by this point and in every branch above.
//
// 2. The values of 'to', 'cc', or 'audience' are Collections owned by
// this server.
var r []*url.URL
to := activity.GetActivityStreamsTo()
if to != nil {
for iter := to.Begin(); iter != to.End(); iter = iter.Next() {
val, err := ToId(iter)
if err != nil {
return err
}
r = append(r, val)
}
}
cc := activity.GetActivityStreamsCc()
if cc != nil {
for iter := cc.Begin(); iter != cc.End(); iter = iter.Next() {
val, err := ToId(iter)
if err != nil {
return err
}
r = append(r, val)
}
}
audience := activity.GetActivityStreamsAudience()
if audience != nil {
for iter := audience.Begin(); iter != audience.End(); iter = iter.Next() {
val, err := ToId(iter)
if err != nil {
return err
}
r = append(r, val)
}
}
// Find all IRIs owned by this server. We need to find all of them so
// that forwarding can properly occur.
var myIRIs []*url.URL
for _, iri := range r {
if err != nil {
return err
}
var unlock func()
unlock, err = a.db.Lock(c, iri)
if err != nil {
return err
}
// WARNING: Unlock is not deferred
owns, err := a.db.Owns(c, iri)
unlock() // unlock even on error
if err != nil {
return err
} else if !owns {
continue
}
// Unlock by this point and in every branch above.
myIRIs = append(myIRIs, iri)
}
// Finally, load our IRIs to determine if they are a Collection or
// OrderedCollection.
//
// Load the unfiltered IRIs.
var colIRIs []*url.URL
col := make(map[string]itemser)
oCol := make(map[string]orderedItemser)
for _, iri := range myIRIs {
var unlock func()
unlock, err = a.db.Lock(c, iri)
if err != nil {
return err
}
// WARNING: Not Unlocked
t, err := a.db.Get(c, iri)
if err != nil {
return err
}
if streams.IsOrExtendsActivityStreamsOrderedCollection(t) {
if im, ok := t.(orderedItemser); ok {
oCol[iri.String()] = im
colIRIs = append(colIRIs, iri)
defer unlock()
} else {
unlock() // unlock instantly
}
} else if streams.IsOrExtendsActivityStreamsCollection(t) {
if im, ok := t.(itemser); ok {
col[iri.String()] = im
colIRIs = append(colIRIs, iri)
defer unlock()
} else {
unlock() // unlock instantly
}
} else {
unlock() // unlock instantly
}
}
// If we own none of the Collection IRIs in 'to', 'cc', or 'audience'
// then no need to do inbox forwarding. We have nothing to forward to.
if len(colIRIs) == 0 {
return nil
}
// 3. The values of 'inReplyTo', 'object', 'target', or 'tag' are owned
// by this server. This is only a boolean trigger: As soon as we get
// a hit that we own something, then we should do inbox forwarding.
maxDepth := a.s2s.MaxInboxForwardingRecursionDepth(c)
ownsValue, err := a.hasInboxForwardingValues(c, inboxIRI, activity, maxDepth, 0)
if err != nil {
return err
}
// If we don't own any of the 'inReplyTo', 'object', 'target', or 'tag'
// values, then no need to do inbox forwarding.
if !ownsValue {
return nil
}
// Do the inbox forwarding since the above conditions hold true. Support
// the behavior of letting the application filter out the resulting
// collections to be targeted.
toSend, err := a.s2s.FilterForwarding(c, colIRIs, activity)
if err != nil {
return err
}
recipients := make([]*url.URL, 0, len(toSend))
for _, iri := range toSend {
if c, ok := col[iri.String()]; ok {
if it := c.GetActivityStreamsItems(); it != nil {
for iter := it.Begin(); iter != it.End(); iter = iter.Next() {
id, err := ToId(iter)
if err != nil {
return err
}
recipients = append(recipients, id)
}
}
} else if oc, ok := oCol[iri.String()]; ok {
if oit := oc.GetActivityStreamsOrderedItems(); oit != nil {
for iter := oit.Begin(); iter != oit.End(); iter = iter.Next() {
id, err := ToId(iter)
if err != nil {
return err
}
recipients = append(recipients, id)
}
}
}
}
return a.deliverToRecipients(c, inboxIRI, activity, recipients)
}
// PostOutbox handles the side effects of adding the activity to the actor's
// outbox, and triggering side effects based on the activity's type.
//
// This implementation assumes all types are meant to be delivered except for
// the ActivityStreams Block type.
func (a *SideEffectActor) PostOutbox(c context.Context, activity Activity, outboxIRI *url.URL, rawJSON map[string]interface{}) (deliverable bool, err error) {
// TODO: Determine this if c2s is nil
deliverable = true
if a.c2s != nil {
var wrapped SocialWrappedCallbacks
var other []interface{}
wrapped, other, err = a.c2s.SocialCallbacks(c)
if err != nil {
return
}
// Populate side channels.
wrapped.db = a.db
wrapped.outboxIRI = outboxIRI
wrapped.rawActivity = rawJSON
wrapped.clock = a.clock
wrapped.newTransport = a.common.NewTransport
undeliverable := false
wrapped.undeliverable = &undeliverable
var res *streams.TypeResolver
res, err = streams.NewTypeResolver(wrapped.callbacks(other)...)
if err != nil {
return
}
if err = res.Resolve(c, activity); err != nil && !streams.IsUnmatchedErr(err) {
return
} else if streams.IsUnmatchedErr(err) {
deliverable = true
err = a.c2s.DefaultCallback(c, activity)
if err != nil {
return
}
} else {
deliverable = !undeliverable
}
}
err = a.addToOutbox(c, outboxIRI, activity)
return
}
// AddNewIDs creates new 'id' entries on an activity and its objects if it is a
// Create activity.
func (a *SideEffectActor) AddNewIDs(c context.Context, activity Activity) error {
id, err := a.db.NewID(c, activity)
if err != nil {
return err
}
activityId := streams.NewJSONLDIdProperty()
activityId.Set(id)
activity.SetJSONLDId(activityId)
if streams.IsOrExtendsActivityStreamsCreate(activity) {
o, ok := activity.(objecter)
if !ok {
return fmt.Errorf("cannot add new id for Create: %T has no object property", activity)
}
if oProp := o.GetActivityStreamsObject(); oProp != nil {
for iter := oProp.Begin(); iter != oProp.End(); iter = iter.Next() {
t := iter.GetType()
if t == nil {
return fmt.Errorf("cannot add new id for object in Create: object is not embedded as a value literal")
}
id, err = a.db.NewID(c, t)
if err != nil {
return err
}
objId := streams.NewJSONLDIdProperty()
objId.Set(id)
t.SetJSONLDId(objId)
}
}
}
return nil
}
// deliver will complete the peer-to-peer sending of a federated message to
// another server.
//
// Must be called if at least the federated protocol is supported.
func (a *SideEffectActor) Deliver(c context.Context, outboxIRI *url.URL, activity Activity) error {
recipients, err := a.prepare(c, outboxIRI, activity)
if err != nil {
return err
}
return a.deliverToRecipients(c, outboxIRI, activity, recipients)
}
// WrapInCreate wraps an object with a Create activity.
func (a *SideEffectActor) WrapInCreate(c context.Context, obj vocab.Type, outboxIRI *url.URL) (create vocab.ActivityStreamsCreate, err error) {
var unlock func()
unlock, err = a.db.Lock(c, outboxIRI)
if err != nil {
return
}
// WARNING: No deferring the Unlock
actorIRI, err := a.db.ActorForOutbox(c, outboxIRI)
unlock() // unlock after regardless
if err != nil {
return
}
// Unlock the lock at this point and every branch above
return wrapInCreate(c, obj, actorIRI)
}
// deliverToRecipients will take a prepared Activity and send it to specific
// recipients on behalf of an actor.
func (a *SideEffectActor) deliverToRecipients(c context.Context, boxIRI *url.URL, activity Activity, recipients []*url.URL) error {
m, err := streams.Serialize(activity)
if err != nil {
return err
}
b, err := json.Marshal(m)
if err != nil {
return err
}
tp, err := a.common.NewTransport(c, boxIRI, goFedUserAgent())
if err != nil {
return err
}
return tp.BatchDeliver(c, b, recipients)
}
// addToOutbox adds the activity to the outbox and creates the activity in the
// internal database as its own entry.
func (a *SideEffectActor) addToOutbox(c context.Context, outboxIRI *url.URL, activity Activity) error {
// Set the activity in the database first.
id := activity.GetJSONLDId()
unlock, err := a.db.Lock(c, id.Get())
if err != nil {
return err
}
// WARNING: Unlock not deferred
err = a.db.Create(c, activity)
unlock() // unlock after regardless
if err != nil {
return err
}
// WARNING: Unlock(c, id) should be called by this point and in every
// return before here.
//
// Acquire a lock to read the outbox. Defer release.
unlock, err = a.db.Lock(c, outboxIRI)
if err != nil {
return err
}
defer unlock()
outbox, err := a.db.GetOutbox(c, outboxIRI)
if err != nil {
return err
}
// Prepend the activity to the list of 'orderedItems'.
oi := outbox.GetActivityStreamsOrderedItems()
if oi == nil {
oi = streams.NewActivityStreamsOrderedItemsProperty()
}
oi.PrependIRI(id.Get())
outbox.SetActivityStreamsOrderedItems(oi)
// Save in the database.
err = a.db.SetOutbox(c, outbox)
return err
}
// addToInboxIfNew will add the activity to the inbox at the specified IRI if
// the activity's ID has not yet been added to the inbox.
//
// It does not add the activity to this database's know federated data.
//
// Returns true when the activity is novel.
func (a *SideEffectActor) addToInboxIfNew(c context.Context, inboxIRI *url.URL, activity Activity) (isNew bool, err error) {
// Acquire a lock to read the inbox. Defer release.
var unlock func()
unlock, err = a.db.Lock(c, inboxIRI)
if err != nil {
return
}
defer unlock()
// Obtain the id of the activity
id := activity.GetJSONLDId()
// If the inbox already contains the URL, early exit.
contains, err := a.db.InboxContains(c, inboxIRI, id.Get())
if err != nil {
return
} else if contains {
return
}
// It is a new id, acquire the inbox.
isNew = true
inbox, err := a.db.GetInbox(c, inboxIRI)
if err != nil {
return
}
// Prepend the activity to the list of 'orderedItems'.
oi := inbox.GetActivityStreamsOrderedItems()
if oi == nil {
oi = streams.NewActivityStreamsOrderedItemsProperty()
}
oi.PrependIRI(id.Get())
inbox.SetActivityStreamsOrderedItems(oi)
// Save in the database.
err = a.db.SetInbox(c, inbox)
return
}
// Given an ActivityStreams value, recursively examines ownership of the id or
// href and the ones on properties applicable to inbox forwarding.
//
// Recursion may be limited by providing a 'maxDepth' greater than zero. A
// value of zero or a negative number will result in infinite recursion.
func (a *SideEffectActor) hasInboxForwardingValues(c context.Context, inboxIRI *url.URL, val vocab.Type, maxDepth, currDepth int) (bool, error) {
// Stop recurring if we are exceeding the maximum depth and the maximum
// is a positive number.
if maxDepth > 0 && currDepth >= maxDepth {
return false, nil
}
// Determine if we own the 'id' of any values on the properties we care
// about.
types, iris := getInboxForwardingValues(val)
// For IRIs, simply check if we own them.
for _, iri := range iris {
unlock, err := a.db.Lock(c, iri)
if err != nil {
return false, err
}
// WARNING: Unlock is not deferred
owns, err := a.db.Owns(c, iri)
unlock() // unlock after regardless
if err != nil {
return false, err
} else if owns {
return true, nil
}
// Unlock by this point and in every branch above
}
// For embedded literals, check the id.
for _, val := range types {
id, err := GetId(val)
if err != nil {
return false, err
}
var unlock func()
unlock, err = a.db.Lock(c, id)
if err != nil {
return false, err
}
// WARNING: Unlock is not deferred
owns, err := a.db.Owns(c, id)
unlock() // unlock after regardless
if err != nil {
return false, err
} else if owns {
return true, nil
}
// Unlock by this point and in every branch above
}
// Recur Preparation: Try fetching the IRIs so we can recur into them.
for _, iri := range iris {
// Dereferencing the IRI.
tport, err := a.common.NewTransport(c, inboxIRI, goFedUserAgent())
if err != nil {
return false, err
}
b, err := tport.Dereference(c, iri)
if err != nil {
// Do not fail the entire process if the data is
// missing.
continue
}
var m map[string]interface{}
if err = json.Unmarshal(b, &m); err != nil {
return false, err
}
t, err := streams.ToType(c, m)
if err != nil {
// Do not fail the entire process if we cannot handle
// the type.
continue
}
types = append(types, t)
}
// Recur.
for _, nextVal := range types {
if has, err := a.hasInboxForwardingValues(c, inboxIRI, nextVal, maxDepth, currDepth+1); err != nil {
return false, err
} else if has {
return true, nil
}
}
return false, nil
}
// prepare takes a deliverableObject and returns a list of the proper recipient
// target URIs. Additionally, the deliverableObject will have any hidden
// hidden recipients ("bto" and "bcc") stripped from it.
//
// Only call if both the social and federated protocol are supported.
func (a *SideEffectActor) prepare(c context.Context, outboxIRI *url.URL, activity Activity) (r []*url.URL, err error) {
// Get inboxes of recipients
if to := activity.GetActivityStreamsTo(); to != nil {
for iter := to.Begin(); iter != to.End(); iter = iter.Next() {
var val *url.URL
val, err = ToId(iter)
if err != nil {
return
}
r = append(r, val)
}
}
if bto := activity.GetActivityStreamsBto(); bto != nil {
for iter := bto.Begin(); iter != bto.End(); iter = iter.Next() {
var val *url.URL
val, err = ToId(iter)
if err != nil {
return
}
r = append(r, val)
}
}
if cc := activity.GetActivityStreamsCc(); cc != nil {
for iter := cc.Begin(); iter != cc.End(); iter = iter.Next() {
var val *url.URL
val, err = ToId(iter)
if err != nil {
return
}
r = append(r, val)
}
}
if bcc := activity.GetActivityStreamsBcc(); bcc != nil {
for iter := bcc.Begin(); iter != bcc.End(); iter = iter.Next() {
var val *url.URL
val, err = ToId(iter)
if err != nil {
return
}
r = append(r, val)
}
}
if audience := activity.GetActivityStreamsAudience(); audience != nil {
for iter := audience.Begin(); iter != audience.End(); iter = iter.Next() {
var val *url.URL
val, err = ToId(iter)
if err != nil {
return
}
r = append(r, val)
}
}
// 1. When an object is being delivered to the originating actor's
// followers, a server MAY reduce the number of receiving actors
// delivered to by identifying all followers which share the same
// sharedInbox who would otherwise be individual recipients and
// instead deliver objects to said sharedInbox.
// 2. If an object is addressed to the Public special collection, a
// server MAY deliver that object to all known sharedInbox endpoints
// on the network.
r = filterURLs(r, IsPublic)
// first check if the implemented database logic can return any inboxes
// from our list of actor IRIs.
foundInboxesFromDB := []*url.URL{}
for _, actorIRI := range r {
// BEGIN LOCK
var unlock func()
unlock, err = a.db.Lock(c, actorIRI)
if err != nil {
return
}
inboxes, err := a.db.InboxesForIRI(c, actorIRI)
if err != nil {
// bail on error
unlock()
return nil, err
}
if len(inboxes) > 0 {
// we have a hit
foundInboxesFromDB = append(foundInboxesFromDB, inboxes...)
// if we found inboxes for this iri, we should remove it from
// the list of actors/iris we still need to dereference
r = removeOne(r, actorIRI)
}
// END LOCK
unlock()
}
// look for any actors' inboxes that weren't already discovered above;
// find these by making dereference calls to remote instances
t, err := a.common.NewTransport(c, outboxIRI, goFedUserAgent())
if err != nil {
return nil, err
}
foundActorsFromRemote, err := a.resolveActors(c, t, r, 0, a.s2s.MaxDeliveryRecursionDepth(c))
if err != nil {
return nil, err
}
foundInboxesFromRemote, err := getInboxes(foundActorsFromRemote)
if err != nil {
return nil, err
}
// combine this list of dereferenced inbox IRIs with the inboxes we already
// found in the db, to make a complete list of target IRIs
targets := []*url.URL{}
targets = append(targets, foundInboxesFromDB...)
targets = append(targets, foundInboxesFromRemote...)
// Get inboxes of sender.
var unlock func()
unlock, err = a.db.Lock(c, outboxIRI)
if err != nil {
return
}
// WARNING: No deferring the Unlock
actorIRI, err := a.db.ActorForOutbox(c, outboxIRI)
unlock() // unlock after regardless
if err != nil {
return
}
// Get the inbox on the sender.
unlock, err = a.db.Lock(c, actorIRI)
if err != nil {
return nil, err
}
// BEGIN LOCK
thisActor, err := a.db.Get(c, actorIRI)
unlock()
// END LOCK -- Still need to handle err
if err != nil {
return nil, err
}
// Post-processing
var ignore *url.URL
ignore, err = getInbox(thisActor)
if err != nil {
return nil, err
}
r = dedupeIRIs(targets, []*url.URL{ignore})
stripHiddenRecipients(activity)
return r, nil
}
// resolveActors takes a list of Actor id URIs and returns them as concrete
// instances of actorObject. It attempts to apply recursively when it encounters
// a target that is a Collection or OrderedCollection.
//
// If maxDepth is zero or negative, then recursion is infinitely applied.
//
// If a recipient is a Collection or OrderedCollection, then the server MUST
// dereference the collection, WITH the user's credentials.
//
// Note that this also applies to CollectionPage and OrderedCollectionPage.
func (a *SideEffectActor) resolveActors(c context.Context, t Transport, r []*url.URL, depth, maxDepth int) (actors []vocab.Type, err error) {
if maxDepth > 0 && depth >= maxDepth {
return
}
for _, u := range r {
var act vocab.Type
var more []*url.URL
// TODO: Determine if more logic is needed here for inaccessible
// collections owned by peer servers.
act, more, err = a.dereferenceForResolvingInboxes(c, t, u)
if err != nil {
// Missing recipient -- skip.
continue
}
var recurActors []vocab.Type
recurActors, err = a.resolveActors(c, t, more, depth+1, maxDepth)
if err != nil {
return
}
if act != nil {
actors = append(actors, act)
}
actors = append(actors, recurActors...)
}
return
}
// dereferenceForResolvingInboxes dereferences an IRI solely for finding an
// actor's inbox IRI to deliver to.
//
// The returned actor could be nil, if it wasn't an actor (ex: a Collection or
// OrderedCollection).
func (a *SideEffectActor) dereferenceForResolvingInboxes(c context.Context, t Transport, actorIRI *url.URL) (actor vocab.Type, moreActorIRIs []*url.URL, err error) {
var resp []byte
resp, err = t.Dereference(c, actorIRI)
if err != nil {
return
}
var m map[string]interface{}
if err = json.Unmarshal(resp, &m); err != nil {
return
}
actor, err = streams.ToType(c, m)
if err != nil {
return
}
// Attempt to see if the 'actor' is really some sort of type that has
// an 'items' or 'orderedItems' property.
if v, ok := actor.(itemser); ok {
if i := v.GetActivityStreamsItems(); i != nil {
for iter := i.Begin(); iter != i.End(); iter = iter.Next() {
var id *url.URL
id, err = ToId(iter)
if err != nil {
return
}
moreActorIRIs = append(moreActorIRIs, id)
}
}
actor = nil
} else if v, ok := actor.(orderedItemser); ok {
if i := v.GetActivityStreamsOrderedItems(); i != nil {
for iter := i.Begin(); iter != i.End(); iter = iter.Next() {
var id *url.URL
id, err = ToId(iter)
if err != nil {
return
}
moreActorIRIs = append(moreActorIRIs, id)
}
}
actor = nil
}
return
}
|