public void UpdateIntervalValid(TimeSpan updateInterval)
        {
            IValidator <ApplicationConfiguration> validator = new ApplicationConfigurationValidator();
            ApplicationConfiguration configuration          = CreateValidApplicationConfiguration();

            configuration.UpdateInterval = updateInterval;

            Assert.True(validator.Validate(configuration).IsValid);
        }
        public void ExternalAddressProvidersInvalid(IEnumerable <ExternalAddressProvider> externalAddressProviders)
        {
            IValidator <ApplicationConfiguration> validator = new ApplicationConfigurationValidator();
            ApplicationConfiguration configuration          = CreateValidApplicationConfiguration();

            configuration.ExternalAddressProviders = externalAddressProviders?.ToList();

            ValidationResult result = validator.Validate(configuration);

            Assert.False(result.IsValid);
        }
        public void UpdateIntervalInvalid(TimeSpan updateInterval)
        {
            IValidator <ApplicationConfiguration> validator = new ApplicationConfigurationValidator();
            ApplicationConfiguration configuration          = CreateValidApplicationConfiguration();

            configuration.UpdateInterval = updateInterval;

            ValidationResult result = validator.Validate(configuration);

            Assert.False(result.IsValid);
            Assert.True(result.Errors.All(m => m.ErrorMessage.Equals(ApplicationConfigurationValidator.UpdateIntervalErrorMessage)));
        }
