- Major changes
- Better sql stuff
- Temp fix for crashes on skins reload
This commit is contained in:
Dawid Bepierszcz
2024-02-08 19:35:29 +01:00
parent e44af369bb
commit d1cbecaecb
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;
}
}
}
}

108
Events.cs
View File

@@ -22,35 +22,35 @@ namespace WeaponPaints
if (!gPlayerWeaponsInfo.ContainsKey((int)player.Index)) if (!gPlayerWeaponsInfo.ContainsKey((int)player.Index))
{ {
Task.Run(async () => _ = Task.Run(async () =>
{ {
if (Config.Additional.SkinEnabled) if (Config.Additional.SkinEnabled)
await weaponSync.GetWeaponPaintsFromDatabase(playerInfo); await weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
if (Config.Additional.KnifeEnabled) if (Config.Additional.KnifeEnabled)
await weaponSync.GetKnifeFromDatabase(playerInfo); await weaponSync.GetKnifeFromDatabase(playerInfo);
}); });
} }
} }
private void OnClientDisconnect(int playerSlot) private void OnClientDisconnect(int playerSlot)
{ {
CCSPlayerController player = Utilities.GetPlayerFromSlot(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) if (Config.Additional.KnifeEnabled)
g_playersKnife.TryRemove((int)player.Index, out _); 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(); innerDictionary.Clear();
gPlayerWeaponsInfo.TryRemove((int)player.Index, out _);
} }
}
if (commandsCooldown.ContainsKey((int)player.UserId))
{
commandsCooldown.Remove((int)player.UserId); commandsCooldown.Remove((int)player.UserId);
} }
}
private void OnEntityCreated(CEntityInstance entity) private void OnEntityCreated(CEntityInstance entity)
{ {
@@ -133,47 +133,56 @@ namespace WeaponPaints
{ {
CCSPlayerController? player = Utilities.GetEntityFromIndex<CCSPlayerPawn>((int)activator.Index).OriginalController.Value; CCSPlayerController? player = Utilities.GetEntityFromIndex<CCSPlayerPawn>((int)activator.Index).OriginalController.Value;
if (player == null || player.IsBot || player.IsHLTV) if (player == null || player.IsBot || player.IsHLTV ||
return HookResult.Continue; player.SteamID.ToString() == "" || !g_knifePickupCount.TryGetValue((int)player.Index, out var pickupCount) ||
!g_playersKnife.ContainsKey((int)player.Index))
if (player == null || !player.IsValid || player.SteamID.ToString() == "" || {
!g_knifePickupCount.ContainsKey((int)player.Index) || !g_playersKnife.ContainsKey((int)player.Index))
return HookResult.Continue; return HookResult.Continue;
}
CBasePlayerWeapon weapon = new(caller.Handle); CBasePlayerWeapon weapon = new(caller.Handle);
if (weapon.AttributeManager.Item.ItemDefinitionIndex != 42 && weapon.AttributeManager.Item.ItemDefinitionIndex != 59) if (weapon.AttributeManager.Item.ItemDefinitionIndex != 42 && weapon.AttributeManager.Item.ItemDefinitionIndex != 59)
{
return HookResult.Continue; 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") if (g_playersKnife[(int)player.Index] != "weapon_knife")
{ {
g_knifePickupCount[(int)player.Index]++; pickupCount++;
g_knifePickupCount[(int)player.Index] = pickupCount;
player.RemoveItemByDesignerName(weapon.DesignerName); player.RemoveItemByDesignerName(weapon.DesignerName);
if (Config.Additional.GiveKnifeAfterRemove) if (Config.Additional.GiveKnifeAfterRemove)
{
AddTimer(0.2f, () => GiveKnifeToPlayer(player)); AddTimer(0.2f, () => GiveKnifeToPlayer(player));
} }
}
return HookResult.Continue; return HookResult.Continue;
} }
private void OnMapStart(string mapName) 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 // TODO
// needed for now // needed for now
AddTimer(2.0f, () => AddTimer(2.0f, () =>
{ {
NativeAPI.IssueServerCommand("mp_t_default_melee \"\""); NativeAPI.IssueServerCommand("mp_t_default_melee \"\"");
NativeAPI.IssueServerCommand("mp_ct_default_melee \"\""); NativeAPI.IssueServerCommand("mp_ct_default_melee \"\"");
NativeAPI.IssueServerCommand("mp_equipment_reset_rounds 0"); NativeAPI.IssueServerCommand("mp_equipment_reset_rounds 0");
if (Config.GlobalShare) if (Config.GlobalShare)
GlobalShareConnect(); GlobalShareConnect();
weaponSync = new WeaponSynchronization(DatabaseConnectionString, Config, GlobalShareApi, GlobalShareServerId);
}); });
/* /*
@@ -237,24 +246,13 @@ namespace WeaponPaints
private HookResult OnPlayerSpawn(EventPlayerSpawn @event, GameEventInfo info) private HookResult OnPlayerSpawn(EventPlayerSpawn @event, GameEventInfo info)
{ {
CCSPlayerController? player = @event.Userid; CCSPlayerController? player = @event.Userid;
if (player == null || !player.IsValid) if (player == null || !player.IsValid || !Config.Additional.KnifeEnabled || PlayerHasKnife(player))
{ {
return HookResult.Continue; return HookResult.Continue;
} }
if (Config.Additional.KnifeEnabled && !PlayerHasKnife(player))
{
g_knifePickupCount[(int)player.Index] = 0; g_knifePickupCount[(int)player.Index] = 0;
GiveKnifeToPlayer(player); GiveKnifeToPlayer(player);
//AddTimer(0.1f, () => GiveKnifeToPlayer(player));
}
/*
if (Config.Additional.SkinVisibilityFix)
{
AddTimer(0.3f, () => RefreshSkins(player));
}
*/
return HookResult.Continue; return HookResult.Continue;
} }
@@ -282,31 +280,34 @@ namespace WeaponPaints
{ {
try 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); var viewModels = GetPlayerViewModels(player);
if (viewModels == null || viewModels.Length == 0)
if (viewModels == null) continue; continue;
var viewModel = viewModels[0]; var viewModel = viewModels[0];
if (viewModel == null || viewModel.Value == null || viewModel.Value.Weapon == null || viewModel.Value.Weapon.Value == null) continue; if (viewModel == null || viewModel.Value == null || viewModel.Value.Weapon == null || viewModel.Value.Weapon.Value == null)
CBasePlayerWeapon weapon = viewModel.Value.Weapon.Value; 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)
if ( continue;
viewModel.Value.CBodyComponent != null
&& viewModel.Value.CBodyComponent.SceneNode != null var skeleton = GetSkeletonInstance(sceneNode);
) if (skeleton == null)
{ continue;
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[] knifePaintKits = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 };
int fallbackPaintKit = weapon.FallbackPaintKit; if (knifePaintKits.Contains(weapon.FallbackPaintKit))
if (array.Contains(fallbackPaintKit))
{ {
skeleton.ModelState.MeshGroupMask = 1; skeleton.ModelState.MeshGroupMask = 1;
} }
@@ -318,13 +319,12 @@ namespace WeaponPaints
} }
} }
}
Utilities.SetStateChanged(viewModel.Value, "CBaseEntity", "m_CBodyComponent"); Utilities.SetStateChanged(viewModel.Value, "CBaseEntity", "m_CBodyComponent");
} }
}
catch (Exception) catch (Exception)
{ } {
// Handle exceptions silently
}
} }
} }

