diff --git a/.idea/.idea.CS2-SimpleAdmin/.idea/.gitignore b/.idea/.idea.CS2-SimpleAdmin/.idea/.gitignore new file mode 100644 index 0000000..8565286 --- /dev/null +++ b/.idea/.idea.CS2-SimpleAdmin/.idea/.gitignore @@ -0,0 +1,13 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Rider ignored files +/modules.xml +/projectSettingsUpdater.xml +/.idea.CS2-SimpleAdmin.iml +/contentModel.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/.idea.CS2-SimpleAdmin/.idea/indexLayout.xml b/.idea/.idea.CS2-SimpleAdmin/.idea/indexLayout.xml new file mode 100644 index 0000000..7b08163 --- /dev/null +++ b/.idea/.idea.CS2-SimpleAdmin/.idea/indexLayout.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/.idea.CS2-SimpleAdmin/.idea/sqldialects.xml b/.idea/.idea.CS2-SimpleAdmin/.idea/sqldialects.xml new file mode 100644 index 0000000..8aaaabe --- /dev/null +++ b/.idea/.idea.CS2-SimpleAdmin/.idea/sqldialects.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/.idea.CS2-SimpleAdmin/.idea/vcs.xml b/.idea/.idea.CS2-SimpleAdmin/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/.idea.CS2-SimpleAdmin/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/CS2-SimpleAdmin.cs b/CS2-SimpleAdmin.cs index cce991f..3adedd6 100644 --- a/CS2-SimpleAdmin.cs +++ b/CS2-SimpleAdmin.cs @@ -18,10 +18,10 @@ public partial class CS2_SimpleAdmin : BasePlugin, IPluginConfig voteAnswers = []; - public static ConcurrentBag godPlayers = []; - public static ConcurrentBag silentPlayers = []; - public static ConcurrentBag bannedPlayers = []; - public static bool TagsDetected = false; + private static ConcurrentBag godPlayers = []; + private static ConcurrentBag silentPlayers = []; + private static ConcurrentBag bannedPlayers = []; + private static bool TagsDetected = false; public static bool voteInProgress = false; public static int? ServerId = null; @@ -52,7 +52,7 @@ public override void Load(bool hotReload) OnMapStart(string.Empty); } - CBasePlayerController_SetPawnFunc = new(GameData.GetSignature("CBasePlayerController_SetPawn")); + CBasePlayerController_SetPawnFunc = new MemoryFunctionVoid(GameData.GetSignature("CBasePlayerController_SetPawn")); } public void OnConfigParsed(CS2_SimpleAdminConfig config) @@ -132,14 +132,14 @@ public void OnConfigParsed(CS2_SimpleAdminConfig config) _localizer = Localizer; if (!string.IsNullOrEmpty(Config.Discord.DiscordLogWebhook)) - _discordWebhookClientLog = new(Config.Discord.DiscordLogWebhook); + _discordWebhookClientLog = new DiscordWebhookClient(Config.Discord.DiscordLogWebhook); if (!string.IsNullOrEmpty(Config.Discord.DiscordPenaltyWebhook)) - _discordWebhookClientPenalty = new(Config.Discord.DiscordPenaltyWebhook); + _discordWebhookClientPenalty = new DiscordWebhookClient(Config.Discord.DiscordPenaltyWebhook); } private static TargetResult? GetTarget(CommandInfo command) { - TargetResult matches = command.GetArgTargetResult(1); + var matches = command.GetArgTargetResult(1); if (!matches.Any()) { @@ -162,13 +162,13 @@ public static void RemoveFromConcurrentBag(ConcurrentBag bag, int playerSlo List tempList = []; while (!bag.IsEmpty) { - if (bag.TryTake(out int item) && item != playerSlot) + if (bag.TryTake(out var item) && item != playerSlot) { tempList.Add(item); } } - foreach (int item in tempList) + foreach (var item in tempList) { bag.Add(item); } diff --git a/Commands/basebans.cs b/Commands/basebans.cs index c4cf433..aa47c12 100644 --- a/Commands/basebans.cs +++ b/Commands/basebans.cs @@ -15,15 +15,15 @@ public partial class CS2_SimpleAdmin [CommandHelper(minArgs: 1, usage: "<#userid or name> [time in minutes/0 perm] [reason]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnBanCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; if (command.ArgCount < 2) return; - string reason = _localizer?["sa_unknown"] ?? "Unknown"; + var reason = _localizer?["sa_unknown"] ?? "Unknown"; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); if (playersToTarget.Count > 1 && Config.DisableDangerousCommands || playersToTarget.Count == 0) { @@ -33,7 +33,7 @@ public void OnBanCommand(CCSPlayerController? caller, CommandInfo command) Database database = new(dbConnectionString); BanManager _banManager = new(database, Config); - int.TryParse(command.GetArg(2), out int time); + int.TryParse(command.GetArg(2), out var time); if (command.ArgCount >= 3 && command.GetArg(3).Length > 0) reason = command.GetArg(3); @@ -47,7 +47,7 @@ public void OnBanCommand(CCSPlayerController? caller, CommandInfo command) }); } - internal void Ban(CCSPlayerController? caller, CCSPlayerController player, int time, string reason, string? callerName = null, BanManager? banManager = null, CommandInfo? command = null) + internal void Ban(CCSPlayerController? caller, CCSPlayerController? player, int time, string reason, string? callerName = null, BanManager? banManager = null, CommandInfo? command = null) { if (_database == null || player is null || !player.IsValid) return; @@ -95,15 +95,15 @@ internal void Ban(CCSPlayerController? caller, CCSPlayerController player, int t player!.PrintToCenter(_localizer!["sa_player_ban_message_perm", reason, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_ban_message_perm", callerName, player.PlayerName, reason]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -115,15 +115,15 @@ internal void Ban(CCSPlayerController? caller, CCSPlayerController player, int t { player!.PrintToCenter(_localizer!["sa_player_ban_message_time", reason, time, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_ban_message_time", callerName, player.PlayerName, reason, time]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -143,40 +143,39 @@ internal void Ban(CCSPlayerController? caller, CCSPlayerController player, int t public void OnAddBanCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; if (command.ArgCount < 2) return; if (string.IsNullOrEmpty(command.GetArg(1))) return; - string steamid = command.GetArg(1); + var steamid = command.GetArg(1); - if (!Helper.IsValidSteamID64(steamid)) + if (!Helper.IsValidSteamId64(steamid)) { command.ReplyToCommand($"Invalid SteamID64."); return; } - string reason = _localizer?["sa_unknown"] ?? "Unknown"; + var reason = _localizer?["sa_unknown"] ?? "Unknown"; Database database = new(dbConnectionString); - BanManager _banManager = new(database, Config); - int.TryParse(command.GetArg(2), out int time); + int.TryParse(command.GetArg(2), out var time); if (command.ArgCount >= 3 && command.GetArg(3).Length > 0) reason = command.GetArg(3); - PlayerInfo adminInfo = new PlayerInfo + var adminInfo = new PlayerInfo { SteamId = caller?.SteamID.ToString(), Name = caller?.PlayerName, IpAddress = caller?.IpAddress?.Split(":")[0] }; - List matches = Helper.GetPlayerFromSteamid64(steamid); + var matches = Helper.GetPlayerFromSteamid64(steamid); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { if (!caller!.CanTarget(player)) @@ -196,36 +195,36 @@ public void OnAddBanCommand(CCSPlayerController? caller, CommandInfo command) { player!.PrintToCenter(_localizer!["sa_player_ban_message_perm", reason, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_ban_message_perm", callerName, player.PlayerName, reason]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } } else { - if (!player.IsBot && !player.IsHLTV) + if (player is { IsBot: false, IsHLTV: false }) using (new WithTemporaryCulture(player.GetLanguage())) { player!.PrintToCenter(_localizer!["sa_player_ban_message_time", reason, time, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_ban_message_time", callerName, player.PlayerName, reason, time]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -241,11 +240,8 @@ public void OnAddBanCommand(CCSPlayerController? caller, CommandInfo command) await _banManager.AddBanBySteamid(steamid, adminInfo, reason, time); }); - if (command != null) - { - Helper.LogCommand(caller, command); - Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - } + Helper.LogCommand(caller, command); + Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); //Helper.SendDiscordPenaltyMessage(caller, player, reason, time, Helper.PenaltyType.Ban, _discordWebhookClientPenalty, _localizer); command?.ReplyToCommand($"Banned player with steamid {steamid}."); @@ -257,15 +253,15 @@ public void OnAddBanCommand(CCSPlayerController? caller, CommandInfo command) public void OnBanIp(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; if (command.ArgCount < 2) return; if (string.IsNullOrEmpty(command.GetArg(1))) return; - string ipAddress = command.GetArg(1); + var ipAddress = command.GetArg(1); - if (!Helper.IsValidIP(ipAddress)) + if (!Helper.IsValidIp(ipAddress)) { command.ReplyToCommand($"Invalid IP address."); return; @@ -273,24 +269,24 @@ public void OnBanIp(CCSPlayerController? caller, CommandInfo command) Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - string reason = _localizer?["sa_unknown"] ?? "Unknown"; + var reason = _localizer?["sa_unknown"] ?? "Unknown"; - PlayerInfo adminInfo = new PlayerInfo + var adminInfo = new PlayerInfo { SteamId = caller?.SteamID.ToString(), Name = caller?.PlayerName, IpAddress = caller?.IpAddress?.Split(":")[0] }; - int.TryParse(command.GetArg(2), out int time); + int.TryParse(command.GetArg(2), out var time); if (command.ArgCount >= 3 && command.GetArg(3).Length > 0) reason = command.GetArg(3); - List matches = Helper.GetPlayerFromIp(ipAddress); + var matches = Helper.GetPlayerFromIp(ipAddress); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { if (!caller!.CanTarget(player)) @@ -303,21 +299,21 @@ public void OnBanIp(CCSPlayerController? caller, CommandInfo command) if (time == 0) { - if (!player.IsBot && !player.IsHLTV) + if (player is { IsBot: false, IsHLTV: false }) using (new WithTemporaryCulture(player.GetLanguage())) { player!.PrintToCenter(_localizer!["sa_player_ban_message_perm", reason, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_ban_message_perm", callerName, player.PlayerName, reason]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -329,15 +325,15 @@ public void OnBanIp(CCSPlayerController? caller, CommandInfo command) { player!.PrintToCenter(_localizer!["sa_player_ban_message_time", reason, time, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_ban_message_time", callerName, player.PlayerName, reason, time]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -360,11 +356,8 @@ public void OnBanIp(CCSPlayerController? caller, CommandInfo command) await _banManager.AddBanByIp(ipAddress, adminInfo, reason, time); }); - if (command != null) - { - Helper.LogCommand(caller, command); - Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - } + Helper.LogCommand(caller, command); + Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); command?.ReplyToCommand($"Banned player with IP address {ipAddress}."); } @@ -376,8 +369,7 @@ public void OnUnbanCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller?.PlayerName ?? "Console"; - string callerSteamId = caller?.SteamID.ToString() ?? "Console"; + var callerSteamId = caller?.SteamID.ToString() ?? "Console"; if (command.GetArg(1).Length <= 1) { @@ -385,8 +377,8 @@ public void OnUnbanCommand(CCSPlayerController? caller, CommandInfo command) return; } - string pattern = command.GetArg(1); - string reason = command.GetArg(2); + var pattern = command.GetArg(1); + var reason = command.GetArg(2); BanManager _banManager = new(_database, Config); Task.Run(async () => await _banManager.UnbanPlayer(pattern, callerSteamId, reason)); diff --git a/Commands/basechat.cs b/Commands/basechat.cs index b347df9..88216fc 100644 --- a/Commands/basechat.cs +++ b/Commands/basechat.cs @@ -18,21 +18,22 @@ public partial class CS2_SimpleAdmin public void OnAdminToAdminSayCommand(CCSPlayerController? caller, CommandInfo command) { if (caller == null || !caller.IsValid || command.GetCommandString[command.GetCommandString.IndexOf(' ')..].Length == 0) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller.PlayerName; Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, command); - byte[] utf8BytesString = Encoding.UTF8.GetBytes(command.GetCommandString[command.GetCommandString.IndexOf(' ')..]); - string utf8String = Encoding.UTF8.GetString(utf8BytesString); + var utf8BytesString = Encoding.UTF8.GetBytes(command.GetCommandString[command.GetCommandString.IndexOf(' ')..]); + var utf8String = Encoding.UTF8.GetString(utf8BytesString); - foreach (CCSPlayerController _player in Helper.GetValidPlayers().Where(p => AdminManager.PlayerHasPermissions(p, "@css/chat"))) + foreach (var player in Helper.GetValidPlayers() + .Where(p => AdminManager.PlayerHasPermissions(p, "@css/chat"))) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(player.GetLanguage())) { StringBuilder sb = new(); sb.Append(_localizer!["sa_adminchat_template_admin", caller == null ? "Console" : caller.PlayerName, utf8String]); - _player.PrintToChat(sb.ToString()); + player.PrintToChat(sb.ToString()); } } } @@ -44,20 +45,20 @@ public void OnAdminSayCommand(CCSPlayerController? caller, CommandInfo command) { if (command.GetCommandString[command.GetCommandString.IndexOf(' ')..].Length == 0) return; - string callerName = caller == null ? "Console" : caller.PlayerName; - byte[] utf8BytesString = Encoding.UTF8.GetBytes(command.GetCommandString[command.GetCommandString.IndexOf(' ')..]); - string utf8String = Encoding.UTF8.GetString(utf8BytesString); + var callerName = caller == null ? "Console" : caller.PlayerName; + var utf8BytesString = Encoding.UTF8.GetBytes(command.GetCommandString[command.GetCommandString.IndexOf(' ')..]); + var utf8String = Encoding.UTF8.GetString(utf8BytesString); Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, command); - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var player in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(player.GetLanguage())) { StringBuilder sb = new(); sb.Append(_localizer!["sa_adminsay_prefix", utf8String]); - _player.PrintToChat(sb.ToString()); + player.PrintToChat(sb.ToString()); } } } @@ -67,26 +68,26 @@ public void OnAdminSayCommand(CCSPlayerController? caller, CommandInfo command) [RequiresPermissions("@css/chat")] public void OnAdminPrivateSayCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); //Helper.LogCommand(caller, command); - int range = command.GetArg(0).Length + command.GetArg(1).Length + 2; - string message = command.GetCommandString[range..]; + var range = command.GetArg(0).Length + command.GetArg(1).Length + 2; + var message = command.GetCommandString[range..]; - byte[] utf8BytesString = Encoding.UTF8.GetBytes(message); - string utf8String = Encoding.UTF8.GetString(utf8BytesString); + var utf8BytesString = Encoding.UTF8.GetBytes(message); + var utf8String = Encoding.UTF8.GetString(utf8BytesString); playersToTarget.ForEach(player => { - player.PrintToChat(StringExtensions.ReplaceColorTags($"({callerName}) {utf8String}")); + player.PrintToChat($"({callerName}) {utf8String}".ReplaceColorTags()); }); - command.ReplyToCommand(StringExtensions.ReplaceColorTags($" Private message sent!")); + command.ReplyToCommand($" Private message sent!".ReplaceColorTags()); } [ConsoleCommand("css_csay", "Say to all players (in center).")] @@ -94,14 +95,14 @@ public void OnAdminPrivateSayCommand(CCSPlayerController? caller, CommandInfo co [RequiresPermissions("@css/chat")] public void OnAdminCenterSayCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - byte[] utf8BytesString = Encoding.UTF8.GetBytes(command.GetCommandString[command.GetCommandString.IndexOf(' ')..]); - string utf8String = Encoding.UTF8.GetString(utf8BytesString); + var callerName = caller == null ? "Console" : caller.PlayerName; + var utf8BytesString = Encoding.UTF8.GetBytes(command.GetCommandString[command.GetCommandString.IndexOf(' ')..]); + var utf8String = Encoding.UTF8.GetString(utf8BytesString); Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, command); - Helper.PrintToCenterAll(StringExtensions.ReplaceColorTags(utf8String)); + Helper.PrintToCenterAll(utf8String.ReplaceColorTags()); } [ConsoleCommand("css_hsay", "Say to all players (in hud).")] @@ -109,16 +110,16 @@ public void OnAdminCenterSayCommand(CCSPlayerController? caller, CommandInfo com [RequiresPermissions("@css/chat")] public void OnAdminHudSayCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - byte[] utf8BytesString = Encoding.UTF8.GetBytes(command.GetCommandString[command.GetCommandString.IndexOf(' ')..]); - string utf8String = Encoding.UTF8.GetString(utf8BytesString); + var callerName = caller == null ? "Console" : caller.PlayerName; + var utf8BytesString = Encoding.UTF8.GetBytes(command.GetCommandString[command.GetCommandString.IndexOf(' ')..]); + var utf8String = Encoding.UTF8.GetString(utf8BytesString); Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, command); VirtualFunctions.ClientPrintAll( HudDestination.Alert, - StringExtensions.ReplaceColorTags(utf8String), + utf8String.ReplaceColorTags(), 0, 0, 0, 0); } } diff --git a/Commands/basecommands.cs b/Commands/basecommands.cs index 1f2c3b1..f18f45d 100644 --- a/Commands/basecommands.cs +++ b/Commands/basecommands.cs @@ -26,24 +26,24 @@ public void OnSaUpgradeCommand(CCSPlayerController? caller, CommandInfo command) { try { - using var connection = await _database.GetConnectionAsync(); + await using var connection = await _database.GetConnectionAsync(); var commandText = "ALTER TABLE `sa_mutes` CHANGE `type` `type` ENUM('GAG','MUTE', 'SILENCE', '') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'GAG';"; - using var commandSql = connection.CreateCommand(); + await using var commandSql = connection.CreateCommand(); commandSql.CommandText = commandText; await commandSql.ExecuteNonQueryAsync(); commandText = "ALTER TABLE `sa_servers` MODIFY COLUMN `hostname` varchar(128);"; - using var commandSql1 = connection.CreateCommand(); + await using var commandSql1 = connection.CreateCommand(); commandSql1.CommandText = commandText; await commandSql1.ExecuteNonQueryAsync(); commandText = "ALTER TABLE `sa_bans` MODIFY `ends` TIMESTAMP NULL DEFAULT NULL;"; - using var commandSql2 = connection.CreateCommand(); + await using var commandSql2 = connection.CreateCommand(); commandSql2.CommandText = commandText; await commandSql2.ExecuteNonQueryAsync(); - Server.NextFrame(() => + await Server.NextFrameAsync(() => { command.ReplyToCommand($"Successfully updated the database - {ModuleVersion}"); }); @@ -83,18 +83,11 @@ public void OnAdminHelpCommand(CCSPlayerController? caller, CommandInfo command) } } */ - string[] lines = File.ReadAllLines(ModuleDirectory + "/admin_help.txt"); + var lines = File.ReadAllLines(ModuleDirectory + "/admin_help.txt"); - foreach (string line in lines) + foreach (var line in lines) { - if (string.IsNullOrWhiteSpace(line)) - { - command.ReplyToCommand(" "); - } - else - { - command.ReplyToCommand(StringExtensions.ReplaceColorTags(line)); - } + command.ReplyToCommand(string.IsNullOrWhiteSpace(line) ? " " : line.ReplaceColorTags()); } } @@ -104,9 +97,9 @@ public void OnAdminHelpCommand(CCSPlayerController? caller, CommandInfo command) public void OnAddAdminCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; - if (!Helper.IsValidSteamID64(command.GetArg(1))) + if (!Helper.IsValidSteamId64(command.GetArg(1))) { command.ReplyToCommand($"Invalid SteamID64."); return; @@ -116,19 +109,20 @@ public void OnAddAdminCommand(CCSPlayerController? caller, CommandInfo command) command.ReplyToCommand($"Invalid player name."); return; } - if (!command.GetArg(3).Contains("@") && !command.GetArg(3).Contains("#")) + if (!command.GetArg(3).Contains('@') && !command.GetArg(3).Contains('#')) { command.ReplyToCommand($"Invalid flag or group."); return; } - string steamid = command.GetArg(1); - string name = command.GetArg(2); - string flags = command.GetArg(3); - bool globalAdmin = command.GetArg(4).ToLower().Equals("-g") || command.GetArg(5).ToLower().Equals("-g") || command.GetArg(6).ToLower().Equals("-g"); - int immunity = 0; + var steamid = command.GetArg(1); + var name = command.GetArg(2); + var flags = command.GetArg(3); + var globalAdmin = command.GetArg(4).ToLower().Equals("-g") || command.GetArg(5).ToLower().Equals("-g") || + command.GetArg(6).ToLower().Equals("-g"); + var immunity = 0; int.TryParse(command.GetArg(4), out immunity); - int time = 0; + var time = 0; int.TryParse(command.GetArg(5), out time); AddAdmin(caller, steamid, name, flags, immunity, time, globalAdmin, command); @@ -139,14 +133,14 @@ public static void AddAdmin(CCSPlayerController? caller, string steamid, string if (_database == null) return; AdminSQLManager _adminManager = new(_database); - List flagsList = flags.Split(',').Select(flag => flag.Trim()).ToList(); + var flagsList = flags.Split(',').Select(flag => flag.Trim()).ToList(); _ = _adminManager.AddAdminBySteamId(steamid, name, flagsList, immunity, time, globalAdmin); if (command != null) Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, $"css_addadmin {steamid} {name} {flags} {immunity} {time}"); - string msg = $"Added '{flags}' flags to '{name}' ({steamid})"; + var msg = $"Added '{flags}' flags to '{name}' ({steamid})"; if (command != null) command.ReplyToCommand(msg); else if (caller != null && caller.IsValid) @@ -161,16 +155,16 @@ public static void AddAdmin(CCSPlayerController? caller, string steamid, string public void OnDelAdminCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; - if (!Helper.IsValidSteamID64(command.GetArg(1))) + if (!Helper.IsValidSteamId64(command.GetArg(1))) { command.ReplyToCommand($"Invalid SteamID64."); return; } - string steamid = command.GetArg(1); - bool globalDelete = command.GetArg(2).ToLower().Equals("-g"); + var steamid = command.GetArg(1); + var globalDelete = command.GetArg(2).ToLower().Equals("-g"); RemoveAdmin(caller, steamid, globalDelete, command); } @@ -183,23 +177,22 @@ public void RemoveAdmin(CCSPlayerController? caller, string steamid, bool global AddTimer(2, () => { - if (!string.IsNullOrEmpty(steamid) && SteamID.TryParse(steamid, out var steamId) && steamId != null) + if (string.IsNullOrEmpty(steamid) || !SteamID.TryParse(steamid, out var steamId) || + steamId == null) return; + if (AdminSQLManager._adminCache.ContainsKey(steamId)) { - if (AdminSQLManager._adminCache.ContainsKey(steamId)) - { - AdminSQLManager._adminCache.TryRemove(steamId, out _); - } - - AdminManager.ClearPlayerPermissions(steamId); - AdminManager.RemovePlayerAdminData(steamId); + AdminSQLManager._adminCache.TryRemove(steamId, out _); } + + AdminManager.ClearPlayerPermissions(steamId); + AdminManager.RemovePlayerAdminData(steamId); }, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); if (command != null) Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, $"css_deladmin {steamid}"); - string msg = $"Removed flags from '{steamid}'"; + var msg = $"Removed flags from '{steamid}'"; if (command != null) command.ReplyToCommand(msg); else if (caller != null && caller.IsValid) @@ -221,15 +214,15 @@ public void OnAddGroup(CCSPlayerController? caller, CommandInfo command) return; } - if (!command.GetArg(2).StartsWith("@") && !command.GetArg(2).StartsWith("#")) + if (!command.GetArg(2).StartsWith($"@") && !command.GetArg(2).StartsWith($"#")) { command.ReplyToCommand($"Invalid flag or group."); return; } - string groupName = command.GetArg(1); - string flags = command.GetArg(2); - int immunity = 0; + var groupName = command.GetArg(1); + var flags = command.GetArg(2); + var immunity = 0; int.TryParse(command.GetArg(3), out immunity); AddGroup(caller, groupName, flags, immunity, command); @@ -240,14 +233,14 @@ public static void AddGroup(CCSPlayerController? caller, string name, string fla if (_database == null) return; AdminSQLManager _adminManager = new(_database); - List flagsList = flags.Split(',').Select(flag => flag.Trim()).ToList(); + var flagsList = flags.Split(',').Select(flag => flag.Trim()).ToList(); _ = _adminManager.AddGroup(name, flagsList, immunity); if (command != null) Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, $"css_addgroup {name} {flags} {immunity}"); - string msg = $"Created group '{name}' with flags '{flags}'"; + var msg = $"Created group '{name}' with flags '{flags}'"; if (command != null) command.ReplyToCommand(msg); else if (caller != null && caller.IsValid) @@ -263,18 +256,18 @@ public void OnDelGroupCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - if (!command.GetArg(1).StartsWith("#")) + if (!command.GetArg(1).StartsWith($"#")) { command.ReplyToCommand($"Group name must start with #."); return; } - string groupName = command.GetArg(1); + var groupName = command.GetArg(1); RemoveGroup(caller, groupName, command); } - public void RemoveGroup(CCSPlayerController? caller, string name, CommandInfo? command = null) + private void RemoveGroup(CCSPlayerController? caller, string name, CommandInfo? command = null) { if (_database == null) return; AdminSQLManager _adminManager = new(_database); @@ -289,7 +282,7 @@ public void RemoveGroup(CCSPlayerController? caller, string name, CommandInfo? c Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, $"css_delgroup {name}"); - string msg = $"Removed group '{name}'"; + var msg = $"Removed group '{name}'"; if (command != null) command.ReplyToCommand(msg); else if (caller != null && caller.IsValid) @@ -314,13 +307,13 @@ public void ReloadAdmins(CCSPlayerController? caller) { if (_database == null) return; - foreach (SteamID steamId in AdminSQLManager._adminCache.Keys.ToList()) + for (var index = 0; index < AdminSQLManager._adminCache.Keys.ToList().Count; index++) { - if (AdminSQLManager._adminCache.TryRemove(steamId, out _)) - { - AdminManager.ClearPlayerPermissions(steamId); - AdminManager.RemovePlayerAdminData(steamId); - } + var steamId = AdminSQLManager._adminCache.Keys.ToList()[index]; + if (!AdminSQLManager._adminCache.TryRemove(steamId, out _)) continue; + + AdminManager.ClearPlayerPermissions(steamId); + AdminManager.RemovePlayerAdminData(steamId); } AdminSQLManager _adminManager = new(_database); @@ -376,15 +369,15 @@ public void OnHideCommand(CCSPlayerController? caller, CommandInfo command) public void OnWhoCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; Helper.LogCommand(caller, command); //Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); Database database = new(dbConnectionString); BanManager _banManager = new(database, Config); @@ -393,53 +386,51 @@ public void OnWhoCommand(CCSPlayerController? caller, CommandInfo command) playersToTarget.ForEach(player => { if (!player.UserId.HasValue) return; - if (caller!.CanTarget(player)) + if (!caller!.CanTarget(player)) return; + PlayerInfo playerInfo = new() { - PlayerInfo playerInfo = new() - { - UserId = player.UserId.Value, - Index = (int)player.Index, - SteamId = player?.SteamID.ToString(), - Name = player?.PlayerName, - IpAddress = player?.IpAddress?.Split(":")[0] - }; - - Task.Run(async () => + UserId = player.UserId.Value, + Index = (int)player.Index, + SteamId = player?.SteamID.ToString(), + Name = player?.PlayerName, + IpAddress = player?.IpAddress?.Split(":")[0] + }; + + Task.Run(async () => + { + var totalBans = 0; + var totalMutes = 0; + + totalBans = await _banManager.GetPlayerBans(playerInfo); + totalMutes = await _muteManager.GetPlayerMutes(playerInfo.SteamId!); + + await Server.NextFrameAsync(() => { - int totalBans = 0; - int totalMutes = 0; + Action printMethod = caller == null ? Server.PrintToConsole : caller.PrintToConsole; - totalBans = await _banManager.GetPlayerBans(playerInfo); - totalMutes = await _muteManager.GetPlayerMutes(playerInfo.SteamId!); + printMethod($"--------- INFO ABOUT \"{playerInfo.Name}\" ---------"); - Server.NextFrame(() => + printMethod($"• Clan: \"{player!.Clan}\" Name: \"{playerInfo.Name}\""); + printMethod($"• UserID: \"{playerInfo.UserId}\""); + if (playerInfo.SteamId != null) + printMethod($"• SteamID64: \"{playerInfo.SteamId}\""); + if (player.SteamID.ToString().Length == 17) + { + printMethod($"• SteamID2: \"{player.SteamID}\""); + printMethod($"• Community link: \"{new SteamID(player.SteamID).ToCommunityUrl()}\""); + } + if (playerInfo.IpAddress != null) + printMethod($"• IP Address: \"{playerInfo.IpAddress}\""); + printMethod($"• Ping: \"{player.Ping}\""); + if (player.SteamID.ToString().Length == 17) { - Action printMethod = caller == null ? Server.PrintToConsole : caller.PrintToConsole; - - printMethod($"--------- INFO ABOUT \"{playerInfo.Name}\" ---------"); - - printMethod($"• Clan: \"{player!.Clan}\" Name: \"{playerInfo.Name}\""); - printMethod($"• UserID: \"{playerInfo.UserId}\""); - if (playerInfo.SteamId != null) - printMethod($"• SteamID64: \"{playerInfo.SteamId}\""); - if (player.SteamID.ToString().Length == 17) - { - printMethod($"• SteamID2: \"{player.SteamID}\""); - printMethod($"• Community link: \"{new SteamID(player.SteamID).ToCommunityUrl()}\""); - } - if (playerInfo.IpAddress != null) - printMethod($"• IP Address: \"{playerInfo.IpAddress}\""); - printMethod($"• Ping: \"{player.Ping}\""); - if (player.SteamID.ToString().Length == 17) - { - printMethod($"• Total Bans: \"{totalBans}\""); - printMethod($"• Total Mutes: \"{totalMutes}\""); - } - - printMethod($"--------- END INFO ABOUT \"{player.PlayerName}\" ---------"); - }); + printMethod($"• Total Bans: \"{totalBans}\""); + printMethod($"• Total Mutes: \"{totalMutes}\""); + } + + printMethod($"--------- END INFO ABOUT \"{player.PlayerName}\" ---------"); }); - } + }); }); } @@ -448,14 +439,15 @@ public void OnWhoCommand(CCSPlayerController? caller, CommandInfo command) [RequiresPermissions("@css/generic")] public void OnPlayersCommand(CCSPlayerController? caller, CommandInfo command) { - List playersToTarget = Helper.GetValidPlayers(); + var playersToTarget = Helper.GetValidPlayers(); if (caller != null) { caller!.PrintToConsole($"--------- PLAYER LIST ---------"); playersToTarget.ForEach(player => { - caller!.PrintToConsole($"• [#{player.UserId}] \"{player.PlayerName}\" (IP Address: \"{player.IpAddress?.Split(":")[0]}\" SteamID64: \"{player.SteamID}\")"); + caller!.PrintToConsole( + $"• [#{player.UserId}] \"{player.PlayerName}\" (IP Address: \"{player.IpAddress?.Split(":")[0]}\" SteamID64: \"{player.SteamID}\")"); }); caller!.PrintToConsole($"--------- END PLAYER LIST ---------"); } @@ -475,15 +467,16 @@ public void OnPlayersCommand(CCSPlayerController? caller, CommandInfo command) [CommandHelper(minArgs: 1, usage: "<#userid or name> [reason]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnKickCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - string reason = _localizer?["sa_unknown"] ?? "Unknown"; + var callerName = caller == null ? "Console" : caller.PlayerName; + var reason = _localizer?["sa_unknown"] ?? "Unknown"; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players + .Where(player => player is { IsValid: true, IsHLTV: false }).ToList(); if (playersToTarget.Count > 1 && Config.DisableDangerousCommands || playersToTarget.Count == 0) { @@ -505,10 +498,10 @@ public void OnKickCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void Kick(CCSPlayerController? caller, CCSPlayerController player, string reason = "Unknown", string? callerName = null, CommandInfo? command = null) + public void Kick(CCSPlayerController? caller, CCSPlayerController? player, string reason = "Unknown", string? callerName = null, CommandInfo? command = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; - if (player.PawnIsAlive) + if (player != null && player.PawnIsAlive) { player.Pawn.Value!.Freeze(); } @@ -517,36 +510,35 @@ public void Kick(CCSPlayerController? caller, CCSPlayerController player, string if (command != null) Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - Helper.LogCommand(caller, $"css_kick {player.PlayerName} {reason}"); + Helper.LogCommand(caller, $"css_kick {player?.PlayerName} {reason}"); if (string.IsNullOrEmpty(reason) == false) { - if (!player.IsBot && !player.IsHLTV) + if (player != null && !player.IsBot && !player.IsHLTV) using (new WithTemporaryCulture(player.GetLanguage())) { player.PrintToCenter(_localizer!["sa_player_kick_message", reason, caller == null ? "Console" : caller.PlayerName]); } - if (player.UserId.HasValue) + if (player != null && player.UserId.HasValue) AddTimer(Config.KickTime, () => Helper.KickPlayer(player.UserId.Value, reason), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); } else { - if (player.UserId.HasValue) + if (player != null && player.UserId.HasValue) AddTimer(Config.KickTime, () => Helper.KickPlayer(player.UserId.Value), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); } - if (caller == null || caller != null && caller.UserId != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && (caller.UserId == null || silentPlayers.Contains(caller.Slot))) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_kick_message", callerName, player.PlayerName, reason]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_kick_message", callerName, player?.PlayerName ?? string.Empty, reason]); + controller.PrintToChat(sb.ToString()); } } } @@ -557,27 +549,22 @@ public void Kick(CCSPlayerController? caller, CCSPlayerController player, string [CommandHelper(minArgs: 1, usage: "", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnMapCommand(CCSPlayerController? caller, CommandInfo command) { - string? map = command.GetCommandString.Split(" ")[1]; + var map = command.GetCommandString.Split(" ")[1]; ChangeMap(caller, map, command); } public void ChangeMap(CCSPlayerController? caller, string map, CommandInfo? command = null) { - string callerName = caller == null ? "Console" : caller.PlayerName; - string _command = string.Empty; + var callerName = caller == null ? "Console" : caller.PlayerName; + string _command; map = map.ToLower(); if (map.StartsWith("ws:")) { - if (long.TryParse(map.Replace("ws:", ""), out long mapId)) - { - _command = $"host_workshop_map {mapId}"; - } - else - { - _command = $"ds_workshop_changelevel {map.Replace("ws:", "")}"; - } + _command = long.TryParse(map.Replace("ws:", ""), out var mapId) + ? $"host_workshop_map {mapId}" + : $"ds_workshop_changelevel {map.Replace("ws:", "")}"; AddTimer(3.0f, () => { @@ -588,7 +575,7 @@ public void ChangeMap(CCSPlayerController? caller, string map, CommandInfo? comm { if (!Server.IsMapValid(map)) { - string msg = $"Map {map} not found."; + var msg = $"Map {map} not found."; if (command != null) command.ReplyToCommand(msg); else if (caller != null && caller.IsValid) @@ -604,24 +591,22 @@ public void ChangeMap(CCSPlayerController? caller, string map, CommandInfo? comm }, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var player in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(player.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_changemap_message", caller == null ? "Console" : caller.PlayerName, map]); - _player.PrintToChat(sb.ToString()); + player.PrintToChat(sb.ToString()); } } } - if (command != null) - { - Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - Helper.LogCommand(caller, command); - } + if (command == null) return; + Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); + Helper.LogCommand(caller, command); } [ConsoleCommand("css_changewsmap", "Change workshop map.")] @@ -631,35 +616,28 @@ public void ChangeMap(CCSPlayerController? caller, string map, CommandInfo? comm [RequiresPermissions("@css/changemap")] public void OnWorkshopMapCommand(CCSPlayerController? caller, CommandInfo command) { - string? map = command.GetArg(1); + var map = command.GetArg(1); ChangeWorkshopMap(caller, map, command); } public void ChangeWorkshopMap(CCSPlayerController? caller, string map, CommandInfo? command = null) { - string callerName = caller == null ? "Console" : caller.PlayerName; - string _command = string.Empty; + var callerName = caller == null ? "Console" : caller.PlayerName; + string _command; map = map.ToLower(); - if (long.TryParse(map, out long mapId)) - { - _command = $"host_workshop_map {mapId}"; - } - else - { - _command = $"ds_workshop_changelevel {map}"; - } + _command = long.TryParse(map, out var mapId) ? $"host_workshop_map {mapId}" : $"ds_workshop_changelevel {map}"; - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var player in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(player.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_changemap_message", caller == null ? "Console" : caller.PlayerName, map]); - _player.PrintToChat(sb.ToString()); + player.PrintToChat(sb.ToString()); } } } @@ -669,11 +647,9 @@ public void ChangeWorkshopMap(CCSPlayerController? caller, string map, CommandIn Server.ExecuteCommand(_command); }, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); - if (command != null) - { - Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - Helper.LogCommand(caller, command); - } + if (command == null) return; + Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); + Helper.LogCommand(caller, command); } [ConsoleCommand("css_cvar", "Change a cvar.")] @@ -682,7 +658,7 @@ public void ChangeWorkshopMap(CCSPlayerController? caller, string map, CommandIn public void OnCvarCommand(CCSPlayerController? caller, CommandInfo command) { var cvar = ConVar.Find(command.GetArg(1)); - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; if (cvar == null) { @@ -712,7 +688,7 @@ public void OnCvarCommand(CCSPlayerController? caller, CommandInfo command) [RequiresPermissions("@css/rcon")] public void OnRconCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, command); diff --git a/Commands/basecomms.cs b/Commands/basecomms.cs index f3c3816..fdfc25b 100644 --- a/Commands/basecomms.cs +++ b/Commands/basecomms.cs @@ -17,14 +17,14 @@ public partial class CS2_SimpleAdmin public void OnGagCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; - int time = 0; - string reason = _localizer?["sa_unknown"] ?? "Unknown"; + var time = 0; + var reason = _localizer?["sa_unknown"] ?? "Unknown"; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); if (playersToTarget.Count > 1 && Config.DisableDangerousCommands || playersToTarget.Count == 0) { @@ -37,7 +37,7 @@ public void OnGagCommand(CCSPlayerController? caller, CommandInfo command) reason = command.GetArg(3); MuteManager _muteManager = new(_database); - PlayerPenaltyManager playerPenaltyManager = new PlayerPenaltyManager(); + var playerPenaltyManager = new PlayerPenaltyManager(); playersToTarget.ForEach(player => { @@ -48,21 +48,21 @@ public void OnGagCommand(CCSPlayerController? caller, CommandInfo command) }); } - internal void Gag(CCSPlayerController? caller, CCSPlayerController player, int time, string reason, string? callerName = null, MuteManager? muteManager = null, PlayerPenaltyManager? playerPenaltyManager = null, CommandInfo? command = null) + internal void Gag(CCSPlayerController? caller, CCSPlayerController? player, int time, string reason, string? callerName = null, MuteManager? muteManager = null, PlayerPenaltyManager? playerPenaltyManager = null, CommandInfo? command = null) { if (_database == null) return; callerName ??= caller == null ? "Console" : caller.PlayerName; muteManager ??= new MuteManager(_database); playerPenaltyManager ??= new PlayerPenaltyManager(); - PlayerInfo playerInfo = new PlayerInfo + var playerInfo = new PlayerInfo { SteamId = player?.SteamID.ToString(), Name = player?.PlayerName, IpAddress = player?.IpAddress?.Split(":")[0] }; - PlayerInfo adminInfo = new PlayerInfo + var adminInfo = new PlayerInfo { SteamId = caller?.SteamID.ToString(), Name = caller?.PlayerName, @@ -88,15 +88,15 @@ internal void Gag(CCSPlayerController? caller, CCSPlayerController player, int t } } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_gag_message_perm", callerName, player.PlayerName, reason]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -111,26 +111,24 @@ internal void Gag(CCSPlayerController? caller, CCSPlayerController player, int t } } - if (caller == null || caller != null && caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_gag_message_time", callerName, player.PlayerName, reason, time]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } } - if (command != null) - { - Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - Helper.SendDiscordPenaltyMessage(caller, player, reason, time, Helper.PenaltyType.Gag, _discordWebhookClientPenalty, _localizer); - Helper.LogCommand(caller, command); - } + if (command == null) return; + Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); + Helper.SendDiscordPenaltyMessage(caller, player, reason, time, Helper.PenaltyType.Gag, _discordWebhookClientPenalty, _localizer); + Helper.LogCommand(caller, command); } [ConsoleCommand("css_addgag")] @@ -139,43 +137,43 @@ internal void Gag(CCSPlayerController? caller, CCSPlayerController player, int t public void OnAddGagCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; if (command.ArgCount < 2) return; if (string.IsNullOrEmpty(command.GetArg(1))) return; - string steamid = command.GetArg(1); + var steamid = command.GetArg(1); - if (!Helper.IsValidSteamID64(steamid)) + if (!Helper.IsValidSteamId64(steamid)) { command.ReplyToCommand($"Invalid SteamID64."); return; } - int time = 0; - string reason = _localizer?["sa_unknown"] ?? "Unknown"; + var time = 0; + var reason = _localizer?["sa_unknown"] ?? "Unknown"; MuteManager _muteManager = new(_database); - PlayerPenaltyManager playerPenaltyManager = new PlayerPenaltyManager(); + var playerPenaltyManager = new PlayerPenaltyManager(); int.TryParse(command.GetArg(2), out time); if (command.ArgCount >= 3 && command.GetArg(3).Length > 0) reason = command.GetArg(3); - PlayerInfo adminInfo = new PlayerInfo + var adminInfo = new PlayerInfo { SteamId = caller?.SteamID.ToString(), Name = caller?.PlayerName, IpAddress = caller?.IpAddress?.Split(":")[0] }; - List matches = Helper.GetPlayerFromSteamid64(steamid); + var matches = Helper.GetPlayerFromSteamid64(steamid); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { if (!caller!.CanTarget(player)) @@ -192,36 +190,36 @@ public void OnAddGagCommand(CCSPlayerController? caller, CommandInfo command) player!.PrintToCenter(_localizer!["sa_player_gag_message_perm", reason, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_gag_message_perm", callerName, player.PlayerName, reason]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } } else { - if (!player.IsBot && !player.IsHLTV) + if (player is { IsBot: false, IsHLTV: false }) using (new WithTemporaryCulture(player.GetLanguage())) { player!.PrintToCenter(_localizer!["sa_player_gag_message_time", reason, time, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_gag_message_time", callerName, player.PlayerName, reason, time]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -241,11 +239,8 @@ public void OnAddGagCommand(CCSPlayerController? caller, CommandInfo command) await _muteManager.AddMuteBySteamid(steamid, adminInfo, reason, time, 0); }); - if (command != null) - { - Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - Helper.LogCommand(caller, command); - } + Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); + Helper.LogCommand(caller, command); command?.ReplyToCommand($"Gagged player with steamid {steamid}."); } @@ -256,12 +251,12 @@ public void OnAddGagCommand(CCSPlayerController? caller, CommandInfo command) public void OnUngagCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; - string callerSteamId = caller?.SteamID.ToString() ?? "Console"; + var callerName = caller == null ? "Console" : caller.PlayerName; + var callerSteamId = caller?.SteamID.ToString() ?? "Console"; - string foundPlayerName = string.Empty; - string foundPlayerSteamId64 = string.Empty; - string reason = command.GetArg(2); + var foundPlayerName = string.Empty; + var foundPlayerSteamId64 = string.Empty; + var reason = command.GetArg(2); if (command.GetArg(1).Length <= 1) { @@ -272,19 +267,19 @@ public void OnUngagCommand(CCSPlayerController? caller, CommandInfo command) Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, command); - bool found = false; + var found = false; - string pattern = command.GetArg(1); + var pattern = command.GetArg(1); MuteManager _muteManager = new(_database); - PlayerPenaltyManager playerPenaltyManager = new PlayerPenaltyManager(); + var playerPenaltyManager = new PlayerPenaltyManager(); - if (Helper.IsValidSteamID64(pattern)) + if (Helper.IsValidSteamId64(pattern)) { - List matches = Helper.GetPlayerFromSteamid64(pattern); + var matches = Helper.GetPlayerFromSteamid64(pattern); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { PlayerPenaltyManager.RemovePenaltiesByType(player!.Slot, PenaltyType.Gag); @@ -300,10 +295,10 @@ public void OnUngagCommand(CCSPlayerController? caller, CommandInfo command) } else { - List matches = Helper.GetPlayerFromName(pattern); + var matches = Helper.GetPlayerFromName(pattern); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { PlayerPenaltyManager.RemovePenaltiesByType(player!.Slot, PenaltyType.Gag); @@ -368,14 +363,14 @@ public void OnUngagCommand(CCSPlayerController? caller, CommandInfo command) public void OnMuteCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; - int time = 0; - string reason = _localizer?["sa_unknown"] ?? "Unknown"; + var time = 0; + var reason = _localizer?["sa_unknown"] ?? "Unknown"; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); if (playersToTarget.Count > 1 && Config.DisableDangerousCommands || playersToTarget.Count == 0) { @@ -388,7 +383,7 @@ public void OnMuteCommand(CCSPlayerController? caller, CommandInfo command) reason = command.GetArg(3); MuteManager _muteManager = new(_database); - PlayerPenaltyManager playerPenaltyManager = new PlayerPenaltyManager(); + var playerPenaltyManager = new PlayerPenaltyManager(); playersToTarget.ForEach(player => { @@ -399,21 +394,20 @@ public void OnMuteCommand(CCSPlayerController? caller, CommandInfo command) }); } - internal void Mute(CCSPlayerController? caller, CCSPlayerController player, int time, string reason, string? callerName = null, MuteManager? muteManager = null, PlayerPenaltyManager? playerPenaltyManager = null, CommandInfo? command = null) + internal void Mute(CCSPlayerController? caller, CCSPlayerController? player, int time, string reason, string? callerName = null, MuteManager? muteManager = null, PlayerPenaltyManager? playerPenaltyManager = null, CommandInfo? command = null) { if (_database == null) return; callerName ??= caller == null ? "Console" : caller.PlayerName; muteManager ??= new MuteManager(_database); - playerPenaltyManager ??= new PlayerPenaltyManager(); - PlayerInfo playerInfo = new PlayerInfo + var playerInfo = new PlayerInfo { SteamId = player?.SteamID.ToString(), Name = player?.PlayerName, IpAddress = player?.IpAddress?.Split(":")[0] }; - PlayerInfo adminInfo = new PlayerInfo + var adminInfo = new PlayerInfo { SteamId = caller?.SteamID.ToString(), Name = caller?.PlayerName, @@ -437,35 +431,35 @@ internal void Mute(CCSPlayerController? caller, CCSPlayerController player, int player!.PrintToCenter(_localizer!["sa_player_mute_message_perm", reason, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_mute_message_perm", callerName, player.PlayerName, reason]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } } else { - if (!player.IsBot && !player.IsHLTV) + if (player is { IsBot: false, IsHLTV: false }) using (new WithTemporaryCulture(player.GetLanguage())) { player!.PrintToCenter(_localizer!["sa_player_mute_message_time", reason, time, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_mute_message_time", callerName, player.PlayerName, reason, time]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -485,42 +479,42 @@ internal void Mute(CCSPlayerController? caller, CCSPlayerController player, int public void OnAddMuteCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; if (command.ArgCount < 2) return; if (string.IsNullOrEmpty(command.GetArg(1))) return; - string steamid = command.GetArg(1); + var steamid = command.GetArg(1); - if (!Helper.IsValidSteamID64(steamid)) + if (!Helper.IsValidSteamId64(steamid)) { command.ReplyToCommand($"Invalid SteamID64."); return; } - int time = 0; - string reason = _localizer?["sa_unknown"] ?? "Unknown"; + var time = 0; + var reason = _localizer?["sa_unknown"] ?? "Unknown"; MuteManager _muteManager = new(_database); - PlayerPenaltyManager playerPenaltyManager = new PlayerPenaltyManager(); + var playerPenaltyManager = new PlayerPenaltyManager(); int.TryParse(command.GetArg(2), out time); if (command.ArgCount >= 3 && command.GetArg(3).Length > 0) reason = command.GetArg(3); - PlayerInfo adminInfo = new PlayerInfo + var adminInfo = new PlayerInfo { SteamId = caller?.SteamID.ToString(), Name = caller?.PlayerName, IpAddress = caller?.IpAddress?.Split(":")[0] }; - List matches = Helper.GetPlayerFromSteamid64(steamid); + var matches = Helper.GetPlayerFromSteamid64(steamid); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { if (!caller!.CanTarget(player)) @@ -533,40 +527,40 @@ public void OnAddMuteCommand(CCSPlayerController? caller, CommandInfo command) if (time == 0) { - if (!player.IsBot && !player.IsHLTV) + if (player is { IsBot: false, IsHLTV: false }) using (new WithTemporaryCulture(player.GetLanguage())) { player!.PrintToCenter(_localizer!["sa_player_mute_message_perm", reason, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_mute_message_perm", callerName, player.PlayerName, reason]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } } else { - if (!player.IsBot && !player.IsHLTV) + if (player is { IsBot: false, IsHLTV: false }) using (new WithTemporaryCulture(player.GetLanguage())) { player!.PrintToCenter(_localizer!["sa_player_mute_message_time", reason, time, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_mute_message_time", callerName, player.PlayerName, reason, time]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -581,11 +575,8 @@ public void OnAddMuteCommand(CCSPlayerController? caller, CommandInfo command) await _muteManager.AddMuteBySteamid(steamid, adminInfo, reason, time, 1); }); - if (command != null) - { - Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - Helper.LogCommand(caller, command); - } + Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); + Helper.LogCommand(caller, command); command?.ReplyToCommand($"Muted player with steamid {steamid}."); } @@ -596,12 +587,12 @@ public void OnAddMuteCommand(CCSPlayerController? caller, CommandInfo command) public void OnUnmuteCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; - string callerSteamId = caller?.SteamID.ToString() ?? "Console"; + var callerName = caller == null ? "Console" : caller.PlayerName; + var callerSteamId = caller?.SteamID.ToString() ?? "Console"; - string foundPlayerName = string.Empty; - string foundPlayerSteamId64 = string.Empty; - string reason = command.GetArg(2); + var foundPlayerName = string.Empty; + var foundPlayerSteamId64 = string.Empty; + var reason = command.GetArg(2); if (command.GetArg(1).Length <= 1) { @@ -612,17 +603,17 @@ public void OnUnmuteCommand(CCSPlayerController? caller, CommandInfo command) Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, command); - string pattern = command.GetArg(1); - bool found = false; + var pattern = command.GetArg(1); + var found = false; MuteManager _muteManager = new(_database); PlayerPenaltyManager playerPenaltyManager = new(); - if (Helper.IsValidSteamID64(pattern)) + if (Helper.IsValidSteamId64(pattern)) { - List matches = Helper.GetPlayerFromSteamid64(pattern); + var matches = Helper.GetPlayerFromSteamid64(pattern); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { PlayerPenaltyManager.RemovePenaltiesByType(player!.Slot, PenaltyType.Mute); @@ -635,10 +626,10 @@ public void OnUnmuteCommand(CCSPlayerController? caller, CommandInfo command) } else { - List matches = Helper.GetPlayerFromName(pattern); + var matches = Helper.GetPlayerFromName(pattern); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { PlayerPenaltyManager.RemovePenaltiesByType(player!.Slot, PenaltyType.Mute); @@ -694,14 +685,14 @@ public void OnUnmuteCommand(CCSPlayerController? caller, CommandInfo command) public void OnSilenceCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; - int time = 0; - string reason = CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; + var time = 0; + var reason = CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player.SteamID.ToString().Length == 17 && !player.IsHLTV).ToList(); if (playersToTarget.Count > 1 && Config.DisableDangerousCommands || playersToTarget.Count == 0) { @@ -714,7 +705,7 @@ public void OnSilenceCommand(CCSPlayerController? caller, CommandInfo command) reason = command.GetArg(3); MuteManager _muteManager = new(_database); - PlayerPenaltyManager playerPenaltyManager = new PlayerPenaltyManager(); + var playerPenaltyManager = new PlayerPenaltyManager(); playersToTarget.ForEach(player => { @@ -725,21 +716,21 @@ public void OnSilenceCommand(CCSPlayerController? caller, CommandInfo command) }); } - internal void Silence(CCSPlayerController? caller, CCSPlayerController player, int time, string reason, string? callerName = null, MuteManager? muteManager = null, PlayerPenaltyManager? playerPenaltyManager = null, CommandInfo? command = null) + internal void Silence(CCSPlayerController? caller, CCSPlayerController? player, int time, string reason, string? callerName = null, MuteManager? muteManager = null, PlayerPenaltyManager? playerPenaltyManager = null, CommandInfo? command = null) { if (_database == null) return; callerName ??= caller == null ? "Console" : caller.PlayerName; muteManager ??= new MuteManager(_database); playerPenaltyManager ??= new PlayerPenaltyManager(); - PlayerInfo playerInfo = new PlayerInfo + var playerInfo = new PlayerInfo { SteamId = player?.SteamID.ToString(), Name = player?.PlayerName, IpAddress = player?.IpAddress?.Split(":")[0] }; - PlayerInfo adminInfo = new PlayerInfo + var adminInfo = new PlayerInfo { SteamId = caller?.SteamID.ToString(), Name = caller?.PlayerName, @@ -767,15 +758,15 @@ internal void Silence(CCSPlayerController? caller, CCSPlayerController player, i } } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_silence_message_perm", callerName, player.PlayerName, reason]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -790,15 +781,15 @@ internal void Silence(CCSPlayerController? caller, CCSPlayerController player, i } } - if (caller == null || caller != null && caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_silence_message_time", callerName, player.PlayerName, reason, time]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -818,42 +809,42 @@ internal void Silence(CCSPlayerController? caller, CCSPlayerController player, i public void OnAddSilenceCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; if (command.ArgCount < 2) return; if (string.IsNullOrEmpty(command.GetArg(1))) return; - string steamid = command.GetArg(1); + var steamid = command.GetArg(1); - if (!Helper.IsValidSteamID64(steamid)) + if (!Helper.IsValidSteamId64(steamid)) { command.ReplyToCommand($"Invalid SteamID64."); return; } - int time = 0; - string reason = CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; + var time = 0; + var reason = CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; MuteManager _muteManager = new(_database); - PlayerPenaltyManager playerPenaltyManager = new PlayerPenaltyManager(); + var playerPenaltyManager = new PlayerPenaltyManager(); int.TryParse(command.GetArg(2), out time); if (command.ArgCount >= 3 && command.GetArg(3).Length > 0) reason = command.GetArg(3); - PlayerInfo adminInfo = new PlayerInfo + var adminInfo = new PlayerInfo { SteamId = caller?.SteamID.ToString(), Name = caller?.PlayerName, IpAddress = caller?.IpAddress?.Split(":")[0] }; - List matches = Helper.GetPlayerFromSteamid64(steamid); + var matches = Helper.GetPlayerFromSteamid64(steamid); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { if (!caller!.CanTarget(player)) @@ -874,15 +865,15 @@ public void OnAddSilenceCommand(CCSPlayerController? caller, CommandInfo command { player!.PrintToCenter(_localizer!["sa_player_silence_message_perm", reason, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_silence_message_perm", callerName, player.PlayerName, reason]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -894,15 +885,15 @@ public void OnAddSilenceCommand(CCSPlayerController? caller, CommandInfo command { player!.PrintToCenter(_localizer!["sa_player_silence_message_time", reason, time, caller == null ? "Console" : caller.PlayerName]); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_silence_message_time", callerName, player.PlayerName, reason, time]); - _player.PrintToChat(sb.ToString()); + controller.PrintToChat(sb.ToString()); } } } @@ -916,11 +907,8 @@ public void OnAddSilenceCommand(CCSPlayerController? caller, CommandInfo command await _muteManager.AddMuteBySteamid(steamid, adminInfo, reason, time, 2); }); - if (command != null) - { - Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - Helper.LogCommand(caller, command); - } + Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); + Helper.LogCommand(caller, command); command?.ReplyToCommand($"Silenced player with steamid {steamid}."); } @@ -931,12 +919,12 @@ public void OnAddSilenceCommand(CCSPlayerController? caller, CommandInfo command public void OnUnsilenceCommand(CCSPlayerController? caller, CommandInfo command) { if (_database == null) return; - string callerName = caller == null ? "Console" : caller.PlayerName; - string callerSteamId = caller?.SteamID.ToString() ?? "Console"; + var callerName = caller == null ? "Console" : caller.PlayerName; + var callerSteamId = caller?.SteamID.ToString() ?? "Console"; - string foundPlayerName = string.Empty; - string foundPlayerSteamId64 = string.Empty; - string reason = command.GetArg(2); + var foundPlayerName = string.Empty; + var foundPlayerSteamId64 = string.Empty; + var reason = command.GetArg(2); if (command.GetArg(1).Length <= 1) { @@ -947,17 +935,17 @@ public void OnUnsilenceCommand(CCSPlayerController? caller, CommandInfo command) Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); Helper.LogCommand(caller, command); - string pattern = command.GetArg(1); - bool found = false; + var pattern = command.GetArg(1); + var found = false; MuteManager _muteManager = new(_database); PlayerPenaltyManager playerPenaltyManager = new(); - if (Helper.IsValidSteamID64(pattern)) + if (Helper.IsValidSteamId64(pattern)) { - List matches = Helper.GetPlayerFromSteamid64(pattern); + var matches = Helper.GetPlayerFromSteamid64(pattern); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { if (TagsDetected) @@ -973,10 +961,10 @@ public void OnUnsilenceCommand(CCSPlayerController? caller, CommandInfo command) } else { - List matches = Helper.GetPlayerFromName(pattern); + var matches = Helper.GetPlayerFromName(pattern); if (matches.Count == 1) { - CCSPlayerController? player = matches.FirstOrDefault(); + var player = matches.FirstOrDefault(); if (player != null && player.IsValid) { if (TagsDetected) diff --git a/Commands/basevotes.cs b/Commands/basevotes.cs index 088ada6..96593da 100644 --- a/Commands/basevotes.cs +++ b/Commands/basevotes.cs @@ -15,7 +15,7 @@ public partial class CS2_SimpleAdmin [CommandHelper(minArgs: 2, usage: " [... options ...]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnVoteCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; if (command.GetArg(1) == null || command.GetArg(1).Length < 0 || command.ArgCount < 2) return; @@ -24,23 +24,23 @@ public void OnVoteCommand(CCSPlayerController? caller, CommandInfo command) voteAnswers.Clear(); - string question = command.GetArg(1); - int answersCount = command.ArgCount; + var question = command.GetArg(1); + var answersCount = command.ArgCount; - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - for (int i = 2; i <= answersCount - 1; i++) + for (var i = 2; i <= answersCount - 1; i++) { voteAnswers.Add(command.GetArg(i), 0); } - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var player in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(player.GetLanguage())) { ChatMenu voteMenu = new(_localizer!["sa_admin_vote_menu_title", question]); - for (int i = 2; i <= answersCount - 1; i++) + for (var i = 2; i <= answersCount - 1; i++) { voteMenu.AddMenuOption(command.GetArg(i), Helper.HandleVotes); } @@ -50,9 +50,9 @@ public void OnVoteCommand(CCSPlayerController? caller, CommandInfo command) Helper.PrintToCenterAll(_localizer!["sa_admin_vote_message", caller == null ? "Console" : caller.PlayerName, question]); StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_vote_message", caller == null ? "Console" : caller.PlayerName, question]); - _player.PrintToChat(sb.ToString()); + player.PrintToChat(sb.ToString()); - MenuManager.OpenChatMenu(_player, voteMenu); + MenuManager.OpenChatMenu(player, voteMenu); } } @@ -63,25 +63,25 @@ public void OnVoteCommand(CCSPlayerController? caller, CommandInfo command) { AddTimer(30, () => { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var player in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(player.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); sb.Append(_localizer["sa_admin_vote_message_results", question]); - _player.PrintToChat(sb.ToString()); + player.PrintToChat(sb.ToString()); } } - foreach (KeyValuePair kvp in voteAnswers) + foreach (var (key, value) in voteAnswers) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var player in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(player.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_vote_message_results_answer", kvp.Key, kvp.Value]); - _player.PrintToChat(sb.ToString()); + sb.Append(_localizer["sa_admin_vote_message_results_answer", key, value]); + player.PrintToChat(sb.ToString()); } } } diff --git a/Commands/funcommands.cs b/Commands/funcommands.cs index f2b7f53..4da16b4 100644 --- a/Commands/funcommands.cs +++ b/Commands/funcommands.cs @@ -15,10 +15,12 @@ public partial class CS2_SimpleAdmin [RequiresPermissions("@css/cheats")] public void OnNoclipCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; - TargetResult? targets = GetTarget(command); - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.SteamID.ToString().Length == 17 && player.PawnIsAlive && !player.IsHLTV).ToList(); + var targets = GetTarget(command); + var playersToTarget = targets!.Players.Where(player => + player.IsValid && player.SteamID.ToString().Length == 17 && + player is { PawnIsAlive: true, IsHLTV: false }).ToList(); Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); @@ -31,23 +33,21 @@ public void OnNoclipCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void NoClip(CCSPlayerController? caller, CCSPlayerController player, string? callerName = null) + public void NoClip(CCSPlayerController? caller, CCSPlayerController? player, string? callerName = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; player!.Pawn.Value!.ToggleNoclip(); Helper.LogCommand(caller, $"css_noclip {player.PlayerName}"); - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_noclip_message", callerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_noclip_message", callerName, player.PlayerName]); + controller.PrintToChat(sb.ToString()); } } } @@ -57,11 +57,11 @@ public void NoClip(CCSPlayerController? caller, CCSPlayerController player, stri [RequiresPermissions("@css/slay")] public void OnFreezeCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - int.TryParse(command.GetArg(2), out int time); + var callerName = caller == null ? "Console" : caller.PlayerName; + int.TryParse(command.GetArg(2), out var time); - TargetResult? targets = GetTarget(command); - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); + var targets = GetTarget(command); + var playersToTarget = targets!.Players.Where(player => player is { IsValid: true, PawnIsAlive: true, IsHLTV: false }).ToList(); Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); @@ -77,27 +77,25 @@ public void OnFreezeCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void Freeze(CCSPlayerController? caller, CCSPlayerController player, int time, string? callerName = null) + public void Freeze(CCSPlayerController? caller, CCSPlayerController? player, int time, string? callerName = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; - player.Pawn.Value!.Freeze(); + player?.Pawn.Value!.Freeze(); - Helper.LogCommand(caller, $"css_freeze {player.PlayerName}"); + Helper.LogCommand(caller, $"css_freeze {player?.PlayerName}"); if (time > 0) - AddTimer(time, () => player.Pawn.Value!.Unfreeze(), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); + AddTimer(time, () => player?.Pawn.Value!.Unfreeze(), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_freeze_message", callerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_freeze_message", callerName, player?.PlayerName ?? string.Empty]); + controller.PrintToChat(sb.ToString()); } } } @@ -107,10 +105,10 @@ public void Freeze(CCSPlayerController? caller, CCSPlayerController player, int [RequiresPermissions("@css/slay")] public void OnUnfreezeCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; - TargetResult? targets = GetTarget(command); - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); + var targets = GetTarget(command); + var playersToTarget = targets!.Players.Where(player => player is { IsValid: true, PawnIsAlive: true, IsHLTV: false }).ToList(); playersToTarget.ForEach(player => { @@ -121,7 +119,7 @@ public void OnUnfreezeCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void Unfreeze(CCSPlayerController? caller, CCSPlayerController player, string? callerName = null, CommandInfo? command = null) + public void Unfreeze(CCSPlayerController? caller, CCSPlayerController? player, string? callerName = null, CommandInfo? command = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; @@ -133,16 +131,14 @@ public void Unfreeze(CCSPlayerController? caller, CCSPlayerController player, st Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_unfreeze_message", callerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_unfreeze_message", callerName, player.PlayerName]); + controller.PrintToChat(sb.ToString()); } } } diff --git a/Commands/playercommands.cs b/Commands/playercommands.cs index 190f3e5..9d8fcc7 100644 --- a/Commands/playercommands.cs +++ b/Commands/playercommands.cs @@ -18,11 +18,11 @@ public partial class CS2_SimpleAdmin [CommandHelper(minArgs: 1, usage: "<#userid or name>", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnSlayCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - TargetResult? targets = GetTarget(command); + var callerName = caller == null ? "Console" : caller.PlayerName; + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player is { PawnIsAlive: true, IsHLTV: false }).ToList(); playersToTarget.ForEach(player => { @@ -30,14 +30,14 @@ public void OnSlayCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void Slay(CCSPlayerController? caller, CCSPlayerController player, string? callerName = null, CommandInfo? command = null) + public void Slay(CCSPlayerController? caller, CCSPlayerController? player, string? callerName = null, CommandInfo? command = null) { - if (!player.IsBot && player.SteamID.ToString().Length != 17) + if (player != null && !player.IsBot && player.SteamID.ToString().Length != 17) return; callerName ??= caller == null ? "Console" : caller.PlayerName; - player.CommitSuicide(false, true); + player?.CommitSuicide(false, true); if (command != null) { @@ -45,16 +45,14 @@ public void Slay(CCSPlayerController? caller, CCSPlayerController player, string Helper.LogCommand(caller, command); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_slay_message", callerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_slay_message", callerName, player?.PlayerName ?? string.Empty]); + controller.PrintToChat(sb.ToString()); } } } @@ -64,15 +62,15 @@ public void Slay(CCSPlayerController? caller, CCSPlayerController player, string [CommandHelper(minArgs: 2, usage: "<#userid or name> ", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnGiveCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - TargetResult? targets = GetTarget(command); + var callerName = caller == null ? "Console" : caller.PlayerName; + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); - string weaponName = command.GetArg(2); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player is { PawnIsAlive: true, IsHLTV: false }).ToList(); + var weaponName = command.GetArg(2); // check if item is typed - if (weaponName == null || weaponName.Length < 5) + if (weaponName.Length < 5) { command.ReplyToCommand($"No weapon typed."); return; @@ -112,7 +110,7 @@ public void GiveWeapon(CCSPlayerController? caller, CCSPlayerController player, SubGiveWeapon(caller, player!, weapon.ToString(), callerName); } - public void GiveWeapon(CCSPlayerController? caller, CCSPlayerController player, string weaponName, string? callerName = null, CommandInfo? command = null) + private void GiveWeapon(CCSPlayerController? caller, CCSPlayerController player, string weaponName, string? callerName = null, CommandInfo? command = null) { if (command != null) { @@ -124,20 +122,18 @@ public void GiveWeapon(CCSPlayerController? caller, CCSPlayerController player, SubGiveWeapon(caller, player!, weaponName, callerName); } - public void SubGiveWeapon(CCSPlayerController? caller, CCSPlayerController player, string weaponName, string? callerName = null) + private void SubGiveWeapon(CCSPlayerController? caller, CCSPlayerController player, string weaponName, string? callerName = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && (silentPlayers.Contains(caller.Slot))) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_give_message", callerName, player.PlayerName, weaponName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_give_message", callerName, player.PlayerName, weaponName]); + controller.PrintToChat(sb.ToString()); } } } @@ -147,11 +143,11 @@ public void SubGiveWeapon(CCSPlayerController? caller, CCSPlayerController playe [CommandHelper(minArgs: 1, usage: "<#userid or name>", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnStripCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - TargetResult? targets = GetTarget(command); + var callerName = caller == null ? "Console" : caller.PlayerName; + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player is { PawnIsAlive: true, IsHLTV: false }).ToList(); playersToTarget.ForEach(player => { @@ -162,14 +158,14 @@ public void OnStripCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void StripWeapons(CCSPlayerController? caller, CCSPlayerController player, string? callerName = null, CommandInfo? command = null) + public void StripWeapons(CCSPlayerController? caller, CCSPlayerController? player, string? callerName = null, CommandInfo? command = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; - if (!player.IsBot && player.SteamID.ToString().Length != 17) + if (player != null && !player.IsBot && player.SteamID.ToString().Length != 17) return; - player.RemoveWeapons(); + player?.RemoveWeapons(); if (command != null) { @@ -177,16 +173,14 @@ public void StripWeapons(CCSPlayerController? caller, CCSPlayerController player Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_strip_message", callerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_strip_message", callerName, player?.PlayerName ?? string.Empty]); + controller.PrintToChat(sb.ToString()); } } } @@ -196,14 +190,13 @@ public void StripWeapons(CCSPlayerController? caller, CCSPlayerController player [CommandHelper(minArgs: 1, usage: "<#userid or name> ", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnHpCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - int health = 100; - int.TryParse(command.GetArg(2), out health); + var callerName = caller == null ? "Console" : caller.PlayerName; + int.TryParse(command.GetArg(2), out var health); - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player is { PawnIsAlive: true, IsHLTV: false }).ToList(); playersToTarget.ForEach(player => { @@ -214,9 +207,9 @@ public void OnHpCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void SetHp(CCSPlayerController? caller, CCSPlayerController player, int health, string? callerName = null, CommandInfo? command = null) + public void SetHp(CCSPlayerController? caller, CCSPlayerController? player, int health, string? callerName = null, CommandInfo? command = null) { - if (!player.IsBot && player.SteamID.ToString().Length != 17) + if (player != null && !player.IsBot && player.SteamID.ToString().Length != 17) return; callerName = caller == null ? "Console" : caller.PlayerName; @@ -229,16 +222,14 @@ public void SetHp(CCSPlayerController? caller, CCSPlayerController player, int h Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_hp_message", callerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_hp_message", callerName, player?.PlayerName ?? string.Empty]); + controller.PrintToChat(sb.ToString()); } } } @@ -248,14 +239,13 @@ public void SetHp(CCSPlayerController? caller, CCSPlayerController player, int h [CommandHelper(minArgs: 1, usage: "<#userid or name> ", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnSpeedCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - double speed = 1.0; - double.TryParse(command.GetArg(2), out speed); + var callerName = caller == null ? "Console" : caller.PlayerName; + double.TryParse(command.GetArg(2), out var speed); - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player is { PawnIsAlive: true, IsHLTV: false }).ToList(); playersToTarget.ForEach(player => { @@ -269,7 +259,7 @@ public void OnSpeedCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void SetSpeed(CCSPlayerController? caller, CCSPlayerController player, double speed, string? callerName = null, CommandInfo? command = null) + public void SetSpeed(CCSPlayerController? caller, CCSPlayerController? player, double speed, string? callerName = null, CommandInfo? command = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; @@ -281,16 +271,14 @@ public void SetSpeed(CCSPlayerController? caller, CCSPlayerController player, do Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_speed_message", callerName, player!.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_speed_message", callerName, player!.PlayerName]); + controller.PrintToChat(sb.ToString()); } } } @@ -300,16 +288,16 @@ public void SetSpeed(CCSPlayerController? caller, CCSPlayerController player, do [CommandHelper(minArgs: 1, usage: "<#userid or name> ", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnGravityCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - double gravity = 1.0; + var callerName = caller == null ? "Console" : caller.PlayerName; + var gravity = 1.0; double.TryParse(command.GetArg(2), out gravity); - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player is { PawnIsAlive: true, IsHLTV: false }).ToList(); playersToTarget.ForEach(player => { @@ -323,7 +311,7 @@ public void OnGravityCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void SetGravity(CCSPlayerController? caller, CCSPlayerController player, double gravity, string? callerName = null, CommandInfo? command = null) + public void SetGravity(CCSPlayerController? caller, CCSPlayerController? player, double gravity, string? callerName = null, CommandInfo? command = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; @@ -335,16 +323,14 @@ public void SetGravity(CCSPlayerController? caller, CCSPlayerController player, Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_gravity_message", callerName, player!.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_gravity_message", callerName, player!.PlayerName]); + controller.PrintToChat(sb.ToString()); } } } @@ -354,14 +340,13 @@ public void SetGravity(CCSPlayerController? caller, CCSPlayerController player, [CommandHelper(minArgs: 1, usage: "<#userid or name> ", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnMoneyCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - int money = 0; - int.TryParse(command.GetArg(2), out money); + var callerName = caller == null ? "Console" : caller.PlayerName; + int.TryParse(command.GetArg(2), out var money); - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player is { PawnIsAlive: true, IsHLTV: false }).ToList(); playersToTarget.ForEach(player => { @@ -375,7 +360,7 @@ public void OnMoneyCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void SetMoney(CCSPlayerController? caller, CCSPlayerController player, int money, string? callerName = null, CommandInfo? command = null) + public void SetMoney(CCSPlayerController? caller, CCSPlayerController? player, int money, string? callerName = null, CommandInfo? command = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; @@ -387,16 +372,14 @@ public void SetMoney(CCSPlayerController? caller, CCSPlayerController player, in Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_money_message", callerName, player!.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_money_message", callerName, player!.PlayerName]); + controller.PrintToChat(sb.ToString()); } } } @@ -406,11 +389,11 @@ public void SetMoney(CCSPlayerController? caller, CCSPlayerController player, in [CommandHelper(minArgs: 1, usage: "<#userid or name>", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnGodCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - TargetResult? targets = GetTarget(command); + var callerName = caller == null ? "Console" : caller.PlayerName; + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player is { PawnIsAlive: true, IsHLTV: false }).ToList(); playersToTarget.ForEach(player => { @@ -424,38 +407,34 @@ public void OnGodCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void God(CCSPlayerController? caller, CCSPlayerController player, string? callerName = null, CommandInfo? command = null) + public void God(CCSPlayerController? caller, CCSPlayerController? player, string? callerName = null, CommandInfo? command = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; - if (player != null) + if (player == null) return; + if (command != null) { - if (command != null) - { - Helper.LogCommand(caller, command); - Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - } + Helper.LogCommand(caller, command); + Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); + } - if (!godPlayers.Contains(player.Slot)) - { - godPlayers.Add(player.Slot); - } - else - { - RemoveFromConcurrentBag(godPlayers, player.Slot); - } + if (!godPlayers.Contains(player.Slot)) + { + godPlayers.Add(player.Slot); + } + else + { + RemoveFromConcurrentBag(godPlayers, player.Slot); + } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) + { + using (new WithTemporaryCulture(controller.GetLanguage())) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) - { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_god_message", callerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_god_message", callerName, player.PlayerName]); + controller.PrintToChat(sb.ToString()); } } } @@ -465,13 +444,13 @@ public void God(CCSPlayerController? caller, CCSPlayerController player, string? [CommandHelper(minArgs: 1, usage: "<#userid or name> [damage]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnSlapCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - int damage = 0; + var callerName = caller == null ? "Console" : caller.PlayerName; + var damage = 0; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && player.PawnIsAlive && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player.IsValid && player is { PawnIsAlive: true, IsHLTV: false }).ToList(); if (command.ArgCount >= 2) { @@ -490,9 +469,9 @@ public void OnSlapCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void Slap(CCSPlayerController? caller, CCSPlayerController player, int damage, CommandInfo? command = null) + public void Slap(CCSPlayerController? caller, CCSPlayerController? player, int damage, CommandInfo? command = null) { - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; player!.Pawn.Value!.Slap(damage); if (command != null) @@ -501,16 +480,14 @@ public void Slap(CCSPlayerController? caller, CCSPlayerController player, int da Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_slap_message", callerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_slap_message", callerName, player.PlayerName]); + controller.PrintToChat(sb.ToString()); } } } @@ -520,15 +497,15 @@ public void Slap(CCSPlayerController? caller, CCSPlayerController player, int da [CommandHelper(minArgs: 2, usage: "<#userid or name> [] [-k]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)] public void OnTeamCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - string teamName = command.GetArg(2).ToLower(); - string _teamName = "SPEC"; - CsTeam teamNum = CsTeam.Spectator; + var callerName = caller == null ? "Console" : caller.PlayerName; + var teamName = command.GetArg(2).ToLower(); + var _teamName = "SPEC"; + var teamNum = CsTeam.Spectator; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player is { IsValid: true, IsHLTV: false }).ToList(); switch (teamName) { @@ -555,7 +532,7 @@ public void OnTeamCommand(CCSPlayerController? caller, CommandInfo command) break; } - bool kill = command.GetArg(3).ToLower().Equals("-k"); + var kill = command.GetArg(3).ToLower().Equals("-k"); playersToTarget.ForEach(player => { @@ -563,25 +540,25 @@ public void OnTeamCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void ChangeTeam(CCSPlayerController? caller, CCSPlayerController player, string teamName, CsTeam teamNum, bool kill, string? callerName = null, CommandInfo? command = null) + public void ChangeTeam(CCSPlayerController? caller, CCSPlayerController? player, string teamName, CsTeam teamNum, bool kill, string? callerName = null, CommandInfo? command = null) { - if (!player.IsBot && player.SteamID.ToString().Length != 17) + if (player != null && !player.IsBot && player.SteamID.ToString().Length != 17) return; callerName ??= caller == null ? "Console" : caller.PlayerName; if (!teamName.Equals("swap")) { - if (player.PawnIsAlive && teamNum != CsTeam.Spectator && !kill && Config.TeamSwitchType == 1) + if (player != null && player.PawnIsAlive && teamNum != CsTeam.Spectator && !kill && Config.TeamSwitchType == 1) player.SwitchTeam(teamNum); else - player.ChangeTeam(teamNum); + player?.ChangeTeam(teamNum); } else { - if (player.TeamNum != (byte)CsTeam.Spectator) + if (player != null && player.TeamNum != (byte)CsTeam.Spectator) { - CsTeam _teamNum = (CsTeam)player.TeamNum == CsTeam.Terrorist ? CsTeam.CounterTerrorist : CsTeam.Terrorist; + var _teamNum = (CsTeam)player.TeamNum == CsTeam.Terrorist ? CsTeam.CounterTerrorist : CsTeam.Terrorist; teamName = _teamNum == CsTeam.Terrorist ? "TT" : "CT"; if (player.PawnIsAlive && !kill && Config.TeamSwitchType == 1) { @@ -594,24 +571,22 @@ public void ChangeTeam(CCSPlayerController? caller, CCSPlayerController player, } } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + foreach (var controller in Helper.GetValidPlayers()) { - using (new WithTemporaryCulture(_player.GetLanguage())) + using (new WithTemporaryCulture(controller.GetLanguage())) { StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_team_message", callerName, player.PlayerName, teamName]); - _player.PrintToChat(sb.ToString()); + sb.Append(_localizer["sa_admin_team_message", callerName, player?.PlayerName ?? string.Empty, teamName]); + controller.PrintToChat(sb.ToString()); } } } - if (command != null) - { - Helper.LogCommand(caller, command); - Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); - } + if (command == null) return; + Helper.LogCommand(caller, command); + Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); } [ConsoleCommand("css_rename", "Rename a player.")] @@ -619,14 +594,14 @@ public void ChangeTeam(CCSPlayerController? caller, CCSPlayerController player, [RequiresPermissions("@css/kick")] public void OnRenameCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; - string? newName = command.GetArg(2); + var callerName = caller == null ? "Console" : caller.PlayerName; + var newName = command.GetArg(2); if (string.IsNullOrEmpty(newName)) return; - TargetResult? targets = GetTarget(command); - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && !player.IsHLTV).ToList(); + var targets = GetTarget(command); + var playersToTarget = targets!.Players.Where(player => player is { IsValid: true, IsHLTV: false }).ToList(); Helper.LogCommand(caller, command); Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); @@ -636,23 +611,21 @@ public void OnRenameCommand(CCSPlayerController? caller, CommandInfo command) if (!player.IsBot && player.SteamID.ToString().Length != 17) return; - if (caller!.CanTarget(player)) + if (!caller!.CanTarget(player)) return; + if (caller == null || !silentPlayers.Contains(caller.Slot)) { - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_rename_message", callerName, player.PlayerName, newName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_rename_message", callerName, player.PlayerName, newName]); + controller.PrintToChat(sb.ToString()); } } - - player.Rename(newName); } + + player.Rename(newName); }); } @@ -661,10 +634,10 @@ public void OnRenameCommand(CCSPlayerController? caller, CommandInfo command) [RequiresPermissions("@css/cheats")] public void OnRespawnCommand(CCSPlayerController? caller, CommandInfo command) { - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller == null ? "Console" : caller.PlayerName; - TargetResult? targets = GetTarget(command); - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && !player.IsHLTV).ToList(); + var targets = GetTarget(command); + var playersToTarget = targets!.Players.Where(player => player is { IsValid: true, IsHLTV: false }).ToList(); playersToTarget.ForEach(player => { @@ -678,11 +651,11 @@ public void OnRespawnCommand(CCSPlayerController? caller, CommandInfo command) }); } - public void Respawn(CCSPlayerController? caller, CCSPlayerController player, string? callerName = null, CommandInfo? command = null) + public void Respawn(CCSPlayerController? caller, CCSPlayerController? player, string? callerName = null, CommandInfo? command = null) { callerName ??= caller == null ? "Console" : caller.PlayerName; - if (CBasePlayerController_SetPawnFunc == null || player.PlayerPawn.Value == null || !player.PlayerPawn.IsValid) return; + if (CBasePlayerController_SetPawnFunc == null || player?.PlayerPawn.Value == null || !player.PlayerPawn.IsValid) return; var playerPawn = player.PlayerPawn.Value; CBasePlayerController_SetPawnFunc.Invoke(player, playerPawn, true, false); @@ -695,16 +668,14 @@ public void Respawn(CCSPlayerController? caller, CCSPlayerController player, str Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); } - if (caller == null || caller != null && !silentPlayers.Contains(caller.Slot)) + if (caller != null && silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) + using (new WithTemporaryCulture(controller.GetLanguage())) { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_respawn_message", callerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_respawn_message", callerName, player.PlayerName]); + controller.PrintToChat(sb.ToString()); } } } @@ -718,14 +689,14 @@ public void OnGotoCommand(CCSPlayerController? caller, CommandInfo command) { if (caller == null || !caller.PawnIsAlive) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller.PlayerName; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null || targets.Count() > 1) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player is { IsValid: true, IsHLTV: false }).ToList(); Helper.LogCommand(caller, command); Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); @@ -735,27 +706,23 @@ public void OnGotoCommand(CCSPlayerController? caller, CommandInfo command) if (!player.IsBot && player.SteamID.ToString().Length != 17 || !player.PawnIsAlive) return; - if (caller!.CanTarget(player)) + if (!caller!.CanTarget(player)) return; + caller!.TeleportPlayer(player); + caller!.Pawn.Value!.ToggleNoclip(); + + AddTimer(3, () => { - caller!.TeleportPlayer(player); caller!.Pawn.Value!.ToggleNoclip(); + }); - AddTimer(3, () => - { - caller!.Pawn.Value!.ToggleNoclip(); - }); - - if (caller != null && !silentPlayers.Contains(caller.Slot)) + if (silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) + { + using (new WithTemporaryCulture(controller.GetLanguage())) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) - { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_tp_message", caller.PlayerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_tp_message", caller.PlayerName, player.PlayerName]); + controller.PrintToChat(sb.ToString()); } } }); @@ -769,14 +736,14 @@ public void OnBringCommand(CCSPlayerController? caller, CommandInfo command) { if (caller == null || !caller.PawnIsAlive) return; - string callerName = caller == null ? "Console" : caller.PlayerName; + var callerName = caller.PlayerName; - TargetResult? targets = GetTarget(command); + var targets = GetTarget(command); if (targets == null || targets.Count() > 1) return; - List playersToTarget = targets!.Players.Where(player => player != null && player.IsValid && !player.IsHLTV).ToList(); + var playersToTarget = targets!.Players.Where(player => player is { IsValid: true, IsHLTV: false }).ToList(); Helper.LogCommand(caller, command); Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer); @@ -786,27 +753,23 @@ public void OnBringCommand(CCSPlayerController? caller, CommandInfo command) if (!player.IsBot && player.SteamID.ToString().Length != 17 || !player.PawnIsAlive) return; - if (caller!.CanTarget(player)) + if (!caller!.CanTarget(player)) return; + player!.TeleportPlayer(caller!); + caller!.Pawn.Value!.ToggleNoclip(); + + AddTimer(3, () => { - player!.TeleportPlayer(caller!); caller!.Pawn.Value!.ToggleNoclip(); + }); - AddTimer(3, () => - { - caller!.Pawn.Value!.ToggleNoclip(); - }); - - if (caller != null && !silentPlayers.Contains(caller.Slot)) + if (silentPlayers.Contains(caller.Slot)) return; + foreach (var controller in Helper.GetValidPlayers()) + { + using (new WithTemporaryCulture(controller.GetLanguage())) { - foreach (CCSPlayerController _player in Helper.GetValidPlayers()) - { - using (new WithTemporaryCulture(_player.GetLanguage())) - { - StringBuilder sb = new(_localizer!["sa_prefix"]); - sb.Append(_localizer["sa_admin_bring_message", caller.PlayerName, player.PlayerName]); - _player.PrintToChat(sb.ToString()); - } - } + StringBuilder sb = new(_localizer!["sa_prefix"]); + sb.Append(_localizer["sa_admin_bring_message", caller.PlayerName, player.PlayerName]); + controller.PrintToChat(sb.ToString()); } } }); diff --git a/Config.cs b/Config.cs index cea7656..ab2b354 100644 --- a/Config.cs +++ b/Config.cs @@ -73,12 +73,12 @@ public class CS2_SimpleAdminConfig : BasePluginConfig public Discord Discord { get; set; } = new Discord(); [JsonPropertyName("DefaultMaps")] - public List DefaultMaps { get; set; } = new List(); + public List DefaultMaps { get; set; } = []; [JsonPropertyName("WorkshopMaps")] - public List WorkshopMaps { get; set; } = new List(); + public List WorkshopMaps { get; set; } = []; [JsonPropertyName("CustomServerCommands")] - public List CustomServerCommands { get; set; } = new List(); + public List CustomServerCommands { get; set; } = []; } } \ No newline at end of file diff --git a/Database/Database.cs b/Database/Database.cs index 3a2addd..2f2659a 100644 --- a/Database/Database.cs +++ b/Database/Database.cs @@ -46,7 +46,7 @@ public void DatabaseMigration() public bool CheckDatabaseConnection() { - using MySqlConnection connection = GetConnection(); + using var connection = GetConnection(); try { diff --git a/Database/Migration.cs b/Database/Migration.cs index 80ade5a..975580a 100644 --- a/Database/Migration.cs +++ b/Database/Migration.cs @@ -9,19 +9,21 @@ public class Migration(Database database) public void ExecuteMigrations() { - string migrationsDirectory = CS2_SimpleAdmin.Instance.ModuleDirectory + "/Database/Migrations"; + var migrationsDirectory = CS2_SimpleAdmin.Instance.ModuleDirectory + "/Database/Migrations"; var files = Directory.GetFiles(migrationsDirectory, "*.sql") .OrderBy(f => f); - using MySqlConnection connection = _database.GetConnection(); + using var connection = _database.GetConnection(); // Create sa_migrations table if not exists - using var cmd = new MySqlCommand(@" - CREATE TABLE IF NOT EXISTS `sa_migrations` ( - `id` INT PRIMARY KEY AUTO_INCREMENT, - `version` VARCHAR(255) NOT NULL - );", connection); + using var cmd = new MySqlCommand(""" + + CREATE TABLE IF NOT EXISTS `sa_migrations` ( + `id` INT PRIMARY KEY AUTO_INCREMENT, + `version` VARCHAR(255) NOT NULL + ); + """, connection); cmd.ExecuteNonQuery(); @@ -33,18 +35,16 @@ public void ExecuteMigrations() var version = Path.GetFileNameWithoutExtension(file); // Check if the migration has already been applied - if (string.Compare(version, lastAppliedVersion, StringComparison.OrdinalIgnoreCase) > 0) - { - var sqlScript = File.ReadAllText(file); + if (string.Compare(version, lastAppliedVersion, StringComparison.OrdinalIgnoreCase) <= 0) continue; + var sqlScript = File.ReadAllText(file); - using var cmdMigration = new MySqlCommand(sqlScript, connection); - cmdMigration.ExecuteNonQuery(); + using var cmdMigration = new MySqlCommand(sqlScript, connection); + cmdMigration.ExecuteNonQuery(); - // Update the last applied migration version - UpdateLastAppliedVersion(connection, version); + // Update the last applied migration version + UpdateLastAppliedVersion(connection, version); - CS2_SimpleAdmin._logger?.LogInformation($"Migration \"{version}\" successfully applied."); - } + CS2_SimpleAdmin._logger?.LogInformation($"Migration \"{version}\" successfully applied."); } } diff --git a/Events.cs b/Events.cs index 23574cd..4b2afa9 100644 --- a/Events.cs +++ b/Events.cs @@ -15,7 +15,7 @@ namespace CS2_SimpleAdmin; public partial class CS2_SimpleAdmin { - public static HashSet loadedPlayers = new HashSet(); + private static readonly HashSet LoadedPlayers = []; private void RegisterEvents() { @@ -40,7 +40,7 @@ public HookResult OnClientDisconnect(EventPlayerDisconnect @event, GameEventInfo return HookResult.Continue; } - if (!loadedPlayers.Contains(player.Slot)) + if (!LoadedPlayers.Contains(player.Slot)) { return HookResult.Continue; } @@ -68,15 +68,15 @@ public HookResult OnClientDisconnect(EventPlayerDisconnect @event, GameEventInfo RemoveFromConcurrentBag(godPlayers, player.Slot); } - SteamID? authorizedSteamID = player.AuthorizedSteamID; - if (authorizedSteamID != null && AdminSQLManager._adminCache.TryGetValue(authorizedSteamID, out DateTime? expirationTime) + SteamID? authorizedSteamId = player.AuthorizedSteamID; + if (authorizedSteamId != null && AdminSQLManager._adminCache.TryGetValue(authorizedSteamId, out var expirationTime) && expirationTime <= DateTime.Now) { - AdminManager.ClearPlayerPermissions(authorizedSteamID); - AdminManager.RemovePlayerAdminData(authorizedSteamID); + AdminManager.ClearPlayerPermissions(authorizedSteamId); + AdminManager.RemovePlayerAdminData(authorizedSteamId); } - loadedPlayers.Remove(player.Slot); + LoadedPlayers.Remove(player.Slot); return HookResult.Continue; } @@ -96,7 +96,7 @@ public HookResult OnPlayerFullConnect(EventPlayerConnectFull @event, GameEventIn || player.IsBot || player.IsHLTV || !player.UserId.HasValue) return HookResult.Continue; - string ipAddress = player.IpAddress.Split(":")[0]; + var ipAddress = player.IpAddress.Split(":")[0]; // Check if the player's IP or SteamID is in the bannedPlayers list if (bannedPlayers.Contains(ipAddress) || bannedPlayers.Contains(player.SteamID.ToString())) @@ -110,7 +110,7 @@ public HookResult OnPlayerFullConnect(EventPlayerConnectFull @event, GameEventIn if (_database == null) return HookResult.Continue; - PlayerInfo playerInfo = new PlayerInfo + var playerInfo = new PlayerInfo { UserId = player.UserId.Value, Index = (ushort)player.Index, @@ -142,10 +142,10 @@ public HookResult OnPlayerFullConnect(EventPlayerConnectFull @event, GameEventIn bannedPlayers.Add(playerInfo.SteamId); // Kick the player if banned - Server.NextFrame(() => + await Server.NextFrameAsync(() => { var victim = Utilities.GetPlayerFromUserid(playerInfo.UserId); - if (victim != null && victim.UserId.HasValue) + if (victim.UserId.HasValue) { Helper.KickPlayer(victim.UserId.Value, "Banned"); } @@ -155,46 +155,46 @@ public HookResult OnPlayerFullConnect(EventPlayerConnectFull @event, GameEventIn } // Check if the player is muted - List activeMutes = await _muteManager.IsPlayerMuted(playerInfo.SteamId); + var activeMutes = await _muteManager.IsPlayerMuted(playerInfo.SteamId); if (activeMutes.Count > 0) { - foreach (dynamic mute in activeMutes) + foreach (var mute in activeMutes) { string muteType = mute.type; DateTime ends = mute.ends; int duration = mute.duration; - // Apply mute penalty based on mute type - if (muteType == "GAG") + switch (muteType) { - PlayerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Gag, ends, duration); - Server.NextFrame(() => - { - if (TagsDetected) + // Apply mute penalty based on mute type + case "GAG": + PlayerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Gag, ends, duration); + await Server.NextFrameAsync(() => { - Server.ExecuteCommand($"css_tag_mute {playerInfo.SteamId}"); - } - }); - } - else if (muteType == "MUTE") - { - PlayerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Mute, ends, duration); - Server.NextFrame(() => - { - player.VoiceFlags = VoiceFlags.Muted; - }); - } - else - { - PlayerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Silence, ends, duration); - Server.NextFrame(() => - { - player.VoiceFlags = VoiceFlags.Muted; - if (TagsDetected) + if (TagsDetected) + { + Server.ExecuteCommand($"css_tag_mute {playerInfo.SteamId}"); + } + }); + break; + case "MUTE": + PlayerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Mute, ends, duration); + await Server.NextFrameAsync(() => + { + player.VoiceFlags = VoiceFlags.Muted; + }); + break; + default: + PlayerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Silence, ends, duration); + await Server.NextFrameAsync(() => { - Server.ExecuteCommand($"css_tag_mute {playerInfo.SteamId}"); - } - }); + player.VoiceFlags = VoiceFlags.Muted; + if (TagsDetected) + { + Server.ExecuteCommand($"css_tag_mute {playerInfo.SteamId}"); + } + }); + break; } } } @@ -206,8 +206,7 @@ public HookResult OnPlayerFullConnect(EventPlayerConnectFull @event, GameEventIn }); // Add player to loadedPlayers - if (!loadedPlayers.Contains(player.Slot)) - loadedPlayers.Add(player.Slot); + LoadedPlayers.Add(player.Slot); return HookResult.Continue; } @@ -225,8 +224,8 @@ public HookResult OnRoundEnd(EventRoundStart @event, GameEventInfo info) public HookResult OnCommandSay(CCSPlayerController? player, CommandInfo info) { - if (player is null || !player.IsValid || player.IsBot || player.IsHLTV || info.GetArg(1).StartsWith("/") - || info.GetArg(1).StartsWith("!") && info.GetArg(1).Length >= 12) + if (player is null || !player.IsValid || player.IsBot || player.IsHLTV || info.GetArg(1).StartsWith($"/") + || info.GetArg(1).StartsWith($"!") && info.GetArg(1).Length >= 12) return HookResult.Continue; if (info.GetArg(1).Length == 0) @@ -242,8 +241,8 @@ public HookResult OnCommandSay(CCSPlayerController? player, CommandInfo info) public HookResult OnCommandTeamSay(CCSPlayerController? player, CommandInfo info) { - if (player is null || !player.IsValid || player.IsBot || player.IsHLTV || info.GetArg(1).StartsWith("/") - || info.GetArg(1).StartsWith("!") && info.GetArg(1).Length >= 12) + if (player is null || !player.IsValid || player.IsBot || player.IsHLTV || info.GetArg(1).StartsWith($"/") + || info.GetArg(1).StartsWith($"!") && info.GetArg(1).Length >= 12) return HookResult.Continue; if (info.GetArg(1).Length == 0) @@ -254,37 +253,35 @@ public HookResult OnCommandTeamSay(CCSPlayerController? player, CommandInfo info if (PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Gag) || PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Silence)) return HookResult.Handled; - if (info.GetArg(1).StartsWith("@")) - { - StringBuilder sb = new(); + if (!info.GetArg(1).StartsWith($"@")) return HookResult.Continue; + + StringBuilder sb = new(); - if (AdminManager.PlayerHasPermissions(player, "@css/chat")) + if (AdminManager.PlayerHasPermissions(player, "@css/chat")) + { + sb.Append(_localizer!["sa_adminchat_template_admin", player!.PlayerName, info.GetArg(1).Remove(0, 1)]); + foreach (var p in Utilities.GetPlayers().Where(p => p.IsValid && p is { IsBot: false, IsHLTV: false } && AdminManager.PlayerHasPermissions(p, "@css/chat"))) { - sb.Append(_localizer!["sa_adminchat_template_admin", player!.PlayerName, info.GetArg(1).Remove(0, 1)]); - foreach (var p in Utilities.GetPlayers().Where(p => p.IsValid && !p.IsBot && !p.IsHLTV && AdminManager.PlayerHasPermissions(p, "@css/chat"))) - { - p.PrintToChat(sb.ToString()); - } + p.PrintToChat(sb.ToString()); } - else + } + else + { + sb.Append(_localizer!["sa_adminchat_template_player", player!.PlayerName, info.GetArg(1).Remove(0, 1)]); + player.PrintToChat(sb.ToString()); + foreach (var p in Utilities.GetPlayers().Where(p => p is { IsValid: true, IsBot: false, IsHLTV: false } && AdminManager.PlayerHasPermissions(p, "@css/chat"))) { - sb.Append(_localizer!["sa_adminchat_template_player", player!.PlayerName, info.GetArg(1).Remove(0, 1)]); - player.PrintToChat(sb.ToString()); - foreach (var p in Utilities.GetPlayers().Where(p => p.IsValid && !p.IsBot && !p.IsHLTV && AdminManager.PlayerHasPermissions(p, "@css/chat"))) - { - p.PrintToChat(sb.ToString()); - } + p.PrintToChat(sb.ToString()); } - - return HookResult.Handled; } - return HookResult.Continue; + return HookResult.Handled; + } private void OnMapStart(string mapName) { - string? path = Path.GetDirectoryName(ModuleDirectory); + var path = Path.GetDirectoryName(ModuleDirectory); if (Directory.Exists(path + "/CS2-Tags")) { TagsDetected = true; @@ -296,9 +293,7 @@ private void OnMapStart(string mapName) PlayerPenaltyManager playerPenaltyManager = new PlayerPenaltyManager(); PlayerPenaltyManager.RemoveAllPenalties(); - _database = new(dbConnectionString); - - if (_database == null) return; + _database = new Database(dbConnectionString); AddTimer(61.0f, () => { @@ -306,8 +301,8 @@ private void OnMapStart(string mapName) Logger.LogCritical("[OnMapStart] Expired check"); #endif - List players = Helper.GetValidPlayers(); - List<(string? IpAddress, ulong SteamID, int? UserId)> onlinePlayers = players + var players = Helper.GetValidPlayers(); + var onlinePlayers = players .Where(player => player.IpAddress != null && player.SteamID.ToString().Length == 17) .Select(player => (player.IpAddress, player.SteamID, player.UserId)) .ToList(); @@ -330,48 +325,41 @@ private void OnMapStart(string mapName) bannedPlayers.Clear(); - Server.NextFrame(() => + await Server.NextFrameAsync(() => { try { - foreach (CCSPlayerController player in players) + foreach (var player in players.Where(player => PlayerPenaltyManager.IsSlotInPenalties(player.Slot))) { - if (PlayerPenaltyManager.IsSlotInPenalties(player.Slot)) + if (!PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Mute) && !PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Silence)) + player.VoiceFlags = VoiceFlags.Normal; + + if (!PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Gag) && !PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Silence)) { - if (!PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Mute) && !PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Silence)) - player.VoiceFlags = VoiceFlags.Normal; + if (TagsDetected) + Server.ExecuteCommand($"css_tag_unmute {player!.SteamID}"); + } - if (!PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Gag) && !PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Silence)) - { - if (TagsDetected) - Server.ExecuteCommand($"css_tag_unmute {player!.SteamID}"); - } - - if ( - !PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Silence) && - !PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Mute) && - !PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Gag) - ) - { - player.VoiceFlags = VoiceFlags.Normal; + if (PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Silence) || + PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Mute) || + PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Gag)) continue; + player.VoiceFlags = VoiceFlags.Normal; - if (TagsDetected) - Server.ExecuteCommand($"css_tag_unmute {player!.SteamID}"); - } - } + if (TagsDetected) + Server.ExecuteCommand($"css_tag_unmute {player!.SteamID}"); } PlayerPenaltyManager.RemoveExpiredPenalties(); } - catch (Exception) { } + catch { } }); }); }, CounterStrikeSharp.API.Modules.Timers.TimerFlags.REPEAT | CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); AddTimer(2.0f, () => { - string? address = $"{ConVar.Find("ip")!.StringValue}:{ConVar.Find("hostport")!.GetPrimitiveValue()}"; - string? hostname = ConVar.Find("hostname")!.StringValue; + var address = $"{ConVar.Find("ip")!.StringValue}:{ConVar.Find("hostport")!.GetPrimitiveValue()}"; + var hostname = ConVar.Find("hostname")!.StringValue; Task.Run(async () => { @@ -379,7 +367,7 @@ private void OnMapStart(string mapName) try { await using var connection = await _database.GetConnectionAsync(); - bool addressExists = await connection.ExecuteScalarAsync( + var addressExists = await connection.ExecuteScalarAsync( "SELECT COUNT(*) FROM sa_servers WHERE address = @address", new { address }); @@ -409,12 +397,12 @@ await connection.ExecuteAsync( if (Config.EnableMetrics) { - string queryString = $"?address={address}&hostname={hostname}"; + var queryString = $"?address={address}&hostname={hostname}"; using HttpClient client = new(); try { - HttpResponseMessage response = await client.GetAsync($"https://api.daffyy.love/index.php{queryString}"); + var response = await client.GetAsync($"https://api.daffyy.love/index.php{queryString}"); } catch (HttpRequestException ex) { @@ -442,11 +430,10 @@ public HookResult OnPlayerHurt(EventPlayerHurt @event, GameEventInfo info) if (player is null || @event.Attacker is null || !player.PawnIsAlive || player.PlayerPawn.Value == null) return HookResult.Continue; - if (godPlayers.Contains(player.Slot)) - { - player.PlayerPawn.Value.Health = player.PlayerPawn.Value.MaxHealth; - player.PlayerPawn.Value.ArmorValue = 100; - } + if (!godPlayers.Contains(player.Slot)) return HookResult.Continue; + + player.PlayerPawn.Value.Health = player.PlayerPawn.Value.MaxHealth; + player.PlayerPawn.Value.ArmorValue = 100; return HookResult.Continue; } diff --git a/Extensions/PlayerExtensions.cs b/Extensions/PlayerExtensions.cs index 0c2f6c5..828e14e 100644 --- a/Extensions/PlayerExtensions.cs +++ b/Extensions/PlayerExtensions.cs @@ -22,44 +22,47 @@ public static void Print(this CCSPlayerController controller, string message = " controller.PrintToChat(_message.ToString()); } - public static bool CanTarget(this CCSPlayerController controller, CCSPlayerController target) + public static bool CanTarget(this CCSPlayerController? controller, CCSPlayerController? target) { - if (target.IsBot) return true; + if (target != null && target.IsBot) return true; if (controller is null) return true; - return AdminManager.CanPlayerTarget(controller, target) || AdminManager.CanPlayerTarget(new SteamID(controller.SteamID), new SteamID(target.SteamID)); + return target != null && (AdminManager.CanPlayerTarget(controller, target) || + AdminManager.CanPlayerTarget(new SteamID(controller.SteamID), + new SteamID(target.SteamID))); } - public static void SetSpeed(this CCSPlayerController controller, float speed) + public static void SetSpeed(this CCSPlayerController? controller, float speed) { - CCSPlayerPawn? playerPawnValue = controller.PlayerPawn.Value; + var playerPawnValue = controller?.PlayerPawn.Value; if (playerPawnValue == null) return; playerPawnValue.VelocityModifier = speed; } - public static void SetGravity(this CCSPlayerController controller, float gravity) + public static void SetGravity(this CCSPlayerController? controller, float gravity) { - CCSPlayerPawn? playerPawnValue = controller.PlayerPawn.Value; + var playerPawnValue = controller?.PlayerPawn.Value; if (playerPawnValue == null) return; playerPawnValue.GravityScale = gravity; } - public static void SetMoney(this CCSPlayerController controller, int money) + public static void SetMoney(this CCSPlayerController? controller, int money) { - var moneyServices = controller.InGameMoneyServices; + var moneyServices = controller?.InGameMoneyServices; if (moneyServices == null) return; moneyServices.Account = money; - Utilities.SetStateChanged(controller, "CCSPlayerController", "m_pInGameMoneyServices"); + if (controller != null) Utilities.SetStateChanged(controller, "CCSPlayerController", "m_pInGameMoneyServices"); } - public static void SetHp(this CCSPlayerController controller, int health = 100) + public static void SetHp(this CCSPlayerController? controller, int health = 100) { - if (health <= 0 || !controller.PawnIsAlive || controller.PlayerPawn.Value == null) return; - + if (controller == null) return; + if ((health <= 0 || !controller.PawnIsAlive || controller.PlayerPawn.Value == null)) return; + controller.PlayerPawn.Value.Health = health; if (health > 100) @@ -116,36 +119,36 @@ public static void ToggleNoclip(this CBasePlayerPawn pawn) } } - public static void Rename(this CCSPlayerController controller, string newName = "Unknown") + public static void Rename(this CCSPlayerController? controller, string newName = "Unknown") { - if (CS2_SimpleAdmin.Instance == null) - return; - newName = newName ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; - SchemaString playerName = new SchemaString(controller, "m_iszPlayerName"); - playerName.Set(newName + " "); - - CS2_SimpleAdmin.Instance.AddTimer(0.25f, () => + if (controller != null) { - Utilities.SetStateChanged(controller, "CCSPlayerController", "m_szClan"); - Utilities.SetStateChanged(controller, "CBasePlayerController", "m_iszPlayerName"); - }); - - CS2_SimpleAdmin.Instance.AddTimer(0.3f, () => - { - playerName.Set(newName); - }); + var playerName = new SchemaString(controller, "m_iszPlayerName"); + playerName.Set(newName + " "); + + CS2_SimpleAdmin.Instance.AddTimer(0.25f, () => + { + Utilities.SetStateChanged(controller, "CCSPlayerController", "m_szClan"); + Utilities.SetStateChanged(controller, "CBasePlayerController", "m_iszPlayerName"); + }); + + CS2_SimpleAdmin.Instance.AddTimer(0.3f, () => + { + playerName.Set(newName); + }); + } CS2_SimpleAdmin.Instance.AddTimer(0.4f, () => { - Utilities.SetStateChanged(controller, "CBasePlayerController", "m_iszPlayerName"); + if (controller != null) Utilities.SetStateChanged(controller, "CBasePlayerController", "m_iszPlayerName"); }); } - public static void TeleportPlayer(this CCSPlayerController controller, CCSPlayerController target) + public static void TeleportPlayer(this CCSPlayerController? controller, CCSPlayerController? target) { - if (controller.PlayerPawn?.Value == null && target!.PlayerPawn?.Value == null) + if (controller?.PlayerPawn?.Value == null && target!.PlayerPawn?.Value == null) return; if ( diff --git a/Helper.cs b/Helper.cs index 51e9e56..88f76cf 100644 --- a/Helper.cs +++ b/Helper.cs @@ -47,28 +47,26 @@ public static List GetPlayerFromIp(string ipAddress) public static List GetValidPlayers() { - return Utilities.GetPlayers().FindAll(p => p != null && p.IsValid && p.SteamID.ToString().Length == 17 && !string.IsNullOrEmpty(p.IpAddress) && p.Connected == PlayerConnectedState.PlayerConnected && !p.IsBot && !p.IsHLTV); + return Utilities.GetPlayers().FindAll(p => p?.IsValid == true && p.SteamID.ToString().Length == 17 && !string.IsNullOrEmpty(p.IpAddress) && p is { Connected: PlayerConnectedState.PlayerConnected, IsBot: false, IsHLTV: false }); } - public static List GetValidPlayersWithBots() + public static IEnumerable GetValidPlayersWithBots() { return Utilities.GetPlayers().FindAll(p => - p != null && p.IsValid && p.SteamID.ToString().Length == 17 && !string.IsNullOrEmpty(p.IpAddress) && p.Connected == PlayerConnectedState.PlayerConnected && !p.IsBot && !p.IsHLTV || - p != null && p.IsValid && p.Connected == PlayerConnectedState.PlayerConnected && p.IsBot && !p.IsHLTV + p.IsValid && p.SteamID.ToString().Length == 17 && !string.IsNullOrEmpty(p.IpAddress) && p is { Connected: PlayerConnectedState.PlayerConnected, IsBot: false, IsHLTV: false } || + p is { IsValid: true, Connected: PlayerConnectedState.PlayerConnected, IsBot: true, IsHLTV: false } ); } - public static bool IsValidSteamID64(string input) + public static bool IsValidSteamId64(string input) { - string pattern = @"^\d{17}$"; - + const string pattern = @"^\d{17}$"; return Regex.IsMatch(input, pattern); } - public static bool IsValidIP(string input) + public static bool IsValidIp(string input) { - string pattern = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; - + const string pattern = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; return Regex.IsMatch(input, pattern); } @@ -81,26 +79,24 @@ public static void GivePlayerFlags(SteamID? steamid, List? flags = null, return; } - if (flags != null) + if (flags == null) return; + foreach (var flag in flags) { - foreach (var flag in flags) + if (string.IsNullOrEmpty(flag)) continue; + + if (flag.StartsWith($"@")) + { + //Console.WriteLine($"Adding permission {flag} to SteamID {steamid}"); + AdminManager.AddPlayerPermissions(steamid, flag); + } + else if (flag.StartsWith($"#")) { - if (!string.IsNullOrEmpty(flag)) - { - if (flag.StartsWith("@")) - { - //Console.WriteLine($"Adding permission {flag} to SteamID {steamid}"); - AdminManager.AddPlayerPermissions(steamid, flag); - } - else if (flag.StartsWith("#")) - { - //Console.WriteLine($"Adding SteamID {steamid} to group {flag}"); - AdminManager.AddPlayerToGroup(steamid, flag); - } - } + //Console.WriteLine($"Adding SteamID {steamid} to group {flag}"); + AdminManager.AddPlayerToGroup(steamid, flag); } - AdminManager.SetPlayerImmunity(steamid, (uint)immunity); } + + AdminManager.SetPlayerImmunity(steamid, (uint)immunity); } catch (Exception) { @@ -112,7 +108,7 @@ public static void KickPlayer(int userId, string? reason = null) { if (!string.IsNullOrEmpty(reason)) { - int escapeChars = reason.IndexOfAny(new char[] { ';', '|' }); + var escapeChars = reason.IndexOfAny([';', '|']); if (escapeChars != -1) { @@ -125,7 +121,7 @@ public static void KickPlayer(int userId, string? reason = null) public static void PrintToCenterAll(string message) { - Utilities.GetPlayers().Where(p => p is not null && p.IsValid && !p.IsBot && !p.IsHLTV).ToList().ForEach(controller => + Utilities.GetPlayers().Where(p => p is { IsValid: true, IsBot: false, IsHLTV: false }).ToList().ForEach(controller => { controller.PrintToCenter(message); }); @@ -142,25 +138,26 @@ internal static void HandleVotes(CCSPlayerController player, ChatMenuOption opti internal static void LogCommand(CCSPlayerController? caller, CommandInfo command) { - if (CS2_SimpleAdmin.Instance == null || CS2_SimpleAdmin._localizer == null) + if (CS2_SimpleAdmin._localizer == null) return; - string playerName = caller?.PlayerName ?? "Console"; + var playerName = caller?.PlayerName ?? "Console"; - string? hostname = ConVar.Find("hostname")!.StringValue ?? CS2_SimpleAdmin._localizer["sa_unknown"]; + var hostname = ConVar.Find("hostname")!.StringValue ?? CS2_SimpleAdmin._localizer["sa_unknown"]; - CS2_SimpleAdmin.Instance.Logger.LogInformation($"{CS2_SimpleAdmin._localizer["sa_discord_log_command", + CS2_SimpleAdmin.Instance.Logger.LogInformation($"{CS2_SimpleAdmin._localizer[ + "sa_discord_log_command", playerName, command.GetCommandString]}".Replace("HOSTNAME", hostname).Replace("**", "")); } internal static void LogCommand(CCSPlayerController? caller, string command) { - if (CS2_SimpleAdmin.Instance == null || CS2_SimpleAdmin._localizer == null) + if (CS2_SimpleAdmin._localizer == null) return; - string playerName = caller?.PlayerName ?? "Console"; + var playerName = caller?.PlayerName ?? "Console"; - string? hostname = ConVar.Find("hostname")!.StringValue ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; + var hostname = ConVar.Find("hostname")!.StringValue ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; CS2_SimpleAdmin.Instance.Logger.LogInformation($"{CS2_SimpleAdmin._localizer?["sa_discord_log_command", playerName, command]}".Replace("HOSTNAME", hostname).Replace("**", "")); @@ -168,8 +165,8 @@ internal static void LogCommand(CCSPlayerController? caller, string command) public static IEnumerable GenerateEmbedsDiscord(string title, string description, string thumbnailUrl, Color color, string[] fieldNames, string[] fieldValues, bool[] inlineFlags) { - string? hostname = ConVar.Find("hostname")!.StringValue ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; - string? address = $"{ConVar.Find("ip")!.StringValue}:{ConVar.Find("hostport")!.GetPrimitiveValue()}"; + var hostname = ConVar.Find("hostname")!.StringValue ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; + var address = $"{ConVar.Find("ip")!.StringValue}:{ConVar.Find("hostport")!.GetPrimitiveValue()}"; description = description.Replace("{hostname}", hostname ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"); description = description.Replace("{address}", address ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"); @@ -182,7 +179,7 @@ public static IEnumerable GenerateEmbedsDiscord(string title, string desc Color = color, }; - for (int i = 0; i < fieldNames.Length; i++) + for (var i = 0; i < fieldNames.Length; i++) { fieldValues[i] = fieldValues[i].Replace("{hostname}", hostname ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"); fieldValues[i] = fieldValues[i].Replace("{address}", address ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"); @@ -200,12 +197,11 @@ public static IEnumerable GenerateEmbedsDiscord(string title, string desc public static void SendDiscordLogMessage(CCSPlayerController? caller, CommandInfo command, DiscordWebhookClient? discordWebhookClientLog, IStringLocalizer? localizer) { - if (discordWebhookClientLog != null && localizer != null) - { - string communityUrl = caller != null ? "<" + new SteamID(caller.SteamID).ToCommunityUrl().ToString() + ">" : ""; - string callerName = caller != null ? caller.PlayerName : "Console"; - discordWebhookClientLog.SendMessageAsync(Helper.GenerateMessageDiscord(localizer["sa_discord_log_command", $"[{callerName}]({communityUrl})", command.GetCommandString])); - } + if (discordWebhookClientLog == null || localizer == null) return; + + var communityUrl = caller != null ? "<" + new SteamID(caller.SteamID).ToCommunityUrl().ToString() + ">" : ""; + var callerName = caller != null ? caller.PlayerName : "Console"; + discordWebhookClientLog.SendMessageAsync(Helper.GenerateMessageDiscord(localizer["sa_discord_log_command", $"[{callerName}]({communityUrl})", command.GetCommandString])); } public enum PenaltyType @@ -216,74 +212,73 @@ public enum PenaltyType Silence, } - public static string ConvertMinutesToTime(int minutes) + private static string ConvertMinutesToTime(int minutes) { - TimeSpan time = TimeSpan.FromMinutes(minutes); + var time = TimeSpan.FromMinutes(minutes); return time.Days > 0 ? $"{time.Days}d {time.Hours}h {time.Minutes}m" : time.Hours > 0 ? $"{time.Hours}h {time.Minutes}m" : $"{time.Minutes}m"; } public static void SendDiscordPenaltyMessage(CCSPlayerController? caller, CCSPlayerController? target, string reason, int duration, PenaltyType penalty, DiscordWebhookClient? discordWebhookClientPenalty, IStringLocalizer? localizer) { - if (discordWebhookClientPenalty != null && localizer != null) + if (discordWebhookClientPenalty == null || localizer == null) return; + + var callerCommunityUrl = caller != null ? "<" + new SteamID(caller.SteamID).ToCommunityUrl().ToString() + ">" : ""; + var targetCommunityUrl = target != null ? "<" + new SteamID(target.SteamID).ToCommunityUrl().ToString() + ">" : ""; + var callerName = caller != null ? caller.PlayerName : "Console"; + var targetName = target != null ? target.PlayerName : localizer?["sa_unknown"] ?? "Unknown"; + var targetSteamId = target != null ? new SteamID(target.SteamID).SteamId2.ToString() : localizer?["sa_unknown"] ?? "Unknown"; + + var time = duration != 0 ? ConvertMinutesToTime(duration) : localizer?["sa_permanent"] ?? "Permanent"; + + string[] fieldNames = [ + localizer?["sa_player"] ?? "Player:", + localizer?["sa_steamid"] ?? "SteamID:", + localizer?["sa_duration"] ?? "Duration:", + localizer?["sa_reason"] ?? "Reason:", + localizer?["sa_admin"] ?? "Admin:"]; + string[] fieldValues = [$"[{targetName}]({targetCommunityUrl})", targetSteamId, time, reason, $"[{callerName}]({callerCommunityUrl})"]; + bool[] inlineFlags = [true, true, true, false, false]; + + var hostname = ConVar.Find("hostname")!.StringValue ?? localizer?["sa_unknown"] ?? "Unknown"; + + var embed = new EmbedBuilder { - string callercommunityUrl = caller != null ? "<" + new SteamID(caller.SteamID).ToCommunityUrl().ToString() + ">" : ""; - string targetcommunityUrl = target != null ? "<" + new SteamID(target.SteamID).ToCommunityUrl().ToString() + ">" : ""; - string callerName = caller != null ? caller.PlayerName : "Console"; - string targetName = target != null ? target.PlayerName : localizer?["sa_unknown"] ?? "Unknown"; - string targetSteamId = target != null ? new SteamID(target.SteamID).SteamId2.ToString() : localizer?["sa_unknown"] ?? "Unknown"; - - string time = duration != 0 ? ConvertMinutesToTime(duration) : localizer?["sa_permanent"] ?? "Permanent"; - - string[] fieldNames = [ - localizer?["sa_player"] ?? "Player:", - localizer?["sa_steamid"] ?? "SteamID:", - localizer?["sa_duration"] ?? "Duration:", - localizer?["sa_reason"] ?? "Reason:", - localizer?["sa_admin"] ?? "Admin:"]; - string[] fieldValues = [$"[{targetName}]({targetcommunityUrl})", targetSteamId, time, reason, $"[{callerName}]({callercommunityUrl})"]; - bool[] inlineFlags = [true, true, true, false, false]; - - string? hostname = ConVar.Find("hostname")!.StringValue ?? localizer?["sa_unknown"] ?? "Unknown"; - - var embed = new EmbedBuilder + Title = penalty switch { - Title = penalty switch - { - PenaltyType.Ban => localizer?["sa_discord_penalty_ban"] ?? "Ban registrered", - PenaltyType.Mute => localizer?["sa_discord_penalty_mute"] ?? "Mute registrered", - PenaltyType.Gag => localizer?["sa_discord_penalty_gag"] ?? "Gag registrered", - PenaltyType.Silence => localizer?["sa_discord_penalty_silence"] ?? "Silence registrered", - _ => localizer?["sa_discord_penalty_unknown"] ?? "Unknown registrered", - }, - - Color = penalty switch - { - PenaltyType.Ban => Color.Red, - PenaltyType.Mute => Color.Blue, - PenaltyType.Gag => Color.Gold, - PenaltyType.Silence => Color.Green, - _ => Color.Default, - }, - - Description = $"{hostname}", + PenaltyType.Ban => localizer?["sa_discord_penalty_ban"] ?? "Ban registrered", + PenaltyType.Mute => localizer?["sa_discord_penalty_mute"] ?? "Mute registrered", + PenaltyType.Gag => localizer?["sa_discord_penalty_gag"] ?? "Gag registrered", + PenaltyType.Silence => localizer?["sa_discord_penalty_silence"] ?? "Silence registrered", + _ => localizer?["sa_discord_penalty_unknown"] ?? "Unknown registrered", + }, + + Color = penalty switch + { + PenaltyType.Ban => Color.Red, + PenaltyType.Mute => Color.Blue, + PenaltyType.Gag => Color.Gold, + PenaltyType.Silence => Color.Green, + _ => Color.Default, + }, - Timestamp = DateTimeOffset.UtcNow - }; + Description = $"{hostname}", - for (int i = 0; i < fieldNames.Length; i++) - { - embed.AddField(fieldNames[i], fieldValues[i], inlineFlags[i]); - } + Timestamp = DateTimeOffset.UtcNow + }; - discordWebhookClientPenalty.SendMessageAsync(embeds: [embed.Build()]); + for (var i = 0; i < fieldNames.Length; i++) + { + embed.AddField(fieldNames[i], fieldValues[i], inlineFlags[i]); } + + discordWebhookClientPenalty.SendMessageAsync(embeds: [embed.Build()]); } - public static string GenerateMessageDiscord(string message) + private static string GenerateMessageDiscord(string message) { - string? hostname = ConVar.Find("hostname")!.StringValue ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; - string? address = $"{ConVar.Find("ip")!.StringValue}:{ConVar.Find("hostport")!.GetPrimitiveValue()}"; + var hostname = ConVar.Find("hostname")!.StringValue ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"; + var address = $"{ConVar.Find("ip")!.StringValue}:{ConVar.Find("hostport")!.GetPrimitiveValue()}"; message = message.Replace("HOSTNAME", hostname); message = message.Replace("ADDRESS", address); @@ -304,7 +299,12 @@ public static string GenerateMessageDiscord(string message) config.Version = newCfgVersion; // serialize the updated config back to json - var updatedJsonContent = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); + var updatedJsonContent = JsonSerializer.Serialize(config, + new JsonSerializerOptions + { + WriteIndented = true, + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }); File.WriteAllText(CfgPath, updatedJsonContent); } @@ -316,22 +316,21 @@ public static void TryLogCommandOnDiscord(CCSPlayerController? caller, string co if (caller != null && caller.IsValid == false) caller = null; - string callerName = caller == null ? "Console" : caller.PlayerName; - string communityUrl = caller != null ? "<" + new SteamID(caller.SteamID).ToCommunityUrl().ToString() + ">" : ""; + var callerName = caller == null ? "Console" : caller.PlayerName; + var communityUrl = caller != null ? "<" + new SteamID(caller.SteamID).ToCommunityUrl().ToString() + ">" : ""; CS2_SimpleAdmin._discordWebhookClientLog.SendMessageAsync(GenerateMessageDiscord(CS2_SimpleAdmin._localizer["sa_discord_log_command", $"[{callerName}]({communityUrl})", commandString])); } } - public class SchemaString : NativeObject where SchemaClass : NativeObject + public class SchemaString(SchemaClass instance, string member) + : NativeObject(Schema.GetSchemaValue(instance.Handle, typeof(SchemaClass).Name!, member)) + where SchemaClass : NativeObject { - public SchemaString(SchemaClass instance, string member) : base(Schema.GetSchemaValue(instance.Handle, typeof(SchemaClass).Name!, member)) - { } - public unsafe void Set(string str) { - byte[] bytes = SchemaString.GetStringBytes(str); + var bytes = SchemaString.GetStringBytes(str); - for (int i = 0; i < bytes.Length; i++) + for (var i = 0; i < bytes.Length; i++) { Unsafe.Write((void*)(Handle.ToInt64() + i), bytes[i]); } diff --git a/Managers/AdminSQLManager.cs b/Managers/AdminSQLManager.cs index 912c403..c0dc9d0 100644 --- a/Managers/AdminSQLManager.cs +++ b/Managers/AdminSQLManager.cs @@ -61,11 +61,11 @@ public class AdminSQLManager(Database database) public async Task, int, DateTime?)>> GetAllPlayersFlags() { - DateTime now = DateTime.UtcNow.ToLocalTime(); + var now = DateTime.UtcNow.ToLocalTime(); try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); + await using var connection = await _database.GetConnectionAsync(); string sql = @" SELECT sa_admins.player_steamid, sa_admins.player_name, sa_admins_flags.flag, sa_admins.immunity, sa_admins.ends @@ -75,7 +75,7 @@ FROM sa_admins_flags AND (sa_admins.server_id IS NULL OR sa_admins.server_id = @serverid) ORDER BY sa_admins.player_steamid"; - List? activeFlags = (await connection.QueryAsync(sql, new { CurrentTime = now, serverid = CS2_SimpleAdmin.ServerId }))?.ToList(); + var activeFlags = (await connection.QueryAsync(sql, new { CurrentTime = now, serverid = CS2_SimpleAdmin.ServerId }))?.ToList(); if (activeFlags == null) { @@ -83,13 +83,13 @@ FROM sa_admins_flags } List<(string, string, List, int, DateTime?)> filteredFlagsWithImmunity = []; - string currentSteamId = string.Empty; - string currentPlayerName = string.Empty; + var currentSteamId = string.Empty; + var currentPlayerName = string.Empty; List currentFlags = []; - int immunityValue = 0; + var immunityValue = 0; DateTime? ends = null; - foreach (dynamic flagInfo in activeFlags) + foreach (var flagInfo in activeFlags) { if (flagInfo is not IDictionary flagInfoDict) { @@ -113,7 +113,7 @@ flagObj is not string flag || continue; } - if (endsObj != null && DateTime.TryParse(endsObj.ToString(), out var parsedEnds)) + if (DateTime.TryParse(endsObj.ToString(), out var parsedEnds)) { ends = parsedEnds; } @@ -207,13 +207,12 @@ FROM sa_admins a } */ - public async Task, int)>> GetAllGroupsData() + private async Task, int)>> GetAllGroupsData() { + await using MySqlConnection connection = await _database.GetConnectionAsync(); try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); - - string sql = "SELECT group_id FROM sa_groups_servers WHERE server_id = @serverid"; + var sql = "SELECT group_id FROM sa_groups_servers WHERE server_id = @serverid"; var groupDataSql = connection.Query(sql, new { serverid = CS2_SimpleAdmin.ServerId }).ToList(); sql = @" @@ -241,7 +240,7 @@ FROM sa_groups_flags f // Check if the group name already exists in the dictionary if (!groupInfoDictionary.TryGetValue(groupName, out (List, int) value)) { - value = (new List(), immunity); + value = ([], immunity); // If it doesn't exist, add a new entry with an empty list of flags and immunity groupInfoDictionary[groupName] = value; } @@ -258,7 +257,7 @@ FROM sa_groups_flags f public async Task CrateGroupsJsonFile() { - Dictionary, int)> groupsData = await GetAllGroupsData(); + var groupsData = await GetAllGroupsData(); var jsonStructure = new Dictionary(); @@ -273,8 +272,8 @@ public async Task CrateGroupsJsonFile() jsonStructure[kvp.Key] = groupData; } - string json = JsonConvert.SerializeObject(jsonStructure, Formatting.Indented); - File.WriteAllText(CS2_SimpleAdmin.Instance.ModuleDirectory + "/data/groups.json", json); + var json = JsonConvert.SerializeObject(jsonStructure, Formatting.Indented); + await File.WriteAllTextAsync(CS2_SimpleAdmin.Instance.ModuleDirectory + "/data/groups.json", json); } /* @@ -370,8 +369,8 @@ public async Task CreateAdminsJsonFile() }) .ToDictionary(item => item.playerName, item => item.playerData); - string json = JsonConvert.SerializeObject(jsonData, Formatting.Indented); - File.WriteAllText(CS2_SimpleAdmin.Instance.ModuleDirectory + "/data/admins.json", json); + var json = JsonConvert.SerializeObject(jsonData, Formatting.Indented); + await File.WriteAllTextAsync(CS2_SimpleAdmin.Instance.ModuleDirectory + "/data/admins.json", json); } public async Task DeleteAdminBySteamId(string playerSteamId, bool globalDelete = false) @@ -382,17 +381,10 @@ public async Task DeleteAdminBySteamId(string playerSteamId, bool globalDelete = try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); - string sql = ""; + await using var connection = await _database.GetConnectionAsync(); - if (globalDelete) - { - sql = "DELETE FROM sa_admins WHERE player_steamid = @PlayerSteamID"; - } - else - { - sql = "DELETE FROM sa_admins WHERE player_steamid = @PlayerSteamID AND server_id = @ServerId"; - } + var sql = ""; + sql = globalDelete ? "DELETE FROM sa_admins WHERE player_steamid = @PlayerSteamID" : "DELETE FROM sa_admins WHERE player_steamid = @PlayerSteamID AND server_id = @ServerId"; await connection.ExecuteAsync(sql, new { PlayerSteamID = playerSteamId, CS2_SimpleAdmin.ServerId }); } @@ -401,9 +393,9 @@ public async Task DeleteAdminBySteamId(string playerSteamId, bool globalDelete = public async Task AddAdminBySteamId(string playerSteamId, string playerName, List flagsList, int immunity = 0, int time = 0, bool globalAdmin = false) { - if (string.IsNullOrEmpty(playerSteamId) || flagsList == null || flagsList.Count == 0) return; + if (string.IsNullOrEmpty(playerSteamId) || flagsList.Count == 0) return; - DateTime now = DateTime.UtcNow.ToLocalTime(); + var now = DateTime.UtcNow.ToLocalTime(); DateTime? futureTime; if (time != 0) @@ -413,13 +405,13 @@ public async Task AddAdminBySteamId(string playerSteamId, string playerName, Lis try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); + await using var connection = await _database.GetConnectionAsync(); // Insert admin into sa_admins table - var insertAdminSql = "INSERT INTO `sa_admins` (`player_steamid`, `player_name`, `immunity`, `ends`, `created`, `server_id`) " + - "VALUES (@playerSteamid, @playerName, @immunity, @ends, @created, @serverid); SELECT LAST_INSERT_ID();"; + const string insertAdminSql = "INSERT INTO `sa_admins` (`player_steamid`, `player_name`, `immunity`, `ends`, `created`, `server_id`) " + + "VALUES (@playerSteamid, @playerName, @immunity, @ends, @created, @serverid); SELECT LAST_INSERT_ID();"; - int adminId = await connection.ExecuteScalarAsync(insertAdminSql, new + var adminId = await connection.ExecuteScalarAsync(insertAdminSql, new { playerSteamId, playerName, @@ -432,14 +424,14 @@ public async Task AddAdminBySteamId(string playerSteamId, string playerName, Lis // Insert flags into sa_admins_flags table foreach (var flag in flagsList) { - if (flag.StartsWith("#")) + if (flag.StartsWith($"#")) { - string sql = "SELECT id FROM `sa_groups` WHERE name = @groupName"; - int? groupId = await connection.QuerySingleOrDefaultAsync(sql, new { groupName = flag }); + const string sql = "SELECT id FROM `sa_groups` WHERE name = @groupName"; + var groupId = await connection.QuerySingleOrDefaultAsync(sql, new { groupName = flag }); if (groupId != null) { - var updateAdminGroup = "UPDATE `sa_admins` SET group_id = @groupId WHERE id = @adminId"; + const string updateAdminGroup = "UPDATE `sa_admins` SET group_id = @groupId WHERE id = @adminId"; await connection.ExecuteAsync(updateAdminGroup, new { groupId, @@ -466,16 +458,15 @@ public async Task AddAdminBySteamId(string playerSteamId, string playerName, Lis public async Task AddGroup(string groupName, List flagsList, int immunity = 0) { - if (string.IsNullOrEmpty(groupName) || flagsList == null || flagsList.Count == 0) return; + if (string.IsNullOrEmpty(groupName) || flagsList.Count == 0) return; + await using var connection = await _database.GetConnectionAsync(); try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); - // Insert group into sa_groups table var insertGroup = "INSERT INTO `sa_groups` (`name`, `immunity`) " + "VALUES (@groupName, @immunity); SELECT LAST_INSERT_ID();"; - int groupId = await connection.ExecuteScalarAsync(insertGroup, new + var groupId = await connection.ExecuteScalarAsync(insertGroup, new { groupName, immunity @@ -484,8 +475,8 @@ public async Task AddGroup(string groupName, List flagsList, int immunit // Insert flags into sa_groups_flags table foreach (var flag in flagsList) { - var insertFlagsSql = "INSERT INTO `sa_groups_flags` (`group_id`, `flag`) " + - "VALUES (@groupId, @flag)"; + const string insertFlagsSql = "INSERT INTO `sa_groups_flags` (`group_id`, `flag`) " + + "VALUES (@groupId, @flag)"; await connection.ExecuteAsync(insertFlagsSql, new { @@ -494,10 +485,10 @@ public async Task AddGroup(string groupName, List flagsList, int immunit }); } + var insertGroupServer = "INSERT INTO `sa_groups_servers` (`group_id`, `server_id`) " + + "VALUES (@groupId, @server_id)"; if (CS2_SimpleAdmin.ServerId != null) { - string insertGroupServer = "INSERT INTO `sa_groups_servers` (`group_id`, `server_id`) " + - "VALUES (@groupId, @server_id)"; await connection.ExecuteAsync(insertGroupServer, new { groupId, server_id = CS2_SimpleAdmin.ServerId }); } } @@ -511,11 +502,10 @@ public async Task DeleteGroup(string groupName) { if (string.IsNullOrEmpty(groupName)) return; + await using var connection = await _database.GetConnectionAsync(); try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); - - string sql = "DELETE FROM `sa_groups` WHERE name = @groupName"; + const string sql = "DELETE FROM `sa_groups` WHERE name = @groupName"; await connection.ExecuteAsync(sql, new { groupName }); } catch (Exception ex) @@ -528,9 +518,9 @@ public async Task DeleteOldAdmins() { try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); + await using var connection = await _database.GetConnectionAsync(); - string sql = "DELETE FROM sa_admins WHERE ends IS NOT NULL AND ends <= @CurrentTime"; + const string sql = "DELETE FROM sa_admins WHERE ends IS NOT NULL AND ends <= @CurrentTime"; await connection.ExecuteAsync(sql, new { CurrentTime = DateTime.Now.ToLocalTime() }); } catch (Exception) diff --git a/Managers/BanManager.cs b/Managers/BanManager.cs index 3e76346..66c7c77 100644 --- a/Managers/BanManager.cs +++ b/Managers/BanManager.cs @@ -19,7 +19,8 @@ public async Task BanPlayer(PlayerInfo player, PlayerInfo issuer, string reason, { await using MySqlConnection connection = await _database.GetConnectionAsync(); - var sql = "INSERT INTO `sa_bans` (`player_steamid`, `player_name`, `player_ip`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `server_id`) " + + var sql = + "INSERT INTO `sa_bans` (`player_steamid`, `player_name`, `player_ip`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `server_id`) " + "VALUES (@playerSteamid, @playerName, @playerIp, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @serverid)"; await connection.ExecuteAsync(sql, new @@ -115,26 +116,22 @@ public async Task IsPlayerBanned(PlayerInfo player) try { - string sql = ""; - - if (_config.MultiServerMode) - { - sql = @" - UPDATE sa_bans - SET player_ip = CASE WHEN player_ip IS NULL THEN @PlayerIP ELSE player_ip END, - player_name = CASE WHEN player_name IS NULL THEN @PlayerName ELSE player_name END - WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP) - AND status = 'ACTIVE' - AND (duration = 0 OR ends > @CurrentTime); - - SELECT COUNT(*) FROM sa_bans - WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP) - AND status = 'ACTIVE' - AND (duration = 0 OR ends > @CurrentTime);"; - } - else - { - sql = @" + var sql = ""; + + sql = _config.MultiServerMode ? """ + + UPDATE sa_bans + SET player_ip = CASE WHEN player_ip IS NULL THEN @PlayerIP ELSE player_ip END, + player_name = CASE WHEN player_name IS NULL THEN @PlayerName ELSE player_name END + WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP) + AND status = 'ACTIVE' + AND (duration = 0 OR ends > @CurrentTime); + + SELECT COUNT(*) FROM sa_bans + WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP) + AND status = 'ACTIVE' + AND (duration = 0 OR ends > @CurrentTime); + """ : @" UPDATE sa_bans SET player_ip = CASE WHEN player_ip IS NULL THEN @PlayerIP ELSE player_ip END, player_name = CASE WHEN player_name IS NULL THEN @PlayerName ELSE player_name END @@ -146,9 +143,8 @@ SELECT COUNT(*) FROM sa_bans WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP) AND status = 'ACTIVE' AND (duration = 0 OR ends > @CurrentTime) AND server_id = @serverid;"; - } - await using MySqlConnection connection = await _database.GetConnectionAsync(); + await using var connection = await _database.GetConnectionAsync(); var parameters = new { @@ -173,28 +169,31 @@ public async Task GetPlayerBans(PlayerInfo player) { try { - string sql = ""; + var sql = ""; - if (_config.MultiServerMode) - { - sql = "SELECT COUNT(*) FROM sa_bans WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP) AND server_id = @serverid"; - } - else - { - sql = "SELECT COUNT(*) FROM sa_bans WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP)"; - } + sql = _config.MultiServerMode + ? "SELECT COUNT(*) FROM sa_bans WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP) AND server_id = @serverid" + : "SELECT COUNT(*) FROM sa_bans WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP)"; int banCount; - await using MySqlConnection connection = await _database.GetConnectionAsync(); + await using var connection = await _database.GetConnectionAsync(); if (!string.IsNullOrEmpty(player.IpAddress)) { - banCount = await connection.ExecuteScalarAsync(sql, new { PlayerSteamID = player.SteamId, PlayerIP = player.IpAddress, serverid = CS2_SimpleAdmin.ServerId }); + banCount = await connection.ExecuteScalarAsync(sql, + new + { + PlayerSteamID = player.SteamId, PlayerIP = player.IpAddress, serverid = CS2_SimpleAdmin.ServerId + }); } else { - banCount = await connection.ExecuteScalarAsync(sql, new { PlayerSteamID = player.SteamId, PlayerIP = DBNull.Value, serverid = CS2_SimpleAdmin.ServerId }); + banCount = await connection.ExecuteScalarAsync(sql, + new + { + PlayerSteamID = player.SteamId, PlayerIP = DBNull.Value, serverid = CS2_SimpleAdmin.ServerId + }); } return banCount; @@ -206,15 +205,15 @@ public async Task GetPlayerBans(PlayerInfo player) public async Task UnbanPlayer(string playerPattern, string adminSteamId, string reason) { - if (playerPattern == null || playerPattern.Length <= 1) + if (playerPattern is not { Length: > 1 }) { return; } try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); + await using var connection = await _database.GetConnectionAsync(); - string sqlRetrieveBans = ""; + var sqlRetrieveBans = ""; if (_config.MultiServerMode) { sqlRetrieveBans = "SELECT id FROM sa_bans WHERE (player_steamid = @pattern OR player_name = @pattern OR player_ip = @pattern) AND status = 'ACTIVE' " + @@ -226,16 +225,17 @@ public async Task UnbanPlayer(string playerPattern, string adminSteamId, string } var bans = await connection.QueryAsync(sqlRetrieveBans, new { pattern = playerPattern, serverid = CS2_SimpleAdmin.ServerId }); - if (!bans.Any()) + var bansList = bans as dynamic[] ?? bans.ToArray(); + if (!bansList.Any()) return; - string sqlAdmin = "SELECT id FROM sa_admins WHERE player_steamid = @adminSteamId"; - string sqlInsertUnban = "INSERT INTO sa_unbans (ban_id, admin_id, reason) VALUES (@banId, @adminId, @reason); SELECT LAST_INSERT_ID();"; + const string sqlAdmin = "SELECT id FROM sa_admins WHERE player_steamid = @adminSteamId"; + var sqlInsertUnban = "INSERT INTO sa_unbans (ban_id, admin_id, reason) VALUES (@banId, @adminId, @reason); SELECT LAST_INSERT_ID();"; - int? sqlAdminId = await connection.ExecuteScalarAsync(sqlAdmin, new { adminSteamId }); - int adminId = sqlAdminId ?? 0; + var sqlAdminId = await connection.ExecuteScalarAsync(sqlAdmin, new { adminSteamId }); + var adminId = sqlAdminId ?? 0; - foreach (var ban in bans) + foreach (var ban in bansList) { int banId = ban.id; int? unbanId; @@ -252,7 +252,7 @@ public async Task UnbanPlayer(string playerPattern, string adminSteamId, string } // Update sa_bans to set unban_id - string sqlUpdateBan = "UPDATE sa_bans SET status = 'UNBANNED', unban_id = @unbanId WHERE id = @banId"; + const string sqlUpdateBan = "UPDATE sa_bans SET status = 'UNBANNED', unban_id = @unbanId WHERE id = @banId"; await connection.ExecuteAsync(sqlUpdateBan, new { unbanId, banId }); } @@ -269,8 +269,8 @@ public async Task CheckOnlinePlayers(List<(string? IpAddress, ulong SteamID, int { try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); - string sql = ""; + await using var connection = await _database.GetConnectionAsync(); + var sql = ""; if (_config.MultiServerMode) { @@ -286,19 +286,21 @@ public async Task CheckOnlinePlayers(List<(string? IpAddress, ulong SteamID, int { if (!UserId.HasValue) continue; - int banCount = 0; + var banCount = 0; if (!string.IsNullOrEmpty(IpAddress)) { - banCount = await connection.ExecuteScalarAsync(sql, new { PlayerSteamID = SteamID, PlayerIP = IpAddress, serverid = CS2_SimpleAdmin.ServerId }); + banCount = await connection.ExecuteScalarAsync(sql, + new { PlayerSteamID = SteamID, PlayerIP = IpAddress, serverid = CS2_SimpleAdmin.ServerId }); } else { - banCount = await connection.ExecuteScalarAsync(sql, new { PlayerSteamID = SteamID, PlayerIP = DBNull.Value, serverid = CS2_SimpleAdmin.ServerId }); + banCount = await connection.ExecuteScalarAsync(sql, + new { PlayerSteamID = SteamID, PlayerIP = DBNull.Value, serverid = CS2_SimpleAdmin.ServerId }); } if (banCount > 0) { - Server.NextFrame(() => + await Server.NextFrameAsync(() => { Helper.KickPlayer(UserId.Value, "Banned"); }); @@ -310,12 +312,11 @@ public async Task CheckOnlinePlayers(List<(string? IpAddress, ulong SteamID, int public async Task ExpireOldBans() { + var currentTime = DateTime.UtcNow.ToLocalTime(); + + await using var connection = await _database.GetConnectionAsync(); try { - DateTime currentTime = DateTime.UtcNow.ToLocalTime(); - - await using MySqlConnection connection = await _database.GetConnectionAsync(); - /* string sql = ""; await using MySqlConnection connection = await _database.GetConnectionAsync(); @@ -324,64 +325,58 @@ public async Task ExpireOldBans() await connection.ExecuteAsync(sql, new { CurrentTime = DateTime.UtcNow.ToLocalTime() }); */ - string sql = ""; - - if (_config.MultiServerMode) - { - sql = @" - UPDATE sa_bans - SET - status = 'EXPIRED' - WHERE - status = 'ACTIVE' - AND - `duration` > 0 - AND - ends <= @currentTime - AND server_id = @serverid"; - } - else - { - sql = @" - UPDATE sa_bans - SET - status = 'EXPIRED' - WHERE - status = 'ACTIVE' - AND - `duration` > 0 - AND - ends <= @currentTime"; - } + var sql = ""; + + sql = _config.MultiServerMode ? """ + + UPDATE sa_bans + SET + status = 'EXPIRED' + WHERE + status = 'ACTIVE' + AND + `duration` > 0 + AND + ends <= @currentTime + AND server_id = @serverid + """ : """ + + UPDATE sa_bans + SET + status = 'EXPIRED' + WHERE + status = 'ACTIVE' + AND + `duration` > 0 + AND + ends <= @currentTime + """; await connection.ExecuteAsync(sql, new { currentTime, serverid = CS2_SimpleAdmin.ServerId }); if (_config.ExpireOldIpBans > 0) { - DateTime ipBansTime = currentTime.AddDays(-_config.ExpireOldIpBans).ToLocalTime(); - if (_config.MultiServerMode) - { - sql = @" - UPDATE sa_bans - SET - player_ip = NULL - WHERE - status = 'ACTIVE' - AND - ends <= @ipBansTime - AND server_id = @serverid"; - } - else - { - sql = @" - UPDATE sa_bans - SET - player_ip = NULL - WHERE - status = 'ACTIVE' - AND - ends <= @ipBansTime"; - } + var ipBansTime = currentTime.AddDays(-_config.ExpireOldIpBans).ToLocalTime(); + sql = _config.MultiServerMode ? """ + + UPDATE sa_bans + SET + player_ip = NULL + WHERE + status = 'ACTIVE' + AND + ends <= @ipBansTime + AND server_id = @serverid + """ : """ + + UPDATE sa_bans + SET + player_ip = NULL + WHERE + status = 'ACTIVE' + AND + ends <= @ipBansTime + """; await connection.ExecuteAsync(sql, new { ipBansTime, CS2_SimpleAdmin.ServerId }); } diff --git a/Managers/MuteManager.cs b/Managers/MuteManager.cs index eb698f0..8ce9787 100644 --- a/Managers/MuteManager.cs +++ b/Managers/MuteManager.cs @@ -10,23 +10,25 @@ internal class MuteManager(Database database) public async Task MutePlayer(PlayerInfo player, PlayerInfo issuer, string reason, int time = 0, int type = 0) { - if (player == null || player.SteamId == null) return; + if (player.SteamId == null) return; - DateTime now = DateTime.UtcNow.ToLocalTime(); - DateTime futureTime = now.AddMinutes(time).ToLocalTime(); + var now = DateTime.UtcNow.ToLocalTime(); + var futureTime = now.AddMinutes(time).ToLocalTime(); - string muteType = "GAG"; - if (type == 1) - muteType = "MUTE"; - else if (type == 2) - muteType = "SILENCE"; + var muteType = type switch + { + 1 => "MUTE", + 2 => "SILENCE", + _ => "GAG" + }; try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); - var sql = "INSERT INTO `sa_mutes` (`player_steamid`, `player_name`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `type`, `server_id`) " + - "VALUES (@playerSteamid, @playerName, @adminSteamid, @adminName, @muteReason, @duration, @ends, @created, @type, @serverid)"; + await using var connection = await _database.GetConnectionAsync(); + const string sql = + "INSERT INTO `sa_mutes` (`player_steamid`, `player_name`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `type`, `server_id`) " + + "VALUES (@playerSteamid, @playerName, @adminSteamid, @adminName, @muteReason, @duration, @ends, @created, @type, @serverid)"; await connection.ExecuteAsync(sql, new { @@ -50,20 +52,21 @@ public async Task AddMuteBySteamid(string playerSteamId, PlayerInfo issuer, stri if (string.IsNullOrEmpty(playerSteamId)) return; - DateTime now = DateTime.UtcNow.ToLocalTime(); - DateTime futureTime = now.AddMinutes(time).ToLocalTime(); + var now = DateTime.UtcNow.ToLocalTime(); + var futureTime = now.AddMinutes(time).ToLocalTime(); - string muteType = "GAG"; - if (type == 1) - muteType = "MUTE"; - else if (type == 2) - muteType = "SILENCE"; + var muteType = type switch + { + 1 => "MUTE", + 2 => "SILENCE", + _ => "GAG" + }; try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); - var sql = "INSERT INTO `sa_mutes` (`player_steamid`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `type`, `server_id`) " + - "VALUES (@playerSteamid, @adminSteamid, @adminName, @muteReason, @duration, @ends, @created, @type, @serverid)"; + await using var connection = await _database.GetConnectionAsync(); + const string sql = "INSERT INTO `sa_mutes` (`player_steamid`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `type`, `server_id`) " + + "VALUES (@playerSteamid, @adminSteamid, @adminName, @muteReason, @duration, @ends, @created, @type, @serverid)"; await connection.ExecuteAsync(sql, new { @@ -95,9 +98,9 @@ public async Task> IsPlayerMuted(string steamId) try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); - DateTime currentTime = DateTime.Now.ToLocalTime(); - string sql = ""; + await using var connection = await _database.GetConnectionAsync(); + var currentTime = DateTime.Now.ToLocalTime(); + var sql = ""; if (CS2_SimpleAdmin.Instance.Config.MultiServerMode) { @@ -123,21 +126,15 @@ public async Task GetPlayerMutes(string steamId) { try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); + await using var connection = await _database.GetConnectionAsync(); - int muteCount; - string sql = ""; + var sql = ""; - if (CS2_SimpleAdmin.Instance.Config.MultiServerMode) - { - sql = "SELECT COUNT(*) FROM sa_mutes WHERE player_steamid = @PlayerSteamID AND server_id = @serverid"; - } - else - { - sql = "SELECT COUNT(*) FROM sa_mutes WHERE player_steamid = @PlayerSteamID"; - } + sql = CS2_SimpleAdmin.Instance.Config.MultiServerMode + ? "SELECT COUNT(*) FROM sa_mutes WHERE player_steamid = @PlayerSteamID AND server_id = @serverid" + : "SELECT COUNT(*) FROM sa_mutes WHERE player_steamid = @PlayerSteamID"; - muteCount = await connection.ExecuteScalarAsync(sql, new { PlayerSteamID = steamId, serverid = CS2_SimpleAdmin.ServerId }); + var muteCount = await connection.ExecuteScalarAsync(sql, new { PlayerSteamID = steamId, serverid = CS2_SimpleAdmin.ServerId }); return muteCount; } catch (Exception) @@ -148,24 +145,23 @@ public async Task GetPlayerMutes(string steamId) public async Task UnmutePlayer(string playerPattern, string adminSteamId, string reason, int type = 0) { - if (playerPattern == null || playerPattern.Length <= 1) + if (playerPattern.Length <= 1) { return; } try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); + await using var connection = await _database.GetConnectionAsync(); - string muteType = "GAG"; - if (type == 1) + var muteType = type switch { - muteType = "MUTE"; - } - else if (type == 2) - muteType = "SILENCE"; + 1 => "MUTE", + 2 => "SILENCE", + _ => "GAG" + }; - string sqlRetrieveMutes = ""; + var sqlRetrieveMutes = ""; if (CS2_SimpleAdmin.Instance.Config.MultiServerMode) { @@ -180,16 +176,17 @@ public async Task UnmutePlayer(string playerPattern, string adminSteamId, string var mutes = await connection.QueryAsync(sqlRetrieveMutes, new { pattern = playerPattern, muteType, serverid = CS2_SimpleAdmin.ServerId }); - if (!mutes.Any()) + var mutesList = mutes as dynamic[] ?? mutes.ToArray(); + if (mutesList.Length == 0) return; - string sqlAdmin = "SELECT id FROM sa_admins WHERE player_steamid = @adminSteamId"; - string sqlInsertUnmute = "INSERT INTO sa_unmutes (mute_id, admin_id, reason) VALUES (@muteId, @adminId, @reason); SELECT LAST_INSERT_ID();"; + const string sqlAdmin = "SELECT id FROM sa_admins WHERE player_steamid = @adminSteamId"; + var sqlInsertUnmute = "INSERT INTO sa_unmutes (mute_id, admin_id, reason) VALUES (@muteId, @adminId, @reason); SELECT LAST_INSERT_ID();"; - int? sqlAdminId = await connection.ExecuteScalarAsync(sqlAdmin, new { adminSteamId }); - int adminId = sqlAdminId ?? 0; + var sqlAdminId = await connection.ExecuteScalarAsync(sqlAdmin, new { adminSteamId }); + var adminId = sqlAdminId ?? 0; - foreach (var mute in mutes) + foreach (var mute in mutesList) { int muteId = mute.id; int? unmuteId; @@ -206,7 +203,7 @@ public async Task UnmutePlayer(string playerPattern, string adminSteamId, string } // Update sa_mutes to set unmute_id - string sqlUpdateMute = "UPDATE sa_mutes SET status = 'UNMUTED', unmute_id = @unmuteId WHERE id = @muteId"; + const string sqlUpdateMute = "UPDATE sa_mutes SET status = 'UNMUTED', unmute_id = @unmuteId WHERE id = @muteId"; await connection.ExecuteAsync(sqlUpdateMute, new { unmuteId, muteId }); } } @@ -220,17 +217,12 @@ public async Task ExpireOldMutes() { try { - await using MySqlConnection connection = await _database.GetConnectionAsync(); + await using var connection = await _database.GetConnectionAsync(); - string sql = ""; - if (CS2_SimpleAdmin.Instance.Config.MultiServerMode) - { - sql = "UPDATE sa_mutes SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND `duration` > 0 AND ends <= @CurrentTime AND server_id = @serverid"; - } - else - { - sql = "UPDATE sa_mutes SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND `duration` > 0 AND ends <= @CurrentTime"; - } + var sql = ""; + sql = CS2_SimpleAdmin.Instance.Config.MultiServerMode + ? "UPDATE sa_mutes SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND `duration` > 0 AND ends <= @CurrentTime AND server_id = @serverid" + : "UPDATE sa_mutes SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND `duration` > 0 AND ends <= @CurrentTime"; await connection.ExecuteAsync(sql, new { CurrentTime = DateTime.Now.ToLocalTime(), serverid = CS2_SimpleAdmin.ServerId }); } diff --git a/Managers/PlayerPenaltyManager.cs b/Managers/PlayerPenaltyManager.cs index 5a9efb8..4392079 100644 --- a/Managers/PlayerPenaltyManager.cs +++ b/Managers/PlayerPenaltyManager.cs @@ -11,13 +11,13 @@ public enum PenaltyType public class PlayerPenaltyManager { - private static ConcurrentDictionary>> penalties = + private static readonly ConcurrentDictionary>> Penalties = new ConcurrentDictionary>>(); // Add a penalty for a player public static void AddPenalty(int slot, PenaltyType penaltyType, DateTime endDateTime, int durationSeconds) { - penalties.AddOrUpdate(slot, + Penalties.AddOrUpdate(slot, (_) => { var dict = new Dictionary> @@ -28,11 +28,13 @@ public static void AddPenalty(int slot, PenaltyType penaltyType, DateTime endDat }, (_, existingDict) => { - if (!existingDict.ContainsKey(penaltyType)) + if (!existingDict.TryGetValue(penaltyType, out var value)) { - existingDict[penaltyType] = new List<(DateTime, int)>(); + value = new List<(DateTime, int)>(); + existingDict[penaltyType] = value; } - existingDict[penaltyType].Add((endDateTime, durationSeconds)); + + value.Add((endDateTime, durationSeconds)); return existingDict; }); } @@ -41,49 +43,47 @@ public static bool IsPenalized(int slot, PenaltyType penaltyType) { //Console.WriteLine($"Checking penalties for player with slot {slot} and penalty type {penaltyType}"); - if (penalties.TryGetValue(slot, out var penaltyDict) && penaltyDict.TryGetValue(penaltyType, out var penaltiesList)) - { - //Console.WriteLine($"Found penalties for player with slot {slot} and penalty type {penaltyType}"); + if (!Penalties.TryGetValue(slot, out var penaltyDict) || + !penaltyDict.TryGetValue(penaltyType, out var penaltiesList)) return false; + //Console.WriteLine($"Found penalties for player with slot {slot} and penalty type {penaltyType}"); - DateTime now = DateTime.UtcNow.ToLocalTime(); + var now = DateTime.UtcNow.ToLocalTime(); - // Check if any active penalties exist - foreach (var penalty in penaltiesList.ToList()) + // Check if any active penalties exist + foreach (var penalty in penaltiesList.ToList()) + { + // Check if the penalty is still active + if (penalty.Duration > 0 && now >= penalty.EndDateTime.AddSeconds(penalty.Duration)) { - // Check if the penalty is still active - if (penalty.Duration > 0 && now >= penalty.EndDateTime.AddSeconds(penalty.Duration)) + //Console.WriteLine($"Removing expired penalty for player with slot {slot} and penalty type {penaltyType}"); + penaltiesList.Remove(penalty); // Remove expired penalty + if (penaltiesList.Count == 0) { - //Console.WriteLine($"Removing expired penalty for player with slot {slot} and penalty type {penaltyType}"); - penaltiesList.Remove(penalty); // Remove expired penalty - if (penaltiesList.Count == 0) - { - //Console.WriteLine($"No more penalties of type {penaltyType} for player with slot {slot}. Removing penalty type."); - penaltyDict.Remove(penaltyType); // Remove penalty type if no more penalties exist - } - } - else if (penalty.Duration == 0 || now < penalty.EndDateTime) - { - //Console.WriteLine($"Player with slot {slot} is penalized for type {penaltyType}"); - // Return true if there's an active penalty - return true; + //Console.WriteLine($"No more penalties of type {penaltyType} for player with slot {slot}. Removing penalty type."); + penaltyDict.Remove(penaltyType); // Remove penalty type if no more penalties exist } } - - // Return false if no active penalties are found - //Console.WriteLine($"Player with slot {slot} is not penalized for type {penaltyType}"); - return false; + else if (penalty.Duration == 0 || now < penalty.EndDateTime) + { + //Console.WriteLine($"Player with slot {slot} is penalized for type {penaltyType}"); + // Return true if there's an active penalty + return true; + } } + // Return false if no active penalties are found + //Console.WriteLine($"Player with slot {slot} is not penalized for type {penaltyType}"); + return false; + // Return false if no penalties of the specified type were found for the player //Console.WriteLine($"No penalties found for player with slot {slot} and penalty type {penaltyType}"); - return false; } // Get the end datetime and duration of penalties for a player and penalty type public static List<(DateTime EndDateTime, int Duration)> GetPlayerPenalties(int slot, PenaltyType penaltyType) { - if (penalties.TryGetValue(slot, out Dictionary>? penaltyDict) && - penaltyDict.TryGetValue(penaltyType, out List<(DateTime EndDateTime, int Duration)>? penaltiesList) && penaltiesList != null) + if (Penalties.TryGetValue(slot, out var penaltyDict) && + penaltyDict.TryGetValue(penaltyType, out var penaltiesList)) { return penaltiesList; } @@ -92,28 +92,28 @@ public static bool IsPenalized(int slot, PenaltyType penaltyType) public static bool IsSlotInPenalties(int slot) { - return penalties.ContainsKey(slot); + return Penalties.ContainsKey(slot); } // Remove all penalties for a player slot public static void RemoveAllPenalties(int slot) { - if (penalties.ContainsKey(slot)) + if (Penalties.ContainsKey(slot)) { - penalties.TryRemove(slot, out _); + Penalties.TryRemove(slot, out _); } } // Remove all penalties public static void RemoveAllPenalties() { - penalties.Clear(); + Penalties.Clear(); } // Remove all penalties of a selected type from a specific player public static void RemovePenaltiesByType(int slot, PenaltyType penaltyType) { - if (penalties.TryGetValue(slot, out Dictionary>? penaltyDict) && + if (Penalties.TryGetValue(slot, out Dictionary>? penaltyDict) && penaltyDict.ContainsKey(penaltyType)) { penaltyDict.Remove(penaltyType); @@ -123,8 +123,8 @@ public static void RemovePenaltiesByType(int slot, PenaltyType penaltyType) // Remove all expired penalties for all players and penalty types public static void RemoveExpiredPenalties() { - DateTime now = DateTime.UtcNow.ToLocalTime(); - foreach (var kvp in penalties.ToList()) // Use ToList to avoid modification while iterating + var now = DateTime.UtcNow.ToLocalTime(); + foreach (var kvp in Penalties.ToList()) // Use ToList to avoid modification while iterating { var playerSlot = kvp.Key; var penaltyDict = kvp.Value; @@ -138,7 +138,7 @@ public static void RemoveExpiredPenalties() // Remove player slot if no penalties left if (penaltyDict.Count == 0) { - penalties.TryRemove(playerSlot, out _); + Penalties.TryRemove(playerSlot, out _); } } } diff --git a/Menus/DurationMenu.cs b/Menus/DurationMenu.cs index b6d28cc..29806a6 100644 --- a/Menus/DurationMenu.cs +++ b/Menus/DurationMenu.cs @@ -16,7 +16,7 @@ public static class DurationMenu new Tuple("Permanent", 0) }; - public static void OpenMenu(CCSPlayerController admin, string menuName, CCSPlayerController player, Action onSelectAction) + public static void OpenMenu(CCSPlayerController admin, string menuName, CCSPlayerController? player, Action onSelectAction) { BaseMenu menu = AdminMenu.CreateMenu(menuName); diff --git a/Menus/FunActionsMenu.cs b/Menus/FunActionsMenu.cs index 59b8909..5778e1c 100644 --- a/Menus/FunActionsMenu.cs +++ b/Menus/FunActionsMenu.cs @@ -15,7 +15,7 @@ private static Dictionary GetWeaponsCache { if (_weaponsCache == null) { - Array weaponsArray = Enum.GetValues(typeof(CsItem)); + var weaponsArray = Enum.GetValues(typeof(CsItem)); // avoid duplicates in the menu _weaponsCache = new(); @@ -44,12 +44,12 @@ public static void OpenMenu(CCSPlayerController admin) return; } - BaseMenu menu = AdminMenu.CreateMenu("Fun Actions"); + var menu = AdminMenu.CreateMenu("Fun Actions"); List options = new(); // permissions - bool hasCheats = AdminManager.PlayerHasPermissions(admin, "@css/cheats"); - bool hasSlay = AdminManager.PlayerHasPermissions(admin, "@css/slay"); + var hasCheats = AdminManager.PlayerHasPermissions(admin, "@css/cheats"); + var hasSlay = AdminManager.PlayerHasPermissions(admin, "@css/slay"); // TODO: Localize options // options added in order @@ -72,35 +72,35 @@ public static void OpenMenu(CCSPlayerController admin) options.Add(new ChatMenuOptionData("Set Money", () => PlayersMenu.OpenMenu(admin, "Set Money", SetMoneyMenu))); } - foreach (ChatMenuOptionData menuOptionData in options) + foreach (var menuOptionData in options) { - string menuName = menuOptionData.name; + var menuName = menuOptionData.name; menu.AddMenuOption(menuName, (_, _) => { menuOptionData.action?.Invoke(); }, menuOptionData.disabled); } AdminMenu.OpenMenu(admin, menu); } - private static void GodMode(CCSPlayerController admin, CCSPlayerController player) + private static void GodMode(CCSPlayerController admin, CCSPlayerController? player) { CS2_SimpleAdmin.Instance.God(admin, player); } - private static void NoClip(CCSPlayerController admin, CCSPlayerController player) + private static void NoClip(CCSPlayerController admin, CCSPlayerController? player) { CS2_SimpleAdmin.Instance.NoClip(admin, player); } - private static void Respawn(CCSPlayerController admin, CCSPlayerController player) + private static void Respawn(CCSPlayerController admin, CCSPlayerController? player) { CS2_SimpleAdmin.Instance.Respawn(admin, player); } private static void GiveWeaponMenu(CCSPlayerController admin, CCSPlayerController player) { - BaseMenu menu = AdminMenu.CreateMenu($"Give Weapon: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Give Weapon: {player.PlayerName}"); - foreach (KeyValuePair weapon in GetWeaponsCache) + foreach (var weapon in GetWeaponsCache) { menu.AddMenuOption(weapon.Value.ToString(), (_, _) => { GiveWeapon(admin, player, weapon.Value); }); } @@ -113,14 +113,14 @@ private static void GiveWeapon(CCSPlayerController admin, CCSPlayerController pl CS2_SimpleAdmin.Instance.GiveWeapon(admin, player, weaponValue); } - private static void StripWeapons(CCSPlayerController admin, CCSPlayerController player) + private static void StripWeapons(CCSPlayerController admin, CCSPlayerController? player) { CS2_SimpleAdmin.Instance.StripWeapons(admin, player); } - private static void Freeze(CCSPlayerController admin, CCSPlayerController player) + private static void Freeze(CCSPlayerController admin, CCSPlayerController? player) { - if (!(player.PlayerPawn?.Value?.IsValid ?? false)) + if (!(player?.PlayerPawn?.Value?.IsValid ?? false)) return; if (player.PlayerPawn.Value.MoveType != MoveType_t.MOVETYPE_OBSOLETE) @@ -129,9 +129,9 @@ private static void Freeze(CCSPlayerController admin, CCSPlayerController player CS2_SimpleAdmin.Instance.Unfreeze(admin, player); } - private static void SetHpMenu(CCSPlayerController admin, CCSPlayerController player) + private static void SetHpMenu(CCSPlayerController admin, CCSPlayerController? player) { - Tuple[] _hpArray = new[] + var hpArray = new[] { new Tuple("1", 1), new Tuple("10", 10), @@ -143,25 +143,25 @@ private static void SetHpMenu(CCSPlayerController admin, CCSPlayerController pla new Tuple("999", 999) }; - BaseMenu menu = AdminMenu.CreateMenu($"Set HP: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Set HP: {player?.PlayerName}"); - foreach (Tuple hpTuple in _hpArray) + foreach (var hpTuple in hpArray) { - string optionName = hpTuple.Item1; + var optionName = hpTuple.Item1; menu.AddMenuOption(optionName, (_, _) => { SetHP(admin, player, hpTuple.Item2); }); } AdminMenu.OpenMenu(admin, menu); } - private static void SetHP(CCSPlayerController admin, CCSPlayerController player, int hp) + private static void SetHP(CCSPlayerController admin, CCSPlayerController? player, int hp) { CS2_SimpleAdmin.Instance.SetHp(admin, player, hp); } - private static void SetSpeedMenu(CCSPlayerController admin, CCSPlayerController player) + private static void SetSpeedMenu(CCSPlayerController admin, CCSPlayerController? player) { - Tuple[] _speedArray = new[] + var speedArray = new[] { new Tuple("0.1", .1f), new Tuple("0.25", .25f), @@ -173,25 +173,25 @@ private static void SetSpeedMenu(CCSPlayerController admin, CCSPlayerController new Tuple("4", 4) }; - BaseMenu menu = AdminMenu.CreateMenu($"Set Speed: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Set Speed: {player?.PlayerName}"); - foreach (Tuple speedTuple in _speedArray) + foreach (var speedTuple in speedArray) { - string optionName = speedTuple.Item1; + var optionName = speedTuple.Item1; menu.AddMenuOption(optionName, (_, _) => { SetSpeed(admin, player, speedTuple.Item2); }); } AdminMenu.OpenMenu(admin, menu); } - private static void SetSpeed(CCSPlayerController admin, CCSPlayerController player, float speed) + private static void SetSpeed(CCSPlayerController admin, CCSPlayerController? player, float speed) { CS2_SimpleAdmin.Instance.SetSpeed(admin, player, speed); } - private static void SetGravityMenu(CCSPlayerController admin, CCSPlayerController player) + private static void SetGravityMenu(CCSPlayerController admin, CCSPlayerController? player) { - Tuple[] _gravityArray = new[] + var gravityArray = new[] { new Tuple("0.1", .1f), new Tuple("0.25", .25f), @@ -201,25 +201,25 @@ private static void SetGravityMenu(CCSPlayerController admin, CCSPlayerControlle new Tuple("2", 2) }; - BaseMenu menu = AdminMenu.CreateMenu($"Set Gravity: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Set Gravity: {player?.PlayerName}"); - foreach (Tuple gravityTuple in _gravityArray) + foreach (var gravityTuple in gravityArray) { - string optionName = gravityTuple.Item1; + var optionName = gravityTuple.Item1; menu.AddMenuOption(optionName, (_, _) => { SetGravity(admin, player, gravityTuple.Item2); }); } AdminMenu.OpenMenu(admin, menu); } - private static void SetGravity(CCSPlayerController admin, CCSPlayerController player, float gravity) + private static void SetGravity(CCSPlayerController admin, CCSPlayerController? player, float gravity) { CS2_SimpleAdmin.Instance.SetGravity(admin, player, gravity); } - private static void SetMoneyMenu(CCSPlayerController admin, CCSPlayerController player) + private static void SetMoneyMenu(CCSPlayerController admin, CCSPlayerController? player) { - Tuple[] _moneyArray = new[] + var moneyArray = new[] { new Tuple("$0", 0), new Tuple("$1000", 1000), @@ -229,18 +229,18 @@ private static void SetMoneyMenu(CCSPlayerController admin, CCSPlayerController new Tuple("$16000", 16000) }; - BaseMenu menu = AdminMenu.CreateMenu($"Set Money: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Set Money: {player?.PlayerName}"); - foreach (Tuple moneyTuple in _moneyArray) + foreach (var moneyTuple in moneyArray) { - string optionName = moneyTuple.Item1; + var optionName = moneyTuple.Item1; menu.AddMenuOption(optionName, (_, _) => { SetMoney(admin, player, moneyTuple.Item2); }); } AdminMenu.OpenMenu(admin, menu); } - private static void SetMoney(CCSPlayerController admin, CCSPlayerController player, int money) + private static void SetMoney(CCSPlayerController admin, CCSPlayerController? player, int money) { CS2_SimpleAdmin.Instance.SetMoney(admin, player, money); } diff --git a/Menus/ManageAdminsMenu.cs b/Menus/ManageAdminsMenu.cs index 0fb1fd0..6d9c81b 100644 --- a/Menus/ManageAdminsMenu.cs +++ b/Menus/ManageAdminsMenu.cs @@ -28,9 +28,9 @@ public static void OpenMenu(CCSPlayerController admin) options.Add(new ChatMenuOptionData("Remove Admin", () => PlayersMenu.OpenAdminPlayersMenu(admin, "Remove Admin", RemoveAdmin, player => player != admin && admin.CanTarget(player)))); options.Add(new ChatMenuOptionData("Reload Admins", () => ReloadAdmins(admin))); - foreach (ChatMenuOptionData menuOptionData in options) + foreach (var menuOptionData in options) { - string menuName = menuOptionData.name; + var menuName = menuOptionData.name; menu.AddMenuOption(menuName, (_, _) => { menuOptionData.action?.Invoke(); }, menuOptionData.disabled); } @@ -39,7 +39,7 @@ public static void OpenMenu(CCSPlayerController admin) private static void AddAdminMenu(CCSPlayerController admin, CCSPlayerController player) { - Tuple[] flags = new[] + var flags = new[] { new Tuple("Generic", "@css/generic"), new Tuple("Chat", "@css/chat"), @@ -54,12 +54,12 @@ private static void AddAdminMenu(CCSPlayerController admin, CCSPlayerController new Tuple("Root", "@css/root"), }; - BaseMenu menu = AdminMenu.CreateMenu($"Add Admin: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Add Admin: {player.PlayerName}"); - foreach (Tuple flagsTuple in flags) + foreach (var flagsTuple in flags) { - string optionName = flagsTuple.Item1; - bool disabled = AdminManager.PlayerHasPermissions(player, flagsTuple.Item2); + var optionName = flagsTuple.Item1; + var disabled = AdminManager.PlayerHasPermissions(player, flagsTuple.Item2); menu.AddMenuOption(optionName, (_, _) => { AddAdmin(admin, player, flagsTuple.Item2); }, disabled); } diff --git a/Menus/ManagePlayersMenu.cs b/Menus/ManagePlayersMenu.cs index 7825838..814c5d4 100644 --- a/Menus/ManagePlayersMenu.cs +++ b/Menus/ManagePlayersMenu.cs @@ -9,7 +9,7 @@ public static class ManagePlayersMenu { public static void OpenMenu(CCSPlayerController admin) { - if (admin == null || admin.IsValid == false) + if (admin.IsValid == false) return; if (AdminManager.PlayerHasPermissions(admin, "@css/generic") == false) @@ -19,14 +19,14 @@ public static void OpenMenu(CCSPlayerController admin) return; } - BaseMenu menu = AdminMenu.CreateMenu("Manage Players"); + var menu = AdminMenu.CreateMenu("Manage Players"); List options = []; // permissions - bool hasSlay = AdminManager.PlayerHasPermissions(admin, "@css/slay"); - bool hasKick = AdminManager.PlayerHasPermissions(admin, "@css/kick"); - bool hasBan = AdminManager.PlayerHasPermissions(admin, "@css/ban"); - bool hasChat = AdminManager.PlayerHasPermissions(admin, "@css/chat"); + var hasSlay = AdminManager.PlayerHasPermissions(admin, "@css/slay"); + var hasKick = AdminManager.PlayerHasPermissions(admin, "@css/kick"); + var hasBan = AdminManager.PlayerHasPermissions(admin, "@css/ban"); + var hasChat = AdminManager.PlayerHasPermissions(admin, "@css/chat"); // TODO: Localize options // options added in order @@ -44,14 +44,14 @@ public static void OpenMenu(CCSPlayerController admin) if (hasBan) { - options.Add(new ChatMenuOptionData("Ban", () => PlayersMenu.OpenRealPlayersMenu(admin, "Ban", (admin, player) => DurationMenu.OpenMenu(admin, $"Ban: {player.PlayerName}", player, BanMenu)))); + options.Add(new ChatMenuOptionData("Ban", () => PlayersMenu.OpenRealPlayersMenu(admin, "Ban", (admin, player) => DurationMenu.OpenMenu(admin, $"Ban: {player?.PlayerName}", player, BanMenu)))); } if (hasChat) { - options.Add(new ChatMenuOptionData("Gag", () => PlayersMenu.OpenRealPlayersMenu(admin, "Gag", (admin, player) => DurationMenu.OpenMenu(admin, $"Gag: {player.PlayerName}", player, GagMenu)))); - options.Add(new ChatMenuOptionData("Mute", () => PlayersMenu.OpenRealPlayersMenu(admin, "Mute", (admin, player) => DurationMenu.OpenMenu(admin, $"Mute: {player.PlayerName}", player, MuteMenu)))); - options.Add(new ChatMenuOptionData("Silence", () => PlayersMenu.OpenRealPlayersMenu(admin, "Silence", (admin, player) => DurationMenu.OpenMenu(admin, $"Silence: {player.PlayerName}", player, SilenceMenu)))); + options.Add(new ChatMenuOptionData("Gag", () => PlayersMenu.OpenRealPlayersMenu(admin, "Gag", (admin, player) => DurationMenu.OpenMenu(admin, $"Gag: {player?.PlayerName}", player, GagMenu)))); + options.Add(new ChatMenuOptionData("Mute", () => PlayersMenu.OpenRealPlayersMenu(admin, "Mute", (admin, player) => DurationMenu.OpenMenu(admin, $"Mute: {player?.PlayerName}", player, MuteMenu)))); + options.Add(new ChatMenuOptionData("Silence", () => PlayersMenu.OpenRealPlayersMenu(admin, "Silence", (admin, player) => DurationMenu.OpenMenu(admin, $"Silence: {player?.PlayerName}", player, SilenceMenu)))); } if (hasKick) @@ -59,18 +59,18 @@ public static void OpenMenu(CCSPlayerController admin) options.Add(new ChatMenuOptionData("Force Team", () => PlayersMenu.OpenMenu(admin, "Force Team", ForceTeamMenu))); } - foreach (ChatMenuOptionData menuOptionData in options) + foreach (var menuOptionData in options) { - string menuName = menuOptionData.name; + var menuName = menuOptionData.name; menu.AddMenuOption(menuName, (_, _) => { menuOptionData.action?.Invoke(); }, menuOptionData.disabled); } AdminMenu.OpenMenu(admin, menu); } - private static void SlapMenu(CCSPlayerController admin, CCSPlayerController player) + private static void SlapMenu(CCSPlayerController admin, CCSPlayerController? player) { - BaseMenu menu = AdminMenu.CreateMenu($"Slap: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Slap: {player?.PlayerName}"); List options = [ // options added in order @@ -82,33 +82,31 @@ private static void SlapMenu(CCSPlayerController admin, CCSPlayerController play new ChatMenuOptionData("100 hp", () => ApplySlapAndKeepMenu(admin, player, 100)), ]; - foreach (ChatMenuOptionData menuOptionData in options) + foreach (var menuOptionData in options) { - string menuName = menuOptionData.name; + var menuName = menuOptionData.name; menu.AddMenuOption(menuName, (_, _) => { menuOptionData.action?.Invoke(); }, menuOptionData.disabled); } AdminMenu.OpenMenu(admin, menu); } - private static void ApplySlapAndKeepMenu(CCSPlayerController admin, CCSPlayerController player, int damage) + private static void ApplySlapAndKeepMenu(CCSPlayerController admin, CCSPlayerController? player, int damage) { - if (player is not null && player.IsValid) - { - CS2_SimpleAdmin.Instance.Slap(admin, player, damage); - SlapMenu(admin, player); - } + if (player is null || !player.IsValid) return; + CS2_SimpleAdmin.Instance.Slap(admin, player, damage); + SlapMenu(admin, player); } - private static void Slay(CCSPlayerController admin, CCSPlayerController player) + private static void Slay(CCSPlayerController admin, CCSPlayerController? player) { if (player is not null && player.IsValid) CS2_SimpleAdmin.Instance.Slay(admin, player); } - private static void KickMenu(CCSPlayerController admin, CCSPlayerController player) + private static void KickMenu(CCSPlayerController admin, CCSPlayerController? player) { - BaseMenu menu = AdminMenu.CreateMenu($"Kick: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Kick: {player?.PlayerName}"); List options = [ "Voice Abuse", @@ -117,7 +115,7 @@ private static void KickMenu(CCSPlayerController admin, CCSPlayerController play "Other" ]; - foreach (string option in options) + foreach (var option in options) { menu.AddMenuOption(option, (_, _) => { @@ -129,15 +127,15 @@ private static void KickMenu(CCSPlayerController admin, CCSPlayerController play AdminMenu.OpenMenu(admin, menu); } - private static void Kick(CCSPlayerController admin, CCSPlayerController player, string reason) + private static void Kick(CCSPlayerController admin, CCSPlayerController? player, string reason) { if (player is not null && player.IsValid) CS2_SimpleAdmin.Instance.Kick(admin, player, reason); } - private static void BanMenu(CCSPlayerController admin, CCSPlayerController player, int duration) + private static void BanMenu(CCSPlayerController admin, CCSPlayerController? player, int duration) { - BaseMenu menu = AdminMenu.CreateMenu($"Ban: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Ban: {player?.PlayerName}"); List options = [ "Hacking", @@ -147,7 +145,7 @@ private static void BanMenu(CCSPlayerController admin, CCSPlayerController playe "Other" ]; - foreach (string option in options) + foreach (var option in options) { menu.AddMenuOption(option, (_, _) => { @@ -159,16 +157,16 @@ private static void BanMenu(CCSPlayerController admin, CCSPlayerController playe AdminMenu.OpenMenu(admin, menu); } - private static void Ban(CCSPlayerController admin, CCSPlayerController player, int duration, string reason) + private static void Ban(CCSPlayerController admin, CCSPlayerController? player, int duration, string reason) { if (player is not null && player.IsValid) CS2_SimpleAdmin.Instance.Ban(admin, player, duration, reason); } - private static void GagMenu(CCSPlayerController admin, CCSPlayerController player, int duration) + private static void GagMenu(CCSPlayerController admin, CCSPlayerController? player, int duration) { // TODO: Localize and make options in config? - BaseMenu menu = AdminMenu.CreateMenu($"Gag: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Gag: {player?.PlayerName}"); List options = [ "Advertising", @@ -179,7 +177,7 @@ private static void GagMenu(CCSPlayerController admin, CCSPlayerController playe "Other" ]; - foreach (string option in options) + foreach (var option in options) { menu.AddMenuOption(option, (_, _) => { @@ -191,16 +189,16 @@ private static void GagMenu(CCSPlayerController admin, CCSPlayerController playe AdminMenu.OpenMenu(admin, menu); } - private static void Gag(CCSPlayerController admin, CCSPlayerController player, int duration, string reason) + private static void Gag(CCSPlayerController admin, CCSPlayerController? player, int duration, string reason) { if (player is not null && player.IsValid) CS2_SimpleAdmin.Instance.Gag(admin, player, duration, reason); } - private static void MuteMenu(CCSPlayerController admin, CCSPlayerController player, int duration) + private static void MuteMenu(CCSPlayerController admin, CCSPlayerController? player, int duration) { // TODO: Localize and make options in config? - BaseMenu menu = AdminMenu.CreateMenu($"Mute: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Mute: {player?.PlayerName}"); List options = [ "Shouting", @@ -213,7 +211,7 @@ private static void MuteMenu(CCSPlayerController admin, CCSPlayerController play "Other" ]; - foreach (string option in options) + foreach (var option in options) { menu.AddMenuOption(option, (_, _) => { @@ -225,16 +223,16 @@ private static void MuteMenu(CCSPlayerController admin, CCSPlayerController play AdminMenu.OpenMenu(admin, menu); } - private static void Mute(CCSPlayerController admin, CCSPlayerController player, int duration, string reason) + private static void Mute(CCSPlayerController admin, CCSPlayerController? player, int duration, string reason) { if (player is not null && player.IsValid) CS2_SimpleAdmin.Instance.Mute(admin, player, duration, reason); } - private static void SilenceMenu(CCSPlayerController admin, CCSPlayerController player, int duration) + private static void SilenceMenu(CCSPlayerController admin, CCSPlayerController? player, int duration) { // TODO: Localize and make options in config? - BaseMenu menu = AdminMenu.CreateMenu($"Silence: {player.PlayerName}"); + var menu = AdminMenu.CreateMenu($"Silence: {player?.PlayerName}"); List options = [ "Shouting", @@ -247,7 +245,7 @@ private static void SilenceMenu(CCSPlayerController admin, CCSPlayerController p "Other" ]; - foreach (string option in options) + foreach (var option in options) { menu.AddMenuOption(option, (_, _) => { @@ -259,16 +257,16 @@ private static void SilenceMenu(CCSPlayerController admin, CCSPlayerController p AdminMenu.OpenMenu(admin, menu); } - private static void Silence(CCSPlayerController admin, CCSPlayerController player, int duration, string reason) + private static void Silence(CCSPlayerController admin, CCSPlayerController? player, int duration, string reason) { if (player is not null && player.IsValid) CS2_SimpleAdmin.Instance.Silence(admin, player, duration, reason); } - private static void ForceTeamMenu(CCSPlayerController admin, CCSPlayerController player) + private static void ForceTeamMenu(CCSPlayerController admin, CCSPlayerController? player) { // TODO: Localize - BaseMenu menu = AdminMenu.CreateMenu($"Force {player.PlayerName}'s Team"); + var menu = AdminMenu.CreateMenu($"Force {player?.PlayerName}'s Team"); List options = [ new ChatMenuOptionData("CT", () => ForceTeam(admin, player, "ct", CsTeam.CounterTerrorist)), @@ -277,16 +275,16 @@ private static void ForceTeamMenu(CCSPlayerController admin, CCSPlayerController new ChatMenuOptionData("Spectator", () => ForceTeam(admin, player, "spec", CsTeam.Spectator)), ]; - foreach (ChatMenuOptionData menuOptionData in options) + foreach (var menuOptionData in options) { - string menuName = menuOptionData.name; + var menuName = menuOptionData.name; menu.AddMenuOption(menuName, (_, _) => { menuOptionData.action?.Invoke(); }, menuOptionData.disabled); } AdminMenu.OpenMenu(admin, menu); } - private static void ForceTeam(CCSPlayerController admin, CCSPlayerController player, string teamName, CsTeam teamNum) + private static void ForceTeam(CCSPlayerController admin, CCSPlayerController? player, string teamName, CsTeam teamNum) { if (player is not null && player.IsValid) CS2_SimpleAdmin.Instance.ChangeTeam(admin, player, teamName, teamNum, true); diff --git a/Menus/PlayersMenu.cs b/Menus/PlayersMenu.cs index dd7989d..5ed5a4e 100644 --- a/Menus/PlayersMenu.cs +++ b/Menus/PlayersMenu.cs @@ -12,7 +12,7 @@ public static void OpenRealPlayersMenu(CCSPlayerController admin, string menuNam OpenMenu(admin, menuName, onSelectAction, p => p.IsBot == false); } - public static void OpenAdminPlayersMenu(CCSPlayerController admin, string menuName, Action onSelectAction, Func? enableFilter = null) + public static void OpenAdminPlayersMenu(CCSPlayerController admin, string menuName, Action onSelectAction, Func? enableFilter = null) { OpenMenu(admin, menuName, onSelectAction, p => AdminManager.GetPlayerAdminData(p)?.Flags?.Count > 0); } @@ -22,28 +22,32 @@ public static void OpenAliveMenu(CCSPlayerController admin, string menuName, Act OpenMenu(admin, menuName, onSelectAction, p => p.PawnIsAlive); } - public static void OpenDeadMenu(CCSPlayerController admin, string menuName, Action onSelectAction, Func? enableFilter = null) + public static void OpenDeadMenu(CCSPlayerController admin, string menuName, Action onSelectAction, Func? enableFilter = null) { OpenMenu(admin, menuName, onSelectAction, p => p.PawnIsAlive == false); } public static void OpenMenu(CCSPlayerController admin, string menuName, Action onSelectAction, Func? enableFilter = null) { - BaseMenu menu = AdminMenu.CreateMenu(menuName); + var menu = AdminMenu.CreateMenu(menuName); - IEnumerable players = Helper.GetValidPlayersWithBots(); - string playerName = string.Empty; + var players = Helper.GetValidPlayersWithBots(); - foreach (CCSPlayerController player in players) + foreach (var player in players) { - playerName = player.PlayerName.Length > 26 ? player.PlayerName[..26] : player.PlayerName; + var playerName = player != null && player.PlayerName.Length > 26 ? player.PlayerName[..26] : player?.PlayerName; - string optionName = HttpUtility.HtmlEncode(playerName); - if (enableFilter != null && enableFilter(player) == false) + var optionName = HttpUtility.HtmlEncode(playerName); + if (player != null && enableFilter != null && enableFilter(player) == false) continue; - bool enabled = admin.CanTarget(player); - menu.AddMenuOption(optionName, (_, _) => { onSelectAction?.Invoke(admin, player); }, enabled == false); + var enabled = admin.CanTarget(player); + if (optionName != null) + menu.AddMenuOption(optionName, (_, _) => + { + if (player != null) onSelectAction?.Invoke(admin, player); + }, + enabled == false); } AdminMenu.OpenMenu(admin, menu); diff --git a/PlayerInfo.cs b/PlayerInfo.cs index 16febb3..4115a87 100644 --- a/PlayerInfo.cs +++ b/PlayerInfo.cs @@ -3,10 +3,10 @@ public class PlayerInfo { public int? Index { get; set; } - public int UserId { get; set; } - public int Slot { get; set; } - public string? SteamId { get; set; } - public string? Name { get; set; } - public string? IpAddress { get; set; } + public int UserId { get; init; } + public int Slot { get; init; } + public string? SteamId { get; init; } + public string? Name { get; init; } + public string? IpAddress { get; init; } } } \ No newline at end of file