Пример #4
0
        public async Task Init()
        {
            IsRunning         = true;
            ExternalIPAddress = await Utilities.GetExternalIP();

            #region DATABASE
            _logger.LogInformation("Beginning database migration sync");
            Console.WriteLine(_translationLookup["MANAGER_MIGRATION_START"]);
            await ContextSeed.Seed(_serviceProvider.GetRequiredService <IDatabaseContextFactory>(), _tokenSource.Token);

            await DatabaseHousekeeping.RemoveOldRatings(_serviceProvider.GetRequiredService <IDatabaseContextFactory>(), _tokenSource.Token);

            _logger.LogInformation("Finished database migration sync");
            Console.WriteLine(_translationLookup["MANAGER_MIGRATION_END"]);
            #endregion

            #region PLUGINS
            foreach (var plugin in Plugins)
            {
                try
                {
                    if (plugin is ScriptPlugin scriptPlugin)
                    {
                        await scriptPlugin.Initialize(this, _scriptCommandFactory, _scriptPluginServiceResolver);

                        scriptPlugin.Watcher.Changed += async(sender, e) =>
                        {
                            try
                            {
                                await scriptPlugin.Initialize(this, _scriptCommandFactory, _scriptPluginServiceResolver);
                            }

                            catch (Exception ex)
                            {
                                Console.WriteLine(Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"].FormatExt(scriptPlugin.Name));
                                _logger.LogError(ex, "Could not properly load plugin {plugin}", scriptPlugin.Name);
                            }
                        };
                    }

                    else
                    {
                        await plugin.OnLoadAsync(this);
                    }
                }

                catch (Exception ex)
                {
                    _logger.LogError(ex, $"{_translationLookup["SERVER_ERROR_PLUGIN"]} {plugin.Name}");
                }
            }
            #endregion

            #region CONFIG
            // copy over default config if it doesn't exist
            if (!_appConfig.Servers?.Any() ?? true)
            {
                var defaultConfig = new BaseConfigurationHandler <DefaultSettings>("DefaultSettings").Configuration();
                //ConfigHandler.Set((ApplicationConfiguration)new ApplicationConfiguration().Generate());
                //var newConfig = ConfigHandler.Configuration();

                _appConfig.AutoMessages          = defaultConfig.AutoMessages;
                _appConfig.GlobalRules           = defaultConfig.GlobalRules;
                _appConfig.DisallowedClientNames = defaultConfig.DisallowedClientNames;

                //if (newConfig.Servers == null)
                {
                    ConfigHandler.Set(_appConfig);
                    _appConfig.Servers = new ServerConfiguration[1];

                    do
                    {
                        var serverConfig = new ServerConfiguration();
                        foreach (var parser in AdditionalRConParsers)
                        {
                            serverConfig.AddRConParser(parser);
                        }

                        foreach (var parser in AdditionalEventParsers)
                        {
                            serverConfig.AddEventParser(parser);
                        }

                        _appConfig.Servers = _appConfig.Servers.Where(_servers => _servers != null).Append((ServerConfiguration)serverConfig.Generate()).ToArray();
                    } while (Utilities.PromptBool(_translationLookup["SETUP_SERVER_SAVE"]));

                    await ConfigHandler.Save();
                }
            }

            else
            {
                if (string.IsNullOrEmpty(_appConfig.Id))
                {
                    _appConfig.Id = Guid.NewGuid().ToString();
                    await ConfigHandler.Save();
                }

                if (string.IsNullOrEmpty(_appConfig.WebfrontBindUrl))
                {
                    _appConfig.WebfrontBindUrl = "http://0.0.0.0:1624";
                    await ConfigHandler.Save();
                }

#pragma warning disable 618
                if (_appConfig.Maps != null)
                {
                    _appConfig.Maps = null;
                }

                if (_appConfig.QuickMessages != null)
                {
                    _appConfig.QuickMessages = null;
                }
#pragma warning restore 618

                var validator        = new ApplicationConfigurationValidator();
                var validationResult = validator.Validate(_appConfig);

                if (!validationResult.IsValid)
                {
                    throw new ConfigurationException("MANAGER_CONFIGURATION_ERROR")
                          {
                              Errors = validationResult.Errors.Select(_error => _error.ErrorMessage).ToArray(),
                              ConfigurationFileName = ConfigHandler.FileName
                          };
                }

                foreach (var serverConfig in _appConfig.Servers)
                {
                    ConfigurationMigration.ModifyLogPath020919(serverConfig);

                    if (serverConfig.RConParserVersion == null || serverConfig.EventParserVersion == null)
                    {
                        foreach (var parser in AdditionalRConParsers)
                        {
                            serverConfig.AddRConParser(parser);
                        }

                        foreach (var parser in AdditionalEventParsers)
                        {
                            serverConfig.AddEventParser(parser);
                        }

                        serverConfig.ModifyParsers();
                    }
                    await ConfigHandler.Save();
                }
            }

            if (_appConfig.Servers.Length == 0)
            {
                throw new ServerException("A server configuration in IW4MAdminSettings.json is invalid");
            }

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Utilities.EncodingType = Encoding.GetEncoding(!string.IsNullOrEmpty(_appConfig.CustomParserEncoding) ? _appConfig.CustomParserEncoding : "windows-1252");

            foreach (var parser in AdditionalRConParsers)
            {
                if (!parser.Configuration.ColorCodeMapping.ContainsKey(ColorCodes.Accent.ToString()))
                {
                    parser.Configuration.ColorCodeMapping.Add(ColorCodes.Accent.ToString(),
                                                              parser.Configuration.ColorCodeMapping.TryGetValue(_appConfig.IngameAccentColorKey, out var colorCode)
                            ? colorCode
                            : "");
                }
            }

            #endregion

            #region COMMANDS
            if (await ClientSvc.HasOwnerAsync(_tokenSource.Token))
            {
                _commands.RemoveAll(_cmd => _cmd.GetType() == typeof(OwnerCommand));
            }

            List <IManagerCommand> commandsToAddToConfig = new List <IManagerCommand>();
            var cmdConfig = _commandConfiguration.Configuration();

            if (cmdConfig == null)
            {
                cmdConfig = new CommandConfiguration();
                commandsToAddToConfig.AddRange(_commands);
            }

            else
            {
                var unsavedCommands = _commands.Where(_cmd => !cmdConfig.Commands.Keys.Contains(_cmd.CommandConfigNameForType()));
                commandsToAddToConfig.AddRange(unsavedCommands);
            }

            // this is because I want to store the command prefix in IW4MAdminSettings, but can't easily
            // inject it to all the places that need it
            cmdConfig.CommandPrefix          = _appConfig?.CommandPrefix ?? "!";
            cmdConfig.BroadcastCommandPrefix = _appConfig?.BroadcastCommandPrefix ?? "@";

            foreach (var cmd in commandsToAddToConfig)
            {
                if (cmdConfig.Commands.ContainsKey(cmd.CommandConfigNameForType()))
                {
                    continue;
                }
                cmdConfig.Commands.Add(cmd.CommandConfigNameForType(),
                                       new CommandProperties
                {
                    Name               = cmd.Name,
                    Alias              = cmd.Alias,
                    MinimumPermission  = cmd.Permission,
                    AllowImpersonation = cmd.AllowImpersonation,
                    SupportedGames     = cmd.SupportedGames
                });
            }

            _commandConfiguration.Set(cmdConfig);
            await _commandConfiguration.Save();

            #endregion

            _metaRegistration.Register();

            #region CUSTOM_EVENTS
            foreach (var customEvent in _customParserEvents.SelectMany(_events => _events.Events))
            {
                foreach (var parser in AdditionalEventParsers)
                {
                    parser.RegisterCustomEvent(customEvent.Item1, customEvent.Item2, customEvent.Item3);
                }
            }
            #endregion

            Console.WriteLine(_translationLookup["MANAGER_COMMUNICATION_INFO"]);
            await InitializeServers();
        }
 public ConfigurationController(IManager manager) : base(manager)
 {
     _validator = new ApplicationConfigurationValidator();
 }
Пример #6
0
        public async Task Init()
        {
            IsRunning         = true;
            ExternalIPAddress = await Utilities.GetExternalIP();

            #region PLUGINS
            foreach (var plugin in Plugins)
            {
                try
                {
                    if (plugin is ScriptPlugin scriptPlugin)
                    {
                        await scriptPlugin.Initialize(this, _scriptCommandFactory, _scriptPluginServiceResolver);

                        scriptPlugin.Watcher.Changed += async(sender, e) =>
                        {
                            try
                            {
                                await scriptPlugin.Initialize(this, _scriptCommandFactory, _scriptPluginServiceResolver);
                            }

                            catch (Exception ex)
                            {
                                Logger.WriteError(Utilities.CurrentLocalization.LocalizationIndex["PLUGIN_IMPORTER_ERROR"].FormatExt(scriptPlugin.Name));
                                Logger.WriteDebug(ex.Message);
                            }
                        };
                    }

                    else
                    {
                        await plugin.OnLoadAsync(this);
                    }
                }

                catch (Exception ex)
                {
                    Logger.WriteError($"{_translationLookup["SERVER_ERROR_PLUGIN"]} {plugin.Name}");
                    Logger.WriteDebug(ex.GetExceptionInfo());
                }
            }
            #endregion

            #region CONFIG
            var config = ConfigHandler.Configuration();

            // copy over default config if it doesn't exist
            if (config == null)
            {
                var defaultConfig = new BaseConfigurationHandler <DefaultConfiguration>("DefaultSettings").Configuration();
                ConfigHandler.Set((ApplicationConfiguration) new ApplicationConfiguration().Generate());
                var newConfig = ConfigHandler.Configuration();

                newConfig.AutoMessages          = defaultConfig.AutoMessages;
                newConfig.GlobalRules           = defaultConfig.GlobalRules;
                newConfig.Maps                  = defaultConfig.Maps;
                newConfig.DisallowedClientNames = defaultConfig.DisallowedClientNames;
                newConfig.QuickMessages         = defaultConfig.QuickMessages;

                if (newConfig.Servers == null)
                {
                    ConfigHandler.Set(newConfig);
                    newConfig.Servers = new ServerConfiguration[1];

                    do
                    {
                        var serverConfig = new ServerConfiguration();
                        foreach (var parser in AdditionalRConParsers)
                        {
                            serverConfig.AddRConParser(parser);
                        }

                        foreach (var parser in AdditionalEventParsers)
                        {
                            serverConfig.AddEventParser(parser);
                        }

                        newConfig.Servers = newConfig.Servers.Where(_servers => _servers != null).Append((ServerConfiguration)serverConfig.Generate()).ToArray();
                    } while (Utilities.PromptBool(_translationLookup["SETUP_SERVER_SAVE"]));

                    config = newConfig;
                    await ConfigHandler.Save();
                }
            }

            else
            {
                if (string.IsNullOrEmpty(config.Id))
                {
                    config.Id = Guid.NewGuid().ToString();
                    await ConfigHandler.Save();
                }

                if (string.IsNullOrEmpty(config.WebfrontBindUrl))
                {
                    config.WebfrontBindUrl = "http://0.0.0.0:1624";
                    await ConfigHandler.Save();
                }

                var validator        = new ApplicationConfigurationValidator();
                var validationResult = validator.Validate(config);

                if (!validationResult.IsValid)
                {
                    throw new ConfigurationException("MANAGER_CONFIGURATION_ERROR")
                          {
                              Errors = validationResult.Errors.Select(_error => _error.ErrorMessage).ToArray(),
                              ConfigurationFileName = ConfigHandler.FileName
                          };
                }

                foreach (var serverConfig in config.Servers)
                {
                    Migration.ConfigurationMigration.ModifyLogPath020919(serverConfig);

                    if (serverConfig.RConParserVersion == null || serverConfig.EventParserVersion == null)
                    {
                        foreach (var parser in AdditionalRConParsers)
                        {
                            serverConfig.AddRConParser(parser);
                        }

                        foreach (var parser in AdditionalEventParsers)
                        {
                            serverConfig.AddEventParser(parser);
                        }

                        serverConfig.ModifyParsers();
                    }
                    await ConfigHandler.Save();
                }
            }

            if (config.Servers.Length == 0)
            {
                throw new ServerException("A server configuration in IW4MAdminSettings.json is invalid");
            }

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Utilities.EncodingType = Encoding.GetEncoding(!string.IsNullOrEmpty(config.CustomParserEncoding) ? config.CustomParserEncoding : "windows-1252");

            #endregion

            #region DATABASE
            using (var db = new DatabaseContext(GetApplicationSettings().Configuration()?.ConnectionString,
                                                GetApplicationSettings().Configuration()?.DatabaseProvider))
            {
                await new ContextSeed(db).Seed();
            }
            #endregion

            #region COMMANDS
            if (ClientSvc.GetOwners().Result.Count > 0)
            {
                _commands.RemoveAll(_cmd => _cmd.GetType() == typeof(OwnerCommand));
            }

            List <IManagerCommand> commandsToAddToConfig = new List <IManagerCommand>();
            var cmdConfig = _commandConfiguration.Configuration();

            if (cmdConfig == null)
            {
                cmdConfig = new CommandConfiguration();
                commandsToAddToConfig.AddRange(_commands);
            }

            else
            {
                var unsavedCommands = _commands.Where(_cmd => !cmdConfig.Commands.Keys.Contains(_cmd.CommandConfigNameForType()));
                commandsToAddToConfig.AddRange(unsavedCommands);
            }

            // this is because I want to store the command prefix in IW4MAdminSettings, but can't easily
            // inject it to all the places that need it
            cmdConfig.CommandPrefix          = config.CommandPrefix;
            cmdConfig.BroadcastCommandPrefix = config.BroadcastCommandPrefix;

            foreach (var cmd in commandsToAddToConfig)
            {
                cmdConfig.Commands.Add(cmd.CommandConfigNameForType(),
                                       new CommandProperties()
                {
                    Name               = cmd.Name,
                    Alias              = cmd.Alias,
                    MinimumPermission  = cmd.Permission,
                    AllowImpersonation = cmd.AllowImpersonation,
                    SupportedGames     = cmd.SupportedGames
                });
            }

            _commandConfiguration.Set(cmdConfig);
            await _commandConfiguration.Save();

            #endregion

            _metaRegistration.Register();

            #region CUSTOM_EVENTS
            foreach (var customEvent in _customParserEvents.SelectMany(_events => _events.Events))
            {
                foreach (var parser in AdditionalEventParsers)
                {
                    parser.RegisterCustomEvent(customEvent.Item1, customEvent.Item2, customEvent.Item3);
                }
            }
            #endregion

            await InitializeServers();
        }