public ResetRankCommand(CommandConfiguration config, ITranslationLookup lookup, IMetaService metaService, IConfigurationHandlerFactory configurationHandlerFactory) : base(config, lookup)
        {
            _metaService          = metaService;
            _configurationHandler = configurationHandlerFactory.GetConfigurationHandler <Configuration>("ClanTagRankCommands");
            if (_configurationHandler.Configuration() == null)
            {
                _configurationHandler.Set((Configuration) new Configuration().Generate());
                _configurationHandler.Save();
            }
            Config = _configurationHandler.Configuration();

            Name           = "ResetRank";
            Description    = "set a user's clan tag Rank (does not give permissions)";
            Alias          = "rr";
            Permission     = EFClient.Permission.Administrator;
            RequiresTarget = true;
            Arguments      = new[]
            {
                new CommandArgument()
                {
                    //Name = "rank",
                    //Required = false
                }
            };
        }
示例#2
0
        private async Task <string> GetNextFeedItem(Server server)
        {
            var items = new List <string>();

            using (var reader = XmlReader.Create(_configurationHandler.Configuration().FeedUrl, new XmlReaderSettings()
            {
                Async = true
            }))
            {
                var feedReader = new RssFeedReader(reader);

                while (await feedReader.Read())
                {
                    switch (feedReader.ElementType)
                    {
                    case SyndicationElementType.Item:
                        var item = await feedReader.ReadItem();

                        items.Add(Regex.Replace(item.Title, @"\<.+\>.*\</.+\>", ""));
                        break;
                    }
                }
            }

            if (_currentFeedItem < items.Count && (_configurationHandler.Configuration().MaxFeedItems == 0 || _currentFeedItem < _configurationHandler.Configuration().MaxFeedItems))
            {
                _currentFeedItem++;
                return(items[_currentFeedItem - 1]);
            }

            _currentFeedItem = 0;
            return(Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_AUTOMESSAGEFEED_NO_ITEMS"]);
        }
示例#3
0
        public async Task <IActionResult> GetTopPlayersAsync(int count, int offset, long?serverId = null)
        {
            // this prevents empty results when we really want aggregate
            if (serverId == 0)
            {
                serverId = null;
            }

            var server = _manager.GetServers().FirstOrDefault(_server => _server.EndPoint == serverId);

            if (server != null)
            {
                serverId = StatManager.GetIdForServer(server);
            }

            var results = _configurationHandler.Configuration().EnableAdvancedMetrics
                ? await Plugin.Manager.GetNewTopStats(offset, count, serverId)
                : await Plugin.Manager.GetTopStats(offset, count, serverId);

            // this returns an empty result so we know to stale the loader
            if (results.Count == 0 && offset > 0)
            {
                return(Ok());
            }

            ViewBag.UseNewStats = _configurationHandler.Configuration().EnableAdvancedMetrics;
            return(View("~/Views/Client/Statistics/Components/TopPlayers/_List.cshtml", results));
        }
示例#4
0
 public async Task OnLoadAsync(IManager manager)
 {
     if (_configHandler.Configuration() == null)
     {
         _configHandler.Set((WelcomeConfiguration) new WelcomeConfiguration().Generate());
         await _configHandler.Save();
     }
 }
示例#5
0
        public Task OnEventAsync(GameEvent E, Server S)
        {
            if (E.IsRemote || _configHandler.Configuration().RequirePrivilegedClientLogin == false)
            {
                return(Task.CompletedTask);
            }

            if (E.Type == GameEvent.EventType.Connect)
            {
                AuthorizedClients.TryAdd(E.Origin.ClientId, false);
                E.Origin.SetAdditionalProperty("IsLoggedIn", false);
            }

            if (E.Type == GameEvent.EventType.Disconnect)
            {
                AuthorizedClients.TryRemove(E.Origin.ClientId, out bool value);
            }

            if (E.Type == GameEvent.EventType.Command)
            {
                if (E.Origin.Level < EFClient.Permission.Moderator ||
                    E.Origin.Level == EFClient.Permission.Console)
                {
                    return(Task.CompletedTask);
                }

                if (E.Extra.GetType() == typeof(SetPasswordCommand) &&
                    E.Origin?.Password == null)
                {
                    return(Task.CompletedTask);
                }

                if (E.Extra.GetType() == typeof(LoginCommand))
                {
                    return(Task.CompletedTask);
                }

                if (E.Extra.GetType() == typeof(RequestTokenCommand))
                {
                    return(Task.CompletedTask);
                }

                if (!AuthorizedClients[E.Origin.ClientId])
                {
                    throw new AuthorizationException(Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_LOGIN_AUTH"]);
                }

                else
                {
                    E.Origin.SetAdditionalProperty("IsLoggedIn", true);
                }
            }

            return(Task.CompletedTask);
        }
示例#6
0
 public GscApiController(IManager manager, IMetaService metaService, IConfigurationHandlerFactory configurationHandlerFactory) : base(manager)
 {
     _metaService          = metaService;
     _configurationHandler = configurationHandlerFactory.GetConfigurationHandler <Configuration>("ClanTagRankCommands");
     if (_configurationHandler.Configuration() == null)
     {
         _configurationHandler.Set((Configuration) new Configuration().Generate());
         _configurationHandler.Save();
     }
     Config = _configurationHandler.Configuration();
 }
示例#7
0
        public Task OnLoadAsync(IManager manager)// => Task.CompletedTask;
        {
            if (_configurationHandler.Configuration() == null)
            {
                _configurationHandler.Set((Configuration) new Configuration().Generate());
                _configurationHandler.Save();
            }
            Config = _configurationHandler.Configuration();
            string version = manager.Version;
            string str     = string.Format("Loaded {0} ({1}) by {2} in {3} ({4})!", (object)((IPlugin)this).Name, (object)((IPlugin)this).Version, (object)((IPlugin)this).Author, (object)"IW4MAdmin", (object)version);

            _logger.LogInformation(str);

            return(Task.CompletedTask);
        }
示例#8
0
 public ClientStatisticsController(IManager manager,
                                   IResourceQueryHelper <StatsInfoRequest, AdvancedStatsInfo> queryHelper,
                                   IConfigurationHandler <DefaultSettings> configurationHandler) : base(manager)
 {
     _queryHelper   = queryHelper;
     _defaultConfig = configurationHandler.Configuration();
 }
示例#9
0
 public async Task OnLoadAsync(IManager manager)
 {
     if (_configurationHandler.Configuration() == null)
     {
         _configurationHandler.Set((LiveRadarConfiguration) new LiveRadarConfiguration().Generate());
         await _configurationHandler.Save();
     }
 }
示例#10
0
 public ApplicationManager(ILogger logger, IMiddlewareActionHandler actionHandler, IEnumerable <IManagerCommand> commands,
                           ITranslationLookup translationLookup, IConfigurationHandler <CommandConfiguration> commandConfiguration,
                           IConfigurationHandler <ApplicationConfiguration> appConfigHandler, IGameServerInstanceFactory serverInstanceFactory,
                           IEnumerable <IPlugin> plugins, IParserRegexFactory parserRegexFactory, IEnumerable <IRegisterEvent> customParserEvents,
                           IEventHandler eventHandler, IScriptCommandFactory scriptCommandFactory, IDatabaseContextFactory contextFactory, IMetaService metaService,
                           IMetaRegistration metaRegistration, IScriptPluginServiceResolver scriptPluginServiceResolver)
 {
     MiddlewareActionHandler = actionHandler;
     _servers               = new ConcurrentBag <Server>();
     MessageTokens          = new List <MessageToken>();
     ClientSvc              = new ClientService(contextFactory);
     AliasSvc               = new AliasService();
     PenaltySvc             = new PenaltyService();
     ConfigHandler          = appConfigHandler;
     StartTime              = DateTime.UtcNow;
     PageList               = new PageList();
     AdditionalEventParsers = new List <IEventParser>()
     {
         new BaseEventParser(parserRegexFactory, logger, appConfigHandler.Configuration())
     };
     AdditionalRConParsers = new List <IRConParser>()
     {
         new BaseRConParser(parserRegexFactory)
     };
     TokenAuthenticator = new TokenAuthentication();
     _logger            = logger;
     _metaService       = metaService;
     _tokenSource       = new CancellationTokenSource();
     _loggers.Add(0, logger);
     _commands                    = commands.ToList();
     _translationLookup           = translationLookup;
     _commandConfiguration        = commandConfiguration;
     _serverInstanceFactory       = serverInstanceFactory;
     _parserRegexFactory          = parserRegexFactory;
     _customParserEvents          = customParserEvents;
     _eventHandler                = eventHandler;
     _scriptCommandFactory        = scriptCommandFactory;
     _metaRegistration            = metaRegistration;
     _scriptPluginServiceResolver = scriptPluginServiceResolver;
     Plugins = plugins;
 }
示例#11
0
        public async Task <IViewComponentResult> InvokeAsync(int count, int offset, long?serverId = null)
        {
            if (serverId == 0)
            {
                serverId = null;
            }

            var server = Plugin.ServerManager.GetServers().FirstOrDefault(_server => _server.EndPoint == serverId);

            if (server != null)
            {
                serverId = StatManager.GetIdForServer(server);
            }


            ViewBag.UseNewStats = _configurationHandler.Configuration()?.EnableAdvancedMetrics ?? true;
            return(View("~/Views/Client/Statistics/Components/TopPlayers/_List.cshtml",
                        ViewBag.UseNewStats
                    ? await Plugin.Manager.GetNewTopStats(offset, count, serverId)
                    : await Plugin.Manager.GetTopStats(offset, count, serverId)));
        }
示例#12
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();
        }
示例#13
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();
        }
