Exemple #1
0
 protected async Task <DialogTurnResult> BeginSetNumberThenId(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await sc.BeginDialogAsync(Actions.SetNumberThenId));
 }
        private async Task <DialogTurnResult> AfterSelectEvent(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                var luisResult = state.LuisResult;
                var topIntent  = luisResult?.TopIntent().intent;

                var generalLuisResult = state.GeneralLuisResult;
                var generalTopIntent  = generalLuisResult?.TopIntent().intent;

                if (topIntent == null)
                {
                    state.Clear();
                    return(await sc.CancelAllDialogsAsync());
                }

                if (generalTopIntent == General.Intent.ShowNext && state.SummaryEvents != null)
                {
                    if ((state.ShowEventIndex + 1) * state.PageSize < state.SummaryEvents.Count)
                    {
                        state.ShowEventIndex++;
                    }
                    else
                    {
                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.CalendarNoMoreEvent));
                    }

                    return(await sc.ReplaceDialogAsync(Actions.ConnectToMeeting, sc.Options));
                }
                else if (generalTopIntent == General.Intent.ShowPrevious && state.SummaryEvents != null)
                {
                    if (state.ShowEventIndex > 0)
                    {
                        state.ShowEventIndex--;
                    }
                    else
                    {
                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SummaryResponses.CalendarNoPreviousEvent));
                    }

                    return(await sc.ReplaceDialogAsync(Actions.ConnectToMeeting, sc.Options));
                }

                sc.Context.Activity.Properties.TryGetValue("OriginText", out var content);
                var userInput = content != null?content.ToString() : sc.Context.Activity.Text;

                var promptRecognizerResult = ConfirmRecognizerHelper.ConfirmYesOrNo(userInput, sc.Context.Activity.Locale);
                if (promptRecognizerResult.Succeeded && promptRecognizerResult.Value == false)
                {
                    state.Clear();
                    return(await sc.CancelAllDialogsAsync());
                }
                else if (promptRecognizerResult.Succeeded && promptRecognizerResult.Value == true)
                {
                    var currentList = GetCurrentPageMeetings(state.SummaryEvents, state);
                    state.ConfirmedMeeting.Add(currentList.First());
                    return(await sc.ReplaceDialogAsync(Actions.ConfirmNumber, sc.Options));
                }
                else if (state.SummaryEvents.Count == 1)
                {
                    state.Clear();
                    return(await sc.CancelAllDialogsAsync());
                }

                if (state.SummaryEvents.Count > 1)
                {
                    var    filteredMeetingList = new List <EventModel>();
                    var    showMeetingReason   = ShowMeetingReason.FirstShowOverview;
                    string filterKeyWord       = null;

                    // filter meetings with number
                    if (luisResult.Entities.ordinal != null)
                    {
                        var value       = luisResult.Entities.ordinal[0];
                        var num         = int.Parse(value.ToString());
                        var currentList = GetCurrentPageMeetings(state.SummaryEvents, state);
                        if (num > 0 && num <= currentList.Count)
                        {
                            filteredMeetingList.Add(currentList[num - 1]);
                        }
                    }

                    if (filteredMeetingList.Count <= 0 && generalLuisResult.Entities.number != null && (luisResult.Entities.ordinal == null || luisResult.Entities.ordinal.Length == 0))
                    {
                        var value       = generalLuisResult.Entities.number[0];
                        var num         = int.Parse(value.ToString());
                        var currentList = GetCurrentPageMeetings(state.SummaryEvents, state);
                        if (num > 0 && num <= currentList.Count)
                        {
                            filteredMeetingList.Add(currentList[num - 1]);
                        }
                    }

                    // filter meetings with start time
                    var timeResult = RecognizeDateTime(userInput, sc.Context.Activity.Locale ?? English, state.GetUserTimeZone(), false);
                    if (filteredMeetingList.Count <= 0 && timeResult != null)
                    {
                        foreach (var result in timeResult)
                        {
                            var dateTimeConvertTypeString = result.Timex;
                            var dateTimeConvertType       = new TimexProperty(dateTimeConvertTypeString);
                            if (result.Value != null || (dateTimeConvertType.Types.Contains(Constants.TimexTypes.Time) || dateTimeConvertType.Types.Contains(Constants.TimexTypes.DateTime)))
                            {
                                var dateTime = DateTime.Parse(result.Value);

                                if (dateTime != null)
                                {
                                    var utcStartTime = TimeZoneInfo.ConvertTimeToUtc(dateTime, state.GetUserTimeZone());
                                    foreach (var meeting in GetCurrentPageMeetings(state.SummaryEvents, state))
                                    {
                                        if (meeting.StartTime.TimeOfDay == utcStartTime.TimeOfDay)
                                        {
                                            showMeetingReason = ShowMeetingReason.ShowFilteredByTimeMeetings;
                                            filterKeyWord     = dateTime.ToString("H:mm");
                                            filteredMeetingList.Add(meeting);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // filter meetings with subject
                    if (filteredMeetingList.Count <= 0)
                    {
                        var subject = userInput;
                        if (luisResult.Entities.Subject != null)
                        {
                            subject = GetSubjectFromEntity(luisResult.Entities);
                        }

                        foreach (var meeting in GetCurrentPageMeetings(state.SummaryEvents, state))
                        {
                            if (meeting.Title.ToLower().Contains(subject.ToLower()))
                            {
                                showMeetingReason = ShowMeetingReason.ShowFilteredByTitleMeetings;
                                filterKeyWord     = subject;
                                filteredMeetingList.Add(meeting);
                            }
                        }
                    }

                    // filter meetings with contact name
                    if (filteredMeetingList.Count <= 0)
                    {
                        var contactNameList = new List <string>()
                        {
                            userInput
                        };
                        if (luisResult.Entities.personName != null)
                        {
                            contactNameList = GetAttendeesFromEntity(luisResult.Entities, userInput);
                        }

                        foreach (var meeting in GetCurrentPageMeetings(state.SummaryEvents, state))
                        {
                            var containsAllContacts = true;
                            foreach (var contactName in contactNameList)
                            {
                                if (!meeting.ContainsAttendee(contactName))
                                {
                                    containsAllContacts = false;
                                    break;
                                }
                            }

                            if (containsAllContacts)
                            {
                                showMeetingReason = ShowMeetingReason.ShowFilteredByParticipantNameMeetings;
                                filterKeyWord     = string.Join(", ", contactNameList);
                                filteredMeetingList.Add(meeting);
                            }
                        }
                    }

                    if (filteredMeetingList.Count == 1)
                    {
                        state.FocusEvents = filteredMeetingList;
                        return(await sc.BeginDialogAsync(Actions.ConfirmNumber, sc.Options));
                    }
                    else if (filteredMeetingList.Count > 1)
                    {
                        state.SummaryEvents        = filteredMeetingList;
                        state.FilterMeetingKeyWord = filterKeyWord;
                        return(await sc.ReplaceDialogAsync(Actions.ConnectToMeeting, new ShowMeetingsDialogOptions(showMeetingReason, sc.Options)));
                    }
                }

                if (state.ConfirmedMeeting != null && state.ConfirmedMeeting.Count > 0)
                {
                    return(await sc.ReplaceDialogAsync(Actions.ConfirmNumber, sc.Options));
                }
                else
                {
                    state.Clear();
                    return(await sc.CancelAllDialogsAsync());
                }
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Exemple #3
0
        public async Task <DialogTurnResult> AfterConfirmRecipient(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await EmailStateAccessor.GetAsync(sc.Context);

                if (state.NameList != null && state.NameList.Count > 0)
                {
                    // result is null when just update the recipient name. show recipients page should be reset.
                    if (sc.Result == null)
                    {
                        state.ShowRecipientIndex = 0;
                        state.ReadRecipientIndex = 0;
                        return(await sc.BeginDialogAsync(Actions.ConfirmRecipient));
                    }

                    var choiceResult = (sc.Result as FoundChoice)?.Value.Trim('*');
                    if (choiceResult != null)
                    {
                        if (choiceResult == General.Intent.Next.ToString())
                        {
                            state.ShowRecipientIndex++;
                            state.ReadRecipientIndex = 0;
                            return(await sc.BeginDialogAsync(Actions.ConfirmRecipient));
                        }

                        if (choiceResult == General.Intent.ReadMore.ToString())
                        {
                            if (state.RecipientChoiceList.Count <= ConfigData.GetInstance().MaxReadSize)
                            {
                                // Set readmore as false when return to next page
                                state.ShowRecipientIndex++;
                                state.ReadRecipientIndex = 0;
                            }
                            else
                            {
                                state.ReadRecipientIndex++;
                            }

                            return(await sc.BeginDialogAsync(Actions.ConfirmRecipient));
                        }

                        if (choiceResult == UpdateUserDialogOptions.UpdateReason.TooMany.ToString())
                        {
                            state.ShowRecipientIndex++;
                            state.ReadRecipientIndex = 0;
                            return(await sc.BeginDialogAsync(Actions.ConfirmRecipient, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.TooMany)));
                        }

                        if (choiceResult == General.Intent.Previous.ToString())
                        {
                            if (state.ShowRecipientIndex > 0)
                            {
                                state.ShowRecipientIndex--;
                                state.ReadRecipientIndex = 0;
                            }

                            return(await sc.BeginDialogAsync(Actions.ConfirmRecipient));
                        }

                        // Find an recipient
                        var recipient    = new Recipient();
                        var emailAddress = new EmailAddress
                        {
                            Name    = choiceResult.Split(": ")[0],
                            Address = choiceResult.Split(": ")[1],
                        };
                        recipient.EmailAddress = emailAddress;
                        if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                        {
                            state.Recipients.Add(recipient);
                        }

                        state.ConfirmRecipientIndex++;

                        // Clean up data
                        state.ShowRecipientIndex = 0;
                        state.ReadRecipientIndex = 0;
                        state.RecipientChoiceList.Clear();
                    }

                    if (state.ConfirmRecipientIndex < state.NameList.Count)
                    {
                        return(await sc.BeginDialogAsync(Actions.ConfirmRecipient));
                    }
                }

                // save emails
                foreach (var email in state.EmailList)
                {
                    var recipient    = new Recipient();
                    var emailAddress = new EmailAddress
                    {
                        Name    = email,
                        Address = email,
                    };
                    recipient.EmailAddress = emailAddress;

                    if (state.Recipients.All(r => r.EmailAddress.Address != emailAddress.Address))
                    {
                        state.Recipients.Add(recipient);
                    }
                }

                return(await sc.EndDialogAsync(true));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Exemple #4
0
 public async Task <DialogTurnResult> AddFirstTask(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await sc.BeginDialogAsync(Action.AddFirstTask));
 }
Exemple #5
0
 /// <summary>
 /// Authenticate the user
 /// </summary>
 /// <param name="stepContext"></param>
 /// <param name="cancellationToken"></param>
 /// <returns></returns>
 private async Task <DialogTurnResult> StartAuthStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
 {
     // Start auth flow
     this.logger.LogInformation("Starting OAuth Prompt.");
     return(await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken));
 }
Exemple #6
0
        // Starts SkillDialog based on the user's selection
        private async Task <DialogTurnResult> ActStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Send a message activity to the skill.
            if (stepContext.Context.Activity.Text.StartsWith("m:", StringComparison.CurrentCultureIgnoreCase))
            {
                var dialogArgs = new SkillDialogArgs
                {
                    SkillId      = _targetSkillId,
                    ActivityType = ActivityTypes.Message,
                    Text         = stepContext.Context.Activity.Text.Substring(2).Trim()
                };
                return(await stepContext.BeginDialogAsync(nameof(SkillDialog), dialogArgs, cancellationToken));
            }

            // Send a message activity to the skill with some artificial parameters in value
            if (stepContext.Context.Activity.Text.StartsWith("mv:", StringComparison.CurrentCultureIgnoreCase))
            {
                var dialogArgs = new SkillDialogArgs
                {
                    SkillId      = _targetSkillId,
                    ActivityType = ActivityTypes.Message,
                    Text         = stepContext.Context.Activity.Text.Substring(3).Trim(),
                    Value        = new BookingDetails {
                        Destination = "New York"
                    }
                };
                return(await stepContext.BeginDialogAsync(nameof(SkillDialog), dialogArgs, cancellationToken));
            }

            // Send an event activity to the skill with "OAuthTest" in the name.
            if (stepContext.Context.Activity.Text.Equals("OAuthTest", StringComparison.CurrentCultureIgnoreCase))
            {
                var dialogArgs = new SkillDialogArgs
                {
                    SkillId      = _targetSkillId,
                    ActivityType = ActivityTypes.Event,
                    Name         = "OAuthTest"
                };
                return(await stepContext.BeginDialogAsync(nameof(SkillDialog), dialogArgs, cancellationToken));
            }

            // Send an event activity to the skill with "BookFlight" in the name.
            if (stepContext.Context.Activity.Text.Equals("BookFlight", StringComparison.CurrentCultureIgnoreCase))
            {
                var dialogArgs = new SkillDialogArgs
                {
                    SkillId      = _targetSkillId,
                    ActivityType = ActivityTypes.Event,
                    Name         = "BookFlight"
                };
                return(await stepContext.BeginDialogAsync(nameof(SkillDialog), dialogArgs, cancellationToken));
            }

            // Send an event activity to the skill "BookFlight" in the name and some testing values.
            if (stepContext.Context.Activity.Text.Equals("BookFlightWithValues", StringComparison.CurrentCultureIgnoreCase))
            {
                var dialogArgs = new SkillDialogArgs
                {
                    SkillId      = _targetSkillId,
                    ActivityType = ActivityTypes.Event,
                    Name         = "BookFlight",
                    Value        = new BookingDetails
                    {
                        Destination = "New York",
                        Origin      = "Seattle"
                    }
                };
                return(await stepContext.BeginDialogAsync(nameof(SkillDialog), dialogArgs, cancellationToken));
            }

            // Send an invoke activity to the skill with "GetWeather" in the name and some testing values.
            // Note that this operation doesn't use SkillDialog, InvokeActivities are single turn Request/Response.
            if (stepContext.Context.Activity.Text.Equals("GetWeather", StringComparison.CurrentCultureIgnoreCase))
            {
                var invokeActivity = Activity.CreateInvokeActivity();
                invokeActivity.Name  = "GetWeather";
                invokeActivity.Value = new Location
                {
                    PostalCode = "11218"
                };
                invokeActivity.ApplyConversationReference(stepContext.Context.Activity.GetConversationReference(), true);

                // Always save state before forwarding
                await _conversationState.SaveChangesAsync(stepContext.Context, true, cancellationToken);

                var skillInfo = _skillsConfig.Skills[_targetSkillId];
                var response  = await _skillClient.PostActivityAsync(_botId, skillInfo, _skillsConfig.SkillHostEndpoint, (Activity)invokeActivity, cancellationToken);

                if (!(response.Status >= 200 && response.Status <= 299))
                {
                    throw new HttpRequestException($"Error invoking the skill id: \"{skillInfo.Id}\" at \"{skillInfo.SkillEndpoint}\" (status is {response.Status}). \r\n {response.Body}");
                }

                var invokeResult = $"Invoke result: {JsonConvert.SerializeObject(response.Body)}";
                await stepContext.Context.SendActivityAsync(MessageFactory.Text(invokeResult, inputHint: InputHints.IgnoringInput), cancellationToken : cancellationToken);

                return(await stepContext.NextAsync(null, cancellationToken));
            }

            // Catch all for unhandled intents
            var didntUnderstandMessageText = "Sorry, I didn't get that. Please try asking in a different way.";
            var didntUnderstandMessage     = MessageFactory.Text(didntUnderstandMessageText, didntUnderstandMessageText, InputHints.IgnoringInput);
            await stepContext.Context.SendActivityAsync(didntUnderstandMessage, cancellationToken);

            return(await stepContext.NextAsync(null, cancellationToken));
        }
 protected async Task <DialogTurnResult> UpdateAttributeLoop(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await sc.BeginDialogAsync(Actions.UpdateAttribute));
 }
Exemple #8
0
 private async Task <DialogTurnResult> InitialStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
 {
     return(await stepContext.BeginDialogAsync(nameof(TopLevelDialog), null, cancellationToken));
 }
 private async Task <DialogTurnResult> ActStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
 {
     // LUIS is not configured, we just run the CreatingTicketDialog path with an empty TicketDetailsInstance.
     return(await stepContext.BeginDialogAsync(nameof(CreateTicketDialog), new TicketDetails(), cancellationToken));
 }
Exemple #10
0
 /// <summary>
 /// This <see cref="WaterfallStep"/> prompts the user to log in using the OAuth provider specified by the connection name.
 /// </summary>
 /// <param name="step">A <see cref="WaterfallStepContext"/> provides context for the current waterfall step.</param>
 /// <param name="cancellationToken" >(Optional) A <see cref="CancellationToken"/> that can be used by other objects
 /// or threads to receive notice of cancellation.</param>
 /// <returns>A <see cref="Task"/> representing the operation result of the operation.</returns>
 private static async Task <DialogTurnResult> PromptStepAsync(WaterfallStepContext step, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await step.BeginDialogAsync(LoginPromptName, cancellationToken : cancellationToken));
 }
Exemple #11
0
        private async Task <DialogTurnResult> SignInStepAsync(WaterfallStepContext context, CancellationToken cancellationToken)
        {
            var userid = context.Context.Activity.From.Id;

            return(await context.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken));
        }
        // Handles routing to additional dialogs logic.
        private async Task <DialogTurnResult> RouteStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var activity = stepContext.Context.Activity;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Get current cognitive models for the current locale.
                var localizedServices = _services.GetCognitiveModels();

                // Get skill LUIS model from configuration.
                localizedServices.LuisServices.TryGetValue("$safeprojectname$", out var luisService);

                if (luisService != null)
                {
                    var result = stepContext.Context.TurnState.Get <$safeprojectname$Luis>(StateProperties.SkillLuisResult);
                    var intent = result?.TopIntent().intent;

                    switch (intent)
                    {
                    case $safeprojectname$Luis.Intent.Sample:
                    {
                        return(await stepContext.BeginDialogAsync(_sampleDialog.Id, cancellationToken : cancellationToken));
                    }

                    case $safeprojectname$Luis.Intent.None:
                    default:
                    {
                        // intent was identified but not yet implemented
                        await stepContext.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("UnsupportedMessage"), cancellationToken);

                        return(await stepContext.NextAsync(cancellationToken : cancellationToken));
                    }
                    }
                }
                else
                {
                    throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
                }
            }
            else if (activity.Type == ActivityTypes.Event)
            {
                var ev = activity.AsEventActivity();

                if (!string.IsNullOrEmpty(ev.Name))
                {
                    switch (ev.Name)
                    {
                    case "SampleAction":
                    {
                        SampleActionInput actionData = null;

                        if (ev.Value is JObject eventValue)
                        {
                            actionData = eventValue.ToObject <SampleActionInput>();
                        }

                        // Invoke the SampleAction dialog passing input data if available
                        return(await stepContext.BeginDialogAsync(nameof(SampleAction), actionData, cancellationToken));
                    }

                    default:
                    {
                        await stepContext.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Unknown Event '{ev.Name ?? "undefined"}' was received but not processed."), cancellationToken);

                        break;
                    }
                    }
                }
                else
                {
                    await stepContext.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : "An event with no name was received but not processed."), cancellationToken);
                }
            }

            // If activity was unhandled, flow should continue to next step
            return(await stepContext.NextAsync(cancellationToken : cancellationToken));
        }
