Esempio n. 1
0
        /// <inheritdoc/>
        public async Task <CognitiveTextAnalysisResult> GetCognitiveTextAnalysisResultAsync(
            TextDeconstructionInformation definition,
            string email)
        {
            var plugins = await GetPluginsAsync();

            foreach (var processor in _commandProcessors)
            {
                if (processor.Subject.Equals(definition.Subject, StringComparison.InvariantCultureIgnoreCase))
                {
                    var plugin = plugins.FirstOrDefault(
                        it => it.ProcessorTypeName.Equals(processor.Name, StringComparison.InvariantCulture));

                    if (plugin.Enabled)
                    {
                        var accessor = PluginPropertiesAccessor.GetInstance(email, plugin, _storageService);
                        return(new CognitiveTextAnalysisResult(
                                   definition,
                                   processor,
                                   accessor));
                    }
                }
            }

            return(null);
        }
Esempio n. 2
0
        /// <inheritdoc/>
        public ValueTask <ChatEventResult> ProcessCommandAsync(TextDeconstructionInformation info, ChatEvent originalChatEvent, IAsyncResponder responder)
        {
            if (info == null)
            {
                return(Value("I can not understand the sentance."));
            }

            var match = RegExp.Match(info.TextSentanceChunk);

            if (match.Success)
            {
                var text     = info.TextSentanceChunk.Substring(match.Length);
                var delayStr = match.Groups[4]?.Value;
                if (delayStr != null &&
                    int.TryParse(delayStr, out int delayMs))
                {
                    Task.Delay(delayMs)
                    .ContinueWith(task => responder.SendMessageAsync(text, new GoogleChatAddress(originalChatEvent)));

                    return(Value(null));
                }

                return(Value(text));
            }

            return(Value("Repeat command can not recognise some segments."));
        }
Esempio n. 3
0
        public async Task WhenAskedItShouldRepeatAsync()
        {
            var sender  = new ChatEventMessageSender();
            var space   = new ChatEventSpace();
            var message = new ChatEventMessage {
                Sender = sender
            };
            var chat = new ChatEvent {
                Space = space, Message = message
            };
            var responder = Substitute.For <IAsyncResponder>();
            var info      = new TextDeconstructionInformation(
                "Repeat delay 100 Test",
                "Time",
                SentenceTypes.Unknown,
                new Dictionary <string, string[]> {
                { "Time", new[] { "100" } }
            },
                null,
                1.0);

            var result = await _processor.ProcessCommandAsync(info, chat, responder, null);

            responder
            .DidNotReceive()
            .SendMessageAsync("Test", Arg.Any <GoogleChatAddress>());

            Thread.Sleep(150);

            responder
            .Received()
            .SendMessageAsync("Test", Arg.Is <GoogleChatAddress>(it => it.Space == space && it.Sender == sender));
        }
Esempio n. 4
0
        /// <inheritdoc/>
        public ValueTask <ChatEventResult> ProcessCommandAsync(TextDeconstructionInformation info, ChatEvent originalChatEvent, IAsyncResponder responder)
        {
            var message       = originalChatEvent?.Message ?? throw new ArgumentNullException(nameof(originalChatEvent));
            var locationMatch = Regex.Match(info?.TextSentanceChunk, "in ([\\w\\s]+)$");

            if (locationMatch.Success)
            {
                var city = locationMatch.Groups[1].Value;

                // TODO: This is not a good method because it doesn't contain all cities. A better method is required.
                var timeZone = TimeZoneInfo
                               .GetSystemTimeZones()
                               .FirstOrDefault(it => it
                                               .DisplayName
                                               .IndexOf(city, StringComparison.InvariantCultureIgnoreCase) > -1);

                if (timeZone == null)
                {
                    return(new ValueTask <ChatEventResult>(
                               new ChatEventResult($"The current time {locationMatch.Value} was not found.")));
                }

                var timeInLocation = TimeZoneInfo.ConvertTime(message.CreateTime, timeZone);
                return(new ValueTask <ChatEventResult>(
                           new ChatEventResult($"The current time {locationMatch.Value} is {timeInLocation.ToLongTimeString()}.")));
            }

            var time = originalChatEvent?.EventTime.ToLongTimeString() ?? string.Empty;

            return(new ValueTask <ChatEventResult>(
                       new ChatEventResult($"The current time is {time} UTC.")));
        }
