public IntentGatewayParser(ChatModel chatModel, IChatScriptManager chatScriptManager, TextClassificationService classificationService, IExternalDataStorageService externalDataStorageService, ChatConfiguration chatConfiguration)
 {
     this.chatModel                  = chatModel;
     this.chatScriptManager          = chatScriptManager;
     this.classificationService      = classificationService;
     this.externalDataStorageService = externalDataStorageService;
     this.chatConfiguration          = chatConfiguration;
 }
        private IGrammarService GetConfiguredGrammarService(ChatConfiguration chatConfig)
        {
            var grammarService = _grammarServices.First(v => v.GrammarAlgorith == chatConfig.GrammarAlgorithm);

            grammarService.SetSelectedLanguage(chatConfig.SelectedLanguage);
            grammarService.SetStrictnessLevel(chatConfig.CorrectionStrictnessLevel);

            return(grammarService);
        }
Exemple #3
0
 public ChatMessageService(
     IOptions <LuisChatResponses> luisChatResponses,
     IOptions <ChatConfiguration> chatConfiguration,
     IEnumerable <IChatMessageRule> listChatMessageRules
     )
 {
     _luisChatResponses    = luisChatResponses.Value ?? throw new ArgumentNullException(nameof(luisChatResponses));
     _chatConfiguration    = chatConfiguration.Value ?? throw new ArgumentNullException(nameof(chatConfiguration));
     _listChatMessageRules = listChatMessageRules.ToArray() ?? throw new ArgumentNullException(nameof(listChatMessageRules));
 }
        public ChatEngineFramework()
        {
            Amazon.AWSConfigs.AWSRegion      = "us-east-1";
            Amazon.AWSConfigs.AWSProfileName = "";

            ChatConfiguration chatConfiguration = new ChatConfiguration();
            AWSDynamoService  dataService       = new AWSDynamoService(chatConfiguration);
            FlowStepProvider  flowStepProvider  = new FlowStepProvider(dataService);

            chatEngine = new ChatWeb.Services.ChatEngine(null, chatConfiguration, null, dataService, null, null, null, null, null, null, null, null, flowStepProvider);
        }
    public async Task AddConfiguration(ChatConfiguration chatConfiguration)
    {
        if (await _repository.Any(x => x.ChatId == chatConfiguration.ChatId))
        {
            await Update(chatConfiguration);

            return;
        }

        await _repository.Add(chatConfiguration);
    }
        public ChatScriptManagerTests()
        {
            var chatModel                      = new ChatModel();
            ChatConfiguration config           = new ChatConfiguration();
            AWSDynamoService  awsDynamoService = new AWSDynamoService(config);
            FlowStepProvider  flowStepProvider = new FlowStepProvider(awsDynamoService);

            var chatEngine = new ChatEngine(null, config, null, awsDynamoService, null, null, null, null, null, null, null, null, flowStepProvider);

            scriptManager = new ChatScriptManager(chatModel, awsDynamoService, config);
            scriptManager.Initialize().Wait();
        }
Exemple #7
0
        private static IGrammarService GetConfiguredGrammarService(ChatConfiguration chatConfig, IServiceProvider serviceProvider)
        {
            var grammarServices = serviceProvider.GetService <IEnumerable <IGrammarService> >();

            var grammarService = grammarServices.First(v => v.GrammarAlgorith == chatConfig.GrammarAlgorithm);

            grammarService.SetSelectedLanguage(chatConfig.SelectedLanguage);
            grammarService.SetStrictnessLevel(chatConfig.CorrectionStrictnessLevel);
            grammarService.SetWhiteListWords(chatConfig.WhiteListWords);

            return(grammarService);
        }
Exemple #8
0
        public AddressParseService(ChatConfiguration chatConfiguration)
        {
            Dictionary <string, string> headers = null;

            if (!String.IsNullOrEmpty(chatConfiguration.AddressParse.Key))
            {
                headers = new Dictionary <string, string>()
                {
                    { "x-api-key", chatConfiguration.AddressParse.Key }
                };
            }

            restApiService = new RestApiService(chatConfiguration.AddressParse.Url, null, headers);
        }