Exemple #13
0
        private async Task <DialogTurnResult> FirstStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            await stepContext.Context.SendActivityAsync("Let's get started.");

            return(await stepContext.BeginDialogAsync(nameof(FileUploadDialog), null, cancellationToken));
        }
        private async Task <DialogTurnResult> FirstStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (stepContext.Context.Adapter is IRemoteUserTokenProvider remoteInvocationAdapter)
            {
                return(await stepContext.BeginDialogAsync(DialogIds.RemoteAuthPrompt, null, cancellationToken).ConfigureAwait(false));
            }

            if (!string.IsNullOrEmpty(stepContext.Context.Activity.ChannelId) && stepContext.Context.Activity.ChannelId == "directlinespeech")
            {
                // Speech channel doesn't support OAuthPrompt./OAuthCards so we rely on tokens being set by the Linked Accounts technique
                // Therefore we don't use OAuthPrompt and instead attempt to directly retrieve the token from the store.
                if (stepContext.Context.Activity.From == null || string.IsNullOrWhiteSpace(stepContext.Context.Activity.From.Id))
                {
                    throw new ArgumentNullException("Missing From or From.Id which is required for token retrieval.");
                }

                if (_appCredentials == null)
                {
                    throw new ArgumentNullException("AppCredentials were not passed which are required for speech enabled authentication scenarios.");
                }

                var client         = new OAuthClient(new Uri(OAuthClientConfig.OAuthEndpoint), _appCredentials);
                var connectionName = _authenticationConnections.First().Name;

                try
                {
                    // Attempt to retrieve the token directly, we can't prompt the user for which Token to use so go with the first
                    // Moving forward we expect to have a "default" choice as part of Linked Accounts,.
                    var tokenResponse = await client.UserToken.GetTokenWithHttpMessagesAsync(
                        stepContext.Context.Activity.From.Id,
                        connectionName,
                        stepContext.Context.Activity.ChannelId,
                        null,
                        null,
                        cancellationToken).ConfigureAwait(false);

                    if (tokenResponse?.Body != null && !string.IsNullOrEmpty(tokenResponse.Body.Token))
                    {
                        var providerTokenResponse = await CreateProviderTokenResponseAsync(stepContext.Context, tokenResponse.Body).ConfigureAwait(false);

                        return(await stepContext.EndDialogAsync(providerTokenResponse, cancellationToken).ConfigureAwait(false));
                    }
                    else
                    {
                        throw new Exception($"Empty token response for user: {stepContext.Context.Activity.From.Id}, connectionName: {connectionName}");
                    }
                }
                catch (Exception ex)
                {
                    TelemetryClient.TrackEvent("DirectLineSpeechTokenRetrievalFailure", new Dictionary <string, string> {
                        { "Exception", ex.Message }
                    });
                }

                var noLinkedAccountResponse = _responseManager.GetResponse(
                    AuthenticationResponses.NoLinkedAccount,
                    new StringDictionary()
                {
                    { "authType", connectionName }
                });

                await stepContext.Context.SendActivityAsync(noLinkedAccountResponse).ConfigureAwait(false);

                // Enable Direct Line Speech clients to receive an event that will tell them
                // to trigger a sign-in flow when a token isn't present
                var requestOAuthFlowEvent = stepContext.Context.Activity.CreateReply();
                requestOAuthFlowEvent.Type = ActivityTypes.Event;
                requestOAuthFlowEvent.Name = "RequestOAuthFlow";

                await stepContext.Context.SendActivityAsync(requestOAuthFlowEvent).ConfigureAwait(false);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled));
            }

            if (localAuthConfigured)
            {
                return(await stepContext.BeginDialogAsync(DialogIds.LocalAuthPrompt).ConfigureAwait(false));
            }

            throw new Exception("Local authentication is not configured, please check the authentication connection section in your configuration file.");
        }
 private async Task <DialogTurnResult> InvokeTaskActionAsyncNoLuis(WaterfallStepContext stepContext, CancellationToken cancellationToken)
 {
     // We only handle book a flight if LUIS is not configured
     return(await stepContext.BeginDialogAsync(nameof(BookingDialog), new BookingDetails(), cancellationToken));
 }
