diff --git a/Database.cs b/Database.cs new file mode 100644 index 00000000..acbd95a8 --- /dev/null +++ b/Database.cs @@ -0,0 +1,28 @@ +using MySqlConnector; + +namespace WeaponPaints +{ + public class Database + { + private readonly string _dbConnectionString; + + public Database(string dbConnectionString) + { + _dbConnectionString = dbConnectionString; + } + + public async Task GetConnectionAsync() + { + try + { + var connection = new MySqlConnection(_dbConnectionString); + await connection.OpenAsync(); + return connection; + } + catch (Exception) + { + throw; + } + } + } +} \ No newline at end of file diff --git a/Events.cs b/Events.cs index bd048126..511ec757 100644 --- a/Events.cs +++ b/Events.cs @@ -22,34 +22,34 @@ namespace WeaponPaints if (!gPlayerWeaponsInfo.ContainsKey((int)player.Index)) { - Task.Run(async () => + _ = Task.Run(async () => { if (Config.Additional.SkinEnabled) await weaponSync.GetWeaponPaintsFromDatabase(playerInfo); + if (Config.Additional.KnifeEnabled) await weaponSync.GetKnifeFromDatabase(playerInfo); }); } } + private void OnClientDisconnect(int playerSlot) { CCSPlayerController player = Utilities.GetPlayerFromSlot(playerSlot); - if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || player.UserId == null) return; + if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || player.UserId == null) + return; if (Config.Additional.KnifeEnabled) g_playersKnife.TryRemove((int)player.Index, out _); - if (Config.Additional.SkinEnabled) + + if (Config.Additional.SkinEnabled && gPlayerWeaponsInfo.TryGetValue((int)player.Index, out var innerDictionary)) { - if (gPlayerWeaponsInfo.TryRemove((int)player.Index, out var innerDictionary)) - { - innerDictionary.Clear(); - } - } - if (commandsCooldown.ContainsKey((int)player.UserId)) - { - commandsCooldown.Remove((int)player.UserId); + innerDictionary.Clear(); + gPlayerWeaponsInfo.TryRemove((int)player.Index, out _); } + + commandsCooldown.Remove((int)player.UserId); } private void OnEntityCreated(CEntityInstance entity) @@ -133,26 +133,34 @@ namespace WeaponPaints { CCSPlayerController? player = Utilities.GetEntityFromIndex((int)activator.Index).OriginalController.Value; - if (player == null || player.IsBot || player.IsHLTV) - return HookResult.Continue; - - if (player == null || !player.IsValid || player.SteamID.ToString() == "" || - !g_knifePickupCount.ContainsKey((int)player.Index) || !g_playersKnife.ContainsKey((int)player.Index)) + if (player == null || player.IsBot || player.IsHLTV || + player.SteamID.ToString() == "" || !g_knifePickupCount.TryGetValue((int)player.Index, out var pickupCount) || + !g_playersKnife.ContainsKey((int)player.Index)) + { return HookResult.Continue; + } CBasePlayerWeapon weapon = new(caller.Handle); if (weapon.AttributeManager.Item.ItemDefinitionIndex != 42 && weapon.AttributeManager.Item.ItemDefinitionIndex != 59) + { return HookResult.Continue; + } - if (g_knifePickupCount[(int)player.Index] >= 2) return HookResult.Continue; + if (pickupCount >= 2) + { + return HookResult.Continue; + } if (g_playersKnife[(int)player.Index] != "weapon_knife") { - g_knifePickupCount[(int)player.Index]++; + pickupCount++; + g_knifePickupCount[(int)player.Index] = pickupCount; player.RemoveItemByDesignerName(weapon.DesignerName); if (Config.Additional.GiveKnifeAfterRemove) + { AddTimer(0.2f, () => GiveKnifeToPlayer(player)); + } } return HookResult.Continue; @@ -160,20 +168,21 @@ namespace WeaponPaints private void OnMapStart(string mapName) { - if (!Config.Additional.KnifeEnabled) return; + if (!Config.Additional.KnifeEnabled && !Config.Additional.SkinEnabled) return; + + if (_database != null) + weaponSync = new WeaponSynchronization(_database, Config, GlobalShareApi, GlobalShareServerId); + // TODO // needed for now AddTimer(2.0f, () => { - NativeAPI.IssueServerCommand("mp_t_default_melee \"\""); NativeAPI.IssueServerCommand("mp_ct_default_melee \"\""); NativeAPI.IssueServerCommand("mp_equipment_reset_rounds 0"); if (Config.GlobalShare) GlobalShareConnect(); - - weaponSync = new WeaponSynchronization(DatabaseConnectionString, Config, GlobalShareApi, GlobalShareServerId); }); /* @@ -237,24 +246,13 @@ namespace WeaponPaints private HookResult OnPlayerSpawn(EventPlayerSpawn @event, GameEventInfo info) { CCSPlayerController? player = @event.Userid; - if (player == null || !player.IsValid) + if (player == null || !player.IsValid || !Config.Additional.KnifeEnabled || PlayerHasKnife(player)) { return HookResult.Continue; } - if (Config.Additional.KnifeEnabled && !PlayerHasKnife(player)) - { - g_knifePickupCount[(int)player.Index] = 0; - GiveKnifeToPlayer(player); - //AddTimer(0.1f, () => GiveKnifeToPlayer(player)); - } - - /* - if (Config.Additional.SkinVisibilityFix) - { - AddTimer(0.3f, () => RefreshSkins(player)); - } - */ + g_knifePickupCount[(int)player.Index] = 0; + GiveKnifeToPlayer(player); return HookResult.Continue; } @@ -282,49 +280,51 @@ namespace WeaponPaints { try { - if (player == null || !player.IsValid || !player.PawnIsAlive || player.IsBot || player.IsHLTV || player.Connected == PlayerConnectedState.PlayerDisconnecting) continue; + if (player is null || !player.IsValid || !player.PawnIsAlive || player.IsBot || player.IsHLTV || player.Connected != PlayerConnectedState.PlayerConnected) + continue; var viewModels = GetPlayerViewModels(player); - - if (viewModels == null) continue; + if (viewModels == null || viewModels.Length == 0) + continue; var viewModel = viewModels[0]; - if (viewModel == null || viewModel.Value == null || viewModel.Value.Weapon == null || viewModel.Value.Weapon.Value == null) continue; - CBasePlayerWeapon weapon = viewModel.Value.Weapon.Value; + if (viewModel == null || viewModel.Value == null || viewModel.Value.Weapon == null || viewModel.Value.Weapon.Value == null) + continue; - if (weapon == null || !weapon.IsValid) continue; + var weapon = viewModel.Value.Weapon.Value; + if (weapon == null || !weapon.IsValid) + continue; - var isKnife = viewModel.Value.VMName.Contains("knife"); + if (viewModel.Value.VMName.Contains("knife")) + continue; - if (!isKnife) + var sceneNode = viewModel.Value.CBodyComponent?.SceneNode; + if (sceneNode == null) + continue; + + var skeleton = GetSkeletonInstance(sceneNode); + if (skeleton == null) + continue; + + int[] knifePaintKits = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 }; + if (knifePaintKits.Contains(weapon.FallbackPaintKit)) { - if ( - viewModel.Value.CBodyComponent != null - && viewModel.Value.CBodyComponent.SceneNode != null - ) - { - var skeleton = GetSkeletonInstance(viewModel.Value.CBodyComponent.SceneNode); - int[] array = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 }; - int fallbackPaintKit = weapon.FallbackPaintKit; - if (array.Contains(fallbackPaintKit)) - { - skeleton.ModelState.MeshGroupMask = 1; - } - else - { - if (skeleton.ModelState.MeshGroupMask != 2) - { - skeleton.ModelState.MeshGroupMask = 2; - } - } - - } - - Utilities.SetStateChanged(viewModel.Value, "CBaseEntity", "m_CBodyComponent"); + skeleton.ModelState.MeshGroupMask = 1; } + else + { + if (skeleton.ModelState.MeshGroupMask != 2) + { + skeleton.ModelState.MeshGroupMask = 2; + } + } + + Utilities.SetStateChanged(viewModel.Value, "CBaseEntity", "m_CBodyComponent"); } catch (Exception) - { } + { + // Handle exceptions silently + } } } diff --git a/Utility.cs b/Utility.cs index d18c8ce2..64afed4a 100644 --- a/Utility.cs +++ b/Utility.cs @@ -1,11 +1,11 @@ using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Modules.Utils; using Dapper; -using MySqlConnector; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json; -using System.Reflection; using Microsoft.Extensions.Logging; +using MySqlConnector; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System.Reflection; namespace WeaponPaints { @@ -23,6 +23,7 @@ namespace WeaponPaints Password = Config.DatabasePassword, Database = Config.DatabaseName, Port = (uint)Config.DatabasePort, + Pooling = true }; return builder.ConnectionString; @@ -65,15 +66,15 @@ namespace WeaponPaints } internal static void LoadSkinsFromFile(string filePath) { - if (File.Exists(filePath)) + try { string json = File.ReadAllText(filePath); var deserializedSkins = JsonConvert.DeserializeObject>(json); WeaponPaints.skinsList = deserializedSkins ?? new List(); } - else + catch (FileNotFoundException) { - throw new FileNotFoundException("File not found.", filePath); + throw; } } @@ -114,11 +115,11 @@ namespace WeaponPaints { try { - HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION"); + HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION").ConfigureAwait(false); if (response.IsSuccessStatusCode) { - string remoteVersion = await response.Content.ReadAsStringAsync(); + string remoteVersion = await response.Content.ReadAsStringAsync().ConfigureAwait(false); remoteVersion = remoteVersion.Trim(); int comparisonResult = string.Compare(version, remoteVersion); @@ -141,9 +142,13 @@ namespace WeaponPaints logger.LogWarning("Failed to check version"); } } + catch (HttpRequestException ex) + { + logger.LogError(ex, "Failed to connect to the version server."); + } catch (Exception ex) { - Console.WriteLine(ex); + logger.LogError(ex, "An error occurred while checking version."); } } } diff --git a/VERSION b/VERSION index d95cdf3d..6e9f3cdc 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.5a \ No newline at end of file +1.6a \ No newline at end of file diff --git a/WeaponAction.cs b/WeaponAction.cs index 5fe1e2c5..d8cc0115 100644 --- a/WeaponAction.cs +++ b/WeaponAction.cs @@ -21,7 +21,6 @@ namespace WeaponPaints int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex; - if (isKnife) { weapon.AttributeManager.Item.EntityQuality = 3; @@ -91,25 +90,31 @@ namespace WeaponPaints { if (!_config.Additional.KnifeEnabled || player == null || !player.IsValid) return; + string knifeToGive; if (g_playersKnife.TryGetValue((int)player.Index, out var knife)) { - player.GiveNamedItem(knife); + knifeToGive = knife; } else if (_config.Additional.GiveRandomKnife) { - var knifeTypes = weaponList.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")).ToDictionary(pair => pair.Key, pair => pair.Value); + var knifeTypes = weaponList.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")).ToList(); + + if (knifeTypes.Count == 0) + { + Utility.Log("No valid knife types found."); + return; + } Random random = new(); int index = random.Next(knifeTypes.Count); - var randomKnifeClass = knifeTypes.Keys.ElementAt(index); - - player.GiveNamedItem(randomKnifeClass); + knifeToGive = knifeTypes[index].Key; } else { - var defaultKnife = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife"; - player.GiveNamedItem(defaultKnife); + knifeToGive = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife"; } + + player.GiveNamedItem(knifeToGive); } internal static bool PlayerHasKnife(CCSPlayerController? player) @@ -141,6 +146,7 @@ namespace WeaponPaints internal void RefreshPlayerKnife(CCSPlayerController? player) { + return; if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return; if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) return; @@ -209,65 +215,68 @@ namespace WeaponPaints internal void RefreshWeapons(CCSPlayerController? player) { - if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return; - if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) return; + if (player == null || !player.IsValid || player.PlayerPawn?.Value == null || !player.PawnIsAlive) + return; + + if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) + return; var weapons = player.PlayerPawn.Value.WeaponServices.MyWeapons; - if (weapons != null && weapons.Count > 0) + if (weapons == null || weapons.Count == 0) + return; + + var itemServices = new CCSPlayer_ItemServices(player.PlayerPawn.Value.ItemServices.Handle); + + foreach (var weapon in weapons) { - CCSPlayer_ItemServices service = new(player.PlayerPawn.Value.ItemServices.Handle); + if (weapon == null || !weapon.IsValid || weapon.Value == null || !weapon.Value.IsValid || weapon.Index <= 0 || !weapon.Value.DesignerName.Contains("weapon_")) + continue; - foreach (var weapon in weapons) + try { - if (weapon != null && weapon.IsValid && weapon.Value != null && weapon.Value.IsValid) + string? weaponByDefindex = null; + + if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet")) { - if (weapon.Index <= 0 || !weapon.Value.DesignerName.Contains("weapon_")) continue; - //if (weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 42 || weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 59) - try + player.RemoveItemByDesignerName(weapon.Value.DesignerName, false); + GiveKnifeToPlayer(player); + } + else + { + if (weaponDefindex.TryGetValue(weapon.Value.AttributeManager.Item.ItemDefinitionIndex, out weaponByDefindex) && weaponByDefindex != null) { - if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet")) + int clip1 = weapon.Value.Clip1; + int reservedAmmo = weapon.Value.ReserveAmmo[0]; + + player.RemoveItemByDesignerName(weapon.Value.DesignerName, false); + var newWeapon = new CBasePlayerWeapon(player.GiveNamedItem(weaponByDefindex)); + + Server.NextFrame(() => { - player.RemoveItemByDesignerName(weapon.Value.DesignerName, true); - GiveKnifeToPlayer(player); - } - else - { - if (!weaponDefindex.ContainsKey(weapon.Value.AttributeManager.Item.ItemDefinitionIndex)) continue; - int clip1, reservedAmmo; - - clip1 = weapon.Value.Clip1; - reservedAmmo = weapon.Value.ReserveAmmo[0]; - - string weaponByDefindex = weaponDefindex[weapon.Value.AttributeManager.Item.ItemDefinitionIndex]; - player.RemoveItemByDesignerName(weapon.Value.DesignerName, true); - CBasePlayerWeapon newWeapon = new(player.GiveNamedItem(weaponByDefindex)); - - Server.NextFrame(() => + try { - if (newWeapon == null) return; - try + if (newWeapon != null) { newWeapon.Clip1 = clip1; newWeapon.ReserveAmmo[0] = reservedAmmo; } - catch (Exception) - { } - }); - } + } + catch (Exception ex) + { + Logger.LogWarning("Error setting weapon properties: " + ex.Message); + } + }); } - catch (Exception ex) + else { - Logger.LogWarning("Refreshing weapons exception"); - Console.WriteLine("[WeaponPaints] Refreshing weapons exception"); - Console.WriteLine(ex.Message); + Logger.LogWarning("Unable to find weapon by defindex."); } } } - - /* - if (Config.Additional.SkinVisibilityFix) - RefreshSkins(player); - */ + catch (Exception ex) + { + Logger.LogWarning("Refreshing weapons exception: " + ex.Message); + } } } @@ -280,13 +289,11 @@ namespace WeaponPaints if (weapons != null && weapons.Count > 0) { CCSPlayer_ItemServices service = new CCSPlayer_ItemServices(player.PlayerPawn.Value.ItemServices.Handle); - //var dropWeapon = VirtualFunction.CreateVoid(service.Handle, GameData.GetOffset("CCSPlayer_ItemServices_DropActivePlayerWeapon")); foreach (var weapon in weapons) { if (weapon != null && weapon.IsValid && weapon.Value != null && weapon.Value.IsValid) { - //if (weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 42 || weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 59) if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet")) { if (!force) @@ -318,26 +325,22 @@ namespace WeaponPaints } private static int GetRandomPaint(int defindex) { + if (skinsList == null || skinsList.Count == 0) + return 0; - if (skinsList != null) - { - Random rnd = new Random(); - // Filter weapons by the provided defindex - var filteredWeapons = skinsList.FindAll(w => w["weapon_defindex"]?.ToString() == defindex.ToString()); + Random rnd = new Random(); + + // Filter weapons by the provided defindex + var filteredWeapons = skinsList.Where(w => w["weapon_defindex"]?.ToString() == defindex.ToString()).ToList(); + + if (filteredWeapons.Count == 0) + return 0; + + var randomWeapon = filteredWeapons[rnd.Next(filteredWeapons.Count)]; + + if (int.TryParse(randomWeapon["paint"]?.ToString(), out int paintValue)) + return paintValue; - if (filteredWeapons.Count > 0) - { - var randomWeapon = filteredWeapons[rnd.Next(filteredWeapons.Count)]; - if (int.TryParse(randomWeapon["paint"]?.ToString(), out int paintValue)) - { - return paintValue; - } - else - { - return 0; - } - } - } return 0; } diff --git a/WeaponPaints.cs b/WeaponPaints.cs index f4733fc8..3ee5ce65 100644 --- a/WeaponPaints.cs +++ b/WeaponPaints.cs @@ -4,6 +4,7 @@ using CounterStrikeSharp.API.Core.Attributes; using CounterStrikeSharp.API.Modules.Cvars; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; +using MySqlConnector; using Newtonsoft.Json.Linq; using System.Collections.Concurrent; @@ -84,7 +85,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig commandsCooldown = new Dictionary(); - private string DatabaseConnectionString = string.Empty; + internal static Database? _database; //private CounterStrikeSharp.API.Modules.Timers.Timer? g_hTimerCheckSkinsData = null; public static Dictionary weaponDefindex { get; } = new Dictionary { @@ -149,7 +150,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig "Nereziel & daffyy"; public override string ModuleDescription => "Skin and knife selector, standalone and web-based"; public override string ModuleName => "WeaponPaints"; - public override string ModuleVersion => "1.5a"; + public override string ModuleVersion => "1.6a"; public static WeaponPaintsConfig GetWeaponPaintsConfig() { @@ -158,27 +159,18 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig players = Utilities.GetPlayers(); - - foreach (CCSPlayerController player in players) + foreach (var player in Utilities.GetPlayers()) { - if (player == null || !player.IsValid || player.IsBot || player.IsHLTV) continue; - //if (gPlayerWeaponsInfo.ContainsKey((int)player.Index)) continue; + if (weaponSync == null || player is null || !player.IsValid || !player.PawnIsAlive || player.IsBot || player.IsHLTV || player.Connected != PlayerConnectedState.PlayerConnected) + continue; - if (gPlayerWeaponsInfo.ContainsKey((int)player.Index)) - gPlayerWeaponsInfo.TryRemove((int)player.Index, out _); - if (g_playersKnife.ContainsKey((int)player.Index)) - g_playersKnife.TryRemove((int)player.Index, out _); + g_knifePickupCount[(int)player.Index] = 0; + gPlayerWeaponsInfo.TryRemove((int)player.Index, out _); + g_playersKnife.TryRemove((int)player.Index, out _); PlayerInfo playerInfo = new PlayerInfo { @@ -189,15 +181,12 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig(query, new { steamid = player.SteamId }); - if (PlayerKnife != null) + 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 }); + + if (playerKnife != null) { - WeaponPaints.g_playersKnife[player.Index] = PlayerKnife; + WeaponPaints.g_playersKnife[player.Index] = playerKnife; } - else - { - return; - } - await connection.CloseAsync(); } } catch (Exception e) @@ -150,36 +144,26 @@ namespace WeaponPaints } } - using (var connection = new MySqlConnection(_databaseConnectionString)) + await using (var connection = await _database.GetConnectionAsync()) { - await connection.OpenAsync(); - string query = "SELECT * FROM `wp_player_skins` WHERE `steamid` = @steamid"; - IEnumerable PlayerSkins = await connection.QueryAsync(query, new { steamid = player.SteamId }); + var playerSkins = await connection.QueryAsync(query, new { steamid = player.SteamId }); - if (PlayerSkins != null && PlayerSkins.AsList().Count > 0) + foreach (var row in playerSkins) { - PlayerSkins.ToList().ForEach(row => + int weaponDefIndex = row.weapon_defindex ?? default; + int weaponPaintId = row.weapon_paint_id ?? default; + float weaponWear = row.weapon_wear ?? default; + int weaponSeed = row.weapon_seed ?? default; + + WeaponInfo weaponInfo = new WeaponInfo { - int weaponDefIndex = row.weapon_defindex ?? default(int); - int weaponPaintId = row.weapon_paint_id ?? default(int); - float weaponWear = row.weapon_wear ?? default(float); - int weaponSeed = row.weapon_seed ?? default(int); - - WeaponInfo weaponInfo = new WeaponInfo - { - Paint = weaponPaintId, - Seed = weaponSeed, - Wear = weaponWear - }; - WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex] = weaponInfo; - }); + Paint = weaponPaintId, + Seed = weaponSeed, + Wear = weaponWear + }; + WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex] = weaponInfo; } - else - { - return; - } - await connection.CloseAsync(); } } catch (Exception e) @@ -192,28 +176,24 @@ namespace WeaponPaints internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife) { if (!_config.Additional.KnifeEnabled) return; + if (player.SteamId == null || player.Index == 0) return; + try { - if (player.SteamId == null || player.Index == 0) return; - - using var connection = new MySqlConnection(_databaseConnectionString); - await connection.OpenAsync(); + await using var connection = await _database.GetConnectionAsync(); string query = "INSERT INTO `wp_player_knife` (`steamid`, `knife`) VALUES(@steamid, @newKnife) ON DUPLICATE KEY UPDATE `knife` = @newKnife"; await connection.ExecuteAsync(query, new { steamid = player.SteamId, newKnife = knife }); - await connection.CloseAsync(); } catch (Exception e) { Utility.Log(e.Message); - return; } } internal async Task SyncWeaponPaintsToDatabase(PlayerInfo player) { if (player == null || player.Index <= 0 || player.SteamId == null) return; - using var connection = new MySqlConnection(_databaseConnectionString); - await connection.OpenAsync(); + await using var connection = await _database.GetConnectionAsync(); if (!WeaponPaints.gPlayerWeaponsInfo.ContainsKey(player.Index)) return; @@ -227,23 +207,15 @@ namespace WeaponPaints float wear = weaponInfo.Wear; int seed = weaponInfo.Seed; - string updateSql = "UPDATE `wp_player_skins` SET `weapon_paint_id` = @paintId, " + - "`weapon_wear` = @wear, `weapon_seed` = @seed WHERE `steamid` = @steamid " + - "AND `weapon_defindex` = @weaponDefIndex"; + string updateSql = "INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, " + + "`weapon_paint_id`, `weapon_wear`, `weapon_seed`) " + + "VALUES (@steamid, @weaponDefIndex, @paintId, @wear, @seed) " + + "ON DUPLICATE KEY UPDATE `weapon_paint_id` = @paintId, " + + "`weapon_wear` = @wear, `weapon_seed` = @seed"; - var updateParams = new { paintId, wear, seed, steamid = player.SteamId, weaponDefIndex }; - int rowsAffected = await connection.ExecuteAsync(updateSql, updateParams); - - if (rowsAffected == 0) - { - string insertSql = "INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, " + - "`weapon_paint_id`, `weapon_wear`, `weapon_seed`) " + - "VALUES (@steamid, @weaponDefIndex, @paintId, @wear, @seed)"; - - await connection.ExecuteAsync(insertSql, updateParams); - } + var updateParams = new { steamid = player.SteamId, weaponDefIndex, paintId, wear, seed }; + await connection.ExecuteAsync(updateSql, updateParams); } - await connection.CloseAsync(); } } } \ No newline at end of file