forked from tompaana/bot-message-routing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractRoutingDataManager.cs
691 lines (588 loc) · 25.4 KB
/
AbstractRoutingDataManager.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
using Microsoft.Bot.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using Underscore.Bot.Models;
using Underscore.Bot.Utils;
namespace Underscore.Bot.MessageRouting.DataStore
{
/// <summary>
/// This class reduces the amount of code needed for data store specific implementations by
/// containing the business logic that works in most cases, but abstracting the simplest,
/// data store specific read and write operations (methods starting with "Execute").
/// </summary>
[Serializable]
public abstract class AbstractRoutingDataManager : IRoutingDataManager
{
/// <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;
}
#if DEBUG
protected IList<MessageRouterResult> LastMessageRouterResults
{
get;
set;
}
#endif
/// <summary>
/// Constructor.
/// </summary>
/// <param name="globalTimeProvider">The global time provider for providing the current
/// time for various events such as when a connection is requested.</param>
public AbstractRoutingDataManager(GlobalTimeProvider globalTimeProvider = null)
{
GlobalTimeProvider = globalTimeProvider ?? new GlobalTimeProvider();
#if DEBUG
LastMessageRouterResults = new List<MessageRouterResult>();
#endif
}
public abstract IList<Party> GetUserParties();
public abstract IList<Party> GetBotParties();
public virtual bool AddParty(Party partyToAdd, bool isUser = true)
{
if (partyToAdd == null
|| (isUser ?
GetUserParties().Contains(partyToAdd)
: GetBotParties().Contains(partyToAdd)))
{
return false;
}
if (!isUser && partyToAdd.ChannelAccount == null)
{
throw new NullReferenceException($"Channel account of a bot party ({nameof(partyToAdd.ChannelAccount)}) cannot be null");
}
return ExecuteAddParty(partyToAdd, isUser);
}
public virtual IList<MessageRouterResult> RemoveParty(Party partyToRemove)
{
List<MessageRouterResult> messageRouterResults = new List<MessageRouterResult>();
bool wasRemoved = false;
// Check user and bot parties
for (int i = 0; i < 2; ++i)
{
bool isUser = (i == 0);
IList<Party> partyList = isUser ? GetUserParties() : GetBotParties();
IList<Party> partiesToRemove = FindPartiesWithMatchingChannelAccount(partyToRemove, partyList);
if (partiesToRemove != null)
{
foreach (Party party in partiesToRemove)
{
wasRemoved = ExecuteRemoveParty(party, isUser);
if (wasRemoved)
{
messageRouterResults.Add(new MessageRouterResult()
{
Type = MessageRouterResultType.OK
});
}
}
}
}
// Check pending requests
IList<Party> pendingRequestsToRemove = FindPartiesWithMatchingChannelAccount(partyToRemove, GetPendingRequests());
foreach (Party pendingRequestToRemove in pendingRequestsToRemove)
{
MessageRouterResult removePendingRequestResult = RemovePendingRequest(pendingRequestToRemove);
if (removePendingRequestResult.Type == MessageRouterResultType.ConnectionRejected)
{
// Pending request was removed
wasRemoved = true;
messageRouterResults.Add(removePendingRequestResult);
}
}
if (wasRemoved)
{
// Check if the party exists in ConnectedParties
List<Party> keys = new List<Party>();
foreach (var partyPair in GetConnectedParties())
{
if (partyPair.Key.HasMatchingChannelInformation(partyToRemove)
|| partyPair.Value.HasMatchingChannelInformation(partyToRemove))
{
keys.Add(partyPair.Key);
}
}
foreach (Party key in keys)
{
messageRouterResults.AddRange(Disconnect(key, ConnectionProfile.Owner));
}
}
if (messageRouterResults.Count == 0)
{
messageRouterResults.Add(new MessageRouterResult()
{
Type = MessageRouterResultType.NoActionTaken
});
}
return messageRouterResults;
}
public abstract IList<Party> GetAggregationParties();
public virtual bool AddAggregationParty(Party aggregationPartyToAdd)
{
if (aggregationPartyToAdd != null)
{
if (aggregationPartyToAdd.ChannelAccount != null)
{
throw new ArgumentException("Aggregation party cannot contain a channel account");
}
IList<Party> aggregationParties = GetAggregationParties();
if (!aggregationParties.Contains(aggregationPartyToAdd))
{
return ExecuteAddAggregationParty(aggregationPartyToAdd);
}
}
return false;
}
public virtual bool RemoveAggregationParty(Party aggregationPartyToRemove)
{
return ExecuteRemoveAggregationParty(aggregationPartyToRemove);
}
public abstract IList<Party> GetPendingRequests();
public virtual MessageRouterResult AddPendingRequest(
Party requestorParty, bool rejectConnectionRequestIfNoAggregationChannel = false)
{
AddParty(requestorParty, true); // Make sure the requestor party is in the list of user parties
MessageRouterResult result = new MessageRouterResult()
{
ConversationClientParty = requestorParty
};
if (requestorParty != null)
{
if (IsAssociatedWithAggregation(requestorParty))
{
result.Type = MessageRouterResultType.Error;
result.ErrorMessage = $"The given party ({requestorParty.ChannelAccount?.Name}) is associated with aggregation and hence invalid to request a connection";
}
else if (GetPendingRequests().Contains(requestorParty))
{
result.Type = MessageRouterResultType.ConnectionAlreadyRequested;
}
else
{
if (!GetAggregationParties().Any() && rejectConnectionRequestIfNoAggregationChannel)
{
result.Type = MessageRouterResultType.NoAgentsAvailable;
}
else
{
requestorParty.ConnectionRequestTime = GetCurrentGlobalTime();
if (ExecuteAddPendingRequest(requestorParty))
{
result.Type = MessageRouterResultType.ConnectionRequested;
}
else
{
result.Type = MessageRouterResultType.Error;
result.ErrorMessage = "Failed to add the pending request - this is likely an error caused by the storage implementation";
}
}
}
}
else
{
result.Type = MessageRouterResultType.Error;
result.ErrorMessage = "The given party instance is null";
}
return result;
}
public virtual MessageRouterResult RemovePendingRequest(Party requestorParty)
{
MessageRouterResult result = new MessageRouterResult()
{
ConversationClientParty = requestorParty
};
if (GetPendingRequests().Contains(requestorParty))
{
if (ExecuteRemovePendingRequest(requestorParty))
{
result.Type = MessageRouterResultType.ConnectionRejected;
}
else
{
result.Type = MessageRouterResultType.Error;
result.ErrorMessage = "Failed to remove the pending request of the given party";
}
}
else
{
result.Type = MessageRouterResultType.Error;
result.ErrorMessage = "Could not find a pending request for the given party";
}
return result;
}
public virtual bool IsConnected(Party party, ConnectionProfile connectionProfile)
{
bool isConnected = false;
if (party != null)
{
switch (connectionProfile)
{
case ConnectionProfile.Client:
isConnected = GetConnectedParties().Values.Contains(party);
break;
case ConnectionProfile.Owner:
isConnected = GetConnectedParties().Keys.Contains(party);
break;
case ConnectionProfile.Any:
isConnected = (GetConnectedParties().Values.Contains(party) || GetConnectedParties().Keys.Contains(party));
break;
default:
break;
}
}
return isConnected;
}
public abstract Dictionary<Party, Party> GetConnectedParties();
public virtual Party GetConnectedCounterpart(Party partyWhoseCounterpartToFind)
{
Party counterparty = null;
Dictionary<Party, Party> connectedParties = GetConnectedParties();
if (IsConnected(partyWhoseCounterpartToFind, ConnectionProfile.Client))
{
for (int i = 0; i < connectedParties.Count; ++i)
{
if (connectedParties.Values.ElementAt(i).Equals(partyWhoseCounterpartToFind))
{
counterparty = connectedParties.Keys.ElementAt(i);
break;
}
}
}
else if (IsConnected(partyWhoseCounterpartToFind, ConnectionProfile.Owner))
{
connectedParties.TryGetValue(partyWhoseCounterpartToFind, out counterparty);
}
return counterparty;
}
public virtual MessageRouterResult ConnectAndClearPendingRequest(
Party conversationOwnerParty, Party conversationClientParty)
{
MessageRouterResult result = new MessageRouterResult()
{
ConversationOwnerParty = conversationOwnerParty,
ConversationClientParty = conversationClientParty
};
if (conversationOwnerParty != null && conversationClientParty != null)
{
DateTime connectionStartedTime = GetCurrentGlobalTime();
conversationClientParty.ResetConnectionRequestTime();
conversationClientParty.ConnectionEstablishedTime = connectionStartedTime;
bool wasConnectionAdded =
ExecuteAddConnection(conversationOwnerParty, conversationClientParty);
if (wasConnectionAdded)
{
ExecuteRemovePendingRequest(conversationClientParty);
result.Type = MessageRouterResultType.Connected;
}
else
{
result.Type = MessageRouterResultType.Error;
result.ErrorMessage =
$"Failed to add connection between {conversationOwnerParty} and {conversationClientParty}";
}
}
else
{
result.Type = MessageRouterResultType.Error;
result.ErrorMessage = "Either the owner or the client is missing";
}
return result;
}
public virtual IList<MessageRouterResult> Disconnect(Party party, ConnectionProfile connectionProfile)
{
IList<MessageRouterResult> messageRouterResults = new List<MessageRouterResult>();
if (party != null)
{
List<Party> keysToRemove = new List<Party>();
foreach (var partyPair in GetConnectedParties())
{
bool removeThisPair = false;
switch (connectionProfile)
{
case ConnectionProfile.Client:
removeThisPair = partyPair.Value.Equals(party);
break;
case ConnectionProfile.Owner:
removeThisPair = partyPair.Key.Equals(party);
break;
case ConnectionProfile.Any:
removeThisPair = (partyPair.Value.Equals(party) || partyPair.Key.Equals(party));
break;
default:
break;
}
if (removeThisPair)
{
keysToRemove.Add(partyPair.Key);
if (connectionProfile == ConnectionProfile.Owner)
{
// Since owner is the key in the dictionary, there can be only one
break;
}
}
}
messageRouterResults = RemoveConnections(keysToRemove);
}
return messageRouterResults;
}
public virtual void DeleteAll()
{
#if DEBUG
LastMessageRouterResults.Clear();
#endif
}
public virtual bool IsAssociatedWithAggregation(Party party)
{
IList<Party> aggregationParties = GetAggregationParties();
return (party != null && aggregationParties != null && aggregationParties.Count() > 0
&& aggregationParties.Where(aggregationParty =>
aggregationParty.ConversationAccount.Id == party.ConversationAccount.Id
&& aggregationParty.ServiceUrl == party.ServiceUrl
&& aggregationParty.ChannelId == party.ChannelId).Count() > 0);
}
public virtual string ResolveBotNameInConversation(Party party)
{
string botName = null;
if (party != null)
{
Party botParty = FindBotPartyByChannelAndConversation(party.ChannelId, party.ConversationAccount);
if (botParty != null && botParty.ChannelAccount != null)
{
botName = botParty.ChannelAccount.Name;
}
}
return botName;
}
public virtual Party FindExistingUserParty(Party partyToFind)
{
Party foundParty = null;
try
{
foundParty = GetUserParties().First(party => partyToFind.Equals(party));
}
catch (ArgumentNullException)
{
}
catch (InvalidOperationException)
{
}
return foundParty;
}
public virtual Party FindPartyByChannelAccountIdAndConversationId(
string channelAccountId, string conversationId)
{
Party userParty = null;
try
{
userParty = GetUserParties().Single(party =>
(party.ChannelAccount.Id.Equals(channelAccountId)
&& party.ConversationAccount.Id.Equals(conversationId)));
}
catch (InvalidOperationException)
{
}
return userParty;
}
public virtual Party FindBotPartyByChannelAndConversation(
string channelId, ConversationAccount conversationAccount)
{
Party botParty = null;
try
{
botParty = GetBotParties().Single(party =>
(party.ChannelId.Equals(channelId)
&& party.ConversationAccount.Id.Equals(conversationAccount.Id)));
}
catch (InvalidOperationException)
{
}
return botParty;
}
public virtual Party FindConnectedPartyByChannel(string channelId, ChannelAccount channelAccount)
{
Party foundParty = null;
try
{
foundParty = GetConnectedParties().Keys.Single(party =>
(party.ChannelId.Equals(channelId)
&& party.ChannelAccount != null
&& party.ChannelAccount.Id.Equals(channelAccount.Id)));
}
catch (InvalidOperationException)
{
}
if (foundParty == null)
{
try
{
// Not found in keys, try the values
foundParty = GetConnectedParties().Values.First(party =>
(party.ChannelId.Equals(channelId)
&& party.ChannelAccount != null
&& party.ChannelAccount.Id.Equals(channelAccount.Id)));
}
catch (InvalidOperationException)
{
}
}
return foundParty;
}
public virtual IList<Party> FindPartiesWithMatchingChannelAccount(Party partyToFind, IList<Party> partyCandidates)
{
IList<Party> matchingParties = null;
IEnumerable<Party> foundParties = null;
try
{
foundParties = partyCandidates.Where(party => party.HasMatchingChannelInformation(partyToFind));
}
catch (ArgumentNullException e)
{
System.Diagnostics.Debug.WriteLine($"Failed to find parties: {e.Message}");
}
catch (InvalidOperationException e)
{
System.Diagnostics.Debug.WriteLine($"Failed to find parties: {e.Message}");
}
if (foundParties != null)
{
matchingParties = foundParties.ToArray();
}
return matchingParties;
}
#if DEBUG
public virtual string ConnectionsToString()
{
string parties = string.Empty;
foreach (KeyValuePair<Party, Party> keyValuePair in GetConnectedParties())
{
parties += $"{keyValuePair.Key} -> {keyValuePair.Value}\n\r";
}
return parties;
}
public virtual string GetLastMessageRouterResults()
{
string lastResultsAsString = string.Empty;
foreach (MessageRouterResult result in LastMessageRouterResults)
{
lastResultsAsString += $"{result.ToString()}\n";
}
return lastResultsAsString;
}
public virtual void AddMessageRouterResult(MessageRouterResult result)
{
if (result != null)
{
if (LastMessageRouterResults.Count > 9)
{
LastMessageRouterResults.Remove(LastMessageRouterResults.ElementAt(0));
}
LastMessageRouterResults.Add(result);
}
}
public virtual void ClearMessageRouterResults()
{
LastMessageRouterResults.Clear();
}
#endif
/// <summary>
/// Adds the given party to the collection. No sanity checks.
/// </summary>
/// <param name="partyToAdd">The new party to add.</param>
/// <param name="isUser">If true, the party is considered a user.
/// If false, the party is considered to be a bot.</param>
/// <returns>True, if successful. False otherwise.</returns>
protected abstract bool ExecuteAddParty(Party partyToAdd, bool isUser);
/// <summary>
/// Removes the given party from the collection. No sanity checks.
/// </summary>
/// <param name="partyToRemove">The party to remove.</param>
/// <param name="isUser">If true, the party is considered a user.
/// If false, the party is considered to be a bot.</param>
/// <returns>True, if successful. False otherwise.</returns>
protected abstract bool ExecuteRemoveParty(Party partyToRemove, bool isUser);
/// <summary>
/// Adds the given aggregation party to the collection. No sanity checks.
/// </summary>
/// <param name="aggregationPartyToAdd">The party to be added as an aggregation party (channel).</param>
/// <returns>True, if successful. False otherwise.</returns>
protected abstract bool ExecuteAddAggregationParty(Party aggregationPartyToAdd);
/// <summary>
/// Removes the given aggregation party from the collection. No sanity checks.
/// </summary>
/// <param name="aggregationPartyToRemove">The aggregation party to remove.</param>
/// <returns>True, if successful. False otherwise.</returns>
protected abstract bool ExecuteRemoveAggregationParty(Party aggregationPartyToRemove);
/// <summary>
/// Adds the pending request for the given party. No sanity checks.
/// </summary>
/// <param name="requestorParty">The party whose pending request to add.</param>
/// <returns>True, if successful. False otherwise.</returns>
protected abstract bool ExecuteAddPendingRequest(Party requestorParty);
/// <summary>
/// Removes the pending request of the given party. No sanity checks.
/// </summary>
/// <param name="requestorParty">The party whose request to remove.</param>
/// <returns>True, if successful. False otherwise.</returns>
protected abstract bool ExecuteRemovePendingRequest(Party requestorParty);
/// <summary>
/// Adds a connection between the given parties. No sanity checks.
/// </summary>
/// <param name="conversationOwnerParty">The conversation owner party.</param>
/// <param name="conversationClientParty">The conversation client (customer) party
/// (i.e. one who requested the connection).</param>
/// <returns>True, if successful. False otherwise.</returns>
protected abstract bool ExecuteAddConnection(Party conversationOwnerParty, Party conversationClientParty);
/// <summary>
/// Removes the connection of the given conversation owner party.
/// </summary>
/// <param name="conversationOwnerParty">The conversation owner party.</param>
/// <returns>True, if successful. False otherwise.</returns>
protected abstract bool ExecuteRemoveConnection(Party conversationOwnerParty);
/// <returns>The current global "now" time.</returns>
protected virtual DateTime GetCurrentGlobalTime()
{
return (GlobalTimeProvider == null) ? DateTime.UtcNow : GlobalTimeProvider.GetCurrentTime();
}
/// <summary>
/// Removes the connections of the given conversation owners.
/// </summary>
/// <param name="conversationOwnerParties">The conversation owners whose connections to remove.</param>
/// <returns>The operation result(s).</returns>
protected virtual IList<MessageRouterResult> RemoveConnections(IList<Party> conversationOwnerParties)
{
IList<MessageRouterResult> messageRouterResults = new List<MessageRouterResult>();
foreach (Party conversationOwnerParty in conversationOwnerParties)
{
Dictionary<Party, Party> connectedParties = GetConnectedParties();
connectedParties.TryGetValue(conversationOwnerParty, out Party conversationClientParty);
if (ExecuteRemoveConnection(conversationOwnerParty))
{
conversationOwnerParty.ResetConnectionEstablishedTime();
conversationClientParty.ResetConnectionEstablishedTime();
messageRouterResults.Add(new MessageRouterResult()
{
Type = MessageRouterResultType.Disconnected,
ConversationOwnerParty = conversationOwnerParty,
ConversationClientParty = conversationClientParty
});
}
}
if (messageRouterResults.Count == 0)
{
messageRouterResults.Add(new MessageRouterResult()
{
Type = MessageRouterResultType.NoActionTaken
});
}
return messageRouterResults;
}
}
}