示例#14
0
        public Task OnEventAsync(GameEvent E, Server S)
        {
            if (!_configHandler.Configuration().EnableProfanityDeterment)
            {
                return(Task.CompletedTask);
            }

            if (E.Type == GameEvent.EventType.Connect)
            {
                E.Origin.SetAdditionalProperty("_profanityInfringements", 0);

                var  objectionalWords        = _configHandler.Configuration().OffensiveWords;
                var  matchedFilters          = new List <string>();
                bool containsObjectionalWord = false;

                foreach (string word in objectionalWords)
                {
                    if (Regex.IsMatch(E.Origin.Name.ToLower(), word, RegexOptions.IgnoreCase))
                    {
                        containsObjectionalWord |= true;
                        matchedFilters.Add(word);
                    }
                }

                if (containsObjectionalWord)
                {
                    var sender = Utilities.IW4MAdminClient(E.Owner);
                    sender.AdministeredPenalties = new List <EFPenalty>()
                    {
                        new EFPenalty()
                        {
                            AutomatedOffense = $"{E.Origin.Name} - {string.Join(",", matchedFilters)}"
                        }
                    };
                    E.Origin.Kick(_configHandler.Configuration().ProfanityKickMessage, sender);
                }
                ;
            }

            if (E.Type == GameEvent.EventType.Disconnect)
            {
                E.Origin.SetAdditionalProperty("_profanityInfringements", 0);
            }

            if (E.Type == GameEvent.EventType.Say)
            {
                var  objectionalWords        = _configHandler.Configuration().OffensiveWords;
                bool containsObjectionalWord = false;
                var  matchedFilters          = new List <string>();

                foreach (string word in objectionalWords)
                {
                    if (Regex.IsMatch(E.Data.ToLower(), word, RegexOptions.IgnoreCase))
                    {
                        containsObjectionalWord |= true;
                        matchedFilters.Add(word);
                    }
                }

                if (containsObjectionalWord)
                {
                    int profanityInfringments = E.Origin.GetAdditionalProperty <int>("_profanityInfringements");

                    var sender = Utilities.IW4MAdminClient(E.Owner);
                    sender.AdministeredPenalties = new List <EFPenalty>()
                    {
                        new EFPenalty()
                        {
                            AutomatedOffense = $"{E.Data} - {string.Join(",", matchedFilters)}"
                        }
                    };

                    if (profanityInfringments >= _configHandler.Configuration().KickAfterInfringementCount)
                    {
                        E.Origin.Kick(_configHandler.Configuration().ProfanityKickMessage, sender);
                    }

                    else if (profanityInfringments < _configHandler.Configuration().KickAfterInfringementCount)
                    {
                        E.Origin.SetAdditionalProperty("_profanityInfringements", profanityInfringments + 1);
                        E.Origin.Warn(_configHandler.Configuration().ProfanityWarningMessage, sender);
                    }
                }
            }
            return(Task.CompletedTask);
        }
