Merge pull request #136 from daffyyyy/main

1.6a
This commit is contained in:
Dawid Bepierszcz
2024-02-08 19:37:40 +01:00
committed by GitHub
7 changed files with 247 additions and 234 deletions

28
Database.cs Normal file
View File

@@ -0,0 +1,28 @@
using MySqlConnector;
namespace WeaponPaints
{
public class Database
{
private readonly string _dbConnectionString;
public Database(string dbConnectionString)
{
_dbConnectionString = dbConnectionString;
}
public async Task<MySqlConnection> GetConnectionAsync()
{
try
{
var connection = new MySqlConnection(_dbConnectionString);
await connection.OpenAsync();
return connection;
}
catch (Exception)
{
throw;
}
}
}
}

136
Events.cs
View File

@@ -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<CCSPlayerPawn>((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
}
}
}

View File

@@ -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<List<JObject>>(json);
WeaponPaints.skinsList = deserializedSkins ?? new List<JObject>();
}
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.");
}
}
}

View File

@@ -1 +1 @@
1.5a
1.6a

View File

@@ -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<nint, nint>(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;
}

View File

@@ -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<WeaponPaintsConfig
internal Uri GlobalShareApi = new("https://weaponpaints.fun/api.php");
internal int GlobalShareServerId = 0;
internal static Dictionary<int, DateTime> commandsCooldown = new Dictionary<int, DateTime>();
private string DatabaseConnectionString = string.Empty;
internal static Database? _database;
//private CounterStrikeSharp.API.Modules.Timers.Timer? g_hTimerCheckSkinsData = null;
public static Dictionary<int, string> weaponDefindex { get; } = new Dictionary<int, string>
{
@@ -149,7 +150,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
public override string ModuleAuthor => "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<WeaponPaintsConfig
public override void Load(bool hotReload)
{
if (!Config.GlobalShare)
{
DatabaseConnectionString = Utility.BuildDatabaseConnectionString();
Utility.TestDatabaseConnection();
}
if (hotReload)
if (hotReload && weaponSync != null)
{
OnMapStart(string.Empty);
List<CCSPlayerController> 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<WeaponPaintsConfig
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (Config.Additional.SkinEnabled && weaponSync != null)
if (Config.Additional.SkinEnabled)
_ = weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
if (Config.Additional.KnifeEnabled && weaponSync != null)
if (Config.Additional.KnifeEnabled)
_ = weaponSync.GetKnifeFromDatabase(playerInfo);
g_knifePickupCount[(int)player!.Index] = 0;
}
}
if (Config.Additional.KnifeEnabled)
SetupKnifeMenu();
if (Config.Additional.SkinEnabled)
@@ -218,6 +207,22 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
Logger.LogError("You need to setup Database credentials in config!");
throw new Exception("[WeaponPaints] You need to setup Database credentials in config!");
}
/*
DatabaseConnectionString = Utility.BuildDatabaseConnectionString();
Utility.TestDatabaseConnection();
*/
var builder = new MySqlConnectionStringBuilder
{
Server = config.DatabaseHost,
UserID = config.DatabaseUser,
Password = config.DatabasePassword,
Database = config.DatabaseName,
Port = (uint)config.DatabasePort,
Pooling = true
};
_database = new(builder.ConnectionString);
}
Config = config;

View File

@@ -1,5 +1,4 @@
using Dapper;
using MySqlConnector;
using Newtonsoft.Json.Linq;
using System.Collections.Concurrent;
@@ -8,13 +7,13 @@ namespace WeaponPaints
internal class WeaponSynchronization
{
private readonly WeaponPaintsConfig _config;
private readonly string _databaseConnectionString;
private readonly Database _database;
private readonly Uri _globalShareApi;
private readonly int _globalShareServerId;
internal WeaponSynchronization(string databaseConnectionString, WeaponPaintsConfig config, Uri globalShareApi, int globalShareServerId)
internal WeaponSynchronization(Database database, WeaponPaintsConfig config, Uri globalShareApi, int globalShareServerId)
{
_databaseConnectionString = databaseConnectionString;
_database = database;
_config = config;
_globalShareApi = globalShareApi;
_globalShareServerId = globalShareServerId;
@@ -64,21 +63,16 @@ namespace WeaponPaints
return;
}
using (var connection = new MySqlConnection(_databaseConnectionString))
{
await connection.OpenAsync();
string query = "SELECT `knife` FROM `wp_player_knife` WHERE `steamid` = @steamid";
string? PlayerKnife = await connection.QueryFirstOrDefaultAsync<string>(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<string>(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<dynamic> PlayerSkins = await connection.QueryAsync<dynamic>(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();
}
}
}