Exemple #16
0
 private async Task <DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
 {
     return(await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken));
 }
Exemple #17
0
        private async Task <DialogTurnResult> CancelCurrentAndBeginNew(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            await EndDialogAsync(stepContext, cancellationToken, Resources.Strings.DialogsCancelledMessage);

            return(await stepContext.BeginDialogAsync(InitialDialogId, null, cancellationToken));
        }
 private async Task <DialogTurnResult> ChoiceEchoStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
 {
     this.processChoiceDialog.userName = this.userName;
     return(await stepContext.BeginDialogAsync(nameof(ProcessChoiceDialog), (stepContext.Result as FoundChoice).Value.ToLower(), cancellationToken));
 }
        private async Task <DialogTurnResult> RouteStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var activity    = stepContext.Context.Activity.AsMessageActivity();
            var userProfile = await _userProfileState.GetAsync(stepContext.Context, () => new UserProfileState(), cancellationToken);

            if (!string.IsNullOrEmpty(activity.Text))
            {
                // Get current cognitive models for the current locale.
                var localizedServices = _services.GetCognitiveModels();

                // Get dispatch result from turn state.
                var dispatchResult = stepContext.Context.TurnState.Get <DispatchLuis>(StateProperties.DispatchResult);
                (var dispatchIntent, var dispatchScore) = dispatchResult.TopIntent();

                if (IsSkillIntent(dispatchIntent))
                {
                    var dispatchIntentSkill = dispatchIntent.ToString();
                    var skillDialogArgs     = new BeginSkillDialogOptions {
                        Activity = (Activity)activity
                    };

                    // Save active skill in state.
                    var selectedSkill = _skillsConfig.Skills[dispatchIntentSkill];
                    await _activeSkillProperty.SetAsync(stepContext.Context, selectedSkill, cancellationToken);

                    // Start the skill dialog.
                    return(await stepContext.BeginDialogAsync(dispatchIntentSkill, skillDialogArgs, cancellationToken));
                }

                if (dispatchIntent == DispatchLuis.Intent.q_Faq)
                {
                    stepContext.SuppressCompletionMessage(true);

                    var knowledgebaseId = FaqDialogId;
                    var qnaDialog       = TryCreateQnADialog(knowledgebaseId, localizedServices);
                    if (qnaDialog != null)
                    {
                        Dialogs.Add(qnaDialog);
                    }

                    return(await stepContext.BeginDialogAsync(knowledgebaseId, cancellationToken : cancellationToken));
                }

                if (ShouldBeginChitChatDialog(stepContext, dispatchIntent, dispatchScore))
                {
                    stepContext.SuppressCompletionMessage(true);

                    var knowledgebaseId = "Chitchat";
                    var qnaDialog       = TryCreateQnADialog(knowledgebaseId, localizedServices);
                    if (qnaDialog != null)
                    {
                        Dialogs.Add(qnaDialog);
                    }

                    return(await stepContext.BeginDialogAsync(knowledgebaseId, cancellationToken : cancellationToken));
                }

                stepContext.SuppressCompletionMessage(true);

                await stepContext.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("UnsupportedMessage", userProfile), cancellationToken);

                return(await stepContext.NextAsync(cancellationToken : cancellationToken));
            }

            return(await stepContext.NextAsync(cancellationToken : cancellationToken));
        }