示例#15
0
        public async Task <IActionResult> ProfileAsync(int id, MetaType?metaFilterType)
        {
            var client = await Manager.GetClientService().Get(id);

            if (client == null)
            {
                return(NotFound());
            }

            var activePenalties = (await Manager.GetPenaltyService().GetActivePenaltiesAsync(client.AliasLinkId, client.IPAddress));

            var tag = await _metaService.GetPersistentMeta(EFMeta.ClientTag, client);

            if (tag?.LinkedMeta != null)
            {
                client.SetAdditionalProperty(EFMeta.ClientTag, tag.LinkedMeta.Value);
            }

            var displayLevelInt = (int)client.Level;
            var displayLevel    = client.Level.ToLocalizedLevelName();

            if (!Authorized && client.Level.ShouldHideLevel())
            {
                displayLevelInt = (int)Data.Models.Client.EFClient.Permission.User;
                displayLevel    = Data.Models.Client.EFClient.Permission.User.ToLocalizedLevelName();
            }

            displayLevel = string.IsNullOrEmpty(client.Tag) ? displayLevel : $"{displayLevel} ({client.Tag})";

            var clientDto = new PlayerInfo()
            {
                Name      = client.Name,
                Level     = displayLevel,
                LevelInt  = displayLevelInt,
                ClientId  = client.ClientId,
                IPAddress = client.IPAddressString,
                NetworkId = client.NetworkId,
                Meta      = new List <InformationResponse>(),
                Aliases   = client.AliasLink.Children
                            .Select(_alias => _alias.Name)
                            .GroupBy(_alias => _alias.StripColors())
                            // we want the longest "duplicate" name
                            .Select(_grp => _grp.OrderByDescending(_name => _name.Length).First())
                            .Distinct()
                            .OrderBy(a => a)
                            .ToList(),
                IPs = client.AliasLink.Children
                      .Where(i => i.IPAddress != null)
                      .OrderByDescending(i => i.DateAdded)
                      .Select(i => i.IPAddress.ConvertIPtoString())
                      .Prepend(client.CurrentAlias.IPAddress.ConvertIPtoString())
                      .Distinct()
                      .ToList(),
                HasActivePenalty = activePenalties.Any(_penalty => _penalty.Type != EFPenalty.PenaltyType.Flag),
                Online           = Manager.GetActiveClients().FirstOrDefault(c => c.ClientId == client.ClientId) != null,
                TimeOnline       = (DateTime.UtcNow - client.LastConnection).HumanizeForCurrentCulture(),
                LinkedAccounts   = client.LinkedAccounts,
                MetaFilterType   = metaFilterType
            };

            var meta = await _metaService.GetRuntimeMeta <InformationResponse>(new ClientPaginationRequest
            {
                ClientId = client.ClientId,
                Before   = DateTime.UtcNow
            }, MetaType.Information);

            var gravatar = await _metaService.GetPersistentMeta("GravatarEmail", client);

            if (gravatar != null)
            {
                clientDto.Meta.Add(new InformationResponse()
                {
                    Key   = "GravatarEmail",
                    Type  = MetaType.Other,
                    Value = gravatar.Value
                });
            }

            clientDto.ActivePenalty = activePenalties.OrderByDescending(_penalty => _penalty.Type).FirstOrDefault();
            clientDto.Meta.AddRange(Authorized ? meta : meta.Where(m => !m.IsSensitive));

            string strippedName = clientDto.Name.StripColors();

            ViewBag.Title = strippedName.Substring(strippedName.Length - 1).ToLower()[0] == 's' ?
                            strippedName + "'" :
                            strippedName + "'s";
            ViewBag.Title      += " " + Localization["WEBFRONT_CLIENT_PROFILE_TITLE"];
            ViewBag.Description = $"Client information for {strippedName}";
            ViewBag.Keywords    = $"IW4MAdmin, client, profile, {strippedName}";
            ViewBag.UseNewStats = _configurationHandler.Configuration()?.EnableAdvancedMetrics ?? true;

            return(View("Profile/Index", clientDto));
        }