Esempio n. 5
0
        /// <inheritdoc/>
        public async ValueTask <ChatEventResult> ProcessCommandAsync(TextDeconstructionInformation info, ChatEvent originalChatEvent, IAsyncResponder responder)
        {
            if (info == null)
            {
                return(new ChatEventResult("I can not understand the sentance."));
            }

            var match = RegExp.Match(info.TextSentanceChunk);

            if (match.Success)
            {
                var text     = info.TextSentanceChunk.Substring(match.Length);
                var delayStr = match.Groups[4]?.Value;
                if (delayStr != null &&
                    int.TryParse(delayStr, out int delayMs))
                {
                    await Task
                    .Delay(delayMs)
                    .ConfigureAwait(false);

                    await responder
                    .SendMessageAsync(text, originalChatEvent.Space, originalChatEvent.Message.Thread, originalChatEvent.Message.Sender)
                    .ConfigureAwait(false);

                    return(null);
                }

                return(new ChatEventResult(text));
            }

            return(new ChatEventResult("Repeat command can not recognise some segments."));
        }
Esempio n. 6
0
        /// <inheritdoc/>
        public ValueTask <ChatEventResult> ProcessCommandAsync(TextDeconstructionInformation info, ChatEvent originalChatEvent, IAsyncResponder responder, IReadOnlyDictionary <string, string> settings)
        {
            var locationMatch = Regex.Match(info?.TextSentanceChunk, "in ([\\w\\s]+)$");

            if (locationMatch.Success)
            {
                var city = locationMatch.Groups[1].Value;

                // TODO: This is not a good method because it doesn't contain all cities. A better method is required.
                var timeZone = TimeZoneInfo
                               .GetSystemTimeZones()
                               .FirstOrDefault(it => it
                                               .DisplayName
                                               .IndexOf(city, StringComparison.InvariantCultureIgnoreCase) > -1);

                if (timeZone == null)
                {
                    return(new ValueTask <ChatEventResult>(
                               new ChatEventResult($"The current time {locationMatch.Value} was not found.")));
                }

                var timeInLocation = ConvertDateTimeToString(_dateTimeFactory(), timeZone);
                return(new ValueTask <ChatEventResult>(
                           new ChatEventResult($"The current time {locationMatch.Value} is {timeInLocation}.")));
            }

            var time = ConvertDateTimeToString(_dateTimeFactory(), _currentTimeZoneFactory());

            return(new ValueTask <ChatEventResult>(
                       new ChatEventResult($"The current time is {time}.")));
        }
        public async Task WhenAskedItShouldGetTimesheets()
        {
            var sender  = new ChatEventMessageSender();
            var space   = new ChatEventSpace();
            var message = new ChatEventMessage {
                Sender = sender
            };
            var chat = new ChatEvent {
                Space = space, Message = message
            };
            var responder = Substitute.For <IHangoutsChatConnector>();
            var timesheet = new Timesheet {
                Name = "A", UserName = "******", UserEmail = "[email protected]", DepartmentName = "F", Total = 20
            };
            var info = new TextDeconstructionInformation("Get unsubmited timesheets", null, SentenceTypes.Command);

            _connector.GetUnsubmittedTimesheetsAsync(DateTime.MinValue).ReturnsForAnyArgs(new[] { timesheet });

            // Act
            var result = await _processor.ProcessCommandAsync(info, chat, responder);

            // Test
            System.Threading.Thread.Sleep(150);

            Assert.AreEqual(null, result.Text);
            responder
            .Received()
            .SendMessageAsync(
                null,
                Arg.Is <GoogleChatAddress>(it => it.Sender == sender && it.Space == space),
                Arg.Any <Card[]>());
        }
        public async Task WhenAskedForCurrentTime(string phrase, string expectedResult)
        {
            var info   = new TextDeconstructionInformation(phrase, null);
            var result = await _processor.ProcessCommandAsync(info, GetChatEvent(phrase), null, null);

            Assert.AreEqual(expectedResult, result.Text);
        }
