private void RequestLogin(Microsoft.Bot.Connector.Activity message)
        {
            var resumptionCookie        = new ResumptionCookie(message);
            var encodedResumptionCookie = UrlToken.Encode <ResumptionCookie>(resumptionCookie);

            Microsoft.Bot.Connector.Activity oriMessage = resumptionCookie.GetMessage();


            var reply = oriMessage.CreateReply(Messages.BOT_PLEASE_LOGIN);

            reply.Recipient   = oriMessage.From;
            reply.Type        = Microsoft.Bot.Connector.ActivityTypes.Message;
            reply.Attachments = new List <Microsoft.Bot.Connector.Attachment>();
            List <Microsoft.Bot.Connector.CardAction> cardButtons = new List <Microsoft.Bot.Connector.CardAction>();
            var encodedCookie = UrlToken.Encode(resumptionCookie);

            Microsoft.Bot.Connector.CardAction button = new Microsoft.Bot.Connector.CardAction()
            {
                Value = $"{ConfigurationHelper.GetString("AgentLogin_URL")}?cookie={encodedCookie}",
                Type  = "signin",
                Title = Messages.BOT_SIGNIN_BUTTON_TEXT,
                Image = "https://michistorageea.blob.core.windows.net/cdn/login.png"
            };
            cardButtons.Add(button);
            Microsoft.Bot.Connector.SigninCard plCard = new Microsoft.Bot.Connector.SigninCard(
                text: $"{Messages.BOT_PLEASE_LOGIN}",
                buttons: cardButtons);
            Microsoft.Bot.Connector.Attachment plAttachment = plCard.ToAttachment();
            reply.Attachments.Add(plAttachment);
            ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));
            var             response  = connector.Conversations.SendToConversation(reply);
        }
Exemple #2
0
        /// <summary>
        /// Generates the state to be utilized with the authentication request.
        /// </summary>
        /// <param name="context">Context for the dialog.</param>
        /// <returns>A string that represents the current state for the user.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// </exception>
        private string GenerateState(IDialogContext context)
        {
            Dictionary <string, string> state;
            Guid uniqueId = Guid.NewGuid();

            context.AssertNotNull(nameof(context));

            try
            {
                state = new Dictionary <string, string>
                {
                    { BotConstants.BotIdKey, conversationReference.Bot.Id },
                    { BotConstants.ChannelIdKey, conversationReference.ChannelId },
                    { BotConstants.ConversationIdKey, conversationReference.Conversation.Id },
                    { BotConstants.UniqueIdentifierKey, uniqueId.ToString() },
                    { BotConstants.ServiceUrlKey, conversationReference.ServiceUrl },
                    { BotConstants.UserIdKey, conversationReference.User.Id }
                };

                // Save the unique identifier in the user's private conversation store. This value will be
                // utilized to verify the authentication request.
                context.PrivateConversationData.SetValue(BotConstants.UniqueIdentifierKey, uniqueId);

                return(UrlToken.Encode(state));
            }
            finally
            {
                state = null;
            }
        }
        public void UrlToken_Can_Serialize_Address()
        {
            var expected = MakeAddress();
            var encoded  = UrlToken.Encode(expected);
            var actual   = UrlToken.Decode <Address>(encoded);

            Assert.AreEqual(expected, actual);
        }
        public void UrlToken_Can_Serialize_ConversationReference()
        {
            // https://github.com/Microsoft/BotBuilder/pull/1279
            var expected = MakeCookie();
            var encoded  = UrlToken.Encode(expected);
            var actual   = UrlToken.Decode <ConversationReference>(encoded);

            Assert.AreEqual(expected, actual);
        }
Exemple #5
0
        private string getStateParam(ConversationReference conversationRef)
        {
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString["conversationRef"]  = UrlToken.Encode(conversationRef);
            queryString["providerassembly"] = this.authProvider.GetType().Assembly.FullName;
            queryString["providertype"]     = this.authProvider.GetType().FullName;
            queryString["providername"]     = this.authProvider.Name;
            return(HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(queryString.ToString())));
        }
Exemple #6
0
        private string getStateParam(ResumptionCookie resumptionCookie)
        {
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString["resumption"]       = UrlToken.Encode(resumptionCookie);
            queryString["providerassembly"] = this.authProvider.GetType().Assembly.FullName;
            queryString["providertype"]     = this.authProvider.GetType().FullName;
            queryString["providername"]     = this.authProvider.Name;
            return(HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(queryString.ToString())));
        }