Exemple #9
0
        /// <summary>
        /// Create the client configration and connect to broker
        /// </summary>
        /// TODO: Move to ServerChat class
        private static void Initialize()
        {
            _configuration = new ChatConfiguration();

            _commands = RegisterCommands();
            Configure();

            _client = new MqttClient(_configuration.ServerAddress);

            _client.MqttMsgPublishReceived += ShowMessage;
            _client.ConnectionClosed       += (sender, args) => Environment.Exit(0);
            _client.MqttMsgSubscribed      += SubscribeUsername;
            _client.MqttMsgUnsubscribed    += UnsubscribeUsername;

            _client.Connect(_configuration.Id);
            _client.Subscribe(_configuration.Topics, _configuration.QosLevels);
        }
        public AWSDynamoService(ChatConfiguration chatConfiguration)
        {
            this.chatConfiguration = chatConfiguration;

            logger.Debug($"Internal: Creating {nameof(AWSDynamoService)}");
            client = new AmazonDynamoDBClient();

#if !XRAY2
            string whitelistPath = System.Web.Hosting.HostingEnvironment.MapPath("/AWSWhitelist.json");

            var tracer = new Amazon.XRay.Recorder.Handlers.AwsSdk.AWSSdkTracingHandler(Amazon.XRay.Recorder.Core.AWSXRayRecorder.Instance, whitelistPath);
            tracer.AddEventHandler(client);
#endif

            DynamoDBContextConfig config = new DynamoDBContextConfig()
            {
                TableNamePrefix = chatConfiguration.AwsTablePrefix
            };
            context = new DynamoDBContext(client, config);
        }
        private async Task <ChatConfiguration> GetChatConfiguration(long chatId)
        {
            var chatConfig = await _chatConfigurationService.GetConfigurationByChatId(chatId);

            if (chatConfig != null)
            {
                return(chatConfig);
            }

            var chatConfiguration = new ChatConfiguration
            {
                ChatId           = chatId,
                GrammarAlgorithm = Defaults.DefaultAlgorithm,
                SelectedLanguage = SupportedLanguages.Auto
            };

            await _chatConfigurationService.AddConfiguration(chatConfiguration);

            return(chatConfiguration);
        }
Exemple #12
0
 public ChatService(ChatConfiguration chatConfig, IConfiguration configuration)
 {
     this.chatConfig    = chatConfig;
     this.overallConfig = configuration;
 }