Esempio n. 9
0
        /// <inheritdoc/>
        public ValueTask <ChatEventResult> ProcessCommandAsync(TextDeconstructionInformation info, ChatEvent originalChatEvent, IAsyncResponder responder, IReadOnlyDictionary <string, string> settings)
        {
            var notify             = info.TextSentanceChunk.StartsWith("Notify", StringComparison.InvariantCultureIgnoreCase);
            var departmentValue    = info.Entities.GetValueOrDefault(nameof(Department))?.FirstOrDefault()?.Replace(". ", ".", StringComparison.InvariantCulture);
            var customersValue     = info.Entities.GetValueOrDefault(nameof(Customer), new string[0]);
            var period             = OpenAirText.GetPeriod(info.Entities.GetValueOrDefault("Period")?.FirstOrDefault());
            var state              = OpenAirText.GetTimesheetState(info.Entities.GetValueOrDefault("State")?.FirstOrDefault());
            var today              = DateTime.Today;
            var date               = period == OpenAirPeriodTypes.LastWeek ? today.AddDays(-((int)today.DayOfWeek + 1)) : today;
            var senderEmail        = originalChatEvent.Message.Sender.Email;
            var customersSetting   = settings.GetAsArray(Default.DefaultExcludedClientKey);
            var customersToExclude = customersValue.Concat(customersSetting ?? new string[0]).ToArray();
            var notifyByEmail      = settings.GetValueOrDefault(Default.NotifyByEmailKey)?.ToLowerInvariant() == "true";

            if (state == TimesheetStates.None)
            {
                return(new ValueTask <ChatEventResult>(
                           new ChatEventResult("Provide a state of the time sheets, like unsubmitted or unapproved!")));
            }

            NotifyAsync(date, state, senderEmail, customersToExclude, departmentValue, notify, notifyByEmail, new GoogleChatAddress(originalChatEvent), responder as IHangoutsChatConnector);

            return(new ValueTask <ChatEventResult>(
                       new ChatEventResult(text: null)));
        }
Esempio n. 10
0
        public async Task IssuesProcessorShouldReturnMessageWhenNoProjectOrStatus()
        {
            var chatEvent          = CreateEvent("*****@*****.**");
            var accessor           = Substitute.For <IPluginPropertiesAccessor>();
            var entities           = new Dictionary <string, string[]>();
            var deconstructionInfo = new TextDeconstructionInformation(null, null, SentenceTypes.Question, entities, null, 1);

            accessor.GetPluginPropertyGroup("Jira.Hosts")
            .Returns(
                new[]
            {
                new []
                {
                    new PluginPropertyValue
                    {
                        Key   = "Jira.Host",
                        Value = "https://jira.com",
                    },
                    new PluginPropertyValue
                    {
                        Key   = "Jira.User",
                        Value = "Bill",
                    },
                    new PluginPropertyValue
                    {
                        Key   = "Jira.Token",
                        Value = "ABC123",
                    },
                }
            });

            var info = await _processor.ProcessCommandAsync(deconstructionInfo, chatEvent, null, accessor);

            Assert.AreEqual("If you try to get Jira issues, please provide project and status!", info.Text);
        }
        public async Task WhenAskedItShouldRepeat(string phrase, string expectedResult)
        {
            var info   = new TextDeconstructionInformation(phrase, null, SentenceTypes.Command);
            var result = await _processor.ProcessCommandAsync(info, new ChatEvent(), null);

            Assert.AreEqual(expectedResult, result.Text);
        }