Exemple #20
0
        public async Task <DialogTurnResult> AfterUpdateStartTime(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                var events = new List <EventModel>();

                var calendarService  = ServiceManager.InitCalendarService(state.APIToken, state.EventSource);
                var searchByEntities = state.StartDate.Any() || state.StartTime.Any() || state.Title != null;

                if (state.StartDate.Any() || state.StartTime.Any())
                {
                    events = await GetEventsByTime(state.StartDate, state.StartTime, state.EndDate, state.EndTime, state.GetUserTimeZone(), calendarService);

                    state.StartDate = new List <DateTime>();
                    state.StartTime = new List <DateTime>();
                }
                else if (state.Title != null)
                {
                    events = await calendarService.GetEventsByTitle(state.Title);

                    state.Title = null;
                }
                else
                {
                    sc.Context.Activity.Properties.TryGetValue("OriginText", out var content);
                    var userInput = content != null?content.ToString() : sc.Context.Activity.Text;

                    try
                    {
                        IList <DateTimeResolution> dateTimeResolutions = sc.Result as List <DateTimeResolution>;
                        if (dateTimeResolutions.Count > 0)
                        {
                            foreach (var resolution in dateTimeResolutions)
                            {
                                if (resolution.Value == null)
                                {
                                    continue;
                                }

                                var startTimeValue = DateTime.Parse(resolution.Value);
                                if (startTimeValue == null)
                                {
                                    continue;
                                }

                                var  dateTimeConvertType = resolution.Timex;
                                bool isRelativeTime      = IsRelativeTime(sc.Context.Activity.Text, dateTimeResolutions.First().Value, dateTimeResolutions.First().Timex);
                                startTimeValue = isRelativeTime ? TimeZoneInfo.ConvertTime(startTimeValue, TimeZoneInfo.Local, state.GetUserTimeZone()) : startTimeValue;

                                startTimeValue = TimeConverter.ConvertLuisLocalToUtc(startTimeValue, state.GetUserTimeZone());
                                events         = await calendarService.GetEventsByStartTime(startTimeValue);

                                if (events != null && events.Count > 0)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    catch
                    {
                    }

                    if (events == null || events.Count <= 0)
                    {
                        state.Title = userInput;
                        events      = await calendarService.GetEventsByTitle(userInput);
                    }
                }

                state.Events = events;

                if (events.Count <= 0)
                {
                    if (searchByEntities)
                    {
                        await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(DeleteEventResponses.EventWithStartTimeNotFound));

                        state.Clear();
                        return(await sc.CancelAllDialogsAsync());
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.UpdateStartTime, new UpdateDateTimeDialogOptions(UpdateDateTimeDialogOptions.UpdateReason.NoEvent)));
                    }
                }
                else if (events.Count > 1)
                {
                    var options = new PromptOptions()
                    {
                        Choices = new List <Choice>(),
                    };

                    for (var i = 0; i < events.Count; i++)
                    {
                        var item   = events[i];
                        var choice = new Choice()
                        {
                            Value    = string.Empty,
                            Synonyms = new List <string> {
                                (i + 1).ToString(), item.Title
                            },
                        };
                        options.Choices.Add(choice);
                    }

                    var replyToConversation = sc.Context.Activity.CreateReply(DeleteEventResponses.MultipleEventsStartAtSameTime);
                    replyToConversation.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    replyToConversation.Attachments      = new List <Microsoft.Bot.Schema.Attachment>();

                    var cardsData = new List <CalendarCardData>();
                    foreach (var item in events)
                    {
                        var meetingCard = item.ToAdaptiveCardData(state.GetUserTimeZone());
                        var replyTemp   = sc.Context.Activity.CreateAdaptiveCardReply(CalendarMainResponses.GreetingMessage, item.OnlineMeetingUrl == null ? "Dialogs/Shared/Resources/Cards/CalendarCardNoJoinButton.json" : "Dialogs/Shared/Resources/Cards/CalendarCard.json", meetingCard);
                        replyToConversation.Attachments.Add(replyTemp.Attachments[0]);
                    }

                    options.Prompt = replyToConversation;

                    return(await sc.PromptAsync(Actions.EventChoice, options));
                }
                else
                {
                    return(await sc.EndDialogAsync(true));
                }
            }
            catch
            {
                await HandleDialogExceptions(sc);

                throw;
            }
        }
        private async Task <DialogTurnResult> HandleNextAction(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                sc.Context.Activity.Properties.TryGetValue("OriginText", out var content);
                var userInput = content != null?content.ToString() : sc.Context.Activity.Text;

                var luisResult        = sc.Context.TurnState.Get <CalendarLuis>(StateProperties.CalendarLuisResultKey);
                var generalLuisResult = sc.Context.TurnState.Get <General>(StateProperties.GeneralLuisResultKey);
                var topIntent         = luisResult?.TopIntent().intent;
                var generalTopIntent  = generalLuisResult?.TopIntent().intent;
                generalTopIntent = MergeShowIntent(generalTopIntent, topIntent, luisResult);

                if (topIntent == null)
                {
                    state.Clear();
                    return(await sc.CancelAllDialogsAsync());
                }

                var promptRecognizerResult = ConfirmRecognizerHelper.ConfirmYesOrNo(userInput, sc.Context.Activity.Locale);
                if (promptRecognizerResult.Succeeded && promptRecognizerResult.Value == true)
                {
                    // answer yes
                    state.ShowMeetingInfo.FocusedEvents.Add(state.ShowMeetingInfo.ShowingMeetings.First());
                    return(await sc.BeginDialogAsync(Actions.Read));
                }
                else if (promptRecognizerResult.Succeeded && promptRecognizerResult.Value == false)
                {
                    // answer no
                    state.Clear();
                    return(await sc.EndDialogAsync());
                }

                if ((generalTopIntent == General.Intent.ShowNext || topIntent == CalendarLuis.Intent.ShowNextCalendar) && state.ShowMeetingInfo.ShowingMeetings != null)
                {
                    if ((state.ShowMeetingInfo.ShowEventIndex + 1) * state.PageSize < state.ShowMeetingInfo.ShowingMeetings.Count)
                    {
                        state.ShowMeetingInfo.ShowEventIndex++;
                    }
                    else
                    {
                        var activity = TemplateEngine.GenerateActivityForLocale(SummaryResponses.CalendarNoMoreEvent);
                        await sc.Context.SendActivityAsync(activity);
                    }

                    var options = sc.Options as ShowMeetingsDialogOptions;
                    options.Reason = ShowMeetingReason.ShowOverviewAfterPageTurning;
                    return(await sc.ReplaceDialogAsync(Actions.ShowEvents, options));
                }
                else if ((generalTopIntent == General.Intent.ShowPrevious || topIntent == CalendarLuis.Intent.ShowPreviousCalendar) && state.ShowMeetingInfo.ShowingMeetings != null)
                {
                    if (state.ShowMeetingInfo.ShowEventIndex > 0)
                    {
                        state.ShowMeetingInfo.ShowEventIndex--;
                    }
                    else
                    {
                        var activity = TemplateEngine.GenerateActivityForLocale(SummaryResponses.CalendarNoPreviousEvent);
                        await sc.Context.SendActivityAsync(activity);
                    }

                    var options = sc.Options as ShowMeetingsDialogOptions;
                    options.Reason = ShowMeetingReason.ShowOverviewAfterPageTurning;
                    return(await sc.ReplaceDialogAsync(Actions.ShowEvents, options));
                }
                else
                {
                    if (state.ShowMeetingInfo.ShowingMeetings.Count == 1)
                    {
                        state.ShowMeetingInfo.FocusedEvents.Add(state.ShowMeetingInfo.ShowingMeetings[0]);
                    }
                    else
                    {
                        var filteredMeetingList = GetFilteredEvents(state, luisResult, userInput, sc.Context.Activity.Locale ?? English, out var showingCardTitle);

                        if (filteredMeetingList.Count == 1)
                        {
                            state.ShowMeetingInfo.FocusedEvents = filteredMeetingList;
                        }
                        else if (filteredMeetingList.Count > 1)
                        {
                            state.ShowMeetingInfo.Clear();
                            state.ShowMeetingInfo.ShowingCardTitle = showingCardTitle;
                            state.ShowMeetingInfo.ShowingMeetings  = filteredMeetingList;
                            return(await sc.ReplaceDialogAsync(Actions.ShowFilteredEvents, sc.Options));
                        }
                    }

                    var intentSwithingResult = await GetIntentSwitchingResult(sc, topIntent.Value, state);

                    if (intentSwithingResult != null)
                    {
                        return(intentSwithingResult);
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.Read));
                    }
                }
            }
            catch (SkillException ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Exemple #22
0
 private async Task <DialogTurnResult> IntentCalificar(WaterfallStepContext stepContext, RecognizerResult luisResult, CancellationToken cancellationToken)
 {
     return(await stepContext.BeginDialogAsync(nameof(QualificationDialog), cancellationToken : cancellationToken));
 }
Exemple #23
0
        private async Task <DialogTurnResult> EndProcessingIntents(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var authenticatedUserIsAuthenticated = await _AuthenticatedUserAccessor.GetAsync(stepContext.Context, () => new AuthenticatedUser());

            // var apiResults = await _AuthenticatedUserAccessor.GetAsync(stepContext.Context, () => new APIResults());

            if (stepContext.Result == null || stepContext.Result.GetType() != typeof(Intent))
            {
                return(await stepContext.EndDialogAsync());
            }

            Intent executingIntent = (Intent)stepContext.Result;

            // now call graph API
            // bur check if token expired
            if (authenticatedUserIsAuthenticated.IsAuthenticated /*&& authenticatedUserIsAuthenticated.Expiration > DateTime.UtcNow*/)
            {
                executingIntent.Offset = stepContext.Context.Activity.LocalTimestamp.Value.Offset;
                Type       T          = System.Reflection.Assembly.GetExecutingAssembly().GetType(executingIntent.APIEndpointHandler);
                APIHandler apiHandler = Activator.CreateInstance(T, new object[] { authenticatedUserIsAuthenticated.JwtSecurityToken }) as APIHandler;
                APIResult  result     = await apiHandler.ExecuteAPI(executingIntent);

                // await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format(executingIntent.ConfirmationText, executingIntent.RequiredEntities.Select(entity => entity.Value).ToArray())), cancellationToken);

                if (result.Code == APIResultCode.Ok)
                {
                    if (authenticatedUserIsAuthenticated.APIResults == null)
                    {
                        authenticatedUserIsAuthenticated.APIResults = new APIResults();
                    }

                    authenticatedUserIsAuthenticated.APIResults.Add(result);

                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(result.ResultText), cancellationToken);
                }
                else
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(result.ErrorText), cancellationToken);

                    //Logger.LogInformation(result.ErrorText);
                }

                await stepContext.Context.SendActivityAsync(MessageFactory.Text("You can make your other request"), cancellationToken);
            }
            else
            {
                // log in again

                authenticatedUserIsAuthenticated.IsAuthenticated = false;

                await _AuthenticatedUserAccessor.SetAsync(stepContext.Context, authenticatedUserIsAuthenticated, cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Session expired. Please, login again."), cancellationToken);

                await stepContext.EndDialogAsync();

                return(await stepContext.BeginDialogAsync(this.InitialDialogId));

                // return await PromptStepAsync(stepContext, cancellationToken);
            }

            return(await stepContext.EndDialogAsync());
        }