Exemple #13
0
 public ChatBase(IOptions <ChatConfiguration> chatConfiguration)
 {
     _chatConfiguration = chatConfiguration.Value;
 }
 public ChatScriptHost(ChatModel chatModel, ChatConfiguration configuration)
 {
     this.chatModel     = chatModel;
     this.Configuration = configuration;
 }
 public TextParserService(ChatConfiguration chatConfiguration)
 {
     restApiService = new RestApiService(chatConfiguration.TextParser);
 }
        private async Task HandleCommand(Message message)
        {
            var text = message.Text;

            // TODO: Evaluate moving all this logic into a service, and do a refactor

            if (IsCommand(Commands.Start, text))
            {
                var chatConfig = await _chatConfigurationService.GetConfigurationByChatId(message.Chat.Id);

                var messageBuilder = new StringBuilder();

                if (chatConfig == null)
                {
                    messageBuilder.AppendLine("Hi, I'm GrammarNazi.");
                    messageBuilder.AppendLine("I'm currently working and correcting all spelling errors in this chat.");
                    messageBuilder.AppendLine($"Type {Commands.Help} to get useful commands.");

                    var chatConfiguration = new ChatConfiguration
                    {
                        ChatId           = message.Chat.Id,
                        GrammarAlgorithm = Defaults.DefaultAlgorithm,
                        SelectedLanguage = SupportedLanguages.Auto
                    };

                    await _chatConfigurationService.AddConfiguration(chatConfiguration);
                }
                else
                {
                    if (chatConfig.IsBotStopped)
                    {
                        if (!await IsUserAdmin())
                        {
                            messageBuilder.AppendLine("Only admins can use this command.");
                        }
                        else
                        {
                            chatConfig.IsBotStopped = false;
                            await _chatConfigurationService.Update(chatConfig);

                            messageBuilder.AppendLine("Bot started");
                        }
                    }
                    else
                    {
                        messageBuilder.AppendLine("Bot is already started");
                    }
                }

                await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString());
            }
            else if (IsCommand(Commands.Help, text))
            {
                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine("Help").AppendLine();
                messageBuilder.AppendLine("Useful commands:");
                messageBuilder.AppendLine($"{Commands.Start} start/activate the Bot.");
                messageBuilder.AppendLine($"{Commands.Stop} stop/disable the Bot.");
                messageBuilder.AppendLine($"{Commands.Settings} get configured settings.");
                messageBuilder.AppendLine($"{Commands.SetAlgorithm} <algorithm_number> to set an algorithm.");
                messageBuilder.AppendLine($"{Commands.Language} <language_number> to set a language.");
                messageBuilder.AppendLine($"{Commands.ShowDetails} Show correction details");
                messageBuilder.AppendLine($"{Commands.HideDetails} Hide correction details");
                messageBuilder.AppendLine($"{Commands.Tolerant} Set strictness level to {CorrectionStrictnessLevels.Tolerant.GetDescription()}");
                messageBuilder.AppendLine($"{Commands.Intolerant} Set strictness level to {CorrectionStrictnessLevels.Intolerant.GetDescription()}");

                await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString());
            }
            else if (IsCommand(Commands.Settings, text))
            {
                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine(GetAvailableAlgorithms(chatConfig.GrammarAlgorithm));
                messageBuilder.AppendLine(GetSupportedLanguages(chatConfig.SelectedLanguage));

                var showCorrectionDetailsIcon = chatConfig.HideCorrectionDetails ? "❌" : "✅";
                messageBuilder.AppendLine($"Show correction details {showCorrectionDetailsIcon}").AppendLine();
                messageBuilder.AppendLine("Strictness level:").AppendLine($"{chatConfig.CorrectionStrictnessLevel.GetDescription()} ✅").AppendLine();

                if (chatConfig.IsBotStopped)
                {
                    messageBuilder.AppendLine($"The bot is currently stopped. Type {Commands.Start} to activate the Bot.");
                }

                await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString());
            }
            else if (IsCommand(Commands.SetAlgorithm, text))
            {
                var messageBuilder = new StringBuilder();

                if (!await IsUserAdmin())
                {
                    messageBuilder.AppendLine("Only admins can use this command.");
                    await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString(), replyToMessageId : message.MessageId);

                    return;
                }

                var parameters = text.Split(" ");
                if (parameters.Length == 1)
                {
                    var chatConfig = await GetChatConfiguration(message.Chat.Id);

                    messageBuilder.AppendLine($"Parameter not received. Type {Commands.SetAlgorithm} <algorithm_numer> to set an algorithm").AppendLine();
                    messageBuilder.AppendLine(GetAvailableAlgorithms(chatConfig.GrammarAlgorithm));
                    await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString());
                }
                else
                {
                    bool parsedOk = int.TryParse(parameters[1], out int algorithm);

                    if (parsedOk)
                    {
                        var chatConfig = await GetChatConfiguration(message.Chat.Id);

                        chatConfig.GrammarAlgorithm = (GrammarAlgorithms)algorithm;

                        // Fire and forget
                        _ = _chatConfigurationService.Update(chatConfig);

                        await _client.SendTextMessageAsync(message.Chat.Id, "Algorithm updated.");
                    }
                    else
                    {
                        await _client.SendTextMessageAsync(message.Chat.Id, $"Invalid parameter. Type {Commands.SetAlgorithm} <algorithm_numer> to set an algorithm.");
                    }
                }
            }
            else if (IsCommand(Commands.Language, text))
            {
                var messageBuilder = new StringBuilder();

                if (!await IsUserAdmin())
                {
                    messageBuilder.AppendLine("Only admins can use this command.");
                    await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString(), replyToMessageId : message.MessageId);

                    return;
                }

                var parameters = text.Split(" ");

                if (parameters.Length == 1)
                {
                    var chatConfig = await GetChatConfiguration(message.Chat.Id);

                    messageBuilder.AppendLine($"Parameter not received. Type {Commands.Language} <language_number> to set a language.").AppendLine();
                    messageBuilder.AppendLine(GetSupportedLanguages(chatConfig.SelectedLanguage));
                    await _client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString());
                }
                else
                {
                    bool parsedOk = int.TryParse(parameters[1], out int language);

                    if (parsedOk)
                    {
                        var chatConfig = await GetChatConfiguration(message.Chat.Id);

                        chatConfig.SelectedLanguage = (SupportedLanguages)language;

                        // Fire and forget
                        _ = _chatConfigurationService.Update(chatConfig);

                        await _client.SendTextMessageAsync(message.Chat.Id, "Language updated.");
                    }
                    else
                    {
                        await _client.SendTextMessageAsync(message.Chat.Id, $"Invalid parameter. Type {Commands.Language} <language_number> to set a language.");
                    }
                }
            }
            else if (IsCommand(Commands.Stop, text))
            {
                if (!await IsUserAdmin())
                {
                    await _client.SendTextMessageAsync(message.Chat.Id, "Only admins can use this command.", replyToMessageId : message.MessageId);

                    return;
                }

                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                chatConfig.IsBotStopped = true;

                // Fire and forget
                _ = _chatConfigurationService.Update(chatConfig);

                await _client.SendTextMessageAsync(message.Chat.Id, $"Bot stopped");
            }
            else if (IsCommand(Commands.HideDetails, text))
            {
                if (!await IsUserAdmin())
                {
                    await _client.SendTextMessageAsync(message.Chat.Id, "Only admins can use this command.", replyToMessageId : message.MessageId);

                    return;
                }

                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                chatConfig.HideCorrectionDetails = true;

                // Fire and forget
                _ = _chatConfigurationService.Update(chatConfig);

                await _client.SendTextMessageAsync(message.Chat.Id, "Correction details hidden ✅");
            }
            else if (IsCommand(Commands.ShowDetails, text))
            {
                if (!await IsUserAdmin())
                {
                    await _client.SendTextMessageAsync(message.Chat.Id, "Only admins can use this command.", replyToMessageId : message.MessageId);

                    return;
                }

                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                chatConfig.HideCorrectionDetails = false;

                // Fire and forget
                _ = _chatConfigurationService.Update(chatConfig);

                await _client.SendTextMessageAsync(message.Chat.Id, "Show correction details ✅");
            }
            else if (IsCommand(Commands.Tolerant, text))
            {
                if (!await IsUserAdmin())
                {
                    await _client.SendTextMessageAsync(message.Chat.Id, "Only admins can use this command.", replyToMessageId : message.MessageId);

                    return;
                }

                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                chatConfig.CorrectionStrictnessLevel = CorrectionStrictnessLevels.Tolerant;

                // Fire and forget
                _ = _chatConfigurationService.Update(chatConfig);

                await _client.SendTextMessageAsync(message.Chat.Id, "Tolerant ✅");
            }
            else if (IsCommand(Commands.Intolerant, text))
            {
                if (!await IsUserAdmin())
                {
                    await _client.SendTextMessageAsync(message.Chat.Id, "Only admins can use this command.", replyToMessageId : message.MessageId);

                    return;
                }

                var chatConfig = await GetChatConfiguration(message.Chat.Id);

                chatConfig.CorrectionStrictnessLevel = CorrectionStrictnessLevels.Intolerant;

                // Fire and forget
                _ = _chatConfigurationService.Update(chatConfig);

                await _client.SendTextMessageAsync(message.Chat.Id, "Intolerant ✅");
            }

            bool IsCommand(string expected, string actual)
            {
                if (actual.Contains("@"))
                {
                    // TODO: Get bot name from config
                    return(_webHostEnvironment.IsDevelopment()
                        ? actual.StartsWith($"{expected}@grammarNaziTest_Bot")
                        : actual.StartsWith($"{expected}@grammarNz_Bot"));
                }

                return(actual.StartsWith(expected));
            }

            async Task <bool> IsUserAdmin()
            {
                if (message.Chat.Type == ChatType.Private)
                {
                    return(true);
                }

                var chatAdministrators = await _client.GetChatAdministratorsAsync(message.Chat.Id);

                var currentUserId = message.From.Id;

                return(chatAdministrators.Any(v => v.User.Id == currentUserId));
            }
 public ChatScriptManager(ChatModel chatModel, IExternalDataStorageService externalDataStorageService, ChatConfiguration configuration)
 {
     ScriptHost  = new ChatScriptHost(chatModel, configuration);
     DataService = externalDataStorageService;
     ChatModel   = chatModel;
 }