Esempio n. 12
0
        /// <inheritdoc/>
        public ValueTask <ChatEventResult> ProcessCommandAsync(
            TextDeconstructionInformation info,
            ChatEvent originalChatEvent,
            IAsyncResponder responder,
            IPluginPropertiesAccessor accessor)
        {
            var text     = RegExp.Replace(info.TextSentenceChunk, string.Empty);
            var delayStr = info.Entities.GetValueOrDefault("Time")?.FirstOrDefault();

            if (!string.IsNullOrEmpty(text))
            {
                if (!string.IsNullOrEmpty(delayStr))
                {
                    var delay = GetTime(delayStr);
                    Task.Delay(delay)
                    .ContinueWith(task => responder.SendMessageAsync(text, new GoogleChatAddress(originalChatEvent)));

                    return(Value(null));
                }

                return(Value(text));
            }

            return(Value("Repeat command can not recognize some segments."));
        }
        public async Task WhenAskedForMeeting_ShouldReturnEvent()
        {
            var info      = new TextDeconstructionInformation("What is my next meeting", null);
            var chatEvent = GetChatEvent("What is my next meeting", "*****@*****.**");
            var item      = new Event
            {
                Summary = "Board Meeting",
                Start   = new EventDateTime
                {
                    DateTime = new DateTime(2000, 1, 1, 1, 1, 1)
                },
                ConferenceData = new ConferenceData
                {
                    EntryPoints = new []
                    {
                        new EntryPoint
                        {
                            Uri = "https://domain.com/link"
                        }
                    }
                }
            };

            _connector.GetNextMeetingAsync("*****@*****.**").Returns(item);

            var result = await _processor.ProcessCommandAsync(info, chatEvent, null, null);

            var value = result.Cards[0].Sections[0].Widgets[0].KeyValue;

            Assert.AreEqual(value.Content, "Board Meeting");
            Assert.AreEqual(value.BottomLabel, "01:01");
            Assert.AreEqual(value.Icon, "INVITE");
            Assert.AreEqual(value.Button.TextButton.Text, "JOIN");
            Assert.AreEqual(value.Button.TextButton.OnClick.OpenLink.Url, "https://domain.com/link");
        }
Esempio n. 14
0
        /// <inheritdoc/>
        public async ValueTask <ChatEventResult> ProcessCommandAsync(TextDeconstructionInformation info, ChatEvent originalChatEvent, IAsyncResponder responder, IReadOnlyDictionary <string, string> settings)
        {
            Contract.Ensures(info != null, "Text deconstruction information is required!");

            var sender = originalChatEvent?.Message.Sender ??
                         throw new ArgumentNullException(nameof(originalChatEvent));

            var item = await _googleCalendarConnector
                       .GetNextMeetingAsync(sender.Email)
                       .ConfigureAwait(false);

            if (item?.Summary == null)
            {
                return(new ChatEventResult("Can not find your next event! You may have no events or the service user account do not see your calendar."));
            }

            var link      = item.ConferenceData?.EntryPoints.FirstOrDefault();
            var startDate = item.Start.DateTime.HasValue ?
                            TimeZoneInfo.ConvertTime(item.Start.DateTime.Value, _currentTimeZoneFactory()).ToString("HH:mm", CultureInfo.InvariantCulture) :
                            null;
            var keyValue = new KeyValue
            {
                Content          = item.Summary,
                ContentMultiline = false,
                BottomLabel      = startDate,
                Icon             = "INVITE",
                Button           = link == null ? null : ChatEventFactory.CreateTextButton("JOIN", link.Uri)
            };

            var card = ChatEventFactory.CreateCard(keyValue);

            return(new ChatEventResult(card));
        }