Exemple #24
0
        private async Task <DialogTurnResult> ShowResultStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {//5
            string check = ((FoundChoice)stepContext.Result).Value;

            if (check.Equals("응")) //기록 DB에 업데이트 해야 함.
            {
                try
                {
                    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

                    builder.ConnectionString = "Server=tcp:team02-server.database.windows.net,1433;Initial Catalog=healtheeDB;Persist Security Info=False;User ID=chatbot02;Password=chatee17!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

                    using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                    {
                        connection.Open();

                        //기록 DB에 사용자가 있는지 찾는다.
                        StringBuilder sb = new StringBuilder();
                        sb.Append("SELECT COUNT(*) FROM [dbo].[ExerciseRecord] WHERE UserID='" + UserInfoManager.keyNum + "'"); //유저의 고유번호로 DB에서 사용자 찾기
                        String sql = sb.ToString();

                        int count = 0;

                        using (SqlCommand command = new SqlCommand(sql, connection))
                        {
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    count = reader.GetInt32(0);
                                }
                            }
                        }

                        SqlCommand q;
                        string     query;

                        if (count == 0)                                                                                          //기록이 없을 때
                        {
                            query = "INSERT INTO [dbo].[ExerciseRecord] VALUES(" + UserInfoManager.keyNum + ", 0, 0, 0, 0, 0);"; //사용자 기록을 만든다.
                            q     = new SqlCommand(query, connection);
                            q.ExecuteNonQuery();
                        }

                        string area  = ""; //DB에서 찾을 부위 string 값
                        int    index = 0;  //DB에서 찾을 부분 index 값
                        int    Time  = 0;  //새로 업데이트 할 시간

                        if (Area.Equals("복근"))
                        {
                            area = "Abs"; index = 1;
                        }
                        else if (Area.Equals("다리, 힙"))
                        {
                            area = "Leg"; index = 2;
                        }
                        else if (Area.Equals("팔"))
                        {
                            area = "Arm"; index = 3;
                        }
                        else if (Area.Equals("어깨 및 등"))
                        {
                            area = "Shoulder"; index = 4;
                        }
                        else if (Area.Equals("가슴"))
                        {
                            area = "Chest"; index = 5;
                        }

                        //이전 기록 읽어옴
                        sb = new StringBuilder();
                        sb.Append("SELECT * FROM [dbo].[ExerciseRecord] WHERE UserID='" + UserInfoManager.keyNum + "'"); //유저의 고유번호로 DB에서 사용자 찾기
                        sql = sb.ToString();

                        if (time[time.Length - 1] == '회')                               //몇 회로 데이터베이스에 저장된 경우
                        {
                            Time = 60;                                                  //1분으로 기록(초단위)
                        }
                        else                                                            //몇 초라고 데이터베이스에 저장된 경우
                        {
                            Time = Convert.ToInt32(time.Substring(0, time.Length - 2)); //DB에 저장된 초를 가져온다.
                        }

                        using (SqlCommand command = new SqlCommand(sql, connection))
                        {
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    Time += reader.GetInt32(index); //시간 가져오기
                                }
                            }
                        }

                        //사용자 기록 업데이트
                        query = "UPDATE [dbo].[ExerciseRecord] SET [" + area + "]=" + Time + " WHERE UserID=" + UserInfoManager.keyNum; //사용자 기록 업데이트
                        q     = new SqlCommand(query, connection);
                        q.ExecuteNonQuery();

                        connection.Close();
                    }
                }
                catch (SqlException e)
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text($"운동 /예외 발생"));
                }

                await stepContext.Context.SendActivityAsync(MessageFactory.Text("기록되었습니다."), cancellationToken);
            }

            ModeManager.mode = (int)ModeManager.Modes.ShowFunction; //기능 보여주기 모드로 바꾼다.
            Thread.Sleep(3000);
            return(await stepContext.BeginDialogAsync(nameof(ShowFunctionsDialog), null, cancellationToken));
        }
