/// <summary>
        /// Tries to initiates the engagement by creating a request on behalf of the sender in the
        /// given activity. This method does nothing, if a request for the same user already exists.
        /// </summary>
        /// <param name="activity">The activity.</param>
        /// <returns>The result of the operation.</returns>
        public MessageRouterResult InitiateEngagement(Activity activity)
        {
            MessageRouterResult messageRouterResult =
                RoutingDataManager.AddPendingRequest(MessagingUtils.CreateSenderParty(activity));

            messageRouterResult.Activity = activity;
            return(messageRouterResult);
        }
Пример #2
0
        /// <summary>
        /// Tries to initiate a connection (1:1 conversation) by creating a request on behalf of
        /// the SENDER in the given activity. This method does nothing, if a request for the same
        /// user already exists.
        /// </summary>
        /// <param name="activity">The activity. The SENDER in this activity (From property) is considered the requestor.</param>
        /// <param name="rejectConnectionRequestIfNoAggregationChannel">If true, will reject all requests, if there is no aggregation channel.</param>
        /// <returns>Same as RequestConnection(Party, bool)</returns>
        public virtual MessageRouterResult RequestConnection(
            Activity activity, bool rejectConnectionRequestIfNoAggregationChannel = false)
        {
            MessageRouterResult messageRouterResult =
                RequestConnection(MessagingUtils.CreateSenderParty(activity), rejectConnectionRequestIfNoAggregationChannel);

            messageRouterResult.Activity = activity;
            return(messageRouterResult);
        }