示例#16
0
        public async Task Initialize()
        {
            await LoadServers();

            _distributionCache.SetCacheItem((async(set, token) =>
            {
                var validPlayTime = _configurationHandler.Configuration()?.TopPlayersMinPlayTime ?? 3600 * 3;

                var distributions = new Dictionary <long, Extensions.LogParams>();

                await LoadServers();

                foreach (var serverId in _serverIds)
                {
                    var performance = await set
                                      .Where(s => s.ServerId == serverId)
                                      .Where(s => s.Skill > 0)
                                      .Where(s => s.EloRating > 0)
                                      .Where(s => s.Client.Level != EFClient.Permission.Banned)
                                      .Where(s => s.TimePlayed >= validPlayTime)
                                      .Where(s => s.UpdatedAt >= Extensions.FifteenDaysAgo())
                                      .Select(s => s.EloRating * 1 / 3.0 + s.Skill * 2 / 3.0).ToListAsync();
                    var distributionParams = performance.GenerateDistributionParameters();
                    distributions.Add(serverId, distributionParams);
                }

                return(distributions);
            }), DistributionCacheKey, Utilities.IsDevelopment ? TimeSpan.FromMinutes(5) : TimeSpan.FromHours(1));

            _maxZScoreCache.SetCacheItem(async(set, token) =>
            {
                var validPlayTime = _configurationHandler.Configuration()?.TopPlayersMinPlayTime ?? 3600 * 3;

                var zScore = await set
                             .Where(AdvancedClientStatsResourceQueryHelper.GetRankingFunc(validPlayTime))
                             .Where(s => s.Skill > 0)
                             .Where(s => s.EloRating > 0)
                             .GroupBy(stat => stat.ClientId)
                             .Select(group =>
                                     group.Sum(stat => stat.ZScore * stat.TimePlayed) / group.Sum(stat => stat.TimePlayed))
                             .MaxAsync(avgZScore => (double?)avgZScore, token);
                return(zScore ?? 0);
            }, MaxZScoreCacheKey, Utilities.IsDevelopment ? TimeSpan.FromMinutes(5) : TimeSpan.FromMinutes(30));

            await _distributionCache.GetCacheItem(DistributionCacheKey);

            await _maxZScoreCache.GetCacheItem(MaxZScoreCacheKey);

            /*foreach (var serverId in _serverIds)
             * {
             *  await using var ctx = _contextFactory.CreateContext(enableTracking: true);
             *
             *  var a = await ctx.Set<EFClientStatistics>()
             *      .Where(s => s.ServerId == serverId)
             *      //.Where(s=> s.ClientId == 216105)
             *      .Where(s => s.Skill > 0)
             *      .Where(s => s.EloRating > 0)
             *      .Where(s => s.Client.Level != EFClient.Permission.Banned)
             *      .Where(s => s.TimePlayed >= 3600 * 3)
             *      .Where(s => s.UpdatedAt >= Extensions.FifteenDaysAgo())
             *      .ToListAsync();
             *
             *  var b = a.Distinct();
             *
             *  foreach (var item in b)
             *  {
             *      await Plugin.Manager.UpdateHistoricalRanking(item.ClientId, item, item.ServerId);
             *      //item.ZScore = await GetZScoreForServer(serverId, item.Performance);
             *     //item.UpdatedAt = DateTime.UtcNow;
             *  }
             *
             *  await ctx.SaveChangesAsync();
             * }*/
        }