Esempio n. 15
0
        /// <inheritdoc/>
        public async ValueTask <ChatEventResult> ProcessCommandAsync(
            TextDeconstructionInformation info,
            ChatEvent originalChatEvent,
            IAsyncResponder responder,
            IPluginPropertiesAccessor accessor)
        {
            var locationMatch = Regex.Match(info?.TextSentenceChunk, "in ([\\w\\s]+)$");

            if (locationMatch.Success)
            {
                var city = locationMatch.Groups[1].Value;
                var data = await _client.QueryAsync(city);

                var timeZone = data == null ? null : TZConvert.GetTimeZoneInfo(data.GenericName);
                if (timeZone == null)
                {
                    return(new ChatEventResult($"The current time {locationMatch.Value} was not found."));
                }

                var timeInLocation = ConvertDateTimeToString(_dateTimeFactory(), timeZone);
                return(new ChatEventResult($"The current time {locationMatch.Value} is {timeInLocation}."));
            }

            var time = ConvertDateTimeToString(_dateTimeFactory(), _currentTimeZoneFactory());

            return(new ChatEventResult($"The current time is {time}."));
        }
Esempio n. 16
0
        public async Task WhenAskedForCurrentTime(string phrase, string expectedResult)
        {
            var today  = new DateTime(2018, 1, 1, 1, 0, 0, DateTimeKind.Utc);
            var info   = new TextDeconstructionInformation(phrase, null, SentenceTypes.Command);
            var result = await _processor.ProcessCommandAsync(info, GetChatEvent(today, phrase), null);

            Assert.AreEqual(expectedResult, result.Text);
        }
Esempio n. 17
0
        public async Task OpenAirProcessor_ShouldReturnNoState()
        {
            var info = new TextDeconstructionInformation("Get unsubmitted timesheets", null);

            // Act
            var result = await _processor.ProcessCommandAsync(info, CreateEvent("[email protected]"), null, new Dictionary <string, string>()) as ChatEventResult;

            Assert.AreEqual("Provide a state of the time sheets, like unsubmitted or unapproved!", result.Text);
        }
Esempio n. 18
0
        /// <inheritdoc/>
        public ValueTask <ChatEventResult> ProcessCommandAsync(
            TextDeconstructionInformation info,
            ChatEvent originalChatEvent,
            IAsyncResponder responder,
            IPluginPropertiesAccessor accessor)
        {
            var response = GetAnswer(info.TextSentenceChunk.ToLowerInvariant());

            return(new ValueTask <ChatEventResult>(
                       new ChatEventResult(response)));
        }
        public async Task WhenAskedForMeeting_ShouldUseConnector(string phrase, string mail)
        {
            var info      = new TextDeconstructionInformation("What is my next meeting", null, SentenceTypes.Question);
            var chatEvent = GetChatEvent(phrase, mail);

            _connector.GetNextMeetingAsync(mail).Returns((Event)null);

            var result = await _processor.ProcessCommandAsync(info, chatEvent, null);

            _connector.Received().GetNextMeetingAsync(mail);
        }
Esempio n. 20
0
        public async Task OpenAirProcessor_ShouldReturnNoState()
        {
            var info     = new TextDeconstructionInformation("Get unsubmitted timesheets", null);
            var accessor = Substitute.For <IPluginPropertiesAccessor>();

            accessor.GetAllPluginPropertyValues <string>(null).ReturnsForAnyArgs(new string[0]);

            // Act
            var result = await _processor.ProcessCommandAsync(info, CreateEvent("[email protected]"), null, accessor) as ChatEventResult;

            Assert.AreEqual("Provide a state of the time sheets, like unsubmitted or unapproved!", result.Text);
        }
        public async Task WhenAskedForMeeting_ShouldUseConnector(string phrase, string mail)
        {
            var info      = new TextDeconstructionInformation("What is my next meeting", null);
            var chatEvent = GetChatEvent(phrase, mail);

            _connector.GetNextMeetingAsync(mail).Returns((Event)null);

            var result = await _processor.ProcessCommandAsync(info, chatEvent, null, null);

            _connector.Received().GetNextMeetingAsync(mail);

            Assert.AreEqual(result.Text, "Can not find your next event! You may have no events or the service user account do not see your calendar.");
        }
