diff --git a/Commands.cs b/Commands.cs index d37914d0..d431aea5 100644 --- a/Commands.cs +++ b/Commands.cs @@ -33,6 +33,8 @@ private void OnCommandRefresh(CCSPlayerController? player, CommandInfo command) if (weaponSync != null) { + _ = Task.Run(async () => await weaponSync.GetPlayerData(playerInfo)); + /* if (Config.Additional.SkinEnabled) { _ = Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo)); @@ -53,6 +55,7 @@ private void OnCommandRefresh(CCSPlayerController? player, CommandInfo command) { _ = Task.Run(async () => await weaponSync.GetMusicFromDatabase(playerInfo)); } + */ RefreshGloves(player); RefreshWeapons(player); diff --git a/Events.cs b/Events.cs index 608a11ba..a1a24824 100644 --- a/Events.cs +++ b/Events.cs @@ -27,6 +27,8 @@ public HookResult OnClientFullConnect(EventPlayerConnectFull @event, GameEventIn try { + _ = Task.Run(async () => await weaponSync.GetPlayerData(playerInfo)); + /* if (Config.Additional.SkinEnabled) { _ = Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo)); @@ -47,6 +49,7 @@ public HookResult OnClientFullConnect(EventPlayerConnectFull @event, GameEventIn { _ = Task.Run(async () => await weaponSync.GetMusicFromDatabase(playerInfo)); } + */ } catch (Exception) { @@ -102,7 +105,6 @@ public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo private void GivePlayerWeaponSkin(CCSPlayerController player, CBasePlayerWeapon weapon) { if (!Config.Additional.SkinEnabled) return; - if (player is null || weapon is null || !weapon.IsValid || !Utility.IsPlayerValid(player)) return; if (!gPlayerWeaponsInfo.ContainsKey(player.Slot)) return; bool isKnife = weapon.DesignerName.Contains("knife") || weapon.DesignerName.Contains("bayonet"); @@ -214,6 +216,7 @@ private HookResult OnPlayerSpawn(EventPlayerSpawn @event, GameEventInfo info) GivePlayerMusicKit(player); GivePlayerAgent(player); + Server.NextFrame(() => { RefreshGloves(player); @@ -266,7 +269,7 @@ public void OnEntitySpawned(CEntityInstance entity) Server.NextFrame(() => { var weapon = new CBasePlayerWeapon(entity.Handle); - if (weapon == null || !weapon.IsValid || weapon.OwnerEntity.Value == null) return; + if (weapon == null || !weapon.IsValid) return; try { @@ -326,10 +329,13 @@ private void RegisterListeners() RegisterListener(OnMapStart); RegisterEventHandler(OnPlayerSpawn); - RegisterEventHandler(OnRoundStart, HookMode.Pre); + RegisterEventHandler(OnRoundStart); RegisterEventHandler(OnRoundEnd); RegisterListener(OnEntitySpawned); - RegisterListener(OnTick); + + if (Config.Additional.ShowSkinImage) + RegisterListener(OnTick); + //VirtualFunctions.GiveNamedItemFunc.Hook(OnGiveNamedItemPost, HookMode.Post); } } diff --git a/PlayerExtensions.cs b/PlayerExtensions.cs index 0e8198b7..6782ce96 100644 --- a/PlayerExtensions.cs +++ b/PlayerExtensions.cs @@ -8,6 +8,7 @@ public static class PlayerExtensions public static void Print(this CCSPlayerController controller, string message) { if (WeaponPaints._localizer == null) return; + StringBuilder _message = new(WeaponPaints._localizer["wp_prefix"]); _message.Append(message); controller.PrintToChat(_message.ToString()); diff --git a/Utility.cs b/Utility.cs index 8bd8b0d1..7e426018 100644 --- a/Utility.cs +++ b/Utility.cs @@ -1,11 +1,9 @@ using CounterStrikeSharp.API.Core; -using CounterStrikeSharp.API.Modules.Utils; +using CounterStrikeSharp.API.Core.Translations; using Dapper; using Microsoft.Extensions.Logging; -using MySqlConnector; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using System.Reflection; namespace WeaponPaints { @@ -13,22 +11,6 @@ internal static class Utility { internal static WeaponPaintsConfig? Config { get; set; } - internal static string BuildDatabaseConnectionString() - { - if (Config == null) return string.Empty; - var builder = new MySqlConnectionStringBuilder - { - Server = Config.DatabaseHost, - UserID = Config.DatabaseUser, - Password = Config.DatabasePassword, - Database = Config.DatabaseName, - Port = (uint)Config.DatabasePort, - Pooling = true - }; - - return builder.ConnectionString; - } - internal static async Task CheckDatabaseTables() { if (WeaponPaints._database is null) return; @@ -41,8 +23,8 @@ internal static async Task CheckDatabaseTables() try { - string[] createTableQueries = new[] - { + string[] createTableQueries = + [ @"CREATE TABLE IF NOT EXISTS `wp_player_skins` ( `steamid` varchar(18) NOT NULL, `weapon_defindex` int(6) NOT NULL, @@ -50,28 +32,28 @@ internal static async Task CheckDatabaseTables() `weapon_wear` float NOT NULL DEFAULT 0.000001, `weapon_seed` int(16) NOT NULL DEFAULT 0 ) ENGINE=InnoDB", - @"CREATE TABLE IF NOT EXISTS `wp_player_knife` ( + @"CREATE TABLE IF NOT EXISTS `wp_player_knife` ( `steamid` varchar(18) NOT NULL, `knife` varchar(64) NOT NULL, UNIQUE (`steamid`) ) ENGINE = InnoDB", - @"CREATE TABLE IF NOT EXISTS `wp_player_gloves` ( + @"CREATE TABLE IF NOT EXISTS `wp_player_gloves` ( `steamid` varchar(18) NOT NULL, `weapon_defindex` int(11) NOT NULL, UNIQUE (`steamid`) ) ENGINE=InnoDB", - @"CREATE TABLE IF NOT EXISTS `wp_player_agents` ( + @"CREATE TABLE IF NOT EXISTS `wp_player_agents` ( `steamid` varchar(18) NOT NULL, `agent_ct` varchar(64) DEFAULT NULL, `agent_t` varchar(64) DEFAULT NULL, UNIQUE (`steamid`) ) ENGINE=InnoDB", - @"CREATE TABLE IF NOT EXISTS `wp_player_music` ( + @"CREATE TABLE IF NOT EXISTS `wp_player_music` ( `steamid` varchar(64) NOT NULL, `music_id` int(11) NOT NULL, UNIQUE (`steamid`) ) ENGINE=InnoDB", - }; + ]; foreach (var query in createTableQueries) { @@ -99,7 +81,7 @@ internal static bool IsPlayerValid(CCSPlayerController? player) return (player.IsValid && !player.IsBot && !player.IsHLTV && player.UserId.HasValue); } - internal static void LoadSkinsFromFile(string filePath) + internal static void LoadSkinsFromFile(string filePath, ILogger logger) { try { @@ -109,11 +91,11 @@ internal static void LoadSkinsFromFile(string filePath) } catch (FileNotFoundException) { - throw; + logger?.LogError("Not found \"skins.json\" file"); } } - internal static void LoadGlovesFromFile(string filePath) + internal static void LoadGlovesFromFile(string filePath, ILogger logger) { try { @@ -123,11 +105,11 @@ internal static void LoadGlovesFromFile(string filePath) } catch (FileNotFoundException) { - throw; + logger?.LogError("Not found \"gloves.json\" file"); } } - internal static void LoadAgentsFromFile(string filePath) + internal static void LoadAgentsFromFile(string filePath, ILogger logger) { try { @@ -137,11 +119,11 @@ internal static void LoadAgentsFromFile(string filePath) } catch (FileNotFoundException) { - throw; + logger?.LogError("Not found \"agents.json\" file"); } } - internal static void LoadMusicFromFile(string filePath) + internal static void LoadMusicFromFile(string filePath, ILogger logger) { try { @@ -151,7 +133,7 @@ internal static void LoadMusicFromFile(string filePath) } catch (FileNotFoundException) { - throw; + logger?.LogError("Not found \"music.json\" file"); } } @@ -165,69 +147,50 @@ internal static void Log(string message) internal static string ReplaceTags(string message) { - if (message.Contains('{')) - { - string modifiedValue = message; - if (Config != null) - { - modifiedValue = modifiedValue.Replace("{WEBSITE}", Config.Website); - } - foreach (FieldInfo field in typeof(ChatColors).GetFields()) - { - string pattern = $"{{{field.Name}}}"; - if (message.Contains(pattern, StringComparison.OrdinalIgnoreCase)) - { - modifiedValue = modifiedValue.Replace(pattern, field.GetValue(null)!.ToString(), StringComparison.OrdinalIgnoreCase); - } - } - return modifiedValue; - } - - return message; + return message.ReplaceColorTags(); } internal static async Task CheckVersion(string version, ILogger logger) { - using (HttpClient client = new HttpClient()) + using HttpClient client = new(); + + try { - try + HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION").ConfigureAwait(false); + + if (response.IsSuccessStatusCode) { - HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION").ConfigureAwait(false); + string remoteVersion = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + remoteVersion = remoteVersion.Trim(); - if (response.IsSuccessStatusCode) + int comparisonResult = string.Compare(version, remoteVersion); + + if (comparisonResult < 0) + { + logger.LogWarning("Plugin is outdated! Check https://github.com/Nereziel/cs2-WeaponPaints"); + } + else if (comparisonResult > 0) { - string remoteVersion = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - remoteVersion = remoteVersion.Trim(); - - int comparisonResult = string.Compare(version, remoteVersion); - - if (comparisonResult < 0) - { - logger.LogWarning("Plugin is outdated! Check https://github.com/Nereziel/cs2-WeaponPaints"); - } - else if (comparisonResult > 0) - { - logger.LogInformation("Probably dev version detected"); - } - else - { - logger.LogInformation("Plugin is up to date"); - } + logger.LogInformation("Probably dev version detected"); } else { - logger.LogWarning("Failed to check version"); + logger.LogInformation("Plugin is up to date"); } } - catch (HttpRequestException ex) + else { - logger.LogError(ex, "Failed to connect to the version server."); - } - catch (Exception ex) - { - logger.LogError(ex, "An error occurred while checking version."); + logger.LogWarning("Failed to check version"); } } + catch (HttpRequestException ex) + { + logger.LogError(ex, "Failed to connect to the version server."); + } + catch (Exception ex) + { + logger.LogError(ex, "An error occurred while checking version."); + } } internal static void ShowAd(string moduleVersion) diff --git a/VERSION b/VERSION index d580a15f..3861d0ae 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.3c \ No newline at end of file +2.4a \ No newline at end of file diff --git a/WeaponAction.cs b/WeaponAction.cs index d6560cf5..4311ba83 100644 --- a/WeaponAction.cs +++ b/WeaponAction.cs @@ -17,7 +17,7 @@ internal static void GiveKnifeToPlayer(CCSPlayerController? player) if (PlayerHasKnife(player)) return; - string knifeToGive = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife"; + //string knifeToGive = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife"; player.GiveNamedItem(CsItem.Knife); } diff --git a/WeaponPaints.cs b/WeaponPaints.cs index 4bec9b3f..b94aab07 100644 --- a/WeaponPaints.cs +++ b/WeaponPaints.cs @@ -10,7 +10,7 @@ namespace WeaponPaints; -[MinimumApiVersion(195)] +[MinimumApiVersion(201)] public partial class WeaponPaints : BasePlugin, IPluginConfig { internal static WeaponPaints Instance { get; private set; } = new(); @@ -160,7 +160,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig "Nereziel & daffyy"; public override string ModuleDescription => "Skin, gloves, agents and knife selector, standalone and web-based"; public override string ModuleName => "WeaponPaints"; - public override string ModuleVersion => "2.3c"; + public override string ModuleVersion => "2.4a"; public static WeaponPaintsConfig GetWeaponPaintsConfig() { @@ -200,6 +200,9 @@ public override void Load(bool hotReload) IpAddress = player?.IpAddress?.Split(":")[0] }; + _ = Task.Run(async () => await weaponSync.GetPlayerData(playerInfo)); + + /* if (Config.Additional.SkinEnabled) { _ = Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo)); @@ -220,13 +223,14 @@ public override void Load(bool hotReload) { _ = Task.Run(async () => await weaponSync.GetMusicFromDatabase(playerInfo)); } + */ } } - Utility.LoadSkinsFromFile(ModuleDirectory + "/skins.json"); - Utility.LoadGlovesFromFile(ModuleDirectory + "/gloves.json"); - Utility.LoadAgentsFromFile(ModuleDirectory + "/agents.json"); - Utility.LoadMusicFromFile(ModuleDirectory + "/music.json"); + Utility.LoadSkinsFromFile(ModuleDirectory + "/skins.json", Logger); + Utility.LoadGlovesFromFile(ModuleDirectory + "/gloves.json", Logger); + Utility.LoadAgentsFromFile(ModuleDirectory + "/agents.json", Logger); + Utility.LoadMusicFromFile(ModuleDirectory + "/music.json", Logger); if (Config.Additional.KnifeEnabled) SetupKnifeMenu(); diff --git a/WeaponPaints.csproj b/WeaponPaints.csproj index 07b7ffb3..e8330b6f 100644 --- a/WeaponPaints.csproj +++ b/WeaponPaints.csproj @@ -1,7 +1,7 @@  - net7.0 + net8.0 enable enable true @@ -9,7 +9,7 @@ - + diff --git a/WeaponSynchronization.cs b/WeaponSynchronization.cs index 90dcce10..c83b7ec8 100644 --- a/WeaponSynchronization.cs +++ b/WeaponSynchronization.cs @@ -1,4 +1,5 @@ using Dapper; +using MySqlConnector; using System.Collections.Concurrent; namespace WeaponPaints @@ -14,16 +15,39 @@ internal WeaponSynchronization(Database database, WeaponPaintsConfig config) _config = config; } - internal async Task GetKnifeFromDatabase(PlayerInfo player) + internal async Task GetPlayerData(PlayerInfo player) + { + try + { + await using MySqlConnection connection = await _database.GetConnectionAsync(); + + if (_config.Additional.KnifeEnabled) + GetKnifeFromDatabase(player, connection); + if (_config.Additional.GloveEnabled) + GetGloveFromDatabase(player, connection); + if (_config.Additional.AgentEnabled) + GetAgentFromDatabase(player, connection); + if (_config.Additional.MusicEnabled) + GetMusicFromDatabase(player, connection); + if (_config.Additional.SkinEnabled) + GetWeaponPaintsFromDatabase(player, connection); + } + catch (Exception ex) + { + // Log the exception or handle it appropriately + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + + internal void GetKnifeFromDatabase(PlayerInfo player, MySqlConnection connection) { try { if (!_config.Additional.KnifeEnabled || string.IsNullOrEmpty(player?.SteamId)) return; - await using var connection = await _database.GetConnectionAsync(); string query = "SELECT `knife` FROM `wp_player_knife` WHERE `steamid` = @steamid"; - string? playerKnife = await connection.QueryFirstOrDefaultAsync(query, new { steamid = player.SteamId }); + string? playerKnife = connection.QueryFirstOrDefault(query, new { steamid = player.SteamId }); if (!string.IsNullOrEmpty(playerKnife)) { @@ -36,16 +60,15 @@ internal async Task GetKnifeFromDatabase(PlayerInfo player) } } - internal async Task GetGloveFromDatabase(PlayerInfo player) + internal void GetGloveFromDatabase(PlayerInfo player, MySqlConnection connection) { try { if (!_config.Additional.GloveEnabled || string.IsNullOrEmpty(player?.SteamId)) return; - await using var connection = await _database.GetConnectionAsync(); string query = "SELECT `weapon_defindex` FROM `wp_player_gloves` WHERE `steamid` = @steamid"; - ushort? gloveData = await connection.QueryFirstOrDefaultAsync(query, new { steamid = player.SteamId }); + ushort? gloveData = connection.QueryFirstOrDefault(query, new { steamid = player.SteamId }); if (gloveData != null) { @@ -58,16 +81,15 @@ internal async Task GetGloveFromDatabase(PlayerInfo player) } } - internal async Task GetAgentFromDatabase(PlayerInfo player) + internal void GetAgentFromDatabase(PlayerInfo player, MySqlConnection connection) { try { if (!_config.Additional.AgentEnabled || string.IsNullOrEmpty(player?.SteamId)) return; - await using var connection = await _database.GetConnectionAsync(); string query = "SELECT `agent_ct`, `agent_t` FROM `wp_player_agents` WHERE `steamid` = @steamid"; - var agentData = await connection.QueryFirstOrDefaultAsync<(string, string)>(query, new { steamid = player.SteamId }); + var agentData = connection.QueryFirstOrDefault<(string, string)>(query, new { steamid = player.SteamId }); if (agentData != default) { @@ -85,11 +107,11 @@ internal async Task GetAgentFromDatabase(PlayerInfo player) } catch (Exception ex) { - Utility.Log($"An error occurred in GetGloveFromDatabase: {ex.Message}"); + Utility.Log($"An error occurred in GetAgentFromDatabase: {ex.Message}"); } } - internal async Task GetWeaponPaintsFromDatabase(PlayerInfo player) + internal void GetWeaponPaintsFromDatabase(PlayerInfo player, MySqlConnection connection) { try { @@ -98,9 +120,8 @@ internal async Task GetWeaponPaintsFromDatabase(PlayerInfo player) var weaponInfos = new ConcurrentDictionary(); - await using var connection = await _database.GetConnectionAsync(); string query = "SELECT * FROM `wp_player_skins` WHERE `steamid` = @steamid"; - var playerSkins = await connection.QueryAsync(query, new { steamid = player.SteamId }); + var playerSkins = connection.Query(query, new { steamid = player.SteamId }); if (playerSkins == null) { @@ -133,16 +154,15 @@ internal async Task GetWeaponPaintsFromDatabase(PlayerInfo player) } } - internal async Task GetMusicFromDatabase(PlayerInfo player) + internal void GetMusicFromDatabase(PlayerInfo player, MySqlConnection connection) { try { if (!_config.Additional.MusicEnabled || string.IsNullOrEmpty(player.SteamId)) return; - await using var connection = await _database.GetConnectionAsync(); string query = "SELECT `music_id` FROM `wp_player_music` WHERE `steamid` = @steamid"; - ushort? musicData = await connection.QueryFirstOrDefaultAsync(query, new { steamid = player.SteamId }); + ushort? musicData = connection.QueryFirstOrDefault(query, new { steamid = player.SteamId }); if (musicData != null) { @@ -155,6 +175,8 @@ internal async Task GetMusicFromDatabase(PlayerInfo player) } } + + internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife) { if (!_config.Additional.KnifeEnabled || player == null || string.IsNullOrEmpty(player.SteamId) || string.IsNullOrEmpty(knife)) return;