public static void Main(string[] args) { AppDomain.CurrentDomain.SetData("DataDirectory", Utilities.OperatingDirectory); Console.OutputEncoding = Encoding.UTF8; Console.ForegroundColor = ConsoleColor.Gray; Version = Utilities.GetVersionAsDouble(); Console.WriteLine("====================================================="); Console.WriteLine(" IW4M ADMIN"); Console.WriteLine(" by RaidMax "); Console.WriteLine($" Version {Utilities.GetVersionAsString()}"); Console.WriteLine("====================================================="); Index loc = null; try { ServerManager = ApplicationManager.GetInstance(); var configuration = ServerManager.GetApplicationSettings().Configuration(); if (configuration != null) { Localization.Configure.Initialize(configuration.EnableCustomLocale ? (configuration.CustomLocale ?? "windows-1252") : "windows-1252"); } else { Localization.Configure.Initialize(); } loc = Utilities.CurrentLocalization.LocalizationIndex; Console.CancelKeyPress += new ConsoleCancelEventHandler(OnCancelKey); CheckDirectories(); // do any needed migrations // todo: move out ConfigurationMigration.MoveConfigFolder10518(null); ServerManager.Logger.WriteInfo($"Version is {Version}"); var api = API.Master.Endpoint.Get(); var version = new API.Master.VersionInfo() { CurrentVersionStable = 99.99f }; try { version = api.GetVersion().Result; } catch (Exception e) { ServerManager.Logger.WriteWarning(loc["MANAGER_VERSION_FAIL"]); while (e.InnerException != null) { e = e.InnerException; } ServerManager.Logger.WriteDebug(e.Message); } if (version.CurrentVersionStable == 99.99f) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(loc["MANAGER_VERSION_FAIL"]); Console.ForegroundColor = ConsoleColor.Gray; } #if !PRERELEASE else if (version.CurrentVersionStable > Version) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine($"IW4MAdmin {loc["MANAGER_VERSION_UPDATE"]} [v{version.CurrentVersionStable.ToString("0.0")}]"); Console.WriteLine(loc["MANAGER_VERSION_CURRENT"].FormatExt($"[v{Version.ToString("0.0")}]")); Console.ForegroundColor = ConsoleColor.Gray; } #else else if (version.CurrentVersionPrerelease > Version) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine($"IW4MAdmin-Prerelease {loc["MANAGER_VERSION_UPDATE"]} [v{version.CurrentVersionPrerelease.ToString("0.0")}-pr]"); Console.WriteLine(loc["MANAGER_VERSION_CURRENT"].FormatExt($"[v{Version.ToString("0.0")}-pr]")); Console.ForegroundColor = ConsoleColor.Gray; } #endif else { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(loc["MANAGER_VERSION_SUCCESS"]); Console.ForegroundColor = ConsoleColor.Gray; } ServerManager.Init().Wait(); var consoleTask = Task.Run(async() => { string userInput; var Origin = Utilities.IW4MAdminClient(ServerManager.Servers[0]); do { userInput = Console.ReadLine(); if (userInput?.ToLower() == "quit") { ServerManager.Stop(); } if (ServerManager.Servers.Count == 0) { Console.WriteLine(loc["MANAGER_CONSOLE_NOSERV"]); continue; } if (userInput?.Length > 0) { GameEvent E = new GameEvent() { Type = GameEvent.EventType.Command, Data = userInput, Origin = Origin, Owner = ServerManager.Servers[0] }; ServerManager.GetEventHandler().AddEvent(E); await E.WaitAsync(30 * 1000); } Console.Write('>'); } while (ServerManager.Running); }); } catch (Exception e) { string failMessage = loc == null ? "Failed to initalize IW4MAdmin" : loc["MANAGER_INIT_FAIL"]; string exitMessage = loc == null ? "Press any key to exit..." : loc["MANAGER_EXIT"]; Console.WriteLine(failMessage); while (e.InnerException != null) { e = e.InnerException; } Console.WriteLine(e.Message); Console.WriteLine(exitMessage); Console.ReadKey(); return; } if (ServerManager.GetApplicationSettings().Configuration().EnableWebFront) { Task.Run(() => WebfrontCore.Program.Init(ServerManager)); } OnShutdownComplete.Reset(); ServerManager.Start(); ServerManager.Logger.WriteVerbose(loc["MANAGER_SHUTDOWN_SUCCESS"]); OnShutdownComplete.Set(); }
/// <summary> /// task that initializes application and starts the application monitoring and runtime tasks /// </summary> /// <returns></returns> private static async Task LaunchAsync(string[] args) { restart: ITranslationLookup translationLookup = null; try { // do any needed housekeeping file/folder migrations ConfigurationMigration.MoveConfigFolder10518(null); ConfigurationMigration.CheckDirectories(); var services = ConfigureServices(args); serviceProvider = services.BuildServiceProvider(); var versionChecker = serviceProvider.GetRequiredService <IMasterCommunication>(); ServerManager = (ApplicationManager)serviceProvider.GetRequiredService <IManager>(); translationLookup = serviceProvider.GetRequiredService <ITranslationLookup>(); ServerManager.Logger.WriteInfo(Utilities.CurrentLocalization.LocalizationIndex["MANAGER_VERSION"].FormatExt(Version)); await versionChecker.CheckVersion(); await ServerManager.Init(); } catch (Exception e) { string failMessage = translationLookup == null ? "Failed to initalize IW4MAdmin" : translationLookup["MANAGER_INIT_FAIL"]; string exitMessage = translationLookup == null ? "Press enter to exit..." : translationLookup["MANAGER_EXIT"]; Console.WriteLine(failMessage); while (e.InnerException != null) { e = e.InnerException; } if (e is ConfigurationException configException) { if (translationLookup != null) { Console.WriteLine(translationLookup[configException.Message].FormatExt(configException.ConfigurationFileName)); } foreach (string error in configException.Errors) { Console.WriteLine(error); } } else { Console.WriteLine(e.Message); } Console.WriteLine(exitMessage); await Console.In.ReadAsync(new char[1], 0, 1); return; } try { ApplicationTask = RunApplicationTasksAsync(); await ApplicationTask; } catch (Exception e) { string failMessage = translationLookup == null ? "Failed to initalize IW4MAdmin" : translationLookup["MANAGER_INIT_FAIL"]; Console.WriteLine($"{failMessage}: {e.GetExceptionInfo()}"); } if (ServerManager.IsRestartRequested) { goto restart; } serviceProvider.Dispose(); }
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(); }
/// <summary> /// task that initializes application and starts the application monitoring and runtime tasks /// </summary> /// <returns></returns> private static async Task LaunchAsync(string[] args) { restart: ITranslationLookup translationLookup = null; var logger = BuildDefaultLogger <Program>(new ApplicationConfiguration()); Utilities.DefaultLogger = logger; IServiceCollection services = null; logger.LogInformation("Begin IW4MAdmin startup. Version is {version} {@args}", Version, args); try { // do any needed housekeeping file/folder migrations ConfigurationMigration.MoveConfigFolder10518(null); ConfigurationMigration.CheckDirectories(); ConfigurationMigration.RemoveObsoletePlugins20210322(); logger.LogDebug("Configuring services..."); services = ConfigureServices(args); serviceProvider = services.BuildServiceProvider(); var versionChecker = serviceProvider.GetRequiredService <IMasterCommunication>(); ServerManager = (ApplicationManager)serviceProvider.GetRequiredService <IManager>(); translationLookup = serviceProvider.GetRequiredService <ITranslationLookup>(); await versionChecker.CheckVersion(); await ServerManager.Init(); } catch (Exception e) { string failMessage = translationLookup == null ? "Failed to initialize IW4MAdmin" : translationLookup["MANAGER_INIT_FAIL"]; string exitMessage = translationLookup == null ? "Press enter to exit..." : translationLookup["MANAGER_EXIT"]; logger.LogCritical(e, "Failed to initialize IW4MAdmin"); Console.WriteLine(failMessage); while (e.InnerException != null) { e = e.InnerException; } if (e is ConfigurationException configException) { if (translationLookup != null) { Console.WriteLine(translationLookup[configException.Message] .FormatExt(configException.ConfigurationFileName)); } foreach (string error in configException.Errors) { Console.WriteLine(error); } } else { Console.WriteLine(e.Message); } Console.WriteLine(exitMessage); await Console.In.ReadAsync(new char[1], 0, 1); return; } try { ApplicationTask = RunApplicationTasksAsync(logger, services); await ApplicationTask; } catch (Exception e) { logger.LogCritical(e, "Failed to launch IW4MAdmin"); string failMessage = translationLookup == null ? "Failed to launch IW4MAdmin" : translationLookup["MANAGER_INIT_FAIL"]; Console.WriteLine($"{failMessage}: {e.GetExceptionInfo()}"); } if (ServerManager.IsRestartRequested) { goto restart; } serviceProvider.Dispose(); }