-
Notifications
You must be signed in to change notification settings - Fork 23
/
RoutingDataManager.cs
901 lines (784 loc) · 37.4 KB
/
RoutingDataManager.cs
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
using Microsoft.Bot.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using Underscore.Bot.MessageRouting.Logging;
using Underscore.Bot.MessageRouting.Models;
using Underscore.Bot.MessageRouting.Results;
using Underscore.Bot.MessageRouting.Utils;
namespace Underscore.Bot.MessageRouting.DataStore
{
/// <summary>
/// The routing data manager.
/// </summary>
[Serializable]
public class RoutingDataManager
{
protected ILogger _logger;
public IRoutingDataStore RoutingDataStore
{
get;
protected set;
}
/// <summary>
/// A global time provider.
/// Used for providing the current time for various of events.
/// For instance, the time when a connection request is made may be useful for customer
/// agent front-ends to see who has waited the longest and/or to collect response times.
/// </summary>
public virtual GlobalTimeProvider GlobalTimeProvider
{
get;
protected set;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="routingDataStore">The routing data store implementation.</param>
/// <param name="globalTimeProvider">The global time provider for providing the current
/// time for various events such as when a connection is requested.</param>
/// <param name="logger">Logger to use.</param>
public RoutingDataManager(
IRoutingDataStore routingDataStore,
GlobalTimeProvider globalTimeProvider = null,
ILogger logger = null)
{
RoutingDataStore = routingDataStore ?? throw new ArgumentNullException("Routing data store missing");
GlobalTimeProvider = globalTimeProvider ?? new GlobalTimeProvider();
_logger = logger ?? new DebugLogger();
}
#region Static helper methods
/// <summary>
/// Checks if the given conversation reference contains the channel account instance of a bot.
/// </summary>
/// <param name="conversationReference">The conversation reference to check.</param>
/// <returns>True, if the given conversation reference is associated with a bot. False otherwise.</returns>
public static bool IsBot(ConversationReference conversationReference)
{
return (conversationReference?.Bot != null);
}
/// <summary>
/// Resolves the non-null channel account instance in the given conversation reference.
/// </summary>
/// <param name="conversationReference">The conversation reference whose channel account to resolve.</param>
/// <param name="isBot">Will be true, if the conversation reference is associated with a bot. False otherwise.</param>
/// <returns>The non-null channel account instance (user or bot) or null, if both are null.</returns>
public static ChannelAccount GetChannelAccount(ConversationReference conversationReference, out bool isBot)
{
if (conversationReference?.User != null)
{
isBot = false;
return conversationReference.User;
}
if (conversationReference?.Bot != null)
{
isBot = true;
return conversationReference.Bot;
}
isBot = false;
return null;
}
/// <summary>
/// Resolves the non-null channel account instance in the given conversation reference.
/// </summary>
/// <param name="conversationReference">The conversation reference whose channel account to resolve.</param>
/// <returns>The non-null channel account instance (user or bot) or null, if both are null.</returns>
public static ChannelAccount GetChannelAccount(ConversationReference conversationReference)
{
return GetChannelAccount(conversationReference, out bool isBot);
}
/// <summary>
/// Compares the conversation and channel account instances of the two given conversation references.
/// </summary>
/// <param name="conversationReference1"></param>
/// <param name="conversationReference2"></param>
/// <returns>True, if the IDs match. False otherwise.</returns>
public static bool Match(
ConversationReference conversationReference1, ConversationReference conversationReference2)
{
if (conversationReference1 == null || conversationReference2 == null)
{
return false;
}
string conversationAccount1Id = conversationReference1.Conversation?.Id;
string conversationAccount2Id = conversationReference2.Conversation?.Id;
if (string.IsNullOrWhiteSpace(conversationAccount1Id) != string.IsNullOrWhiteSpace(conversationAccount2Id))
{
return false;
}
bool conversationAccountsMatch =
(string.IsNullOrWhiteSpace(conversationAccount1Id)
&& string.IsNullOrWhiteSpace(conversationAccount2Id))
|| conversationAccount1Id.Equals(conversationAccount2Id);
ChannelAccount channelAccount1 = GetChannelAccount(conversationReference1, out bool isBot1);
ChannelAccount channelAccount2 = GetChannelAccount(conversationReference2, out bool isBot2);
bool channelAccountsMatch =
(isBot1 == isBot2)
&& ((channelAccount1 == null && channelAccount2 == null)
|| (channelAccount1 != null && channelAccount2 != null
&& channelAccount1.Id.Equals(channelAccount2.Id)));
return (conversationAccountsMatch && channelAccountsMatch);
}
/// <summary>
/// Checks whether the given list of conversation references contains the given one.
/// </summary>
/// <param name="conversationReferences">The list of conversation references possibly containing the given one.</param>
/// <param name="conversationReferenceToCheck">The conversation reference to check.</param>
/// <returns>True, if the given conversation reference is contained by the list. False otherwise.</returns>
public static bool Contains(
IList<ConversationReference> conversationReferences,
ConversationReference conversationReferenceToCheck)
{
if (conversationReferences != null)
{
foreach (ConversationReference conversationReference in conversationReferences)
{
if (Match(conversationReference, conversationReferenceToCheck))
{
return true;
}
}
}
return false;
}
#endregion Static helper methods
/// <returns>The current global time.</returns>
public virtual DateTime GetCurrentGlobalTime()
{
return (GlobalTimeProvider == null) ? DateTime.UtcNow : GlobalTimeProvider.GetCurrentTime();
}
#region Users and bots
/// <returns>The users as a readonly list.</returns>
public IList<ConversationReference> GetUsers()
{
return RoutingDataStore.GetUsers();
}
/// <returns>The bot instances as a readonly list.</returns>
public IList<ConversationReference> GetBotInstances()
{
return RoutingDataStore.GetBotInstances();
}
/// <summary>
/// Tries to resolve the name of the bot in the same conversation with the given
/// conversation reference instance.
/// </summary>
/// <param name="conversationReference">The conversation reference from whose perspective to resolve the name.</param>
/// <returns>The name of the bot or null, if unable to resolve.</returns>
public virtual string ResolveBotNameInConversation(ConversationReference conversationReference)
{
string botName = null;
if (conversationReference != null)
{
ConversationReference botConversationReference = FindConversationReference(
conversationReference.ChannelId, conversationReference.Conversation.Id, null, true);
if (botConversationReference != null)
{
botName = botConversationReference.Bot.Name;
}
}
return botName;
}
/// <summary>
/// Adds the given ConversationReference.
/// </summary>
/// <param name="conversationReferenceToAdd">The new ConversationReference to add.</param>
/// <returns>The result of the operation with type:
/// - ModifyRoutingDataResultType.Added,
/// - ModifyRoutingDataResultType.AlreadyExists or
/// - ModifyRoutingDataResultType.Error (see the error message for more details).
/// </returns>
public virtual ModifyRoutingDataResult AddConversationReference(ConversationReference conversationReferenceToAdd)
{
if (conversationReferenceToAdd == null)
{
throw new ArgumentNullException("The given conversation reference is null");
}
if (conversationReferenceToAdd.Bot == null
&& conversationReferenceToAdd.User == null)
{
throw new ArgumentNullException("Both channel accounts in the conversation reference cannot be null");
}
if (IsBot(conversationReferenceToAdd)
? Contains(GetBotInstances(), conversationReferenceToAdd)
: Contains(GetUsers(), conversationReferenceToAdd))
{
return new ModifyRoutingDataResult()
{
Type = ModifyRoutingDataResultType.AlreadyExists
};
}
if (RoutingDataStore.AddConversationReference(conversationReferenceToAdd))
{
return new ModifyRoutingDataResult()
{
Type = ModifyRoutingDataResultType.Added
};
}
return new ModifyRoutingDataResult()
{
Type = ModifyRoutingDataResultType.Error,
ErrorMessage = "Failed to add the conversation reference"
};
}
/// <summary>
/// Removes the specified ConversationReference from all possible containers.
/// </summary>
/// <param name="conversationReferenceToRemove">The ConversationReference to remove.</param>
/// <returns>A list of operation result(s).</returns>
public virtual IList<AbstractMessageRouterResult> RemoveConversationReference(
ConversationReference conversationReferenceToRemove)
{
if (conversationReferenceToRemove == null)
{
throw new ArgumentNullException("The given conversation reference is null");
}
List<AbstractMessageRouterResult> messageRouterResults = new List<AbstractMessageRouterResult>();
bool wasRemoved = false;
// Check users and bots
IList<ConversationReference> conversationReferenceToSearch =
IsBot(conversationReferenceToRemove) ? GetBotInstances() : GetUsers();
IList<ConversationReference> conversationReferencesToRemove = FindConversationReferences(
conversationReferenceToSearch, null, null,
GetChannelAccount(conversationReferenceToRemove)?.Id);
foreach (ConversationReference conversationReference in conversationReferencesToRemove)
{
if (RoutingDataStore.RemoveConversationReference(conversationReference))
{
messageRouterResults.Add(new ModifyRoutingDataResult()
{
Type = ModifyRoutingDataResultType.Removed
});
}
else
{
messageRouterResults.Add(new ModifyRoutingDataResult()
{
Type = ModifyRoutingDataResultType.Error,
ErrorMessage = "Failed to remove conversation reference"
});
}
}
// Check connection requests
wasRemoved = true;
while (wasRemoved)
{
wasRemoved = false;
foreach (ConnectionRequest connectionRequest in GetConnectionRequests())
{
if (Match(conversationReferenceToRemove, connectionRequest.Requestor))
{
ConnectionRequestResult removeConnectionRequestResult =
RemoveConnectionRequest(connectionRequest);
if (removeConnectionRequestResult.Type == ConnectionRequestResultType.Rejected)
{
wasRemoved = true;
messageRouterResults.Add(removeConnectionRequestResult);
break;
}
}
}
}
// Check the connections
wasRemoved = true;
while (wasRemoved)
{
wasRemoved = false;
foreach (Connection connection in GetConnections())
{
if (Match(conversationReferenceToRemove, connection.ConversationReference1)
|| Match(conversationReferenceToRemove, connection.ConversationReference2))
{
wasRemoved = true;
messageRouterResults.Add(Disconnect(connection)); // TODO: Check that the disconnect was successful
break;
}
}
}
return messageRouterResults;
}
#endregion Users and bots
#region Aggregation channels
/// <returns>The aggregation channels as a readonly list.</returns>
public IList<ConversationReference> GetAggregationChannels()
{
return RoutingDataStore.GetAggregationChannels();
}
/// <summary>
/// Checks if the given conversation reference instance is associated with aggregation.
/// In human toung this means that the given conversation reference is, for instance,
/// a customer service agent who deals with the customer connection requests.
/// </summary>
/// <param name="conversationReference">The conversation reference to check.</param>
/// <returns>True, if is associated. False otherwise.</returns>
public virtual bool IsAssociatedWithAggregation(ConversationReference conversationReference)
{
IList<ConversationReference> aggregationParties = GetAggregationChannels();
return (conversationReference != null
&& aggregationParties != null
&& aggregationParties.Count() > 0
&& aggregationParties.Where(aggregationChannel =>
aggregationChannel.Conversation.Id == conversationReference.Conversation.Id
&& aggregationChannel.ServiceUrl == conversationReference.ServiceUrl
&& aggregationChannel.ChannelId == conversationReference.ChannelId).Count() > 0);
}
/// <summary>
/// Adds the given aggregation channel.
/// </summary>
/// <param name="aggregationChannelToAdd">The aggregation channel to add.</param>
/// <returns>The result of the operation with type:
/// - ModifyRoutingDataResultType.Added,
/// - ModifyRoutingDataResultType.AlreadyExists or
/// - ModifyRoutingDataResultType.Error (see the error message for more details).
/// </returns>
public virtual ModifyRoutingDataResult AddAggregationChannel(ConversationReference aggregationChannelToAdd)
{
if (aggregationChannelToAdd == null)
{
throw new ArgumentNullException("The given conversation reference is null");
}
if (GetChannelAccount(aggregationChannelToAdd) != null)
{
throw new ArgumentException("The conversation reference instance for an aggregation channel cannot contain a channel account");
}
if (string.IsNullOrWhiteSpace(aggregationChannelToAdd.ChannelId)
|| aggregationChannelToAdd.Conversation == null
|| string.IsNullOrWhiteSpace(aggregationChannelToAdd.Conversation.Id))
{
return new ModifyRoutingDataResult()
{
Type = ModifyRoutingDataResultType.Error,
ErrorMessage = "Aggregation channel must contain a valid channel and conversation ID"
};
}
IList<ConversationReference> aggregationParties = GetAggregationChannels();
if (Contains(aggregationParties, aggregationChannelToAdd))
{
return new ModifyRoutingDataResult()
{
Type = ModifyRoutingDataResultType.AlreadyExists
};
}
if (RoutingDataStore.AddAggregationChannel(aggregationChannelToAdd))
{
return new ModifyRoutingDataResult()
{
Type = ModifyRoutingDataResultType.Added
};
}
return new ModifyRoutingDataResult()
{
Type = ModifyRoutingDataResultType.Error,
ErrorMessage = "Failed to add the aggregation channel"
};
}
/// <summary>
/// Removes the given aggregation channel.
/// </summary>
/// <param name="aggregationChannelToRemove">The aggregation channel to remove.</param>
/// <returns>True, if removed successfully. False otherwise.</returns>
public virtual bool RemoveAggregationChannel(ConversationReference aggregationChannelToRemove)
{
return RoutingDataStore.RemoveAggregationChannel(aggregationChannelToRemove);
}
#endregion Aggregation channels
#region Connection requests
/// <returns>The connection requests as a readonly list.</returns>
public IList<ConnectionRequest> GetConnectionRequests()
{
return RoutingDataStore.GetConnectionRequests();
}
/// <summary>
/// Tries to find a connection request by the given conversation reference
/// (associated with the requestor).
/// </summary>
/// <param name="conversationReference">The conversation reference associated with the requestor.</param>
/// <returns>The connection request or null, if not found.</returns>
public ConnectionRequest FindConnectionRequest(ConversationReference conversationReference)
{
foreach (ConnectionRequest connectionRequest in GetConnectionRequests())
{
if (Match(conversationReference, connectionRequest.Requestor))
{
return connectionRequest;
}
}
return null;
}
/// <summary>
/// Adds the given connection request.
/// </summary>
/// <param name="connectionRequestToAdd">The connection request to add.</param>
/// <param name="rejectConnectionRequestIfNoAggregationChannel">
/// If true, will reject all requests, if there is no aggregation channel.</param>
/// <returns>The result of the operation:
/// - ConnectionRequestResultType.Created,
/// - ConnectionRequestResultType.AlreadyExists,
/// - ConnectionRequestResultType.NotSetup or
/// - ConnectionRequestResultType.Error (see the error message for more details).
/// </returns>
public virtual ConnectionRequestResult AddConnectionRequest(
ConnectionRequest connectionRequestToAdd, bool rejectConnectionRequestIfNoAggregationChannel = false)
{
if (connectionRequestToAdd == null)
{
throw new ArgumentNullException("Connection request is null");
}
ConnectionRequestResult addConnectionRequestResult = new ConnectionRequestResult()
{
ConnectionRequest = connectionRequestToAdd
};
if (GetConnectionRequests().Contains(connectionRequestToAdd))
{
addConnectionRequestResult.Type = ConnectionRequestResultType.AlreadyExists;
}
else
{
if (!GetAggregationChannels().Any() && rejectConnectionRequestIfNoAggregationChannel)
{
addConnectionRequestResult.Type = ConnectionRequestResultType.NotSetup;
}
else
{
connectionRequestToAdd.ConnectionRequestTime = GetCurrentGlobalTime();
if (RoutingDataStore.AddConnectionRequest(connectionRequestToAdd))
{
addConnectionRequestResult.Type = ConnectionRequestResultType.Created;
}
else
{
addConnectionRequestResult.Type = ConnectionRequestResultType.Error;
addConnectionRequestResult.ErrorMessage = "Failed to add the connection request - this is likely an error caused by the storage implementation";
}
}
}
return addConnectionRequestResult;
}
/// <summary>
/// Removes the connection request of the user with the given conversation reference.
/// </summary>
/// <param name="connectionRequestToRemove">The connection request to remove.</param>
/// <returns>The result of the operation:
/// - ConnectionRequestResultType.Rejected or
/// - ConnectionRequestResultType.Error (see the error message for more details).
/// </returns>
public virtual ConnectionRequestResult RemoveConnectionRequest(ConnectionRequest connectionRequestToRemove)
{
if (connectionRequestToRemove == null)
{
throw new ArgumentNullException("Connection request is null");
}
ConnectionRequestResult removeConnectionRequestResult = new ConnectionRequestResult
{
ConnectionRequest = connectionRequestToRemove
};
if (GetConnectionRequests().Contains(connectionRequestToRemove))
{
if (RoutingDataStore.RemoveConnectionRequest(connectionRequestToRemove))
{
removeConnectionRequestResult.Type = ConnectionRequestResultType.Rejected;
}
else
{
removeConnectionRequestResult.Type = ConnectionRequestResultType.Error;
removeConnectionRequestResult.ErrorMessage = "Failed to remove the connection request associated with the given user";
}
}
else
{
removeConnectionRequestResult.Type = ConnectionRequestResultType.Error;
removeConnectionRequestResult.ErrorMessage = "Could not find a connection request associated with the given user";
}
return removeConnectionRequestResult;
}
#endregion Connection requests
#region Connections
/// <returns>The connections.</returns>
public IList<Connection> GetConnections()
{
return RoutingDataStore.GetConnections();
}
/// <summary>
/// Tries to find a connection associated with the given conversation reference.
/// </summary>
/// <param name="conversationReference">The conversation reference associated with the connection to find.</param>
/// <returns>The connection or null, if not found.</returns>
public virtual Connection FindConnection(ConversationReference conversationReference)
{
foreach (Connection connection in GetConnections())
{
if (Match(conversationReference, connection.ConversationReference1)
|| Match(conversationReference, connection.ConversationReference2))
{
return connection;
}
}
return null;
}
/// <summary>
/// Checks if the there is a connection associated with the given conversation reference instance.
/// </summary>
/// <param name="ConversationReference">The conversation reference to check.</param>
/// <returns>True, if a connection was found. False otherwise.</returns>
public virtual bool IsConnected(ConversationReference conversationReference)
{
return (FindConnection(conversationReference) != null);
}
/// <summary>
/// Resolves the conversation reference sharing a connection with the given one.
/// </summary>
/// <param name="conversationReferenceWhoseCounterpartToFind">The conversation reference whose counterpart to resolve.</param>
/// <returns>The counterpart or null, if not found.</returns>
public virtual ConversationReference GetConnectedCounterpart(
ConversationReference conversationReferenceWhoseCounterpartToFind)
{
foreach (Connection connection in GetConnections())
{
if (Match(
conversationReferenceWhoseCounterpartToFind, connection.ConversationReference1))
{
return connection.ConversationReference2;
}
else if (Match(
conversationReferenceWhoseCounterpartToFind, connection.ConversationReference2))
{
return connection.ConversationReference1;
}
}
return null;
}
/// <summary>
/// Adds the given connection and clears the connection request associated with the given
/// conversation reference instance, if one exists.
/// </summary>
/// <param name="connectionToAdd">The connection to add.</param>
/// <param name="requestor">The requestor.</param>
/// <returns>The result of the operation:
/// - ConnectionResultType.Connected,
/// - ConnectionResultType.Error (see the error message for more details).
/// </returns>
public virtual ConnectionResult ConnectAndRemoveConnectionRequest(
Connection connectionToAdd, ConversationReference requestor)
{
ConnectionResult connectResult = new ConnectionResult()
{
Connection = connectionToAdd
};
connectionToAdd.TimeSinceLastActivity = GetCurrentGlobalTime();
bool wasConnectionAdded = RoutingDataStore.AddConnection(connectionToAdd);
if (wasConnectionAdded)
{
ConnectionRequest acceptedConnectionRequest = FindConnectionRequest(requestor);
if (acceptedConnectionRequest == null)
{
_logger.Log("Failed to find the connection request to remove");
}
else
{
RemoveConnectionRequest(acceptedConnectionRequest);
}
connectResult.Type = ConnectionResultType.Connected;
connectResult.ConnectionRequest = acceptedConnectionRequest;
}
else
{
connectResult.Type = ConnectionResultType.Error;
connectResult.ErrorMessage = $"Failed to add the connection {connectionToAdd}";
}
return connectResult;
}
/// <summary>
/// Updates the time since last activity property of the given connection instance.
/// </summary>
/// <param name="connection">The connection to update.</param>
/// <returns>True, if the connection was updated successfully. False otherwise.</returns>
public virtual bool UpdateTimeSinceLastActivity(Connection connection)
{
if (RoutingDataStore.RemoveConnection(connection))
{
connection.TimeSinceLastActivity = GetCurrentGlobalTime();
return RoutingDataStore.AddConnection(connection);
}
return false;
}
/// <summary>
/// Disconnects the given connection.
/// </summary>
/// <param name="connectionToDisconnect">The connection to disconnect.</param>
/// <returns>The result of the operation:
/// - ConnectionResultType.Disconnected,
/// - ConnectionResultType.Error (see the error message for more details).
/// </returns>
public virtual ConnectionResult Disconnect(Connection connectionToDisconnect)
{
ConnectionResult disconnectResult = new ConnectionResult()
{
Connection = connectionToDisconnect
};
foreach (Connection connection in GetConnections())
{
if (connectionToDisconnect.Equals(connection))
{
if (RoutingDataStore.RemoveConnection(connectionToDisconnect))
{
disconnectResult.Type = ConnectionResultType.Disconnected;
}
else
{
disconnectResult.Type = ConnectionResultType.Error;
disconnectResult.ErrorMessage = "Failed to remove the connection";
}
break;
}
}
return disconnectResult;
}
#endregion Connections
/// <summary>
/// Tries to find the conversation references in the given list matching the given criteria.
/// You can define one or more criteria, but you must define at least one.
/// </summary>
/// <param name="conversationReferencesToSearch">The list of conversation references to search.</param>
/// <param name="channelId">The channel ID to match (optional).</param>
/// <param name="conversationAccountId">The conversation account ID to match (optional).</param>
/// <param name="channelAccountId">The channel account ID to match (optional).</param>
/// <param name="onlyBotInstances">If true, will only look for the conversation reference instances belonging to a bot.</param>
/// <returns>The list of matching conversation references or null, if none found.</returns>
public virtual IList<ConversationReference> FindConversationReferences(
IList<ConversationReference> conversationReferencesToSearch,
string channelId = null,
string conversationAccountId = null,
string channelAccountId = null,
bool onlyBotInstances = false)
{
if (string.IsNullOrWhiteSpace(channelId)
&& string.IsNullOrWhiteSpace(conversationAccountId)
&& string.IsNullOrWhiteSpace(channelAccountId))
{
throw new ArgumentNullException("At least one search criteria must be defined");
}
IEnumerable<ConversationReference> conversationReferencesFound = null;
try
{
conversationReferencesFound = conversationReferencesToSearch.Where(conversationReference =>
{
if (onlyBotInstances && !IsBot(conversationReference))
{
return false;
}
if (!string.IsNullOrWhiteSpace(channelId))
{
if (string.IsNullOrWhiteSpace(conversationReference.ChannelId)
|| !conversationReference.ChannelId.Equals(channelId))
{
return false;
}
}
if (!string.IsNullOrWhiteSpace(conversationAccountId))
{
if (conversationReference.Conversation == null
|| string.IsNullOrWhiteSpace(conversationReference.Conversation.Id)
|| !conversationReference.Conversation.Id.Equals(conversationAccountId))
{
return false;
}
}
if (!string.IsNullOrWhiteSpace(channelAccountId))
{
ChannelAccount channelAccount = GetChannelAccount(conversationReference);
if (channelAccount == null
|| string.IsNullOrWhiteSpace(channelAccount.Id)
|| !channelAccount.Id.Equals(channelAccountId))
{
return false;
}
}
return true;
});
}
catch (ArgumentNullException e)
{
_logger.Log($"Failed to search conversation references: {e.Message}");
}
catch (InvalidOperationException e)
{
_logger.Log($"Failed to search conversation references: {e.Message}");
}
return conversationReferencesFound?.ToArray();
}
/// <summary>
/// Tries to find the conversation references in all the collections including connection
/// requests and connections.
///
/// You can define one or more criteria, but you must define at least one.
/// </summary>
/// <param name="channelId">The channel ID to match (optional).</param>
/// <param name="conversationAccountId">The conversation account ID to match (optional).</param>
/// <param name="channelAccountId">The channel account ID to match (optional).</param>
/// <param name="onlyBotInstances">If true, will only look for the conversation reference instances belonging to a bot.</param>
/// <returns>The conversation reference instance matching the given search criteria or null, if not found.</returns>
public virtual ConversationReference FindConversationReference(
string channelId = null,
string conversationAccountId = null,
string channelAccountId = null,
bool onlyBotInstances = false)
{
List<ConversationReference> conversationReferencesToSearch =
new List<ConversationReference>();
if (!onlyBotInstances)
{
// Users
conversationReferencesToSearch.AddRange(GetUsers());
}
conversationReferencesToSearch.AddRange(GetBotInstances()); // Bots
IList<ConversationReference> conversationReferencesFound = FindConversationReferences(
conversationReferencesToSearch,
channelId, conversationAccountId, channelAccountId, onlyBotInstances);
if (conversationReferencesFound == null || conversationReferencesFound.Count == 0)
{
conversationReferencesToSearch.Clear();
// Connection requests
foreach (ConnectionRequest connectionRequest in GetConnectionRequests())
{
conversationReferencesToSearch.Add(connectionRequest.Requestor);
}
conversationReferencesFound = FindConversationReferences(
conversationReferencesToSearch,
channelId, conversationAccountId, channelAccountId, onlyBotInstances);
}
if (conversationReferencesFound == null || conversationReferencesFound.Count == 0)
{
conversationReferencesToSearch.Clear();
// Connections
foreach (Connection connection in GetConnections())
{
conversationReferencesToSearch.Add(connection.ConversationReference1);
conversationReferencesToSearch.Add(connection.ConversationReference2);
}
conversationReferencesFound = FindConversationReferences(
conversationReferencesToSearch,
channelId, conversationAccountId, channelAccountId, onlyBotInstances);
}
if (conversationReferencesFound != null && conversationReferencesFound.Count > 0)
{
return conversationReferencesFound[0];
}
return null;
}
/// <summary>
/// Tries to find the bot instance that can reach the recipient.
/// This means that the bot instance, if found, is in the same channel and the conversation
/// as the recipient.
/// </summary>
/// <param name="recipient">The recipient.</param>
/// <returns>The bot instance or null, if not found.</returns>
public ConversationReference FindBotInstanceForRecipient(ConversationReference recipient)
{
if (recipient == null)
{
throw new ArgumentNullException("The given conversation reference is null");
}
return FindConversationReference(
recipient.ChannelId, recipient.Conversation?.Id, null, true);
}
}
}