示例#17
0
 public WeaponNameParser(ILogger <WeaponNameParser> logger, IConfigurationHandler <StatsConfiguration> config)
 {
     _logger = logger;
     _config = config.Configuration();
 }
示例#18
0
        public async Task UpdateServerStates()
        {
            // store the server hash code and task for it
            var runningUpdateTasks = new Dictionary <long, (Task task, CancellationTokenSource tokenSource, DateTime startTime)>();

            while (!_tokenSource.IsCancellationRequested)
            {
                // select the server ids that have completed the update task
                var serverTasksToRemove = runningUpdateTasks
                                          .Where(ut => ut.Value.task.Status == TaskStatus.RanToCompletion ||
                                                 ut.Value.task.Status == TaskStatus.Canceled || // we want to cancel if a task takes longer than 5 minutes
                                                 ut.Value.task.Status == TaskStatus.Faulted || DateTime.Now - ut.Value.startTime > TimeSpan.FromMinutes(5))
                                          .Select(ut => ut.Key)
                                          .ToList();

                // this is to prevent the log reader from starting before the initial
                // query of players on the server
                if (serverTasksToRemove.Count > 0)
                {
                    IsInitialized = true;
                }

                // remove the update tasks as they have completed
                foreach (var serverId in serverTasksToRemove.Where(serverId => runningUpdateTasks.ContainsKey(serverId)))
                {
                    if (!runningUpdateTasks[serverId].tokenSource.Token.IsCancellationRequested)
                    {
                        runningUpdateTasks[serverId].tokenSource.Cancel();
                    }

                    runningUpdateTasks.Remove(serverId);
                }

                // select the servers where the tasks have completed
                var serverIds = Servers.Select(s => s.EndPoint).Except(runningUpdateTasks.Select(r => r.Key)).ToList();
                foreach (var server in Servers.Where(s => serverIds.Contains(s.EndPoint)))
                {
                    var tokenSource = new CancellationTokenSource();
                    runningUpdateTasks.Add(server.EndPoint, (Task.Run(async() =>
                    {
                        try
                        {
                            if (runningUpdateTasks.ContainsKey(server.EndPoint))
                            {
                                await server.ProcessUpdatesAsync(_tokenSource.Token)
                                .WithWaitCancellation(runningUpdateTasks[server.EndPoint].tokenSource.Token);
                            }
                        }

                        catch (Exception e)
                        {
                            using (LogContext.PushProperty("Server", server.ToString()))
                            {
                                _logger.LogError(e, "Failed to update status");
                            }
                        }

                        finally
                        {
                            server.IsInitialized = true;
                        }
                    }, tokenSource.Token), tokenSource, DateTime.Now));
                }

                try
                {
                    await Task.Delay(ConfigHandler.Configuration().RConPollRate, _tokenSource.Token);
                }
                // if a cancellation is received, we want to return immediately after shutting down
                catch
                {
                    foreach (var server in Servers.Where(s => serverIds.Contains(s.EndPoint)))
                    {
                        await server.ProcessUpdatesAsync(_tokenSource.Token);
                    }
                    break;
                }
            }
        }