Exemple #25
0
        private async Task <DialogTurnResult> ActStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
            var luisResult = await _luisRecognizer.RecognizeAsync <GeneralStatemenHandler>(stepContext.Context, cancellationToken);

            switch (luisResult.TopIntent().intent)
            {
            case GeneralStatemenHandler.Intent.Statement:

                if (luisResult.Entities.Value[0] != null)
                {
                    ClauseHandler ch = new ClauseHandler(luisResult, clauses);

                    List <IData> list = database.getData();
                    List <IData> res  = list;

                    List <IData> foundItems = list.FindAll(findData);
                    res = res.Intersect(foundItems).ToList();
                    await handleResultsAsync(res, stepContext);

                    queryText = luisResult.Text;
                }

                break;

            case GeneralStatemenHandler.Intent.QueryManagment:
                string txt = "The queries so far:";
                await stepContext.Context.SendActivityAsync(MessageFactory.Text(txt));

                foreach (var q in queries)
                {
                    string queryId      = "Query ID: " + q.Key.ToString() + Environment.NewLine;
                    string queryText    = q.Value.getText() + Environment.NewLine;
                    string queryClauses = "";

                    foreach (var cl in q.Value.getClauses())
                    {
                        queryClauses += "Clause ID: " + cl.Key.ToString() + " searchkey: " + cl.Value.SearchKey;
                        queryClauses += cl.Value.Negated != false ? ", not equals" : "";
                        queryClauses += cl.Value.Smaller != false ? ", smaller than" : "";
                        queryClauses += cl.Value.Bigger != false ? ", bigger than" : "";
                        queryClauses += ", value: " + cl.Value.Value + Environment.NewLine;
                    }

                    var msg = MessageFactory.Text(queryId + queryText + queryClauses);
                    await stepContext.Context.SendActivityAsync(msg);
                }

                return(await stepContext.BeginDialogAsync(nameof(EditQueryDialog), null, cancellationToken));

            default:
                // Catch all for unhandled intents
                var didntUnderstandMessageText = $"Sorry, I didn't get that. Please try asking in a different way (intent was {luisResult.TopIntent().intent})";
                var didntUnderstandMessage     = MessageFactory.Text(didntUnderstandMessageText, didntUnderstandMessageText, InputHints.IgnoringInput);
                await stepContext.Context.SendActivityAsync(didntUnderstandMessage, cancellationToken);

                return(await stepContext.NextAsync(null, cancellationToken));
            }

            return(await stepContext.NextAsync(null, cancellationToken));
        }