Exemple #18
0
        private static KernelBase SetupNinject(ChatConfiguration configuration)
        {
            var kernel = new StandardKernel(new[] { new FactoryModule() });


            kernel.Bind <IRecentMessageCache>()
            .To <NoopCache>()
            .InSingletonScope();

            //data layer
            var dataSettingsManager  = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            kernel.Bind <DataSettings>().ToMethod(context =>
            {
                return(dataSettingsManager.LoadSettings());
            });
            kernel.Bind <BaseDataProviderManager>().ToMethod(context =>
            {
                var recentDataSettings = context.Kernel.Get <DataSettings>();
                return(new MongoDBDataProviderManager(recentDataSettings));
            });
            kernel.Bind <IDataProvider>().ToMethod(context =>
            {
                var recentBaseDataProviderManager = context.Kernel.Get <BaseDataProviderManager>();
                return(recentBaseDataProviderManager.LoadDataProvider());
            });
            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                var mongoDBDataProviderManager = new MongoDBDataProviderManager(dataSettingsManager.LoadSettings());
                var dataProvider = mongoDBDataProviderManager.LoadDataProvider();
                kernel.Bind <IMongoClient>().ToMethod(context =>
                {
                    return(new MongoClient(dataProviderSettings.DataConnectionString));
                });
            }

            kernel.Bind(typeof(IRepository <>)).To(typeof(MongoDBRepository <>)).InSingletonScope();

            kernel.Bind <IChatService>()
            .To <ChatService>();

            kernel.Bind <IDataProtector>()
            .To <ChatDataProtection>();

            kernel.Bind <ICookieAuthenticationProvider>()
            .To <ChatFormsAuthenticationProvider>();

            kernel.Bind <ILogger>()
            .To <RealtimeLogger>();

            //kernel.Bind<IUserIdProvider>()
            //      .To<ChatUserIdProvider>();

            kernel.Bind <IChatConfiguration>()
            .ToConstant(configuration);

            // We're doing this manually since we want the chat repository to be shared
            // between the chat service and the chat hub itself
            kernel.Bind <Chat>()
            .ToMethod(context =>
            {
                //   var resourceProcessor = context.Kernel.Get<ContentProviderProcessor>();
                var recentMessageCache = context.Kernel.Get <IRecentMessageCache>();
                //  var repository = context.Kernel.Get<IChatRepository>();
                var cache    = context.Kernel.Get <ICache>();
                var logger   = context.Kernel.Get <ILogger>();
                var settings = context.Kernel.Get <ApplicationSettings>();
                IRepository <ChatUser> repository = context.Kernel.Get <IRepository <ChatUser> >();
                IRepository <ChatUserIdentity> chatUserIdentityRepository = context.Kernel.Get <IRepository <ChatUserIdentity> >();
                IRepository <Attachment> attachmentRepository             = context.Kernel.Get <IRepository <Attachment> >();
                IRepository <ChatClient> chatClientRepository             = context.Kernel.Get <IRepository <ChatClient> >();
                IRepository <ChatMessage> chatMessagerepository           = context.Kernel.Get <IRepository <ChatMessage> >();
                IRepository <ChatRoom> chatRoomRepository         = context.Kernel.Get <IRepository <ChatRoom> >();
                IRepository <Notification> notificationRepository = context.Kernel.Get <IRepository <Notification> >();
                IRepository <Settings> settingsRepository         = context.Kernel.Get <IRepository <Settings> >();
                var service = new ChatService(cache, repository, chatUserIdentityRepository, attachmentRepository, chatClientRepository
                                              , chatMessagerepository, chatRoomRepository, notificationRepository, settingsRepository);

                return(new Chat(repository, chatUserIdentityRepository, attachmentRepository, chatClientRepository
                                , chatMessagerepository, chatRoomRepository, notificationRepository, settingsRepository,
                                settings,
                                service,
                                cache,
                                logger
                                ));
            });

            kernel.Bind <ICryptoService>()
            .To <CryptoService>();

            kernel.Bind <IJavaScriptMinifier>()
            .To <AjaxMinMinifier>()
            .InSingletonScope();

            kernel.Bind <IMembershipService>()
            .To <MembershipService>();

            kernel.Bind <ApplicationSettings>()
            .ToMethod(context =>
            {
                return(context.Kernel.Get <ISettingsManager>().Load());
            });

            kernel.Bind <ISettingsManager>()
            .To <SettingsManager>();


            kernel.Bind <IUserAuthenticator>()
            .To <DefaultUserAuthenticator>();

            kernel.Bind <ICache>()
            .To <DefaultCache>()
            .InSingletonScope();

            //kernel.Bind<IChatNotificationService>()
            //      .To<ChatNotificationService>();

            kernel.Bind <IKeyProvider>()
            .To <SettingsKeyProvider>();


            RegisterContentProviders(kernel);

            var serializer = JsonSerializer.Create(new JsonSerializerSettings()
            {
                DateFormatHandling = DateFormatHandling.IsoDateFormat
            });

            kernel.Bind <JsonSerializer>()
            .ToConstant(serializer);


            return(kernel);
        }
 public Task AddConfiguration(ChatConfiguration chatConfiguration)
 {
     return(_repository.Add(chatConfiguration));
 }
 public Task Delete(ChatConfiguration chatConfiguration)
 {
     return(_repository.Delete(chatConfiguration));
 }
Exemple #21
0
 public ChatController(ChatConfiguration chatConfiguration)
 {
     this.chatConfiguration = chatConfiguration;
 }
Exemple #22
0
 public ChatScriptNodeManager(ChatModel chatModel, IExternalDataStorageService externalDataStorageService, IHubContext <NodeJSHub> nodeJsHubContext, INodeServices nodeServices, ChatConfiguration configuration)
 {
     this.ChatScriptHost   = new ChatScriptHost(chatModel, configuration);
     this.DataService      = externalDataStorageService;
     this.nodeJsHubContext = nodeJsHubContext;
     NodeServices          = nodeServices;
 }
 public async Task Update(ChatConfiguration chatConfiguration)
 {
     await _repository.Update(chatConfiguration, v => v.ChatId == chatConfiguration.ChatId);
 }
Exemple #24
0
 public FuzzyMatchService(ChatConfiguration chatConfiguration)
 {
     restApiService = new RestApiService(chatConfiguration.FuzzyMatch);
 }