-
Notifications
You must be signed in to change notification settings - Fork 23
/
MessageRouter.cs
459 lines (405 loc) · 20.4 KB
/
MessageRouter.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
using Microsoft.Bot.Connector;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Bot.Schema;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Underscore.Bot.MessageRouting.DataStore;
using Underscore.Bot.MessageRouting.Logging;
using Underscore.Bot.MessageRouting.Models;
using Underscore.Bot.MessageRouting.Results;
using Underscore.Bot.MessageRouting.Utils;
namespace Underscore.Bot.MessageRouting
{
/// <summary>
/// Provides the main interface for message routing.
/// </summary>
public class MessageRouter
{
protected MicrosoftAppCredentials _microsoftAppCredentials;
/// <summary>
/// The routing data and all the parties the bot has seen including the instances of itself.
/// </summary>
public RoutingDataManager RoutingDataManager
{
get;
protected set;
}
public ILogger Logger
{
get;
set;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="routingDataStore">The routing data store implementation.</param>
/// <param name="microsoftAppCredentials">The bot application credentials.
/// May be required, depending on the setup of your app, for sending messages.</param>
/// <param name="globalTimeProvider">The global time provider for providing the current
/// <param name="ILogger">Logger to use. Defaults to DebugLogger.</param>
/// time for various events such as when a connection is requested.</param>
public MessageRouter(
IRoutingDataStore routingDataStore,
MicrosoftAppCredentials microsoftAppCredentials,
GlobalTimeProvider globalTimeProvider = null,
ILogger logger = null)
{
Logger = logger ?? new DebugLogger();
RoutingDataManager = new RoutingDataManager(routingDataStore, globalTimeProvider, Logger);
_microsoftAppCredentials = microsoftAppCredentials;
}
/// <summary>
/// Constructs a conversation reference instance using the sender of the given activity.
/// </summary>
/// <param name="activity">The activity.</param>
/// <param name="senderIsBot">Defines whether to classify the sender as a bot or a user.</param>
/// <returns>A newly created conversation reference instance.</returns>
public static ConversationReference CreateSenderConversationReference(
IActivity activity, bool senderIsBot = false)
{
return new ConversationReference(
null,
senderIsBot ? null : activity.From,
senderIsBot ? activity.From : null,
activity.Conversation,
activity.ChannelId,
activity.ServiceUrl);
}
/// <summary>
/// Constructs a conversation reference instance using the recipient, which is expected to
/// be a bot instance, of the given activity.
/// </summary>
/// <param name="activity">The activity.</param>
/// <returns>A newly created conversation reference instance.</returns>
public static ConversationReference CreateRecipientConversationReference(IActivity activity)
{
return new ConversationReference(
null,
null,
activity.Recipient,
activity.Conversation,
activity.ChannelId,
activity.ServiceUrl);
}
/// <summary>
/// Sends the given message to the given recipient.
/// </summary>
/// <param name="recipient">The conversation reference of the recipient.</param>
/// <param name="messageActivity">The message activity to send.</param>
/// <returns>A valid resource response instance, if successful. Null in case of an error.</returns>
public virtual async Task<ResourceResponse> SendMessageAsync(
ConversationReference recipient, IMessageActivity messageActivity)
{
if (recipient == null)
{
Logger.Log("The conversation reference is null");
return null;
}
// We need the bot identity in the SAME CHANNEL/CONVERSATION as the RECIPIENT -
// Otherwise, the platform (e.g. Slack) will reject the incoming message as it does not
// recognize the sender
ConversationReference botInstance =
RoutingDataManager.FindBotInstanceForRecipient(recipient);
if (botInstance == null || botInstance.Bot == null)
{
Logger.Log("Failed to find the bot instance");
return null;
}
messageActivity.From = botInstance.Bot;
messageActivity.Recipient = RoutingDataManager.GetChannelAccount(recipient);
// Make sure the message activity contains a valid conversation ID
if (messageActivity.Conversation == null)
{
messageActivity.Conversation = recipient.Conversation;
}
ConnectorClientMessageBundle bundle = new ConnectorClientMessageBundle(
recipient.ServiceUrl, messageActivity, _microsoftAppCredentials);
ResourceResponse resourceResponse = null;
try
{
resourceResponse =
await bundle.ConnectorClient.Conversations.SendToConversationAsync(
(Activity)bundle.MessageActivity);
}
catch (UnauthorizedAccessException e)
{
Logger.Log($"Failed to send message: {e.Message}");
}
catch (Exception e)
{
Logger.Log($"Failed to send message: {e.Message}");
}
return resourceResponse;
}
/// <summary>
/// Sends the given message to the given recipient.
/// </summary>
/// <param name="recipient">The conversation reference of the recipient.</param>
/// <param name="message">The message to send.</param>
/// <returns>A valid resource response instance, if successful. Null in case of an error.</returns>
public virtual async Task<ResourceResponse> SendMessageAsync(
ConversationReference recipient, string message)
{
IMessageActivity messageActivity =
ConnectorClientMessageBundle.CreateMessageActivity(null, recipient, message);
// The sender to the message activity above is resolved in the method here:
return await SendMessageAsync(recipient, messageActivity);
}
/// <summary>
/// Stores the conversation reference instances (sender and recipient) in the given activity.
/// </summary>
/// <param name="activity">The activity.</param>
/// <returns>The list of two results, where the first element is for the sender and the last for the recipient.</returns>
public IList<ModifyRoutingDataResult> StoreConversationReferences(IActivity activity)
{
return new List<ModifyRoutingDataResult>()
{
RoutingDataManager.AddConversationReference(CreateSenderConversationReference(activity)),
RoutingDataManager.AddConversationReference(CreateRecipientConversationReference(activity))
};
}
/// <summary>
/// Tries to initiate a connection (1:1 conversation) by creating a request on behalf of
/// the given requestor. This method does nothing, if a request for the same user already exists.
/// </summary>
/// <param name="requestor">The requestor conversation reference.</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 CreateConnectionRequest(
ConversationReference requestor, bool rejectConnectionRequestIfNoAggregationChannel = false)
{
if (requestor == null)
{
throw new ArgumentNullException("Requestor missing");
}
ConnectionRequestResult createConnectionRequestResult = null;
RoutingDataManager.AddConversationReference(requestor);
ConnectionRequest connectionRequest = new ConnectionRequest(requestor);
if (RoutingDataManager.IsAssociatedWithAggregation(requestor))
{
createConnectionRequestResult = new ConnectionRequestResult()
{
Type = ConnectionRequestResultType.Error,
ErrorMessage = $"The given ConversationReference ({RoutingDataManager.GetChannelAccount(requestor)?.Name}) is associated with aggregation and hence invalid to request a connection"
};
}
else
{
createConnectionRequestResult = RoutingDataManager.AddConnectionRequest(
connectionRequest, rejectConnectionRequestIfNoAggregationChannel);
}
return createConnectionRequestResult;
}
/// <summary>
/// Tries to reject the connection request of the associated with the given conversation reference.
/// </summary>
/// <param name="requestorToReject">The conversation reference of the party whose request to reject.</param>
/// <param name="rejecter">The conversation reference of the party rejecting the request (optional).</param>
/// <returns>The result of the operation:
/// - ConnectionRequestResultType.Rejected or
/// - ConnectionRequestResultType.Error (see the error message for more details).
/// </returns>
public virtual ConnectionRequestResult RejectConnectionRequest(
ConversationReference requestorToReject, ConversationReference rejecter = null)
{
if (requestorToReject == null)
{
throw new ArgumentNullException("The conversation reference instance of the party whose request to reject cannot be null");
}
ConnectionRequestResult rejectConnectionRequestResult = null;
ConnectionRequest connectionRequest =
RoutingDataManager.FindConnectionRequest(requestorToReject);
if (connectionRequest != null)
{
rejectConnectionRequestResult = RoutingDataManager.RemoveConnectionRequest(connectionRequest);
rejectConnectionRequestResult.Rejecter = rejecter;
}
return rejectConnectionRequestResult;
}
/// <summary>
/// Tries to establish a connection (1:1 chat) between the two given parties.
///
/// Note that the conversation owner will have a new separate conversation reference in the created
/// conversation, if a new direct conversation is created.
/// </summary>
/// <param name="conversationReference1">The conversation reference who owns the conversation (e.g. customer service agent).</param>
/// <param name="conversationReference2">The other conversation reference in the conversation.</param>
/// <param name="createNewDirectConversation">
/// If true, will try to create a new direct conversation between the bot and the
/// conversation owner (e.g. agent) where the messages from the other (client) conversation
/// reference are routed.
///
/// Note that this will result in the conversation owner having a new separate conversation
/// reference in the created connection (for the new direct conversation).
/// </param>
/// <returns>
/// The result of the operation:
/// - ConnectionResultType.Connected,
/// - ConnectionResultType.Error (see the error message for more details).
/// </returns>
public virtual async Task<ConnectionResult> ConnectAsync(
ConversationReference conversationReference1,
ConversationReference conversationReference2,
bool createNewDirectConversation)
{
if (conversationReference1 == null || conversationReference2 == null)
{
throw new ArgumentNullException(
$"Neither of the arguments ({nameof(conversationReference1)}, {nameof(conversationReference2)}) can be null");
}
ConversationReference botInstance =
RoutingDataManager.FindConversationReference(
conversationReference1.ChannelId, conversationReference1.Conversation.Id, null, true);
if (botInstance == null)
{
return new ConnectionResult()
{
Type = ConnectionResultType.Error,
ErrorMessage = "Failed to find the bot instance"
};
}
ConversationResourceResponse conversationResourceResponse = null;
if (createNewDirectConversation)
{
ChannelAccount conversationReference1ChannelAccount =
RoutingDataManager.GetChannelAccount(
conversationReference1, out bool conversationReference1IsBot);
ConnectorClient connectorClient = new ConnectorClient(
new Uri(conversationReference1.ServiceUrl), _microsoftAppCredentials);
try
{
conversationResourceResponse =
await connectorClient.Conversations.CreateDirectConversationAsync(
botInstance.Bot, conversationReference1ChannelAccount);
}
catch (Exception e)
{
Logger.Log($"Failed to create a direct conversation: {e.Message}");
// Do nothing here as we fallback (continue without creating a direct conversation)
}
if (conversationResourceResponse != null
&& !string.IsNullOrEmpty(conversationResourceResponse.Id))
{
// The conversation account of the conversation owner for this 1:1 chat is different -
// thus, we need to re-create the conversation owner instance
ConversationAccount directConversationAccount =
new ConversationAccount(id: conversationResourceResponse.Id);
conversationReference1 = new ConversationReference(
null,
conversationReference1IsBot ? null : conversationReference1ChannelAccount,
conversationReference1IsBot ? conversationReference1ChannelAccount : null,
directConversationAccount,
conversationReference1.ChannelId,
conversationReference1.ServiceUrl);
RoutingDataManager.AddConversationReference(conversationReference1);
RoutingDataManager.AddConversationReference(new ConversationReference(
null,
null,
botInstance.Bot,
directConversationAccount,
botInstance.ChannelId,
botInstance.ServiceUrl));
}
}
Connection connection = new Connection(conversationReference1, conversationReference2);
ConnectionResult connectResult =
RoutingDataManager.ConnectAndRemoveConnectionRequest(connection, conversationReference2);
connectResult.ConversationResourceResponse = conversationResourceResponse;
return connectResult;
}
/// <summary>
/// Disconnects all connections associated with the given conversation reference.
/// </summary>
/// <param name="conversationReference">The conversation reference connected in a conversation.</param>
/// <returns>The results:
/// - ConnectionResultType.Disconnected,
/// - ConnectionResultType.Error (see the error message for more details).
/// </returns>
public virtual IList<ConnectionResult> Disconnect(ConversationReference conversationReference)
{
IList<ConnectionResult> disconnectResults = new List<ConnectionResult>();
bool wasDisconnected = true;
while (wasDisconnected)
{
wasDisconnected = false;
Connection connection = RoutingDataManager.FindConnection(conversationReference);
if (connection != null)
{
ConnectionResult disconnectResult = RoutingDataManager.Disconnect(connection);
disconnectResults.Add(disconnectResult);
if (disconnectResult.Type == ConnectionResultType.Disconnected)
{
wasDisconnected = true;
}
}
}
return disconnectResults;
}
/// <summary>
/// Routes the message in the given activity, if the sender is connected in a conversation.
/// </summary>
/// <param name="activity">The activity to handle.</param>
/// <param name="addNameToMessage">If true, will add the name of the sender to the beginning of the message.</param>
/// <returns>The result of the operation:
/// - MessageRouterResultType.NoActionTaken, if no routing rule for the sender is found OR
/// - MessageRouterResultType.OK, if the message was routed successfully OR
/// - MessageRouterResultType.FailedToForwardMessage in case of an error (see the error message).
/// </returns>
public virtual async Task<MessageRoutingResult> RouteMessageIfSenderIsConnectedAsync(
IMessageActivity activity, bool addNameToMessage = true)
{
ConversationReference sender = CreateSenderConversationReference(activity);
Connection connection = RoutingDataManager.FindConnection(sender);
MessageRoutingResult messageRoutingResult = new MessageRoutingResult()
{
Type = MessageRoutingResultType.NoActionTaken,
Connection = connection
};
if (connection != null)
{
ConversationReference recipient =
RoutingDataManager.Match(sender, connection.ConversationReference1)
? connection.ConversationReference2 : connection.ConversationReference1;
if (recipient != null)
{
string message = activity.Text;
if (addNameToMessage)
{
string senderName = RoutingDataManager.GetChannelAccount(sender).Name;
if (!string.IsNullOrWhiteSpace(senderName))
{
message = $"{senderName}: {message}";
}
}
ResourceResponse resourceResponse = await SendMessageAsync(recipient, message);
if (resourceResponse != null)
{
messageRoutingResult.Type = MessageRoutingResultType.MessageRouted;
if (!RoutingDataManager.UpdateTimeSinceLastActivity(connection))
{
Logger.Log("Failed to update the time since the last activity property of the connection");
}
}
else
{
messageRoutingResult.Type = MessageRoutingResultType.FailedToRouteMessage;
messageRoutingResult.ErrorMessage = $"Failed to forward the message to the recipient";
}
}
else
{
messageRoutingResult.Type = MessageRoutingResultType.Error;
messageRoutingResult.ErrorMessage = "Failed to find the recipient to forward the message to";
}
}
return messageRoutingResult;
}
}
}