View File

@@ -1,11 +1,11 @@
using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Utils; using CounterStrikeSharp.API.Modules.Utils;
using Dapper; using Dapper;
using MySqlConnector;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Reflection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using MySqlConnector;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection;
namespace WeaponPaints namespace WeaponPaints
{ {
@@ -23,6 +23,7 @@ namespace WeaponPaints
Password = Config.DatabasePassword, Password = Config.DatabasePassword,
Database = Config.DatabaseName, Database = Config.DatabaseName,
Port = (uint)Config.DatabasePort, Port = (uint)Config.DatabasePort,
Pooling = true
}; };
return builder.ConnectionString; return builder.ConnectionString;
@@ -65,15 +66,15 @@ namespace WeaponPaints
} }
internal static void LoadSkinsFromFile(string filePath) internal static void LoadSkinsFromFile(string filePath)
{ {
if (File.Exists(filePath)) try
{ {
string json = File.ReadAllText(filePath); string json = File.ReadAllText(filePath);
var deserializedSkins = JsonConvert.DeserializeObject<List<JObject>>(json); var deserializedSkins = JsonConvert.DeserializeObject<List<JObject>>(json);
WeaponPaints.skinsList = deserializedSkins ?? new List<JObject>(); WeaponPaints.skinsList = deserializedSkins ?? new List<JObject>();
} }
else catch (FileNotFoundException)
{ {
throw new FileNotFoundException("File not found.", filePath); throw;
} }
} }
@@ -114,11 +115,11 @@ namespace WeaponPaints
{ {
try 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) if (response.IsSuccessStatusCode)
{ {
string remoteVersion = await response.Content.ReadAsStringAsync(); string remoteVersion = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
remoteVersion = remoteVersion.Trim(); remoteVersion = remoteVersion.Trim();
int comparisonResult = string.Compare(version, remoteVersion); int comparisonResult = string.Compare(version, remoteVersion);
@@ -141,9 +142,13 @@ namespace WeaponPaints
logger.LogWarning("Failed to check version"); logger.LogWarning("Failed to check version");
} }
} }
catch (HttpRequestException ex)
{
logger.LogError(ex, "Failed to connect to the version server.");
}
catch (Exception ex) 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; int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex;
if (isKnife) if (isKnife)
{ {
weapon.AttributeManager.Item.EntityQuality = 3; weapon.AttributeManager.Item.EntityQuality = 3;
@@ -91,25 +90,31 @@ namespace WeaponPaints
{ {
if (!_config.Additional.KnifeEnabled || player == null || !player.IsValid) return; if (!_config.Additional.KnifeEnabled || player == null || !player.IsValid) return;
string knifeToGive;
if (g_playersKnife.TryGetValue((int)player.Index, out var knife)) if (g_playersKnife.TryGetValue((int)player.Index, out var knife))
{ {
player.GiveNamedItem(knife); knifeToGive = knife;
} }
else if (_config.Additional.GiveRandomKnife) 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(); Random random = new();
int index = random.Next(knifeTypes.Count); int index = random.Next(knifeTypes.Count);
var randomKnifeClass = knifeTypes.Keys.ElementAt(index); knifeToGive = knifeTypes[index].Key;
player.GiveNamedItem(randomKnifeClass);
} }
else else
{ {
var defaultKnife = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife"; knifeToGive = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife";
player.GiveNamedItem(defaultKnife);
} }
player.GiveNamedItem(knifeToGive);
} }
internal static bool PlayerHasKnife(CCSPlayerController? player) internal static bool PlayerHasKnife(CCSPlayerController? player)
@@ -141,6 +146,7 @@ namespace WeaponPaints
internal void RefreshPlayerKnife(CCSPlayerController? player) internal void RefreshPlayerKnife(CCSPlayerController? player)
{ {
return;
if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) 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; if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) return;
@@ -209,68 +215,71 @@ namespace WeaponPaints
internal void RefreshWeapons(CCSPlayerController? player) internal void RefreshWeapons(CCSPlayerController? player)
{ {
if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return; if (player == null || !player.IsValid || player.PlayerPawn?.Value == null || !player.PawnIsAlive)
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) return; return;
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null)
return;
var weapons = player.PlayerPawn.Value.WeaponServices.MyWeapons; var weapons = player.PlayerPawn.Value.WeaponServices.MyWeapons;
if (weapons != null && weapons.Count > 0) if (weapons == null || weapons.Count == 0)
{ return;
CCSPlayer_ItemServices service = new(player.PlayerPawn.Value.ItemServices.Handle);
var itemServices = new CCSPlayer_ItemServices(player.PlayerPawn.Value.ItemServices.Handle);
foreach (var weapon in weapons) foreach (var weapon in weapons)
{ {
if (weapon != null && weapon.IsValid && weapon.Value != null && weapon.Value.IsValid) if (weapon == null || !weapon.IsValid || weapon.Value == null || !weapon.Value.IsValid || weapon.Index <= 0 || !weapon.Value.DesignerName.Contains("weapon_"))
{ continue;
if (weapon.Index <= 0 || !weapon.Value.DesignerName.Contains("weapon_")) continue;
//if (weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 42 || weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 59)
try try
{ {
string? weaponByDefindex = null;
if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet")) if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet"))
{ {
player.RemoveItemByDesignerName(weapon.Value.DesignerName, true); player.RemoveItemByDesignerName(weapon.Value.DesignerName, false);
GiveKnifeToPlayer(player); GiveKnifeToPlayer(player);
} }
else else
{ {
if (!weaponDefindex.ContainsKey(weapon.Value.AttributeManager.Item.ItemDefinitionIndex)) continue; if (weaponDefindex.TryGetValue(weapon.Value.AttributeManager.Item.ItemDefinitionIndex, out weaponByDefindex) && weaponByDefindex != null)
int clip1, reservedAmmo; {
int clip1 = weapon.Value.Clip1;
int reservedAmmo = weapon.Value.ReserveAmmo[0];
clip1 = weapon.Value.Clip1; player.RemoveItemByDesignerName(weapon.Value.DesignerName, false);
reservedAmmo = weapon.Value.ReserveAmmo[0]; var newWeapon = new CBasePlayerWeapon(player.GiveNamedItem(weaponByDefindex));
string weaponByDefindex = weaponDefindex[weapon.Value.AttributeManager.Item.ItemDefinitionIndex];
player.RemoveItemByDesignerName(weapon.Value.DesignerName, true);
CBasePlayerWeapon newWeapon = new(player.GiveNamedItem(weaponByDefindex));
Server.NextFrame(() => Server.NextFrame(() =>
{ {
if (newWeapon == null) return;
try try
{
if (newWeapon != null)
{ {
newWeapon.Clip1 = clip1; newWeapon.Clip1 = clip1;
newWeapon.ReserveAmmo[0] = reservedAmmo; newWeapon.ReserveAmmo[0] = reservedAmmo;
} }
catch (Exception) }
{ } catch (Exception ex)
{
Logger.LogWarning("Error setting weapon properties: " + ex.Message);
}
}); });
} }
else
{
Logger.LogWarning("Unable to find weapon by defindex.");
}
}
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogWarning("Refreshing weapons exception"); Logger.LogWarning("Refreshing weapons exception: " + ex.Message);
Console.WriteLine("[WeaponPaints] Refreshing weapons exception");
Console.WriteLine(ex.Message);
} }
} }
} }
/*
if (Config.Additional.SkinVisibilityFix)
RefreshSkins(player);
*/
}
}
internal void RemovePlayerKnife(CCSPlayerController? player, bool force = false) internal void RemovePlayerKnife(CCSPlayerController? player, bool force = false)
{ {
if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return; if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return;
@@ -280,13 +289,11 @@ namespace WeaponPaints
if (weapons != null && weapons.Count > 0) if (weapons != null && weapons.Count > 0)
{ {
CCSPlayer_ItemServices service = new CCSPlayer_ItemServices(player.PlayerPawn.Value.ItemServices.Handle); 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) foreach (var weapon in weapons)
{ {
if (weapon != null && weapon.IsValid && weapon.Value != null && weapon.Value.IsValid) 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 (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet"))
{ {
if (!force) if (!force)
@@ -318,26 +325,22 @@ namespace WeaponPaints
} }
private static int GetRandomPaint(int defindex) private static int GetRandomPaint(int defindex)
{ {
if (skinsList == null || skinsList.Count == 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());
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;
}
} 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;
return 0; return 0;
} }

View File

@@ -4,6 +4,7 @@ using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Cvars; using CounterStrikeSharp.API.Modules.Cvars;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using MySqlConnector;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System.Collections.Concurrent; 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 Uri GlobalShareApi = new("https://weaponpaints.fun/api.php");
internal int GlobalShareServerId = 0; internal int GlobalShareServerId = 0;
internal static Dictionary<int, DateTime> commandsCooldown = new Dictionary<int, DateTime>(); 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; //private CounterStrikeSharp.API.Modules.Timers.Timer? g_hTimerCheckSkinsData = null;
public static Dictionary<int, string> weaponDefindex { get; } = new Dictionary<int, string> 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 ModuleAuthor => "Nereziel & daffyy";
public override string ModuleDescription => "Skin and knife selector, standalone and web-based"; public override string ModuleDescription => "Skin and knife selector, standalone and web-based";
public override string ModuleName => "WeaponPaints"; public override string ModuleName => "WeaponPaints";
public override string ModuleVersion => "1.5a"; public override string ModuleVersion => "1.6a";
public static WeaponPaintsConfig GetWeaponPaintsConfig() public static WeaponPaintsConfig GetWeaponPaintsConfig()
{ {
@@ -158,26 +159,17 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
public override void Load(bool hotReload) public override void Load(bool hotReload)
{ {
if (!Config.GlobalShare) if (hotReload && weaponSync != null)
{
DatabaseConnectionString = Utility.BuildDatabaseConnectionString();
Utility.TestDatabaseConnection();
}
if (hotReload)
{ {
OnMapStart(string.Empty); OnMapStart(string.Empty);
List<CCSPlayerController> players = Utilities.GetPlayers(); foreach (var player in Utilities.GetPlayers())
foreach (CCSPlayerController player in players)
{ {
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV) continue; if (weaponSync == null || player is null || !player.IsValid || !player.PawnIsAlive || player.IsBot || player.IsHLTV || player.Connected != PlayerConnectedState.PlayerConnected)
//if (gPlayerWeaponsInfo.ContainsKey((int)player.Index)) continue; continue;
if (gPlayerWeaponsInfo.ContainsKey((int)player.Index)) g_knifePickupCount[(int)player.Index] = 0;
gPlayerWeaponsInfo.TryRemove((int)player.Index, out _); gPlayerWeaponsInfo.TryRemove((int)player.Index, out _);
if (g_playersKnife.ContainsKey((int)player.Index))
g_playersKnife.TryRemove((int)player.Index, out _); g_playersKnife.TryRemove((int)player.Index, out _);
PlayerInfo playerInfo = new PlayerInfo PlayerInfo playerInfo = new PlayerInfo
@@ -189,15 +181,12 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
IpAddress = player?.IpAddress?.Split(":")[0] IpAddress = player?.IpAddress?.Split(":")[0]
}; };
if (Config.Additional.SkinEnabled && weaponSync != null) if (Config.Additional.SkinEnabled)
_ = weaponSync.GetWeaponPaintsFromDatabase(playerInfo); _ = weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
if (Config.Additional.KnifeEnabled && weaponSync != null) if (Config.Additional.KnifeEnabled)
_ = weaponSync.GetKnifeFromDatabase(playerInfo); _ = weaponSync.GetKnifeFromDatabase(playerInfo);
g_knifePickupCount[(int)player!.Index] = 0;
} }
} }
if (Config.Additional.KnifeEnabled) if (Config.Additional.KnifeEnabled)
SetupKnifeMenu(); SetupKnifeMenu();
if (Config.Additional.SkinEnabled) 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!"); Logger.LogError("You need to setup Database credentials in config!");
throw new Exception("[WeaponPaints] 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; Config = config;

View File

@@ -1,5 +1,4 @@
using Dapper; using Dapper;
using MySqlConnector;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System.Collections.Concurrent; using System.Collections.Concurrent;
@@ -8,13 +7,13 @@ namespace WeaponPaints
internal class WeaponSynchronization internal class WeaponSynchronization
{ {
private readonly WeaponPaintsConfig _config; private readonly WeaponPaintsConfig _config;
private readonly string _databaseConnectionString; private readonly Database _database;
private readonly Uri _globalShareApi; private readonly Uri _globalShareApi;
private readonly int _globalShareServerId; 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; _config = config;
_globalShareApi = globalShareApi; _globalShareApi = globalShareApi;
_globalShareServerId = globalShareServerId; _globalShareServerId = globalShareServerId;
@@ -64,21 +63,16 @@ namespace WeaponPaints
return; 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())
{ {
WeaponPaints.g_playersKnife[player.Index] = PlayerKnife; string query = "SELECT `knife` FROM `wp_player_knife` WHERE `steamid` = @steamid";
} string? playerKnife = await connection.QueryFirstOrDefaultAsync<string>(query, new { steamid = player.SteamId });
else
if (playerKnife != null)
{ {
return; WeaponPaints.g_playersKnife[player.Index] = playerKnife;
} }
await connection.CloseAsync();
} }
} }
catch (Exception e) catch (Exception e)
@@ -150,21 +144,17 @@ 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"; 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;
int weaponDefIndex = row.weapon_defindex ?? default(int); float weaponWear = row.weapon_wear ?? default;
int weaponPaintId = row.weapon_paint_id ?? default(int); int weaponSeed = row.weapon_seed ?? default;
float weaponWear = row.weapon_wear ?? default(float);
int weaponSeed = row.weapon_seed ?? default(int);
WeaponInfo weaponInfo = new WeaponInfo WeaponInfo weaponInfo = new WeaponInfo
{ {
@@ -173,13 +163,7 @@ namespace WeaponPaints
Wear = weaponWear Wear = weaponWear
}; };
WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex] = weaponInfo; WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex] = weaponInfo;
});
} }
else
{
return;
}
await connection.CloseAsync();
} }
} }
catch (Exception e) catch (Exception e)
@@ -192,28 +176,24 @@ namespace WeaponPaints
internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife) internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife)
{ {
if (!_config.Additional.KnifeEnabled) return; if (!_config.Additional.KnifeEnabled) return;
try
{
if (player.SteamId == null || player.Index == 0) return; if (player.SteamId == null || player.Index == 0) return;
using var connection = new MySqlConnection(_databaseConnectionString); try
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"; 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.ExecuteAsync(query, new { steamid = player.SteamId, newKnife = knife });
await connection.CloseAsync();
} }
catch (Exception e) catch (Exception e)
{ {
Utility.Log(e.Message); Utility.Log(e.Message);
return;
} }
} }
internal async Task SyncWeaponPaintsToDatabase(PlayerInfo player) internal async Task SyncWeaponPaintsToDatabase(PlayerInfo player)
{ {
if (player == null || player.Index <= 0 || player.SteamId == null) return; if (player == null || player.Index <= 0 || player.SteamId == null) return;
using var connection = new MySqlConnection(_databaseConnectionString); await using var connection = await _database.GetConnectionAsync();
await connection.OpenAsync();
if (!WeaponPaints.gPlayerWeaponsInfo.ContainsKey(player.Index)) if (!WeaponPaints.gPlayerWeaponsInfo.ContainsKey(player.Index))
return; return;
@@ -227,23 +207,15 @@ namespace WeaponPaints
float wear = weaponInfo.Wear; float wear = weaponInfo.Wear;
int seed = weaponInfo.Seed; int seed = weaponInfo.Seed;
string updateSql = "UPDATE `wp_player_skins` SET `weapon_paint_id` = @paintId, " + string updateSql = "INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, " +
"`weapon_wear` = @wear, `weapon_seed` = @seed WHERE `steamid` = @steamid " +
"AND `weapon_defindex` = @weaponDefIndex";
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`) " + "`weapon_paint_id`, `weapon_wear`, `weapon_seed`) " +
"VALUES (@steamid, @weaponDefIndex, @paintId, @wear, @seed)"; "VALUES (@steamid, @weaponDefIndex, @paintId, @wear, @seed) " +
"ON DUPLICATE KEY UPDATE `weapon_paint_id` = @paintId, " +
"`weapon_wear` = @wear, `weapon_seed` = @seed";
await connection.ExecuteAsync(insertSql, updateParams); var updateParams = new { steamid = player.SteamId, weaponDefIndex, paintId, wear, seed };
await connection.ExecuteAsync(updateSql, updateParams);
} }
} }
await connection.CloseAsync();
}
} }
} }