Esempio n. 22
0
        public async Task WhenAskedForCurrentTime(string phrase, string word, string data, string expectedResult)
        {
            var info         = new TextDeconstructionInformation(phrase, null);
            var timeZoneData = data == null ? null : new BingMapsClient.TimeZoneData {
                GenericName = data
            };

            _client.QueryAsync(word).Returns(timeZoneData);

            var result = await _processor.ProcessCommandAsync(info, GetChatEvent(phrase), null, null);

            Assert.AreEqual(expectedResult, result.Text);
        }
Esempio n. 23
0
        /// <inheritdoc/>
        public async ValueTask <ChatEventResult> ProcessCommandAsync(
            TextDeconstructionInformation info,
            ChatEvent originalChatEvent,
            IAsyncResponder responder,
            IPluginPropertiesAccessor accessor)
        {
            var jobNames = await accessor.GetAllUserPropertyValuesAsync <string>(BuildInfoProperties.JobName);

            if (jobNames == null ||
                jobNames.Count == 0)
            {
                return(new ChatEventResult("No jobs are assign to you!"));
            }

            var hosts = accessor.GetPluginPropertyGroup(BuildInfoProperties.HostsGroup).FirstOrDefault();

            if (hosts == null)
            {
                return(new ChatEventResult("No jenkins hosts are configured!"));
            }

            var host           = hosts.GetValue <string>(BuildInfoProperties.Host);
            var user           = hosts.GetValue <string>(BuildInfoProperties.User);
            var token          = hosts.GetValue <string>(BuildInfoProperties.Token);
            var jenkinsResults = await Task.WhenAll(
                jobNames.Select(jobName =>
                                _jenkinsClient.QueryAsync(jobName, host, user, token)));

            var widgets = jenkinsResults.Select(it => new WidgetMarkup
            {
                KeyValue = new KeyValue
                {
                    TopLabel    = it.DisplayName,
                    Content     = string.Join(", ", it.ChangeSet?.Items?.Select(cs => cs.Comment)),
                    BottomLabel = it.Result,
                    Button      = ChatEventFactory.CreateTextButton("Link", it.Url),
                },
            }).ToList();

            return(new ChatEventResult(
                       new Card
            {
                Sections = new[]
                {
                    new Section
                    {
                        Widgets = widgets
                    },
                },
            }));
        }
Esempio n. 24
0
        /// <inheritdoc/>
        public async ValueTask <ChatEventResult> ProcessCommandAsync(
            TextDeconstructionInformation info,
            ChatEvent originalChatEvent,
            IAsyncResponder responder,
            IPluginPropertiesAccessor accessor)
        {
            var hosts = accessor.GetPluginPropertyGroup(IssuesProperties.HostsGroup).FirstOrDefault();

            if (hosts == null)
            {
                return(new ChatEventResult("No jira hosts are configured!"));
            }

            var host    = hosts.GetValue <string>(IssuesProperties.Host);
            var user    = hosts.GetValue <string>(IssuesProperties.User);
            var token   = hosts.GetValue <string>(IssuesProperties.Token);
            var project = info.Entities.GetValueOrDefault("Project")?.FirstOrDefault();
            var status  = info.Entities.GetValueOrDefault("State")?.FirstOrDefault();

            if (string.IsNullOrEmpty(project) ||
                string.IsNullOrEmpty(status))
            {
                return(new ChatEventResult("If you try to get Jira issues, please provide project and status!"));
            }

            var result = await _jenkinsClient.QueryAsync(project, status, host, user, token);

            var widgets = result.Issues.Select(it => new WidgetMarkup
            {
                KeyValue = new KeyValue
                {
                    TopLabel    = it.Key,
                    Content     = it.Fields.Summary,
                    BottomLabel = it.Fields.Assignee != null ? $"Assigned to {it.Fields.Assignee.DisplayName}" : null
                },
            }).ToList();

            return(new ChatEventResult(
                       new Card
            {
                Sections = new[]
                {
                    new Section
                    {
                        Widgets = widgets
                    },
                },
            }));
        }