示例#19
0
        public async Task UpdateServerStates()
        {
            // store the server hash code and task for it
            var runningUpdateTasks = new Dictionary <long, Task>();

            while (!_tokenSource.IsCancellationRequested)
            {
                // select the server ids that have completed the update task
                var serverTasksToRemove = runningUpdateTasks
                                          .Where(ut => ut.Value.Status == TaskStatus.RanToCompletion ||
                                                 ut.Value.Status == TaskStatus.Canceled ||
                                                 ut.Value.Status == TaskStatus.Faulted)
                                          .Select(ut => ut.Key)
                                          .ToList();

                // this is to prevent the log reader from starting before the initial
                // query of players on the server
                if (serverTasksToRemove.Count > 0)
                {
                    IsInitialized = true;
                }

                // remove the update tasks as they have completd
                foreach (long serverId in serverTasksToRemove)
                {
                    runningUpdateTasks.Remove(serverId);
                }

                // select the servers where the tasks have completed
                var serverIds = Servers.Select(s => s.EndPoint).Except(runningUpdateTasks.Select(r => r.Key)).ToList();
                foreach (var server in Servers.Where(s => serverIds.Contains(s.EndPoint)))
                {
                    runningUpdateTasks.Add(server.EndPoint, Task.Run(async() =>
                    {
                        try
                        {
                            await server.ProcessUpdatesAsync(_tokenSource.Token);

                            if (server.Throttled)
                            {
                                await Task.Delay((int)_throttleTimeout.TotalMilliseconds, _tokenSource.Token);
                            }
                        }

                        catch (Exception e)
                        {
                            Logger.WriteWarning($"Failed to update status for {server}");
                            Logger.WriteDebug(e.GetExceptionInfo());
                        }

                        finally
                        {
                            server.IsInitialized = true;
                        }
                    }));
                }
#if DEBUG
                Logger.WriteDebug($"{runningUpdateTasks.Count} servers queued for stats updates");
                ThreadPool.GetMaxThreads(out int workerThreads, out int n);
                ThreadPool.GetAvailableThreads(out int availableThreads, out int m);
                Logger.WriteDebug($"There are {workerThreads - availableThreads} active threading tasks");
#endif
                try
                {
                    await Task.Delay(ConfigHandler.Configuration().RConPollRate, _tokenSource.Token);
                }
                // if a cancellation is received, we want to return immediately after shutting down
                catch
                {
                    foreach (var server in Servers.Where(s => serverIds.Contains(s.EndPoint)))
                    {
                        await server.ProcessUpdatesAsync(_tokenSource.Token);
                    }
                    break;
                }
            }
        }