Exemple #26
0
        public async Task <DialogTurnResult> AfterGetNewEventTime(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                if (state.NewStartDate.Any() || state.NewStartTime.Any() || state.MoveTimeSpan != 0)
                {
                    var originalEvent         = state.Events[0];
                    var originalStartDateTime = TimeConverter.ConvertUtcToUserTime(originalEvent.StartTime, state.GetUserTimeZone());
                    var userNow = TimeConverter.ConvertUtcToUserTime(DateTime.UtcNow, state.GetUserTimeZone());

                    if (state.NewStartDate.Any() || state.NewStartTime.Any())
                    {
                        var newStartDate = state.NewStartDate.Any() ?
                                           state.NewStartDate.Last() :
                                           originalStartDateTime;

                        var newStartTime = new List <DateTime>();
                        if (state.NewStartTime.Any())
                        {
                            foreach (var time in state.NewStartTime)
                            {
                                var newStartDateTime = new DateTime(
                                    newStartDate.Year,
                                    newStartDate.Month,
                                    newStartDate.Day,
                                    time.Hour,
                                    time.Minute,
                                    time.Second);

                                if (state.NewStartDateTime == null)
                                {
                                    state.NewStartDateTime = newStartDateTime;
                                }

                                if (newStartDateTime >= userNow)
                                {
                                    state.NewStartDateTime = newStartDateTime;
                                    break;
                                }
                            }
                        }
                    }
                    else if (state.MoveTimeSpan != 0)
                    {
                        state.NewStartDateTime = originalStartDateTime.AddSeconds(state.MoveTimeSpan);
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.UpdateNewStartTime, new UpdateDateTimeDialogOptions(UpdateDateTimeDialogOptions.UpdateReason.NotFound)));
                    }

                    state.NewStartDateTime = TimeZoneInfo.ConvertTimeToUtc(state.NewStartDateTime.Value, state.GetUserTimeZone());

                    return(await sc.ContinueDialogAsync());
                }
                else if (sc.Result != null)
                {
                    IList <DateTimeResolution> dateTimeResolutions = sc.Result as List <DateTimeResolution>;

                    DateTime?newStartTime = null;

                    foreach (var resolution in dateTimeResolutions)
                    {
                        var utcNow = DateTime.UtcNow;
                        var dateTimeConvertTypeString = resolution.Timex;
                        var dateTimeConvertType       = new TimexProperty(dateTimeConvertTypeString);
                        var dateTimeValue             = DateTime.Parse(resolution.Value);
                        if (dateTimeValue == null)
                        {
                            continue;
                        }

                        var originalStartDateTime = TimeConverter.ConvertUtcToUserTime(state.Events[0].StartTime, state.GetUserTimeZone());
                        if (dateTimeConvertType.Types.Contains(Constants.TimexTypes.Date) && !dateTimeConvertType.Types.Contains(Constants.TimexTypes.DateTime))
                        {
                            dateTimeValue = new DateTime(
                                dateTimeValue.Year,
                                dateTimeValue.Month,
                                dateTimeValue.Day,
                                originalStartDateTime.Hour,
                                originalStartDateTime.Minute,
                                originalStartDateTime.Second);
                        }
                        else if (dateTimeConvertType.Types.Contains(Constants.TimexTypes.Time) && !dateTimeConvertType.Types.Contains(Constants.TimexTypes.DateTime))
                        {
                            dateTimeValue = new DateTime(
                                originalStartDateTime.Year,
                                originalStartDateTime.Month,
                                originalStartDateTime.Day,
                                dateTimeValue.Hour,
                                dateTimeValue.Minute,
                                dateTimeValue.Second);
                        }

                        dateTimeValue = TimeZoneInfo.ConvertTimeToUtc(dateTimeValue, state.GetUserTimeZone());

                        if (newStartTime == null)
                        {
                            newStartTime = dateTimeValue;
                        }

                        if (dateTimeValue >= utcNow)
                        {
                            newStartTime = dateTimeValue;
                            break;
                        }
                    }

                    if (newStartTime != null)
                    {
                        state.NewStartDateTime = newStartTime;

                        return(await sc.ContinueDialogAsync());
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.UpdateNewStartTime, new UpdateDateTimeDialogOptions(UpdateDateTimeDialogOptions.UpdateReason.NotADateTime)));
                    }
                }
                else
                {
                    return(await sc.BeginDialogAsync(Actions.UpdateNewStartTime, new UpdateDateTimeDialogOptions(UpdateDateTimeDialogOptions.UpdateReason.NotADateTime)));
                }
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Exemple #27
0
        public async Task <DialogTurnResult> ConfirmRecipient(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await EmailStateAccessor.GetAsync(sc.Context);

                if ((state.NameList == null) || (state.NameList.Count == 0))
                {
                    return(await sc.NextAsync());
                }

                var currentRecipientName = state.NameList[state.ConfirmRecipientIndex];

                var originPersonList = await GetPeopleWorkWithAsync(sc, currentRecipientName);

                var originContactList = await GetContactsAsync(sc, currentRecipientName);

                originPersonList.AddRange(originContactList);

                // msa account can not get user from your org. and token type is not jwt.
                // TODO: find a way to check the account is msa or aad.
                var handler        = new JwtSecurityTokenHandler();
                var originUserList = new List <Person>();
                try
                {
                    originUserList = await GetUserAsync(sc, currentRecipientName);
                }
                catch
                {
                    // do nothing when get user failed. because can not use token to ensure user use a work account.
                }

                (var personList, var userList) = DisplayHelper.FormatRecipientList(originPersonList, originUserList);

                // todo: should set updatename reason in stepContext.Result
                if (personList.Count > 10)
                {
                    return(await sc.BeginDialogAsync(Actions.UpdateRecipientName, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.TooMany)));
                }

                // if cannot find related user's name and cannot take user input as email address, send not found
                if ((personList.Count < 1) && (userList.Count < 1) && (state.EmailList.Count < 1))
                {
                    return(await sc.BeginDialogAsync(Actions.UpdateRecipientName, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.NotFound)));
                }

                if (personList.Count == 1)
                {
                    var user = personList.FirstOrDefault();
                    if (user != null)
                    {
                        var result =
                            new FoundChoice()
                        {
                            Value =
                                $"{user.DisplayName}: {user.ScoredEmailAddresses.FirstOrDefault()?.Address ?? user.UserPrincipalName}",
                        };

                        return(await sc.NextAsync(result));
                    }
                }

                if (state.EmailList.Count == 1)
                {
                    var email = state.EmailList.FirstOrDefault();
                    if (email != null)
                    {
                        var result =
                            new FoundChoice()
                        {
                            Value =
                                $"{email}: {email}",
                        };

                        return(await sc.NextAsync(result));
                    }
                }

                if (sc.Options is UpdateUserDialogOptions updateUserDialogOptions)
                {
                    state.ShowRecipientIndex = 0;
                    state.ReadRecipientIndex = 0;
                    return(await sc.BeginDialogAsync(Actions.UpdateRecipientName, updateUserDialogOptions));
                }

                // TODO: should be simplify
                var selectOption = await GenerateOptions(personList, userList, sc);

                var startIndex = ConfigData.GetInstance().MaxReadSize *state.ReadRecipientIndex;
                var choices    = new List <Choice>();
                for (int i = startIndex; i < selectOption.Choices.Count; i++)
                {
                    choices.Add(selectOption.Choices[i]);
                }

                selectOption.Choices      = choices;
                state.RecipientChoiceList = choices;

                // If no more recipient to show, start update name flow and reset the recipient paging index.
                if (selectOption.Choices.Count == 0)
                {
                    state.ShowRecipientIndex = 0;
                    state.ReadRecipientIndex = 0;
                    state.RecipientChoiceList.Clear();
                    return(await sc.BeginDialogAsync(Actions.UpdateRecipientName, new UpdateUserDialogOptions(UpdateUserDialogOptions.UpdateReason.NotFound)));
                }

                selectOption.Prompt.Speak = SpeakHelper.ToSpeechSelectionDetailString(selectOption, ConfigData.GetInstance().MaxReadSize);

                // Update prompt string to include the choices because the list style is none;
                // TODO: should be removed if use adaptive card show choices.
                var choiceString = GetSelectPromptString(selectOption, true);
                selectOption.Prompt.Text = choiceString;

                return(await sc.PromptAsync(Actions.Choice, selectOption));
            }
            catch (SkillException skillEx)
            {
                await HandleDialogExceptions(sc, skillEx);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Exemple #28
0
        public async Task <DialogTurnResult> AfterReadOutEvent(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                var luisResult = state.LuisResult;

                var topIntent = luisResult?.TopIntent().intent;

                if (state.ReadOutEvents.Count > 0)
                {
                    sc.Context.Activity.Properties.TryGetValue("OriginText", out var content);
                    var userInput = content != null?content.ToString() : sc.Context.Activity.Text;

                    var promptRecognizerResult = ConfirmRecognizerHelper.ConfirmYesOrNo(userInput, sc.Context.Activity.Locale);
                    if (promptRecognizerResult.Succeeded && promptRecognizerResult.Value == false)
                    {
                        state.Clear();
                        return(await sc.CancelAllDialogsAsync());
                    }
                    else if (promptRecognizerResult.Succeeded && promptRecognizerResult.Value == true)
                    {
                        state.ReadOutEvents = null;
                        state.SummaryEvents = null;
                        return(await sc.ReplaceDialogAsync(Actions.ShowEventsSummary, new ShowMeetingsDialogOptions(ShowMeetingReason.ShowOverviewAgain, sc.Options)));
                    }

                    var readoutEvent = state.ReadOutEvents[0];
                    state.ReadOutEvents = null;
                    state.SummaryEvents = null;
                    if (readoutEvent.IsOrganizer)
                    {
                        if (topIntent == CalendarLuis.Intent.ChangeCalendarEntry)
                        {
                            state.Events.Add(readoutEvent);
                            state.IsActionFromSummary = true;
                            return(await sc.BeginDialogAsync(nameof(UpdateEventDialog), sc.Options));
                        }

                        if (topIntent == CalendarLuis.Intent.DeleteCalendarEntry)
                        {
                            state.Events.Add(readoutEvent);
                            state.IsActionFromSummary = true;
                            return(await sc.BeginDialogAsync(nameof(ChangeEventStatusDialog), sc.Options));
                        }

                        state.Clear();
                        return(await sc.CancelAllDialogsAsync());
                    }
                    else if (readoutEvent.IsAccepted)
                    {
                        if (topIntent == CalendarLuis.Intent.DeleteCalendarEntry)
                        {
                            state.Events.Add(readoutEvent);
                            state.IsActionFromSummary = true;
                            return(await sc.BeginDialogAsync(nameof(ChangeEventStatusDialog), sc.Options));
                        }

                        state.Clear();
                        return(await sc.CancelAllDialogsAsync());
                    }
                    else
                    {
                        if (topIntent == CalendarLuis.Intent.DeleteCalendarEntry || topIntent == CalendarLuis.Intent.AcceptEventEntry)
                        {
                            state.Events.Add(readoutEvent);
                            state.IsActionFromSummary = true;
                            return(await sc.BeginDialogAsync(nameof(ChangeEventStatusDialog), sc.Options));
                        }

                        state.Clear();
                        return(await sc.CancelAllDialogsAsync());
                    }
                }

                state.Clear();
                return(await sc.CancelAllDialogsAsync());
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Exemple #29
0
        protected async Task <DialogTurnResult> HandleMore(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await EmailStateAccessor.GetAsync(sc.Context);

                var luisResult = state.LuisResult;

                var topIntent        = luisResult?.TopIntent().intent;
                var topGeneralIntent = state.GeneralLuisResult?.TopIntent().intent;
                if (topIntent == null)
                {
                    return(await sc.EndDialogAsync(true));
                }

                await DigestFocusEmailAsync(sc);

                var skillOptions = (EmailSkillDialogOptions)sc.Options;
                skillOptions.SubFlowMode = true;

                if (IsReadMoreIntent(topGeneralIntent, sc.Context.Activity.Text))
                {
                    return(await sc.BeginDialogAsync(Actions.Reshow, skillOptions));
                }
                else if (topIntent == Email.Intent.Delete)
                {
                    return(await sc.BeginDialogAsync(Actions.Delete, skillOptions));
                }
                else if (topIntent == Email.Intent.Forward)
                {
                    return(await sc.BeginDialogAsync(Actions.Forward, skillOptions));
                }
                else if (topIntent == Email.Intent.Reply)
                {
                    return(await sc.BeginDialogAsync(Actions.Reply, skillOptions));
                }
                else if (topIntent == Email.Intent.ReadAloud || topIntent == Email.Intent.SelectItem)
                {
                    var message = state.Message.FirstOrDefault();

                    if (message == null)
                    {
                        return(await sc.BeginDialogAsync(Actions.Reshow, skillOptions));
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Actions.Read, skillOptions));
                    }
                }
                else if (topIntent == Email.Intent.None && (topGeneralIntent == General.Intent.Previous || topGeneralIntent == General.Intent.Next))
                {
                    return(await sc.BeginDialogAsync(Actions.Reshow, skillOptions));
                }
                else
                {
                    // return a signal for main flow need to start a new ComponentDialog.
                    return(await sc.EndDialogAsync(true));
                }
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Exemple #30
0
        private async Task <DialogTurnResult> PromptLogin(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            await StorePrePromptUtterance(stepContext, cancellationToken);

            return(await stepContext.BeginDialogAsync(_oAuthPromptKey, null, cancellationToken));
        }