Exemple #7
0
        public async Task SayMyName(IDialogContext context)
        {
            try
            {
                // make a simple request to Microsoft Graph API using the Active Directory access token.
                var me = await client.Me.Request().GetAsync();

                await context.PostAsync($"Your name is {me.DisplayName}");
            }
            catch (AdalSilentTokenAcquisitionException)
            {
                await context.PostAsync(loginUri.AbsoluteUri + UrlToken.Encode(cookie));
            }
        }
        private static string BuildExtraParameters(ResumptionCookie resumptionCookie)
        {
            var encodedCookie = UrlToken.Encode(resumptionCookie);

            //var queryString = HttpUtility.ParseQueryString(string.Empty);
            //queryString["userId"] = resumptionCookie.Address.UserId;
            //queryString["botId"] = resumptionCookie.Address.BotId;
            //queryString["conversationId"] = resumptionCookie.Address.ConversationId;
            //queryString["serviceUrl"] = resumptionCookie.Address.ServiceUrl;
            //queryString["channelId"] = resumptionCookie.Address.ChannelId;
            //queryString["locale"] = resumptionCookie.Locale ?? "en";

            //return TokenEncoder(queryString.ToString());
            return(encodedCookie);
        }
Exemple #9
0
        public static string GetGoogleLoginURL(ConversationReference conversationReference, string oauthCallback)
        {
            // 把 conversationreference 的内容放到 state 的參數裏面
            string stateToken = UrlToken.Encode(conversationReference);

            var uri = BotUtility.GetUri("https://accounts.google.com/o/oauth2/v2/auth",
                                        Tuple.Create("client_id", Google_clientId),
                                        Tuple.Create("redirect_uri", oauthCallback),
                                        Tuple.Create("response_type", "code"),
                                        Tuple.Create("access_type", "online"),
                                        Tuple.Create("scope", Uri.EscapeDataString("profile")),
                                        Tuple.Create("state", stateToken)
                                        );

            return(uri.ToString());
        }
        public async Task DispatchAsync(IDialogContext context, IAwaitable <Microsoft.Bot.Connector.IMessageActivity> item)
        {
            Microsoft.Bot.Connector.Activity activity = (Microsoft.Bot.Connector.Activity) await item;
            Logger.Info($"message received from {activity.From.Name}/{activity.From.Id} : {JsonConvert.SerializeObject(activity)}");
            Logger.Info($"message received to {activity.Recipient.Name}/{activity.Recipient.Id}");

            var storage = new AgentStatusStorage(
                ConfigurationHelper.GetString("BotStatusDBConnectionString"));

            if (activity.From.Name.EndsWith("@ocsuser"))
            {
                //Messages from OCS User, when message from OCS User sent to this method, it has to be coming from DirectLine
                AgentStatus agent = null;
                //retrieve ChannelData which includes channelId for our conversation
                //TODO:figure out a way that simplier
                JObject o  = (JObject)activity.ChannelData;
                var     os = JsonConvert.SerializeObject(o);
                DirectLineChannelData channelData = JsonConvert.DeserializeObject <DirectLineChannelData>(os);

                Logger.Info($"ChannelData = {channelData}");
                //ConversationStatus conversation = null;
                Logger.Info($"RoundTrip = {channelData.RoundTrip}");
                //first message send to agent, find an available agent
                //TODO:the agent has been selected in OCS Bot, need to make it sync
                //      Instead of selecting another one here...
                agent = (await storage.FindAvailableAgentsAsync()).FirstOrDefault();
                var convRecord = (await storage.FindConversationActivityAsync(a => a.UserID == agent.Id)).FirstOrDefault();
                convRecord.RemoteConversationID = channelData.ConversationId;
                convRecord.RemoteBotId          = activity.From.Id;//remote user id actually...
                convRecord.RemoteActivity       = UrlToken.Encode <ResumptionCookie>(
                    new ResumptionCookie((Microsoft.Bot.Connector.Activity)activity));
                convRecord.RemoteUserId   = channelData.UserID;
                convRecord.RemoteUserName = channelData.UserName;
                await storage.UpdateConversationActivityAsync(convRecord);

                Logger.Info($"agent:{agent}");
                if (!agent.IsLoggedIn)
                {
                    //Agent somehow is occupied (logout?)
                    Logger.Info("Agent is occupied");
                    var             reply     = activity.CreateReply($"Agent is occupied");
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
                else
                {
                    //Agnet is available to answer questions, send message to agent
                    Logger.Info("Sending to conversation...");

                    //TODO:Need to check if current agent is this user
                    //agent.IsOccupied = true;
                    //await storage.UpdateAgentStatusAsync(agent);

                    //First retrieve last conversaion if exists
                    //resumptionCookie = UrlToken.Decode<ResumptionCookie>(conversation.AgentResumptionCookie);
                    var localResumptionCookie = UrlToken.Decode <ResumptionCookie>(convRecord.LocalActivity);
                    Logger.Info($"AgentBot::LocalResumptionCookie:{localResumptionCookie}");
                    var localActivity  = localResumptionCookie.GetMessage();
                    var localReply     = localActivity.CreateReply($"[{activity.From.Name}]{activity.Text}");
                    var localConnector = new ConnectorClient(new Uri(localActivity.ServiceUrl),
                                                             new MicrosoftAppCredentials(
                                                                 ConfigurationHelper.GetString("MicrosoftAppId"),
                                                                 ConfigurationHelper.GetString("MicrosoftAppPassword")),
                                                             true);

                    Microsoft.Bot.Connector.Conversations localConversation = new Microsoft.Bot.Connector.Conversations(localConnector);
                    localConversation.ReplyToActivity(localReply);
                    Logger.Info("done");


                    return;
                }
            }
            else
            {
                resumptionCookie = new ResumptionCookie(await item);
                await MessageReceivedAsync(context, item);
            }
        }
Exemple #11
0
        public async Task LogOut(IDialogContext context)
        {
            // We will store the conversation reference in the callback URL. When Office 365 logs out it will hit the LogOut endpoint and pass
            // that reference. That event signifies that log out has completed, and will prompt a message from the bot to the user to indicate that fact.
            var conversationRef = context.Activity.ToConversationReference();

            var options = GetDefaultOffice365Options();

            options.RedirectUrl = $"{ConfigurationManager.AppSettings["PostLogoutUrl"]}?conversationRef={UrlToken.Encode(conversationRef)}";

            // We need to know the resource ID. This *should be* stored in bot state from when user logged in.
            string lastSiteCollectionUrl = null;

            context.UserData.TryGetValue <string>(Constants.StateKeys.LastLoggedInSiteCollectionUrl, out lastSiteCollectionUrl);
            options.ResourceId = lastSiteCollectionUrl;


            await new ADALAuthProvider().Logout(options, context);
        }
Exemple #12
0
        public static string EncodeResumptionCookie(ResumptionCookie resumptionCookie)
        {
            var encodedCookie = UrlToken.Encode(resumptionCookie);

            return(encodedCookie);
        }
        public async Task <bool> HumanProcess(IDialogContext context)
        {
            //TODO:end human investigating process
            var statusDB = Configuration.ConfigurationHelper.GetString("BotStatusDBConnectionString");
            var db       = new AgentStatusStorage(statusDB);
            var agents   = await db.FindAvailableAgentsAsync();

            var agent = agents.FirstOrDefault();

            Logger.Info($"Human Investigating:{IsHumanInvestigating}");

            if (agent != null)
            {
                //from bot to agent
                //find agent's conversation record
                var agentConversation   = (await db.FindMyConversationActivityAsync(agent.Id)).FirstOrDefault();
                var localConversation   = (await db.FindMyConversationActivityAsync(context.Activity.From.Id)).FirstOrDefault();
                ResumptionCookie cookie = new ResumptionCookie((Microsoft.Bot.Connector.IMessageActivity)context.Activity);
                if (localConversation == null)
                {
                    localConversation = new ConversationRecord();
                }
                localConversation.UserID              = context.Activity.From.Id;
                localConversation.LocalUserName       = context.Activity.From.Name;
                localConversation.LocalBotId          = context.Activity.Recipient.Id;
                localConversation.LocalChannelID      = context.Activity.ChannelId;
                localConversation.LocalConversationID = context.Activity.Conversation.Id;
                localConversation.LocalActivity       = UrlToken.Encode <ResumptionCookie>(cookie);

                var resp2 = await PostToAgentBotAsync(new Microsoft.Bot.Connector.DirectLine.Activity()
                {
                    Type = Microsoft.Bot.Connector.DirectLine.ActivityTypes.Message,
                    From = new Microsoft.Bot.Connector.DirectLine.ChannelAccount(
                        /*id: agentConversation.LocalBotId,*/
                        id: context.Activity.From.Id,
                        name: context.Activity.From.Name
                        ),
                    Recipient = new Microsoft.Bot.Connector.DirectLine.ChannelAccount(
                        id: agentConversation.UserID),
                    ChannelId = agent.ChannelId,
                    Text      = $"{context.Activity.AsMessageActivity().Text}"
                });

                await db.UpdateConversationActivityAsync(localConversation);


                SetHumanInvestigating(true, context.Activity.From.Id, context.Activity.From.Name);

                return(true);
            }
            else
            {
                var connector = new ConnectorClient(new Uri(context.Activity.ServiceUrl));
                connector.Conversations.ReplyToActivity(context.Activity.Conversation.Id,
                                                        context.Activity.Id,
                                                        new Microsoft.Bot.Connector.Activity
                {
                    Type      = Microsoft.Bot.Connector.DirectLine.ActivityTypes.Message,
                    Text      = Messages.BOT_NO_AGENTS_AVAILABLE,
                    From      = context.Activity.Recipient,
                    Recipient = context.Activity.From,
                    ChannelId = context.Activity.ChannelId
                });
                SetHumanInvestigating(false, null, null);
                return(false);
            }
        }