Пример #3
0
        private Activity HandleSystemMessage(Activity activity)
        {
            MessageRouterManager messageRouterManager = WebApiConfig.MessageRouterManager;

            if (activity.Type == ActivityTypes.DeleteUserData)
            {
                Party senderParty = MessagingUtils.CreateSenderParty(activity);
                IList <MessageRouterResult> messageRouterResults = messageRouterManager.RemoveParty(senderParty);

                foreach (MessageRouterResult messageRouterResult in messageRouterResults)
                {
                    if (messageRouterResult.Type == MessageRouterResultType.OK)
                    {
                        System.Diagnostics.Debug.WriteLine(ConversationText.UserDataDeleted, senderParty.ChannelAccount?.Name);
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
                if (activity.MembersRemoved != null && activity.MembersRemoved.Count > 0)
                {
                    foreach (ChannelAccount channelAccount in activity.MembersRemoved)
                    {
                        Party partyToRemove = new Party(activity.ServiceUrl, activity.ChannelId, channelAccount, activity.Conversation);
                        IList <MessageRouterResult> messageRouterResults = messageRouterManager.RemoveParty(partyToRemove);

                        foreach (MessageRouterResult messageRouterResult in messageRouterResults)
                        {
                            if (messageRouterResult.Type == MessageRouterResultType.OK)
                            {
                                System.Diagnostics.Debug.WriteLine(ConversationText.PartyRemoved, partyToRemove.ChannelAccount?.Name);
                            }
                        }
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (activity.Type == ActivityTypes.Typing)
            {
                // Handle knowing that the user is typing
            }
            else if (activity.Type == ActivityTypes.Ping)
            {
            }

            return(null);
        }
Пример #4
0
        /// <summary>
        /// Checks the given activity for back channel messages and handles them, if detected.
        /// Currently the only back channel message supported is for creating connections
        /// (establishing 1:1 conversations).
        /// </summary>
        /// <param name="activity">The activity to check for back channel messages.</param>
        /// <returns>
        /// The result:
        ///     * MessageRouterResultType.Connected: A connection (1:1 conversation) was created
        ///     * MessageRouterResultType.NoActionTaken: No back channel message detected
        ///     * MessageRouterResultType.Error: See the error message for details
        /// </returns>
        public virtual MessageRouterResult HandleBackChannelMessage(Activity activity)
        {
            MessageRouterResult messageRouterResult = new MessageRouterResult();

            if (activity == null || string.IsNullOrEmpty(activity.Text))
            {
                messageRouterResult.Type         = MessageRouterResultType.Error;
                messageRouterResult.ErrorMessage = $"The given activity ({nameof(activity)}) is either null or the message is missing";
            }
            else if (activity.Text.Equals(BackChannelId))
            {
                if (activity.ChannelData == null)
                {
                    messageRouterResult.Type         = MessageRouterResultType.Error;
                    messageRouterResult.ErrorMessage = "No channel data";
                }
                else
                {
                    // Handle accepted request and start 1:1 conversation
                    Party conversationClientParty = null;

                    try
                    {
                        conversationClientParty = ParsePartyFromChannelData(activity.ChannelData);
                    }
                    catch (Exception e)
                    {
                        messageRouterResult.Type         = MessageRouterResultType.Error;
                        messageRouterResult.ErrorMessage =
                            $"Failed to parse the party information from the back channel message: {e.Message}";
                    }

                    if (conversationClientParty != null)
                    {
                        Party conversationOwnerParty = MessagingUtils.CreateSenderParty(activity);

                        messageRouterResult = _routingDataManager.ConnectAndClearPendingRequest(
                            conversationOwnerParty, conversationClientParty);

                        messageRouterResult.Activity = activity;
                    }
                }
            }
            else
            {
                // No back channel message detected
                messageRouterResult.Type = MessageRouterResultType.NoActionTaken;
            }

            return(messageRouterResult);
        }
Пример #5
0
#pragma warning disable 1998
        private async Task <Activity> HandleSystemMessageAsync(Activity message)
        {
            MessageRouterManager messageRouterManager = WebApiConfig.MessageRouterManager;

            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
                Party senderParty = MessagingUtils.CreateSenderParty(message);

                if (messageRouterManager.RemoveParty(senderParty)?.Count > 0)
                {
                    return(message.CreateReply($"Data of user {senderParty.ChannelAccount?.Name} removed"));
                }
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
                if (message.MembersRemoved != null && message.MembersRemoved.Count > 0)
                {
                    foreach (ChannelAccount channelAccount in message.MembersRemoved)
                    {
                        Party party = new Party(
                            message.ServiceUrl, message.ChannelId, channelAccount, message.Conversation);

                        if (messageRouterManager.RemoveParty(party)?.Count > 0)
                        {
                            System.Diagnostics.Debug.WriteLine($"Party {party.ToString()} removed");
                        }
                    }
                }
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing that the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return(null);
        }
        /// <summary>
        /// Notifies the user that there are no aggregation channels setup
        /// </summary>
        /// <param name="messageRouterResult">The result to handle.</param>
        private static async Task <string> HandleNoAggregationChannelResultAsync(MessageRouterResult messageRouterResult)
        {
            string message = string.Empty;

            if (messageRouterResult.Activity != null)
            {
                MessageRouterManager messageRouterManager = WebApiConfig.MessageRouterManager;
                string botName = messageRouterManager.RoutingDataManager.ResolveBotNameInConversation(
                    MessagingUtils.CreateSenderParty(messageRouterResult.Activity));

                message  = $"{(string.IsNullOrEmpty(messageRouterResult.ErrorMessage) ? "" : $"{messageRouterResult.ErrorMessage}: ")}The message router manager is not initialized; type \"";
                message += string.IsNullOrEmpty(botName) ? $"{Commands.CommandKeyword} " : $"@{botName} ";
                message += $"{Commands.CommandAddAggregationChannel}\" to setup the aggregation channel";

                await MessagingUtils.ReplyToActivityAsync(messageRouterResult.Activity, message);
            }
        /// <summary>
        /// Checks the given activity for back channel messages and handles them, if detected.
        /// Currently the only back channel message supported is for adding engagements
        /// (establishing 1:1 conversations).
        /// </summary>
        /// <param name="activity">The activity to check for back channel messages.</param>
        /// <returns>The result; if the type of the result is
        /// MessageRouterResultType.EngagementAdded, the operation was successful.</returns>
        public MessageRouterResult HandleBackChannelMessage(Activity activity)
        {
            MessageRouterResult messageRouterResult = new MessageRouterResult();

            if (activity == null || string.IsNullOrEmpty(activity.Text))
            {
                messageRouterResult.Type         = MessageRouterResultType.Error;
                messageRouterResult.ErrorMessage = $"The given activity ({nameof(activity)}) is either null or the message is missing";
            }
            else if (activity.Text.StartsWith(BackChannelId))
            {
                if (activity.ChannelData == null)
                {
                    messageRouterResult.Type         = MessageRouterResultType.Error;
                    messageRouterResult.ErrorMessage = "No channel data";
                }
                else
                {
                    // Handle accepted request and start 1:1 conversation
                    string partyAsJsonString       = ((JObject)activity.ChannelData)[BackChannelId][DefaultPartyPropertyId].ToString();
                    Party  conversationClientParty = Party.FromJsonString(partyAsJsonString);

                    Party conversationOwnerParty = MessagingUtils.CreateSenderParty(activity);

                    messageRouterResult = RoutingDataManager.AddEngagementAndClearPendingRequest(
                        conversationOwnerParty, conversationClientParty);
                    messageRouterResult.Activity = activity;
                }
            }
            else
            {
                // No back channel message detected
                messageRouterResult.Type = MessageRouterResultType.NoActionTaken;
            }

            return(messageRouterResult);
        }
Пример #8
0
        /// <summary>
        /// Checks the given activity for a possible command.
        ///
        /// All messages that start with a specific command keyword or contain a mention of the bot
        /// ("@<bot name>") are checked for possible commands.
        /// </summary>
        /// <param name="activity">An Activity instance containing a possible command.</param>
        /// <returns>True, if a command was detected and handled. False otherwise.</returns>
        public async virtual Task <bool> HandleCommandAsync(Activity activity)
        {
            bool     wasHandled    = false;
            Activity replyActivity = null;
            Command  command       = ExtractCommand(activity);

            if (command != null)
            {
                Party senderParty = MessagingUtils.CreateSenderParty(activity);

                switch (command.BaseCommand.ToLower())
                {
                case string baseCommand when(baseCommand.Equals(Commands.CommandListOptions)):
                    // Present all command options in a card
                    replyActivity = CommandCardFactory.AddCardToActivity(
                        activity.CreateReply(), CommandCardFactory.CreateCommandOptionsCard(activity.Recipient?.Name));

                    wasHandled = true;
                    break;

                case string baseCommand when(baseCommand.Equals(Commands.CommandAddAggregationChannel)):
                    // Establish the sender's channel/conversation as an aggreated one if not already exists
                    Party aggregationPartyToAdd =
                        new Party(activity.ServiceUrl, activity.ChannelId, null, activity.Conversation);

                    if (_messageRouterManager.RoutingDataManager.AddAggregationParty(aggregationPartyToAdd))
                    {
                        replyActivity = activity.CreateReply(ConversationText.AggregationChannelSet);
                    }
                    else
                    {
                        replyActivity = activity.CreateReply(ConversationText.AggregationChannelAlreadySet);
                    }

                    wasHandled = true;
                    break;

                case string baseCommand when(baseCommand.Equals(Commands.CommandRemoveAggregationChannel)):
                    // Remove the sender's channel/conversation from the list of aggregation channels
                    if (_messageRouterManager.RoutingDataManager.IsAssociatedWithAggregation(senderParty))
                    {
                        Party aggregationPartyToRemove =
                            new Party(activity.ServiceUrl, activity.ChannelId, null, activity.Conversation);

                        if (_messageRouterManager.RoutingDataManager.RemoveAggregationParty(aggregationPartyToRemove))
                        {
                            replyActivity = activity.CreateReply(ConversationText.AggregationChannelRemoved);
                        }
                        else
                        {
                            replyActivity = activity.CreateReply(ConversationText.FailedToRemoveAggregationChannel);
                        }

                        wasHandled = true;
                    }

                    break;

                case string baseCommand when(baseCommand.Equals(Commands.CommandAcceptRequest) || baseCommand.Equals(Commands.CommandRejectRequest)):
                    // Accept/reject conversation request
                    bool doAccept = baseCommand.Equals(Commands.CommandAcceptRequest);

                    if (_messageRouterManager.RoutingDataManager.IsAssociatedWithAggregation(senderParty))
                    {
                        // The party is associated with the aggregation and has the right to accept/reject
                        if (command.Parameters.Count == 0)
                        {
                            replyActivity = activity.CreateReply();

                            IList <Party> pendingRequests =
                                _messageRouterManager.RoutingDataManager.GetPendingRequests();

                            if (pendingRequests.Count == 0)
                            {
                                replyActivity.Text = ConversationText.NoPendingRequests;
                            }
                            else
                            {
                                replyActivity = CommandCardFactory.AddCardToActivity(
                                    replyActivity, CommandCardFactory.CreateAcceptOrRejectCardForMultipleRequests(
                                        pendingRequests, doAccept, activity.Recipient?.Name));
                            }
                        }
                        else if (!doAccept &&
                                 command.Parameters[0].Equals(Commands.CommandParameterAll))
                        {
                            if (!await new MessageRoutingUtils().RejectAllPendingRequestsAsync(
                                    _messageRouterManager, _messageRouterResultHandler))
                            {
                                replyActivity      = activity.CreateReply();
                                replyActivity.Text = ConversationText.FailedToRejectPendingRequests;
                            }
                        }
                        else
                        {
                            string errorMessage = await new MessageRoutingUtils().AcceptOrRejectRequestAsync(
                                _messageRouterManager, _messageRouterResultHandler, senderParty, doAccept, command.Parameters[0]);

                            if (!string.IsNullOrEmpty(errorMessage))
                            {
                                replyActivity      = activity.CreateReply();
                                replyActivity.Text = errorMessage;
                            }
                        }
                    }
#if DEBUG
                    // We shouldn't respond to command attempts by regular users, but I guess
                    // it's okay when debugging
                    else
                    {
                        replyActivity = activity.CreateReply(ConversationText.ConnectionRequestResponseNotAllowed);
                    }
#endif

                    wasHandled = true;
                    break;

                case string baseCommand when(baseCommand.Equals(Commands.CommandDisconnect)):
                    // End the 1:1 conversation
                    IList <MessageRouterResult> messageRouterResults = _messageRouterManager.Disconnect(senderParty);

                    foreach (MessageRouterResult messageRouterResult in messageRouterResults)
                    {
                        await _messageRouterResultHandler.HandleResultAsync(messageRouterResult);
                    }

                    wasHandled = true;
                    break;


                    #region Implementation of debugging commands
#if DEBUG
                case string baseCommand when(baseCommand.Equals(Commands.CommandDeleteAllRoutingData)):
                    // DELETE ALL ROUTING DATA
                    replyActivity = activity.CreateReply(ConversationText.DeletingAllData);

                    _messageRouterManager.RoutingDataManager.DeleteAll();
                    wasHandled = true;
                    break;

                case string baseCommand when(baseCommand.Equals(Commands.CommandList)):
                    bool listAll = command.Parameters.Contains(Commands.CommandParameterAll);

                    replyActivity = activity.CreateReply();
                    string replyMessageText = string.Empty;

                    if (listAll || command.Parameters.Contains(Commands.CommandParameterParties))
                    {
                        // List user and bot parties
                        IRoutingDataManager routingDataManager = _messageRouterManager.RoutingDataManager;
                        string partiesAsString = PartyListToString(routingDataManager.GetUserParties());

                        replyMessageText += string.IsNullOrEmpty(partiesAsString)
                                ? $"{ConversationText.NoUsersStored}{StringAndCharConstants.LineBreak}"
                                : $"{ConversationText.Users}:{StringAndCharConstants.LineBreak}{partiesAsString}{StringAndCharConstants.LineBreak}";

                        partiesAsString = PartyListToString(routingDataManager.GetBotParties());

                        replyMessageText += string.IsNullOrEmpty(partiesAsString)
                                ? $"{ConversationText.NoBotsStored}{StringAndCharConstants.LineBreak}"
                                : $"{ConversationText.Bots}:{StringAndCharConstants.LineBreak}{partiesAsString}{StringAndCharConstants.LineBreak}";

                        wasHandled = true;
                    }

                    if (listAll || command.Parameters.Contains(Commands.CommandParameterRequests))
                    {
                        // List all pending requests
                        IList <Attachment> attachments =
                            CommandCardFactory.CreateMultipleRequestCards(
                                _messageRouterManager.RoutingDataManager.GetPendingRequests(), activity.Recipient?.Name);

                        if (attachments.Count > 0)
                        {
                            replyMessageText += string.Format(ConversationText.PendingRequestsFoundWithCount, attachments.Count);
                            replyMessageText += StringAndCharConstants.LineBreak;
                            replyActivity.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                            replyActivity.Attachments      = attachments;
                        }
                        else
                        {
                            replyMessageText += $"{ConversationText.NoPendingRequests}{StringAndCharConstants.LineBreak}";
                        }

                        wasHandled = true;
                    }

                    if (listAll || command.Parameters.Contains(Commands.CommandParameterConnections))
                    {
                        // List all connections (conversations)
                        string connectionsAsString = _messageRouterManager.RoutingDataManager.ConnectionsToString();

                        replyMessageText += string.IsNullOrEmpty(connectionsAsString)
                                ? $"{ConversationText.NoConversations}{StringAndCharConstants.LineBreak}"
                                : $"{connectionsAsString}{StringAndCharConstants.LineBreak}";

                        wasHandled = true;
                    }

                    if (listAll || command.Parameters.Contains(Commands.CommandParameterResults))
                    {
                        // List all logged message router results
                        string resultsAsString = _messageRouterManager.RoutingDataManager.GetLastMessageRouterResults();

                        replyMessageText += string.IsNullOrEmpty(resultsAsString)
                                ? $"{ConversationText.NoResults}{StringAndCharConstants.LineBreak}"
                                : $"{resultsAsString}{StringAndCharConstants.LineBreak}";

                        wasHandled = true;
                    }

                    if (!wasHandled)
                    {
                        replyMessageText = ConversationText.InvalidOrMissingCommandParameter;
                    }

                    replyActivity.Text = replyMessageText;
                    break;
#endif
                    #endregion

                default:
                    replyActivity = activity.CreateReply(string.Format(ConversationText.CommandNotRecognized, command.BaseCommand));
                    break;
                }

                if (replyActivity != null)
                {
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                    await connector.Conversations.ReplyToActivityAsync(replyActivity);
                }
            }

            return(wasHandled);
        }
        /// <summary>
        /// Handles the incoming message activities. For instance, if it is a message from party
        /// engaged in a chat, the message will be forwarded to the counterpart in whatever
        /// channel that party is on.
        /// </summary>
        /// <param name="activity">The activity to handle.</param>
        /// <param name="addClientNameToMessage">If true, will add the client's name to the beginning of the message.</param>
        /// <param name="addOwnerNameToMessage">If true, will add the owner's (agent) name to the beginning of the message.</param>
        /// <returns>The result of the operation.</returns>
        public async Task <MessageRouterResult> HandleMessageAsync(
            Activity activity, bool addClientNameToMessage = true, bool addOwnerNameToMessage = false)
        {
            MessageRouterResult result = new MessageRouterResult()
            {
                Type     = MessageRouterResultType.NoActionTaken,
                Activity = activity
            };

            Party senderParty = MessagingUtils.CreateSenderParty(activity);

            if (RoutingDataManager.IsEngaged(senderParty, EngagementProfile.Owner))
            {
                // Sender is an owner of an ongoing conversation - forward the message
                result.ConversationOwnerParty = senderParty;
                Party partyToForwardMessageTo = RoutingDataManager.GetEngagedCounterpart(senderParty);

                if (partyToForwardMessageTo != null)
                {
                    result.ConversationClientParty = partyToForwardMessageTo;
                    string message = addOwnerNameToMessage
                        ? $"{senderParty.ChannelAccount.Name}: {activity.Text}" : activity.Text;
                    ResourceResponse resourceResponse =
                        await SendMessageToPartyByBotAsync(partyToForwardMessageTo, activity.Text);

                    if (resourceResponse != null)
                    {
                        result.Type = MessageRouterResultType.OK;
                    }
                    else
                    {
                        result.Type         = MessageRouterResultType.FailedToForwardMessage;
                        result.ErrorMessage = $"Failed to forward the message to user {partyToForwardMessageTo}";
                    }
                }
                else
                {
                    result.Type         = MessageRouterResultType.FailedToForwardMessage;
                    result.ErrorMessage = "Failed to find the party to forward the message to";
                }
            }
            else if (RoutingDataManager.IsEngaged(senderParty, EngagementProfile.Client))
            {
                // Sender is a participant of an ongoing conversation - forward the message
                result.ConversationClientParty = senderParty;
                Party partyToForwardMessageTo = RoutingDataManager.GetEngagedCounterpart(senderParty);

                if (partyToForwardMessageTo != null)
                {
                    result.ConversationOwnerParty = partyToForwardMessageTo;
                    string message = addClientNameToMessage
                        ? $"{senderParty.ChannelAccount.Name}: {activity.Text}" : activity.Text;
                    await SendMessageToPartyByBotAsync(partyToForwardMessageTo, message);

                    result.Type = MessageRouterResultType.OK;
                }
                else
                {
                    result.Type         = MessageRouterResultType.FailedToForwardMessage;
                    result.ErrorMessage = "Failed to find the party to forward the message to";
                }
            }

            return(result);
        }
 /// <summary>
 /// Checks the given activity for new parties and adds them to the collection, if not
 /// already there.
 /// </summary>
 /// <param name="activity">The activity.</param>
 public void MakeSurePartiesAreTracked(IActivity activity)
 {
     MakeSurePartiesAreTracked(
         MessagingUtils.CreateSenderParty(activity),
         MessagingUtils.CreateRecipientParty(activity));
 }
Пример #11
0
        /// <summary>
        /// Checks the given activity for back channel messages and handles them, if detected.
        /// Currently the only back channel message supported is for creating connections
        /// (establishing 1:1 conversations).
        /// </summary>
        /// <param name="activity">The activity to check for back channel messages.</param>
        /// <returns>
        /// The result:
        ///     * MessageRouterResultType.Connected: A connection (1:1 conversation) was created
        ///     * MessageRouterResultType.NoActionTaken: No back channel message detected
        ///     * MessageRouterResultType.Error: See the error message for details
        /// </returns>
        public virtual MessageRouterResult HandleBackChannelMessage(Activity activity)
        {
            MessageRouterResult messageRouterResultNoAction = new MessageRouterResult {
                Type = MessageRouterResultType.NoActionTaken
            };
            MessageRouterResult messageRouterResult = new MessageRouterResult();
            var     Settings = new BotSettings();
            Manager manager  = new Manager(Settings[BotSettings.KeyRoutingDataStorageConnectionString]);

            if (activity == null || string.IsNullOrEmpty(activity.Text))
            {
                messageRouterResult.Type         = MessageRouterResultType.Error;
                messageRouterResult.ErrorMessage = $"The given activity ({nameof(activity)}) is either null or the message is missing";
            }
            else if (activity.Text.Equals(BackChannelId))
            {
                if (activity.ChannelData == null)
                {
                    messageRouterResult.Type         = MessageRouterResultType.Error;
                    messageRouterResult.ErrorMessage = "No channel data";
                }
                else
                {
                    // Handle accepted request and start 1:1 conversation
                    Party conversationClientParty = null;

                    try
                    {
                        conversationClientParty = ParsePartyFromChannelData(activity.ChannelData);
                        Debug.WriteLine($"Client : {JsonConvert.SerializeObject(conversationClientParty)}");
                    }
                    catch (Exception e)
                    {
                        messageRouterResult.Type         = MessageRouterResultType.Error;
                        messageRouterResult.ErrorMessage =
                            $"Failed to parse the party information from the back channel message: {e.Message}";
                    }

                    if (conversationClientParty != null)
                    {
                        Party conversationOwnerParty = MessagingUtils.CreateSenderParty(activity);
                        Debug.WriteLine($"Owner : {JsonConvert.SerializeObject(conversationOwnerParty)}");

                        MessageRouterManager messageRouterManager = WebApiConfig.MessageRouterManager;
                        IRoutingDataManager  routingDataManager   = messageRouterManager.RoutingDataManager;

                        bool isConnected = false;

                        Dictionary <Party, Party> connectedParties = routingDataManager.GetConnectedParties();

                        foreach (var connectedPartie in connectedParties)
                        {
                            if (connectedPartie.Value.ConversationAccount.Id == conversationClientParty.ConversationAccount.Id)
                            {
                                isConnected = true;
                                break;
                            }
                        }

                        if (isConnected)
                        {
                            bool deleteConnexion = manager.ExecuteRemoveConnexionByConversationClientId(conversationClientParty.ConversationAccount.Id);
                            messageRouterResult = deleteConnexion ? manager.Connect(conversationOwnerParty, conversationClientParty) : messageRouterResultNoAction;
                        }
                        else
                        {
                            Dictionary <Party, Party> waitingConnectedParties = manager.GetWaitingConnectedParties();
                            bool isWaitingConnected = false;

                            foreach (var waitingConnectedPartie in waitingConnectedParties)
                            {
                                if (waitingConnectedPartie.Value.ConversationAccount.Id == conversationClientParty.ConversationAccount.Id)
                                {
                                    isWaitingConnected = true;
                                    break;
                                }
                            }

                            if (isWaitingConnected)
                            {
                                bool deleteWaitingConnection = manager.ExecuteRemoveWaitingConnexionByConversationClientId(conversationClientParty.ConversationAccount.Id);
                                messageRouterResult = deleteWaitingConnection ? manager.WaitingConnectAndClearPendingRequest(conversationOwnerParty, conversationClientParty) : messageRouterResultNoAction;

                                messageRouterResult.Activity = activity;
                            }
                            else
                            {
                                messageRouterResult = manager.WaitingConnectAndClearPendingRequest(conversationOwnerParty, conversationClientParty);

                                //messageRouterResult = _routingDataManager.ConnectAndClearPendingRequest(
                                //    conversationOwnerParty, conversationClientParty);

                                messageRouterResult.Activity = activity;
                            }
                        }
                    }
                }
            }
            else
            {
                // No back channel message detected
                //messageRouterResult.Type = MessageRouterResultType.NoActionTaken;
                ConnectionEntity waitingConnection = manager.RetrieveWaitingConnectionByConversationIdOwner(activity.Conversation.Id);

                if (waitingConnection != null)
                {
                    Party conversationOwnerParty  = JsonConvert.DeserializeObject <PartyEntity>(waitingConnection.Owner).ToParty();
                    Party conversationClientParty = JsonConvert.DeserializeObject <PartyEntity>(waitingConnection.Client).ToParty();

                    if (activity.Text == $"@{conversationOwnerParty.ChannelAccount.Name} accept {conversationClientParty.ChannelAccount.Id}" || activity.Text == $"@{conversationOwnerParty.ChannelAccount.Name} reject {conversationClientParty.ChannelAccount.Id}")
                    {
                        if (activity.Text.Contains("accept"))
                        {
                            messageRouterResult = manager.Connect(conversationOwnerParty, conversationClientParty);
                        }
                        else
                        {
                            messageRouterResult.Type = MessageRouterResultType.ConnectionRejected;
                            messageRouterResult.ConversationClientParty = conversationClientParty;
                            messageRouterResult.ConversationOwnerParty  = conversationOwnerParty;
                        }

                        manager.RemoveWaitingConnection(conversationOwnerParty, conversationClientParty);
                    }
                    else
                    {
                        messageRouterResult.Type = MessageRouterResultType.ConnectionAlreadyRequested;

                        if (activity.Conversation.Id == conversationOwnerParty.ConversationAccount.Id)
                        {
                            messageRouterResult.ConversationOwnerParty  = conversationOwnerParty;
                            messageRouterResult.ConversationClientParty = conversationClientParty;
                        }
                        else
                        {
                            messageRouterResult.ConversationClientParty = conversationClientParty;
                        }
                    }
                }
                else
                {
                    // No back channel message detected
                    messageRouterResult.Type = MessageRouterResultType.NoActionTaken;
                }
            }

            return(messageRouterResult);
        }
Пример #12
0
        /// <summary>
        /// Checks the given activity for a possible command.
        ///
        /// All messages that start with a specific command keyword or contain a mention of the bot
        /// ("@<bot name>") are checked for possible commands.
        /// </summary>
        /// <param name="activity">An Activity instance containing a possible command.</param>
        /// <returns>True, if a command was detected and handled. False otherwise.</returns>
        public async virtual Task <bool> HandleCommandAsync(Activity activity)
        {
            bool     wasHandled    = false;
            Activity replyActivity = null;

            if ((!string.IsNullOrEmpty(activity.Text) && activity.Text.StartsWith($"{Commands.CommandKeyword} ")) ||
                WasBotAddressedDirectly(activity, false))
            {
                string commandMessage = ExtractCleanCommandMessage(activity);
                Party  senderParty    = MessagingUtils.CreateSenderParty(activity);

                switch (commandMessage.ToLower())
                {
                case string command when(command.StartsWith(Commands.CommandListOptions)):
                    // Present all command options in a card
                    replyActivity = CreateCommandOptionsCard(activity);

                    wasHandled = true;
                    break;

                case string command when(command.StartsWith(Commands.CommandAddAggregationChannel)):
                    // Establish the sender's channel/conversation as an aggreated one if not already exists
                    Party aggregationParty = new Party(activity.ServiceUrl, activity.ChannelId, null, activity.Conversation);

                    if (_messageRouterManager.RoutingDataManager.AddAggregationParty(aggregationParty))
                    {
                        replyActivity = activity.CreateReply("This channel/conversation is now where the requests are aggregated");
                    }
                    else
                    {
                        replyActivity = activity.CreateReply("This channel/conversation is already receiving requests");
                    }

                    wasHandled = true;
                    break;

                case string command when(command.StartsWith(Commands.CommandAcceptRequest) || command.StartsWith(Commands.CommandRejectRequest)):
                    // Accept/reject conversation request
                    bool doAccept = command.StartsWith(Commands.CommandAcceptRequest);

                    if (_messageRouterManager.RoutingDataManager.IsAssociatedWithAggregation(senderParty))
                    {
                        // The party is associated with the aggregation and has the right to accept/reject
                        string errorMessage = await AcceptOrRejectRequestAsync(senderParty, commandMessage, doAccept);

                        if (!string.IsNullOrEmpty(errorMessage))
                        {
                            replyActivity = activity.CreateReply(errorMessage);
                        }
                    }
                    else
                    {
                        replyActivity = activity.CreateReply("Sorry, you are not allowed to accept/reject requests");
                    }

                    wasHandled = true;
                    break;

                case string command when(command.StartsWith(Commands.CommandDisconnect)):
                    // End the 1:1 conversation
                    IList <MessageRouterResult> messageRouterResults = _messageRouterManager.Disconnect(senderParty);

                    foreach (MessageRouterResult messageRouterResult in messageRouterResults)
                    {
                        await _messageRouterResultHandler.HandleResultAsync(messageRouterResult);
                    }

                    wasHandled = true;
                    break;


                    #region Implementation of debugging commands
#if DEBUG
                case string command when(command.StartsWith(Commands.CommandDeleteAllRoutingData)):
                    // DELETE ALL ROUTING DATA
                    await _messageRouterManager.BroadcastMessageToAggregationChannelsAsync(
                        $"Deleting all data as requested by \"{senderParty.ChannelAccount?.Name}\"...");

                    replyActivity = activity.CreateReply("Deleting all data...");
                    _messageRouterManager.RoutingDataManager.DeleteAll();
                    wasHandled = true;
                    break;

                case string command when(command.StartsWith(Commands.CommandListAllParties)):
                    // List user and bot parties
                    IRoutingDataManager routingDataManager = _messageRouterManager.RoutingDataManager;

                    string replyMessage    = string.Empty;
                    string partiesAsString = PartyListToString(routingDataManager.GetUserParties());

                    if (string.IsNullOrEmpty(partiesAsString))
                    {
                        replyMessage = $"No user parties{LineBreak}";
                    }
                    else
                    {
                        replyMessage = $"Users:{LineBreak}{partiesAsString}";
                    }

                    partiesAsString = PartyListToString(routingDataManager.GetBotParties());

                    if (string.IsNullOrEmpty(partiesAsString))
                    {
                        replyMessage += "No bot parties";
                    }
                    else
                    {
                        replyMessage += $"Bot:{LineBreak}{partiesAsString}";
                    }

                    replyActivity = activity.CreateReply(replyMessage);
                    wasHandled    = true;
                    break;

                case string command when(command.StartsWith(Commands.CommandListPendingRequests)):
                    // List all pending requests
                    var attachments = new List <Attachment>();

                    foreach (Party party in _messageRouterManager.RoutingDataManager.GetPendingRequests())
                    {
                        attachments.Add(CreateRequestCard(party, activity.Recipient.Name));
                    }

                    if (attachments.Count > 0)
                    {
                        replyActivity = activity.CreateReply($"{attachments.Count} pending request(s) found:");
                        replyActivity.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                        replyActivity.Attachments      = attachments;
                    }
                    else
                    {
                        replyActivity = activity.CreateReply("No pending requests");
                    }

                    wasHandled = true;
                    break;

                case string command when(command.StartsWith(Commands.CommandListConnections)):
                    // List all connections (conversations)
                    string parties = _messageRouterManager.RoutingDataManager.ConnectionsToString();

                    if (string.IsNullOrEmpty(parties))
                    {
                        replyActivity = activity.CreateReply("No conversations");
                    }
                    else
                    {
                        replyActivity = activity.CreateReply(parties);
                    }

                    wasHandled = true;
                    break;

                case string command when(command.StartsWith(Commands.CommandListLastMessageRouterResults)):
                    // List all logged message router results
                    string resultsAsString = _messageRouterManager.RoutingDataManager.GetLastMessageRouterResults();

                    replyActivity = activity.CreateReply($"{(string.IsNullOrEmpty(resultsAsString) ? "No results" : resultsAsString)}");
                    wasHandled    = true;
                    break;
#endif
                    #endregion

                default:
                    replyActivity = activity.CreateReply($"Command \"{commandMessage}\" not recognized");
                    break;
                }

                if (replyActivity != null)
                {
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                    await connector.Conversations.ReplyToActivityAsync(replyActivity);
                }
            }

            return(wasHandled);
        }