Esempio n. 25
0
        public async Task SendScheduledTimesheetShouldStoreStatistics()
        {
            var date = new DateTime(2020, 7, 1, 20, 0, 0, DateTimeKind.Local);
            var timesheetProcessor        = Substitute.For <ITimesheetProcessor>();
            var propertiesAccessor        = Substitute.For <IPluginPropertiesAccessor>();
            var deconstructionInformation = new TextDeconstructionInformation(null, null);
            var analysisResult            = new CognitiveTextAnalysisResult(deconstructionInformation, timesheetProcessor, propertiesAccessor);

            _cognitiveService.GetCognitiveTextAnalysisResultAsync(null, null).ReturnsForAnyArgs(analysisResult);
            propertiesAccessor
            .GetPluginPropertyGroup("OpenAir.GlobalReport")
            .Returns(
                new[]
            {
                new []
                {
                    new PluginPropertyValue
                    {
                        Key   = "OpenAir.GlobalReport.Cron",
                        Value = "20 Wed"
                    },
                    new PluginPropertyValue
                    {
                        Key   = "OpenAir.GlobalReport.Email",
                        Value = "[email protected]"
                    },
                }
            });

            timesheetProcessor
            .GetTimesheetsAsync(Arg.Any <DateTime>(), TimesheetStates.Unsubmitted, "[email protected]", true, null)
            .Returns(new[] {
                new Timesheet
                {
                    UserEmail          = "[email protected]",
                    UserName           = "******",
                    DepartmentName     = "Account",
                    ManagerName        = "*****@*****.**",
                    Total              = 5,
                    UtilizationInHours = 10
                }
            });

            await _timesheetService.SendScheduledTimesheetNotificationsAsync(date);

            _storageService
            .Received()
            .AddOrUpdateStatisticsAsync(Arg.Any <Statistics <TimesheetStatistics[]> >());
        }
        public async Task WhenAskedItShouldRepeatAsync()
        {
            var sender  = new ChatEventMessageSender();
            var space   = new ChatEventSpace();
            var message = new ChatEventMessage {
                Sender = sender
            };
            var chat = new ChatEvent {
                Space = space, Message = message
            };
            var responder = Substitute.For <IAsyncResponder>();
            var info      = new TextDeconstructionInformation("Repeat delay 1000 Test", null, SentenceTypes.Command);
            var result    = await _processor.ProcessCommandAsync(info, chat, responder);

            responder.Received().SendMessageAsync("Test", space, null, sender);
        }
        public async Task CognitiveService_ProcessShouldReturnActiveProcessor()
        {
            var processor1 = Substitute.For <ICommandProcessor>();
            var processor2 = Substitute.For <ICommandProcessor>();
            var chatEvent  = GetChatEvent("@mentorbot Get My Processor. ");
            var info       = new TextDeconstructionInformation(null, "My");
            var settings   = new MentorBotSettings
            {
                Processors = new[]
                {
                    new ProcessorSettings
                    {
                        Name    = "Processor 1",
                        Enabled = false
                    },
                    new ProcessorSettings
                    {
                        Name    = "Processor 2",
                        Enabled = true,
                        Data    = new[] { new KeyValuePair <string, string>("K", "") }
                    }
                }
            };

            _commandProcessors.Add(processor1);
            _commandProcessors.Add(processor2);

            processor1.Subject.Returns("My");
            processor2.Subject.Returns("My");
            processor1.Name.Returns("Processor 1");
            processor2.Name.Returns("Processor 2");

            _connector.DeconstructAsync("Get My Processor").Returns(info);

            _cache.TryGetValue(Constants.SettingsCacheKey, out Arg.Any <object>())
            .Returns(x =>
            {
                x[1] = settings;
                return(true);
            });

            var result = await _service.ProcessAsync(chatEvent);

            Assert.AreEqual(result.TextDeconstructionInformation, info);
            Assert.AreEqual(result.CommandProcessor.Name, "Processor 2");
            Assert.AreEqual(result.Settings.Count, 1);
        }
Esempio n. 28
0
        /// <inheritdoc/>
        public ValueTask <ChatEventResult> ProcessCommandAsync(
            TextDeconstructionInformation info,
            ChatEvent originalChatEvent,
            IAsyncResponder responder,
            IPluginPropertiesAccessor accessor)
        {
            var notify          = info.TextSentenceChunk.StartsWith("Notify", StringComparison.InvariantCultureIgnoreCase);
            var departmentValue = info
                                  .Entities
                                  .GetValueOrDefault(nameof(Department))
                                  ?.FirstOrDefault()
                                  ?.Replace(". ", ".", StringComparison.InvariantCulture);

            var customersValue     = info.Entities.GetValueOrDefault(nameof(Customer), new string[0]);
            var period             = OpenAirText.GetPeriod(info.Entities.GetValueOrDefault("Period")?.FirstOrDefault());
            var state              = OpenAirText.GetTimesheetState(info.Entities.GetValueOrDefault("State")?.FirstOrDefault());
            var today              = Contract.LocalDateTime.Date;
            var date               = period == OpenAirPeriodTypes.LastWeek ? today.AddDays(-((int)today.DayOfWeek + 1)) : today;
            var senderEmail        = originalChatEvent.Message.Sender.Email;
            var customersSetting   = accessor.GetAllPluginPropertyValues <string>(TimesheetsProperties.FilterByCustomer);
            var customersToExclude = customersValue.Concat(customersSetting ?? new string[0]).ToArray();

            if (state == TimesheetStates.None)
            {
                return(new ValueTask <ChatEventResult>(
                           new ChatEventResult("Provide a state of the time sheets, like unsubmitted or unapproved!")));
            }

            var address = new GoogleChatAddress(originalChatEvent);

            NotifyAsync(
                date,
                state,
                senderEmail,
                customersToExclude,
                departmentValue,
                notify,
                false,
                true,
                address,
                responder as IHangoutsChatConnector)
            .ConfigureAwait(false);

            return(new ValueTask <ChatEventResult>(
                       new ChatEventResult(text: null)));
        }
Esempio n. 29
0
        /// <inheritdoc/>
        public async ValueTask <ChatEventResult> ProcessCommandAsync(
            TextDeconstructionInformation info,
            ChatEvent originalChatEvent,
            IAsyncResponder responder,
            IPluginPropertiesAccessor accessor)
        {
            var plugins = await _storageService.GetAllPluginsAsync();

            var results = plugins.SelectMany(it => it.Examples ?? Array.Empty <string>()).DefaultIfEmpty(string.Empty);

            return(new ChatEventResult(
                       ChatEventFactory.CreateCard(
                           new TextParagraph
            {
                Text = string.Join("<br />", results)
            })));
        }
        public async Task CognitiveService_ProcessShouldReturnActiveProcessor()
        {
            var processor1 = Substitute.For <ICommandProcessor>();
            var processor2 = Substitute.For <ICommandProcessor>();
            var chatEvent  = GetChatEvent("@mentorbot Get My Processor. ");
            var info       = new TextDeconstructionInformation(null, "My");
            var settings   = new Plugin[]
            {
                new Plugin
                {
                    ProcessorTypeName = "Processor 1",
                    Enabled           = false,
                },
                new Plugin
                {
                    ProcessorTypeName = "Processor 2",
                    Enabled           = true,
                }
            };

            _commandProcessors.Add(processor1);
            _commandProcessors.Add(processor2);

            processor1.Subject.Returns("My");
            processor2.Subject.Returns("My");
            processor1.Name.Returns("Processor 1");
            processor2.Name.Returns("Processor 2");

            _connector.DeconstructAsync("Get My Processor").Returns(info);

            _cache.TryGetValue(Constants.PluginsCacheKey, out Arg.Any <object>())
            .Returns(x =>
            {
                x[1] = settings;
                return(true);
            });

            var result = await _service.ProcessAsync(chatEvent);

            Assert.AreEqual(result.TextDeconstructionInformation, info);
            Assert.AreEqual(result.CommandProcessor.Name, "Processor 2");
            Assert.IsNotNull(result.PropertiesAccessor);
        }