Compare commits

..

3 Commits

Author SHA1 Message Date
Dawid Bepierszcz
4d3db5b34f Merge pull request #174 from daffyyyy/main
1.9c
2024-02-25 13:20:57 +01:00
Dawid Bepierszcz
85d4e11f26 Merge branch 'Nereziel:main' into main 2024-02-25 13:19:55 +01:00
Dawid Bepierszcz
34b086a140 1.9c
- Some changes
2024-02-25 12:55:44 +01:00
20 changed files with 920 additions and 560 deletions

View File

@@ -1,8 +1,6 @@
using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Commands; using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Menu; using CounterStrikeSharp.API.Modules.Menu;
using Newtonsoft.Json.Linq;
using System.Text;
namespace WeaponPaints namespace WeaponPaints
{ {
@@ -14,14 +12,17 @@ namespace WeaponPaints
if (!Utility.IsPlayerValid(player)) return; if (!Utility.IsPlayerValid(player)) return;
if (player == null || !player.IsValid || player.UserId == null || player.IsBot) return; if (player == null || !player.IsValid || player.UserId == null || player.IsBot) return;
PlayerInfo playerInfo = new (
(int)player.Index, PlayerInfo playerInfo = new PlayerInfo
player.Slot, {
player.UserId, UserId = player.UserId,
player.SteamID.ToString(), Slot = player.Slot,
player.PlayerName, Index = (int)player.Index,
player.IpAddress?.Split(":")[0] SteamId = player?.SteamID.ToString(),
); Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
try try
{ {
if (player != null && !commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime) || if (player != null && !commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime) ||
@@ -124,372 +125,321 @@ namespace WeaponPaints
} }
} }
private void SetupKnifeMenu() private void SetupKnifeMenu()
{ {
if (!Config.Additional.KnifeEnabled || !g_bCommandsAllowed) return; if (!Config.Additional.KnifeEnabled || !g_bCommandsAllowed) return;
var knivesOnly = GetKnivesOnly(); var knivesOnly = weaponList
var giveItemMenu = new ChatMenu(Localizer["wp_knife_menu_title"]); .Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet"))
.ToDictionary(pair => pair.Key, pair => pair.Value);
AddMenuOptions(giveItemMenu, knivesOnly); var giveItemMenu = new ChatMenu(Localizer["wp_knife_menu_title"]);
AddCommandToOpenKnifeMenu(giveItemMenu); var handleGive = (CCSPlayerController player, ChatMenuOption option) =>
} {
if (!Utility.IsPlayerValid(player)) return;
private Dictionary<string, string> GetKnivesOnly() var knifeName = option.Text;
{ var knifeKey = knivesOnly.FirstOrDefault(x => x.Value == knifeName).Key;
return weaponList if (!string.IsNullOrEmpty(knifeKey))
.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")) {
.ToDictionary(pair => pair.Key, pair => pair.Value); if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_select"]))
} {
player!.Print(Localizer["wp_knife_menu_select", knifeName]);
}
private void AddMenuOptions(ChatMenu giveItemMenu, Dictionary<string, string> knivesOnly) if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_kill"]) && Config.Additional.CommandKillEnabled)
{ {
foreach (var knifePair in knivesOnly) player!.Print(Localizer["wp_knife_menu_kill"]);
{ }
giveItemMenu.AddMenuOption(knifePair.Value, (player, option) => HandleGiveOption(player, option, knivesOnly));
}
}
private void HandleGiveOption(CCSPlayerController player, ChatMenuOption option, Dictionary<string, string> knivesOnly) PlayerInfo playerInfo = new PlayerInfo
{ {
if (!Utility.IsPlayerValid(player)) return; UserId = player.UserId,
Slot = player.Slot,
Index = (int)player.Index,
SteamId = player.SteamID.ToString(),
Name = player.PlayerName,
IpAddress = player.IpAddress?.Split(":")[0]
};
var knifeName = option.Text; g_playersKnife[player.Slot] = knifeKey;
var knifeKey = knivesOnly.FirstOrDefault(x => x.Value == knifeName).Key;
if (!string.IsNullOrEmpty(knifeKey)) if (g_bCommandsAllowed && (LifeState_t)player.LifeState == LifeState_t.LIFE_ALIVE)
{ RefreshWeapons(player);
PrintMessages(player, knifeName);
SetPlayerKnife(player, knifeKey);
SyncKnifeToDatabase(player, knifeKey);
}
}
private void PrintMessages(CCSPlayerController player, string knifeName) if (weaponSync != null)
{ Task.Run(async () => await weaponSync.SyncKnifeToDatabase(playerInfo, knifeKey));
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_select"])) }
{ };
player!.Print(Localizer["wp_knife_menu_select", knifeName]); foreach (var knifePair in knivesOnly)
} {
giveItemMenu.AddMenuOption(knifePair.Value, handleGive);
}
AddCommand($"css_{Config.Additional.CommandKnife}", "Knife Menu", (player, info) =>
{
if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return;
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_kill"]) && Config.Additional.CommandKillEnabled) if (player == null || player.UserId == null) return;
{
player!.Print(Localizer["wp_knife_menu_kill"]);
}
}
private void SetPlayerKnife(CCSPlayerController player, string knifeKey) if (player != null && !commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime) ||
{ player != null && DateTime.UtcNow >= (commandsCooldown.TryGetValue(player.Slot, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
g_playersKnife[player.Slot] = knifeKey; {
commandsCooldown[player.Slot] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
giveItemMenu.PostSelectAction = PostSelectAction.Close;
MenuManager.OpenChatMenu(player, giveItemMenu);
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_cooldown"]);
}
});
}
if (g_bCommandsAllowed && (LifeState_t)player.LifeState == LifeState_t.LIFE_ALIVE) private void SetupSkinsMenu()
RefreshWeapons(player); {
} var classNamesByWeapon = weaponList.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
var weaponSelectionMenu = new ChatMenu(Localizer["wp_skin_menu_weapon_title"]);
private void SyncKnifeToDatabase(CCSPlayerController player, string knifeKey) // Function to handle skin selection for a specific weapon
{ var handleWeaponSelection = (CCSPlayerController? player, ChatMenuOption option) =>
if (weaponSync != null) {
Task.Run(async () => await weaponSync.SyncKnifeToDatabase(GetPlayerInfo(player), knifeKey)); if (!Utility.IsPlayerValid(player)) return;
}
private PlayerInfo GetPlayerInfo(CCSPlayerController player) string selectedWeapon = option.Text;
{ if (classNamesByWeapon.TryGetValue(selectedWeapon, out string? selectedWeaponClassname))
return new PlayerInfo {
{ if (selectedWeaponClassname == null) return;
UserId = player.UserId, var skinsForSelectedWeapon = skinsList?.Where(skin =>
Slot = player.Slot, skin != null &&
Index = (int)player.Index, skin.TryGetValue("weapon_name", out var weaponName) &&
SteamId = player.SteamID.ToString(), weaponName?.ToString() == selectedWeaponClassname
Name = player.PlayerName, )?.ToList();
IpAddress = player.IpAddress?.Split(":")[0]
};
}
private void AddCommandToOpenKnifeMenu(ChatMenu giveItemMenu) var skinSubMenu = new ChatMenu(Localizer["wp_skin_menu_skin_title", selectedWeapon]);
{ skinSubMenu.PostSelectAction = PostSelectAction.Close;
AddCommand($"css_{Config.Additional.CommandKnife}", "Knife Menu", (player, info) =>
{
if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return;
if (player == null || player.UserId == null) return; // Function to handle skin selection for the chosen weapon
var handleSkinSelection = (CCSPlayerController p, ChatMenuOption opt) =>
{
if (!Utility.IsPlayerValid(p)) return;
if (IsCommandAllowed(player)) string steamId = p.SteamID.ToString();
{ var firstSkin = skinsList?.FirstOrDefault(skin =>
commandsCooldown[player.Slot] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds); {
giveItemMenu.PostSelectAction = PostSelectAction.Close; if (skin != null && skin.TryGetValue("weapon_name", out var weaponName))
MenuManager.OpenChatMenu(player, giveItemMenu); {
return; return weaponName?.ToString() == selectedWeaponClassname;
} }
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"])) return false;
{ });
player!.Print(Localizer["wp_command_cooldown"]);
}
});
}
private bool IsCommandAllowed(CCSPlayerController player) string selectedSkin = opt.Text;
{ string selectedPaintID = selectedSkin.Split('(')[1].Trim(')').Trim();
if (!commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime))
{
return true;
}
return DateTime.UtcNow >= cooldownEndTime;
}
private void SetupSkinsMenu() if (firstSkin != null &&
{ firstSkin.TryGetValue("weapon_defindex", out var weaponDefIndexObj) &&
var classNamesByWeapon = weaponList.ToDictionary(kvp => kvp.Value, kvp => kvp.Key); weaponDefIndexObj != null &&
var weaponSelectionMenu = new ChatMenu(Localizer["wp_skin_menu_weapon_title"]); int.TryParse(weaponDefIndexObj.ToString(), out var weaponDefIndex) &&
int.TryParse(selectedPaintID, out var paintID))
{
if (Config.Additional.ShowSkinImage && skinsList != null)
{
var foundSkin = skinsList.FirstOrDefault(skin =>
((int?)skin?["weapon_defindex"] ?? 0) == weaponDefIndex &&
((int?)skin?["paint"] ?? 0) == paintID &&
skin?["image"] != null
);
string image = foundSkin?["image"]?.ToString() ?? "";
PlayerWeaponImage[p.Slot] = image;
AddTimer(2.0f, () => PlayerWeaponImage.Remove(p.Slot), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
}
// Add weapon options to the weapon selection menu p.Print(Localizer["wp_skin_menu_select", selectedSkin]);
foreach (var weaponClass in weaponList.Keys)
{
string weaponName = weaponList[weaponClass];
weaponSelectionMenu.AddMenuOption(weaponName, (player, option) => HandleWeaponSelection(player, option, classNamesByWeapon));
}
// Command to open the weapon selection menu for players if (!gPlayerWeaponsInfo[p.Slot].ContainsKey(weaponDefIndex))
AddCommand($"css_{Config.Additional.CommandSkinSelection}", "Skins selection menu", (player, info) => OpenWeaponSelectionMenu(player, weaponSelectionMenu)); {
} gPlayerWeaponsInfo[p.Slot][weaponDefIndex] = new WeaponInfo();
}
private void HandleWeaponSelection(CCSPlayerController? player, ChatMenuOption option, Dictionary<string, string> classNamesByWeapon) gPlayerWeaponsInfo[p.Slot][weaponDefIndex].Paint = paintID;
{ gPlayerWeaponsInfo[p.Slot][weaponDefIndex].Wear = 0.00f;
if (!Utility.IsPlayerValid(player)) return; gPlayerWeaponsInfo[p.Slot][weaponDefIndex].Seed = 0;
string selectedWeapon = option.Text; PlayerInfo playerInfo = new PlayerInfo
if (classNamesByWeapon.TryGetValue(selectedWeapon, out string? selectedWeaponClassname)) {
{ UserId = p.UserId,
if (selectedWeaponClassname == null) return; Index = (int)p.Index,
var skinsForSelectedWeapon = skinsList?.Where(skin => SteamId = p.SteamID.ToString(),
skin != null && Name = p.PlayerName,
skin.TryGetValue("weapon_name", out var weaponName) && IpAddress = p.IpAddress?.Split(":")[0]
weaponName?.ToString() == selectedWeaponClassname };
)?.ToList();
var skinSubMenu = new ChatMenu(Localizer["wp_skin_menu_skin_title", selectedWeapon]); if (g_bCommandsAllowed && (LifeState_t)p.LifeState == LifeState_t.LIFE_ALIVE)
skinSubMenu.PostSelectAction = PostSelectAction.Close; {
RefreshWeapons(player);
}
}
};
// Add skin options to the submenu for the selected weapon // Add skin options to the submenu for the selected weapon
if (skinsForSelectedWeapon != null) if (skinsForSelectedWeapon != null)
{ {
foreach (var skin in skinsForSelectedWeapon.Where(s => s != null)) foreach (var skin in skinsForSelectedWeapon.Where(s => s != null))
{ {
if (skin.TryGetValue("paint_name", out var paintNameObj) && skin.TryGetValue("paint", out var paintObj)) if (skin.TryGetValue("paint_name", out var paintNameObj) && skin.TryGetValue("paint", out var paintObj))
{ {
var paintName = paintNameObj?.ToString(); var paintName = paintNameObj?.ToString();
var paint = paintObj?.ToString(); var paint = paintObj?.ToString();
if (!string.IsNullOrEmpty(paintName) && !string.IsNullOrEmpty(paint)) if (!string.IsNullOrEmpty(paintName) && !string.IsNullOrEmpty(paint))
{ {
var optionText = new StringBuilder(paintName).Append(" (").Append(paint).Append(")").ToString(); skinSubMenu.AddMenuOption($"{paintName} ({paint})", handleSkinSelection);
skinSubMenu.AddMenuOption(optionText, (p, opt) => HandleSkinSelection(p, opt, selectedWeaponClassname)); }
} }
} }
} }
} if (player != null && Utility.IsPlayerValid(player))
if (player != null && Utility.IsPlayerValid(player)) MenuManager.OpenChatMenu(player, skinSubMenu);
MenuManager.OpenChatMenu(player, skinSubMenu); }
} };
}
private void HandleSkinSelection(CCSPlayerController p, ChatMenuOption opt, string selectedWeaponClassname) // Add weapon options to the weapon selection menu
{ foreach (var weaponClass in weaponList.Keys)
if (!Utility.IsPlayerValid(p)) return; {
string weaponName = weaponList[weaponClass];
weaponSelectionMenu.AddMenuOption(weaponName, handleWeaponSelection);
}
// Command to open the weapon selection menu for players
AddCommand($"css_{Config.Additional.CommandSkinSelection}", "Skins selection menu", (player, info) =>
{
if (!Utility.IsPlayerValid(player)) return;
string steamId = p.SteamID.ToString(); if (player == null || player.UserId == null) return;
var firstSkin = skinsList?.Find(skin =>
{
if (skin != null && skin.TryGetValue("weapon_name", out var weaponName))
{
return weaponName?.ToString() == selectedWeaponClassname;
}
return false;
});
string selectedSkin = opt.Text; if (player != null && !commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime) ||
string selectedPaintID = selectedSkin.Split('(')[1].Trim(')').Trim(); player != null && DateTime.UtcNow >= (commandsCooldown.TryGetValue(player.Slot, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
{
commandsCooldown[player.Slot] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
MenuManager.OpenChatMenu(player, weaponSelectionMenu);
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_cooldown"]);
}
});
}
if (firstSkin != null && private void SetupGlovesMenu()
firstSkin.TryGetValue("weapon_defindex", out var weaponDefIndexObj) && {
weaponDefIndexObj != null && var glovesSelectionMenu = new ChatMenu(Localizer["wp_glove_menu_title"]);
int.TryParse(weaponDefIndexObj.ToString(), out var weaponDefIndex) && glovesSelectionMenu.PostSelectAction = PostSelectAction.Close;
int.TryParse(selectedPaintID, out var paintID))
{
HandleSkinImage(p, weaponDefIndex, paintID);
p.Print(Localizer["wp_skin_menu_select", selectedSkin]);
UpdatePlayerWeaponInfo(p, weaponDefIndex, paintID);
}
}
private void HandleSkinImage(CCSPlayerController p, int weaponDefIndex, int paintID) var handleGloveSelection = (CCSPlayerController? player, ChatMenuOption option) =>
{ {
if (Config.Additional.ShowSkinImage && skinsList != null) if (!Utility.IsPlayerValid(player) || player is null) return;
{
var foundSkin = skinsList.FirstOrDefault(skin =>
((int?)skin?["weapon_defindex"] ?? 0) == weaponDefIndex &&
((int?)skin?["paint"] ?? 0) == paintID &&
skin?["image"] != null
);
string image = foundSkin?["image"]?.ToString() ?? "";
PlayerWeaponImage[p.Slot] = image;
AddTimer(2.0f, () => PlayerWeaponImage.Remove(p.Slot), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
}
}
private void UpdatePlayerWeaponInfo(CCSPlayerController p, int weaponDefIndex, int paintID) string selectedPaintName = option.Text;
{
if (!gPlayerWeaponsInfo[p.Slot].TryGetValue(weaponDefIndex, out WeaponInfo? value))
{
value = new WeaponInfo();
gPlayerWeaponsInfo[p.Slot][weaponDefIndex] = value;
}
value.Paint = paintID; var selectedGlove = glovesList.FirstOrDefault(g => g.ContainsKey("paint_name") && g["paint_name"]?.ToString() == selectedPaintName);
value.Wear = 0.00f; if (selectedGlove != null)
value.Seed = 0; {
if (
selectedGlove != null &&
selectedGlove.ContainsKey("weapon_defindex") &&
selectedGlove.ContainsKey("paint") &&
int.TryParse(selectedGlove["weapon_defindex"]?.ToString(), out int weaponDefindex) &&
int.TryParse(selectedGlove["paint"]?.ToString(), out int paint)
)
{
if (Config.Additional.ShowSkinImage)
{
string image = selectedGlove["image"]?.ToString() ?? "";
PlayerWeaponImage[player.Slot] = image;
AddTimer(2.0f, () => PlayerWeaponImage.Remove(player.Slot), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
}
if (g_bCommandsAllowed && (LifeState_t)p.LifeState == LifeState_t.LIFE_ALIVE) PlayerInfo playerInfo = new PlayerInfo
{ {
RefreshWeapons(p); UserId = player.UserId,
} Slot = player.Slot,
} Index = (int)player.Index,
SteamId = player.SteamID.ToString(),
Name = player.PlayerName,
IpAddress = player.IpAddress?.Split(":")[0]
};
private void OpenWeaponSelectionMenu(CCSPlayerController? player, ChatMenu weaponSelectionMenu) if (paint != 0)
{ {
if (!Utility.IsPlayerValid(player)) return; g_playersGlove[player.Slot] = (ushort)weaponDefindex;
if (player == null || player.UserId == null) return; if (!gPlayerWeaponsInfo[player.Slot].ContainsKey(weaponDefindex))
{
WeaponInfo weaponInfo = new();
weaponInfo.Paint = paint;
gPlayerWeaponsInfo[player.Slot][weaponDefindex] = weaponInfo;
}
}
else
{
g_playersGlove.TryRemove(player.Slot, out _);
}
if (player != null && !commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime) || if (!string.IsNullOrEmpty(Localizer["wp_glove_menu_select"]))
player != null && DateTime.UtcNow >= (commandsCooldown.TryGetValue(player.Slot, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow)) {
{ player!.Print(Localizer["wp_glove_menu_select", selectedPaintName]);
commandsCooldown[player.Slot] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds); }
MenuManager.OpenChatMenu(player, weaponSelectionMenu);
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_cooldown"]);
}
}
private void SetupGlovesMenu()
{
var glovesSelectionMenu = new ChatMenu(Localizer["wp_glove_menu_title"]);
glovesSelectionMenu.PostSelectAction = PostSelectAction.Close;
var handleGloveSelection = (CCSPlayerController? player, ChatMenuOption option) => if (weaponSync != null)
{ {
if (!Utility.IsPlayerValid(player) || player is null) return; Task.Run(async () =>
{
await weaponSync.SyncGloveToDatabase(playerInfo, weaponDefindex);
string selectedPaintName = option.Text; if (!gPlayerWeaponsInfo[playerInfo.Slot].ContainsKey(weaponDefindex))
var selectedGlove = glovesList.FirstOrDefault(g => g.ContainsKey("paint_name") && g["paint_name"]?.ToString() == selectedPaintName); {
if (selectedGlove != null) gPlayerWeaponsInfo[playerInfo.Slot][weaponDefindex] = new WeaponInfo();
{ }
HandleSelectedGlove(player, selectedGlove, selectedPaintName);
}
};
AddGloveOptionsToMenu(glovesSelectionMenu, handleGloveSelection); gPlayerWeaponsInfo[playerInfo.Slot][weaponDefindex].Paint = paint;
AddCommandToOpenGloveSelectionMenu(glovesSelectionMenu); gPlayerWeaponsInfo[playerInfo.Slot][weaponDefindex].Wear = 0.00f;
} gPlayerWeaponsInfo[playerInfo.Slot][weaponDefindex].Seed = 0;
});
void HandleSelectedGlove(CCSPlayerController? player, JObject selectedGlove, string selectedPaintName) }
{ RefreshGloves(player);
if (selectedGlove != null && }
selectedGlove.ContainsKey("weapon_defindex") && };
selectedGlove.ContainsKey("paint") && };
int.TryParse(selectedGlove["weapon_defindex"]?.ToString(), out int weaponDefindex) &&
int.TryParse(selectedGlove["paint"]?.ToString(), out int paint))
{
if (Config.Additional.ShowSkinImage)
{
string image = selectedGlove["image"]?.ToString() ?? "";
PlayerWeaponImage[player.Slot] = image;
AddTimer(2.0f, () => PlayerWeaponImage.Remove(player.Slot), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
}
PlayerInfo playerInfo = new(
(int)player.Index,
player.Slot,
player.UserId,
player.SteamID.ToString(),
player.PlayerName,
player.IpAddress?.Split(":")[0]
);
if (paint != 0) // Add weapon options to the weapon selection menu
{ foreach (var gloveObject in glovesList)
g_playersGlove[player.Slot] = (ushort)weaponDefindex; {
string paintName = gloveObject["paint_name"]?.ToString() ?? "";
if (!gPlayerWeaponsInfo[player.Slot].TryGetValue(weaponDefindex, out _)) if (paintName.Length > 0)
{ glovesSelectionMenu.AddMenuOption(paintName, handleGloveSelection);
WeaponInfo weaponInfo = new(); }
weaponInfo.Paint = paint;
gPlayerWeaponsInfo[player.Slot][weaponDefindex] = weaponInfo;
}
}
else
{
g_playersGlove.TryRemove(player.Slot, out _);
}
if (!string.IsNullOrEmpty(Localizer["wp_glove_menu_select"])) // Command to open the weapon selection menu for players
{ AddCommand($"css_{Config.Additional.CommandGlove}", "Gloves selection menu", (player, info) =>
player!.Print(Localizer["wp_glove_menu_select", selectedPaintName]); {
} if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return;
if (weaponSync != null) if (player == null || player.UserId == null) return;
{
Task.Run(async () =>
{
await weaponSync.SyncGloveToDatabase(playerInfo, weaponDefindex);
if (!gPlayerWeaponsInfo[playerInfo.Slot].TryGetValue(weaponDefindex, out var weaponInfo)) if (player != null && !commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime) ||
{ player != null && DateTime.UtcNow >= (commandsCooldown.TryGetValue(player.Slot, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
weaponInfo = new WeaponInfo(); {
gPlayerWeaponsInfo[playerInfo.Slot][weaponDefindex] = weaponInfo; commandsCooldown[player.Slot] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
} MenuManager.OpenChatMenu(player, glovesSelectionMenu);
return;
weaponInfo.Paint = paint; }
weaponInfo.Wear = 0.00f; if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
weaponInfo.Seed = 0; {
player!.Print(Localizer["wp_command_cooldown"]);
}); }
} });
RefreshGloves(player); }
}
}
private void AddGloveOptionsToMenu(ChatMenu glovesSelectionMenu, Action<CCSPlayerController?, ChatMenuOption> handleGloveSelection)
{
foreach (var gloveObject in glovesList)
{
string paintName = gloveObject["paint_name"]?.ToString() ?? "";
if (paintName.Length > 0)
glovesSelectionMenu.AddMenuOption(paintName, handleGloveSelection);
}
}
private void AddCommandToOpenGloveSelectionMenu(ChatMenu glovesSelectionMenu)
{
AddCommand($"css_{Config.Additional.CommandGlove}", "Gloves selection menu", (player, info) =>
{
if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return;
if (player == null || player.UserId == null) return;
if (player != null && !commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime) ||
player != null && DateTime.UtcNow >= (commandsCooldown.TryGetValue(player.Slot, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
{
commandsCooldown[player.Slot] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
MenuManager.OpenChatMenu(player, glovesSelectionMenu);
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_cooldown"]);
}
});
}
} }
} }

View File

@@ -11,11 +11,18 @@ namespace WeaponPaints
_dbConnectionString = dbConnectionString; _dbConnectionString = dbConnectionString;
} }
public async Task<MySqlConnection> GetConnectionAsync() public async Task<MySqlConnection> GetConnectionAsync()
{ {
var connection = new MySqlConnection(_dbConnectionString); try
await connection.OpenAsync(); {
return connection; var connection = new MySqlConnection(_dbConnectionString);
} await connection.OpenAsync();
return connection;
}
catch (Exception)
{
throw;
}
}
} }
} }

111
Events.cs
View File

@@ -14,33 +14,42 @@ namespace WeaponPaints
if (player is null || !player.IsValid || player.IsBot || player.IsHLTV || player.SteamID.ToString().Length != 17 || if (player is null || !player.IsValid || player.IsBot || player.IsHLTV || player.SteamID.ToString().Length != 17 ||
weaponSync == null || _database == null) return HookResult.Continue; weaponSync == null || _database == null) return HookResult.Continue;
PlayerInfo playerInfo = new( PlayerInfo playerInfo = new PlayerInfo
(int)player.Index,
player.Slot,
player.UserId,
player.SteamID.ToString(),
player.PlayerName,
player.IpAddress?.Split(":")[0]
);
try
{ {
UserId = player.UserId,
Slot = player.Slot,
Index = (int)player.Index,
SteamId = player.SteamID.ToString(),
Name = player.PlayerName,
IpAddress = player.IpAddress?.Split(":")[0]
};
try
{
List<Task> tasks = new List<Task>();
if (Config.Additional.SkinEnabled) if (Config.Additional.SkinEnabled)
{ {
Task.Run(() => weaponSync.GetWeaponPaintsFromDatabase(playerInfo)); tasks.Add(Task.Run(() => weaponSync.GetWeaponPaintsFromDatabase(playerInfo)));
} }
if (Config.Additional.KnifeEnabled) if (Config.Additional.KnifeEnabled)
{ {
Task.Run(() => weaponSync.GetKnifeFromDatabase(playerInfo)); tasks.Add(Task.Run(() => weaponSync.GetKnifeFromDatabase(playerInfo)));
} }
if (Config.Additional.GloveEnabled) if (Config.Additional.GloveEnabled)
{ {
Task.Run(() => weaponSync.GetGloveFromDatabase(playerInfo)); tasks.Add(Task.Run(() => weaponSync.GetGloveFromDatabase(playerInfo)));
} }
Task.WaitAll(tasks.ToArray());
} }
catch (Exception ex) catch (AggregateException ex)
{ {
Console.WriteLine($"An error occurred: {ex.Message}"); // Handle the exception
foreach (var innerException in ex.InnerExceptions)
{
Console.WriteLine($"An error occurred for player {player}: {innerException.Message}");
}
} }
return HookResult.Continue; return HookResult.Continue;
@@ -54,36 +63,42 @@ namespace WeaponPaints
if (player is null || !player.IsValid || player.IsBot || if (player is null || !player.IsValid || player.IsBot ||
player.IsHLTV || player.SteamID.ToString().Length != 17) return HookResult.Continue; player.IsHLTV || player.SteamID.ToString().Length != 17) return HookResult.Continue;
PlayerInfo playerInfo = new( PlayerInfo playerInfo = new PlayerInfo
(int)player.Index, {
player.Slot, UserId = player.UserId,
player.UserId, Slot = player.Slot,
player.SteamID.ToString(), Index = (int)player.Index,
player.PlayerName, SteamId = player.SteamID.ToString(),
player.IpAddress?.Split(":")[0] Name = player.PlayerName,
); IpAddress = player.IpAddress?.Split(":")[0]
};
if (weaponSync != null)
if (weaponSync != null)
{ {
// Run weapon sync tasks asynchronously
Task.Run(async () => Task.Run(async () =>
{ {
await weaponSync.SyncWeaponPaintsToDatabase(playerInfo); try
}); {
await weaponSync.SyncWeaponPaintsToDatabase(playerInfo);
}
catch (Exception ex)
{
Utility.Log($"Error syncing weapon paints: {ex.Message}");
}
// Remove player data if (Config.Additional.SkinEnabled)
if (Config.Additional.SkinEnabled) {
{ gPlayerWeaponsInfo.TryRemove(player.Slot, out _);
gPlayerWeaponsInfo.TryRemove(player.Slot, out _); }
} if (Config.Additional.KnifeEnabled)
if (Config.Additional.KnifeEnabled) {
{ g_playersKnife.TryRemove(player.Slot, out _);
g_playersKnife.TryRemove(player.Slot, out _); }
} if (Config.Additional.GloveEnabled)
if (Config.Additional.GloveEnabled) {
{ g_playersGlove.TryRemove(player.Slot, out _);
g_playersGlove.TryRemove(player.Slot, out _); }
} });
} }
// Remove player's command cooldown // Remove player's command cooldown
@@ -134,7 +149,7 @@ 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.PlayerPawn == null || !player.PlayerPawn.IsValid || !player.PawnIsAlive ||
player.SteamID.ToString().Length != 17 || !g_knifePickupCount.TryGetValue(player.Slot, out var pickupCount) || player.SteamID.ToString().Length != 17 || !g_knifePickupCount.TryGetValue(player.Slot, out var pickupCount) ||
!g_playersKnife.ContainsKey(player.Slot)) !g_playersKnife.ContainsKey(player.Slot))
{ {
@@ -188,6 +203,11 @@ namespace WeaponPaints
if (player is null || !player.IsValid || !Config.Additional.KnifeEnabled && !Config.Additional.GloveEnabled) if (player is null || !player.IsValid || !Config.Additional.KnifeEnabled && !Config.Additional.GloveEnabled)
return HookResult.Continue; return HookResult.Continue;
CCSPlayerPawn? pawn = player.PlayerPawn.Value;
if (pawn == null || !pawn.IsValid)
return HookResult.Continue;
g_knifePickupCount[player.Slot] = 0; g_knifePickupCount[player.Slot] = 0;
if (!PlayerHasKnife(player)) if (!PlayerHasKnife(player))
@@ -218,12 +238,13 @@ namespace WeaponPaints
return HookResult.Continue; return HookResult.Continue;
} }
private void OnTick() private void OnTick()
{ {
foreach (var player in Utilities.GetPlayers().Where(p => foreach (var player in Utilities.GetPlayers().Where(p =>
p is not null && p.IsValid && p is not null && p.IsValid && p.PlayerPawn != null && p.PlayerPawn.IsValid &&
(LifeState_t)p.LifeState == LifeState_t.LIFE_ALIVE && p.SteamID.ToString().Length == 17 (LifeState_t)p.LifeState == LifeState_t.LIFE_ALIVE && p.SteamID.ToString().Length == 17
&& !p.IsBot && !p.IsHLTV && p.Connected == PlayerConnectedState.PlayerConnected && p.Team != CounterStrikeSharp.API.Modules.Utils.CsTeam.None && !p.IsBot && !p.IsHLTV && p.Connected == PlayerConnectedState.PlayerConnected
) )
) )
{ {
@@ -295,7 +316,7 @@ namespace WeaponPaints
//RegisterListener<Listeners.OnClientPutInServer>(OnClientPutInServer); //RegisterListener<Listeners.OnClientPutInServer>(OnClientPutInServer);
//RegisterListener<Listeners.OnClientDisconnect>(OnClientDisconnect); //RegisterListener<Listeners.OnClientDisconnect>(OnClientDisconnect);
RegisterListener<Listeners.OnMapStart>(OnMapStart); RegisterListener<Listeners.OnMapStart>(OnMapStart);
RegisterListener<Listeners.OnTick>(OnTick); //RegisterListener<Listeners.OnTick>(OnTick);
RegisterEventHandler<EventPlayerSpawn>(OnPlayerSpawn); RegisterEventHandler<EventPlayerSpawn>(OnPlayerSpawn);
RegisterEventHandler<EventRoundStart>(OnRoundStart, HookMode.Pre); RegisterEventHandler<EventRoundStart>(OnRoundStart, HookMode.Pre);

View File

@@ -5,17 +5,11 @@ namespace WeaponPaints;
public static class PlayerExtensions public static class PlayerExtensions
{ {
public static void Print(this CCSPlayerController controller, string message) public static void Print(this CCSPlayerController controller, string message)
{ {
if (WeaponPaints._localizer == null) if (WeaponPaints._localizer == null) return;
{ StringBuilder _message = new(WeaponPaints._localizer["wp_prefix"]);
controller.PrintToChat(message); _message.Append(message);
} controller.PrintToChat(_message.ToString());
else }
{
StringBuilder _message = new(WeaponPaints._localizer["wp_prefix"]);
_message.Append(message);
controller.PrintToChat(_message.ToString());
}
}
} }

View File

@@ -1,24 +1,12 @@
namespace WeaponPaints namespace WeaponPaints
{ {
public class PlayerInfo public class PlayerInfo
{ {
public int Index { get; set; } public int Index { get; set; }
public int Slot { get; set; } public int Slot { get; set; }
public int? UserId { get; set; } public int? UserId { get; set; }
public string? SteamId { get; set; } public string? SteamId { get; set; }
public string? Name { get; set; } public string? Name { get; set; }
public string? IpAddress { get; set; } public string? IpAddress { get; set; }
}
public PlayerInfo() { }
public PlayerInfo(int index, int slot, int? userId, string? steamId, string? name, string? ipAddress)
{
Index = index;
Slot = slot;
UserId = userId;
SteamId = steamId;
Name = name;
IpAddress = ipAddress;
}
}
} }

View File

@@ -10,16 +10,15 @@ public class SchemaString<TSchemaClass> : NativeObject where TSchemaClass : Nati
internal SchemaString(TSchemaClass instance, string member) : base(Schema.GetSchemaValue<nint>(instance.Handle, typeof(TSchemaClass).Name!, member)) internal SchemaString(TSchemaClass instance, string member) : base(Schema.GetSchemaValue<nint>(instance.Handle, typeof(TSchemaClass).Name!, member))
{ } { }
internal unsafe void Set(string str) internal unsafe void Set(string str)
{ {
var bytes = Encoding.UTF8.GetBytes(str); var bytes = Encoding.UTF8.GetBytes(str);
var handle = Handle.ToInt64();
for (var i = 0; i < bytes.Length; i++) for (var i = 0; i < bytes.Length; i++)
{ {
Unsafe.Write((void*)(handle + i), bytes[i]); Unsafe.Write((void*)(Handle.ToInt64() + i), bytes[i]);
} }
Unsafe.Write((void*)(handle + bytes.Length), 0); Unsafe.Write((void*)(Handle.ToInt64() + bytes.Length), 0);
} }
} }

View File

@@ -43,33 +43,26 @@ namespace WeaponPaints
{ {
string[] createTableQueries = new[] string[] createTableQueries = new[]
{ {
@"CREATE TABLE IF NOT EXISTS `wp_player_skins` ( @"CREATE TABLE IF NOT EXISTS `wp_player_skins` (
`steamid` varchar(64) NOT NULL, `steamid` varchar(64) NOT NULL,
`weapon_defindex` int(6) NOT NULL, `weapon_defindex` int(6) NOT NULL,
`weapon_paint_id` int(6) NOT NULL, `weapon_paint_id` int(6) NOT NULL,
`weapon_wear` float NOT NULL DEFAULT 0.000001, `weapon_wear` float NOT NULL DEFAULT 0.000001,
`weapon_seed` int(16) NOT NULL DEFAULT 0 `weapon_seed` int(16) NOT NULL DEFAULT 0
) ENGINE=InnoDB", ) ENGINE=InnoDB",
@"CREATE TABLE IF NOT EXISTS `wp_player_knife` ( @"CREATE TABLE IF NOT EXISTS `wp_player_knife` (
`steamid` varchar(64) NOT NULL, `steamid` varchar(64) NOT NULL,
`knife` varchar(64) NOT NULL, `knife` varchar(64) NOT NULL,
UNIQUE (`steamid`) UNIQUE (`steamid`)
) ENGINE = InnoDB", ) ENGINE = InnoDB",
@"CREATE TABLE IF NOT EXISTS `wp_player_gloves` ( @"CREATE TABLE IF NOT EXISTS `wp_player_gloves` (
`steamid` varchar(64) NOT NULL, `steamid` varchar(64) NOT NULL,
`weapon_defindex` int(11) NOT NULL, `weapon_defindex` int(11) NOT NULL,
UNIQUE (`steamid`) UNIQUE (`steamid`)
) ENGINE=InnoDB" ) ENGINE=InnoDB"
}; };
/*string[] createTableQueries = new[]
{ foreach (var query in createTableQueries)
@"CREATE TABLE IF NOT EXISTS `wp_players` (`steamid` BIGINT UNSIGNED NOT NULL, `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
@"CREATE TABLE IF NOT EXISTS `wp_players_skins` (`steamid` BIGINT UNSIGNED NOT NULL, `team` SMALLINT UNSIGNED NOT NULL, `weapon` SMALLINT UNSIGNED NOT NULL, `paint` SMALLINT UNSIGNED NOT NULL, `wear` FLOAT NOT NULL DEFAULT 0.00001, `seed` SMALLINT UNSIGNED NOT NULL DEFAULT 0, `nametag` VARCHAR(20) DEFAULT NULL, `stattrack` INT UNSIGNED NOT NULL DEFAULT 0, `stattrack_enabled` SMALLINT NOT NULL DEFAULT 0, PRIMARY KEY (`steamid`,`weapon`,`team`), FOREIGN KEY (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
@"CREATE TABLE IF NOT EXISTS `wp_players_knife` (`steamid` BIGINT UNSIGNED NOT NULL, `knife_t` SMALLINT UNSIGNED NOT NULL, `knife_ct` SMALLINT UNSIGNED NOT NULL, PRIMARY KEY (`steamid`), FOREIGN KEY (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
@"CREATE TABLE IF NOT EXISTS `wp_players_music` (`steamid` BIGINT UNSIGNED NOT NULL, `music` SMALLINT UNSIGNED DEFAULT NULL, PRIMARY KEY (`steamid`), FOREIGN KEY (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
@"CREATE TABLE IF NOT EXISTS `wp_players_gloves` (`steamid` BIGINT UNSIGNED NOT NULL, `glove_t` SMALLINT UNSIGNED NOT NULL, `glove_ct` SMALLINT UNSIGNED NOT NULL, PRIMARY KEY (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"
};*/
foreach (var query in createTableQueries)
{ {
await connection.ExecuteAsync(query, transaction: transaction); await connection.ExecuteAsync(query, transaction: transaction);
} }

View File

@@ -1 +1 @@
1.9b 1.9c

View File

@@ -13,7 +13,8 @@ namespace WeaponPaints
internal static void ChangeWeaponAttributes(CBasePlayerWeapon? weapon, CCSPlayerController? player, bool isKnife = false) internal static void ChangeWeaponAttributes(CBasePlayerWeapon? weapon, CCSPlayerController? player, bool isKnife = false)
{ {
if (player is null || weapon is null || !weapon.IsValid || !Utility.IsPlayerValid(player)) return; if (player is null || weapon is null || !weapon.IsValid || !Utility.IsPlayerValid(player)) return;
if (!gPlayerWeaponsInfo.TryGetValue(player.Slot, out _)) return;
if (!gPlayerWeaponsInfo.ContainsKey(player.Slot)) return;
if (isKnife && !g_playersKnife.ContainsKey(player.Slot) || isKnife && g_playersKnife[player.Slot] == "weapon_knife") return; if (isKnife && !g_playersKnife.ContainsKey(player.Slot) || isKnife && g_playersKnife[player.Slot] == "weapon_knife") return;
@@ -141,8 +142,10 @@ namespace WeaponPaints
{ {
if (!_config.Additional.KnifeEnabled || player == null || !player.IsValid) return; if (!_config.Additional.KnifeEnabled || player == null || !player.IsValid) return;
WeaponPaints.Instance.AddTimer(1.0f, () => Instance.AddTimer(1.0f, () =>
{ {
if (PlayerHasKnife(player)) return;
string knifeToGive; string knifeToGive;
if (g_playersKnife.TryGetValue(player.Slot, out var knife)) if (g_playersKnife.TryGetValue(player.Slot, out var knife))
{ {
@@ -180,7 +183,7 @@ namespace WeaponPaints
return false; return false;
} }
if (player.PlayerPawn?.Value == null || player.PlayerPawn?.Value.WeaponServices == null || player.PlayerPawn?.Value.ItemServices == null) if (player.PlayerPawn.Value == null || player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null)
return false; return false;
var weapons = player.PlayerPawn.Value.WeaponServices?.MyWeapons; var weapons = player.PlayerPawn.Value.WeaponServices?.MyWeapons;
@@ -255,8 +258,6 @@ namespace WeaponPaints
weaponsWithAmmo[weaponByDefindex].Add((clip1, reservedAmmo)); weaponsWithAmmo[weaponByDefindex].Add((clip1, reservedAmmo));
} }
//player.RemoveItemByDesignerName(weapon.Value.DesignerName, false);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -270,18 +271,21 @@ namespace WeaponPaints
player.ExecuteClientCommand($"slot {i}"); player.ExecuteClientCommand($"slot {i}");
player.ExecuteClientCommand($"slot {i}"); player.ExecuteClientCommand($"slot {i}");
AddTimer(0.1f, () => AddTimer(0.2f, () =>
{ {
var weapon = player.PlayerPawn.Value.WeaponServices.ActiveWeapon.Value; var weapon = player.PlayerPawn.Value.WeaponServices.ActiveWeapon.Value;
CCSWeaponBaseGun? gun = weapon?.As<CCSWeaponBaseGun>();
if (weapon is null || !weapon.IsValid) return;
CCSWeaponBaseGun gun = weapon.As<CCSWeaponBaseGun>();
if (gun == null || gun.VData == null) return; if (gun == null || gun.VData == null) return;
if (gun?.VData?.GearSlot == gear_slot_t.GEAR_SLOT_C4 || gun?.VData?.GearSlot == gear_slot_t.GEAR_SLOT_GRENADES) return; if (gun.VData.GearSlot == gear_slot_t.GEAR_SLOT_C4 || gun.VData.GearSlot == gear_slot_t.GEAR_SLOT_GRENADES) return;
player.DropActiveWeapon(); player.DropActiveWeapon();
AddTimer(0.22f, () => AddTimer(0.25f, () =>
{ {
if (gun != null && gun.IsValid && gun.State == CSWeaponState_t.WEAPON_NOT_CARRIED) if (gun != null && gun.IsValid && gun.State == CSWeaponState_t.WEAPON_NOT_CARRIED)
{ {

View File

@@ -1,18 +1,9 @@
namespace WeaponPaints namespace WeaponPaints
{ {
public class WeaponInfo public class WeaponInfo
{ {
public int Paint { get; set; } public int Paint { get; set; }
public int Seed { get; set; } public int Seed { get; set; } = 0;
public float Wear { get; set; } public float Wear { get; set; } = 0f;
}
public WeaponInfo() : this(0, 0, 0f) { }
public WeaponInfo(int paint, int seed, float wear)
{
Paint = paint;
Seed = seed;
Wear = wear;
}
}
} }

View File

@@ -14,8 +14,8 @@ namespace WeaponPaints;
public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig> public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig>
{ {
internal static WeaponPaints Instance { get; private set; } = new(); internal static WeaponPaints Instance { get; private set; } = new();
internal static readonly int[] newPaints = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 };
internal static readonly Dictionary<string, string> weaponList = new() internal static readonly Dictionary<string, string> weaponList = new()
{ {
{"weapon_deagle", "Desert Eagle"}, {"weapon_deagle", "Desert Eagle"},
{"weapon_elite", "Dual Berettas"}, {"weapon_elite", "Dual Berettas"},
@@ -151,12 +151,12 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{ 525, "weapon_knife_skeleton" }, { 525, "weapon_knife_skeleton" },
{ 526, "weapon_knife_kukri" } { 526, "weapon_knife_kukri" }
}; };
public static MemoryFunctionVoid<IntPtr, string, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr> GiveNamedItem2 = new(@"\x55\x48\x89\xE5\x41\x57\x41\x56\x41\x55\x41\x54\x53\x48\x83\xEC\x18\x48\x89\x7D\xC8\x48\x85\xF6\x74");
public WeaponPaintsConfig Config { get; set; } = new(); public WeaponPaintsConfig Config { get; set; } = new();
public override string ModuleAuthor => "Nereziel & daffyy"; public override string ModuleAuthor => "Nereziel & daffyy";
public override string ModuleDescription => "Skin, gloves and knife selector, standalone and web-based"; public override string ModuleDescription => "Skin, gloves and knife selector, standalone and web-based";
public override string ModuleName => "WeaponPaints"; public override string ModuleName => "WeaponPaints";
public override string ModuleVersion => "1.9b"; public override string ModuleVersion => "1.9c";
public static WeaponPaintsConfig GetWeaponPaintsConfig() public static WeaponPaintsConfig GetWeaponPaintsConfig()
{ {
@@ -181,13 +181,15 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
gPlayerWeaponsInfo.TryRemove((int)player.Slot, out _); gPlayerWeaponsInfo.TryRemove((int)player.Slot, out _);
g_playersKnife.TryRemove((int)player.Slot, out _); g_playersKnife.TryRemove((int)player.Slot, out _);
PlayerInfo playerInfo = new PlayerInfo( PlayerInfo playerInfo = new PlayerInfo
(int)player.Slot, {
player.Slot, UserId = player.UserId,
player.UserId, Slot = player.Slot,
player?.SteamID.ToString(), Index = (int)player.Slot,
player?.PlayerName, SteamId = player?.SteamID.ToString(),
player?.IpAddress?.Split(":")[0]); Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (Config.Additional.SkinEnabled) if (Config.Additional.SkinEnabled)
{ {
@@ -217,16 +219,8 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
RegisterListeners(); RegisterListeners();
RegisterCommands(); RegisterCommands();
} }
public static void PlayerGiveNamedItem(CCSPlayerController player, string item)
{
if (!player.PlayerPawn.IsValid) return;
if (player.PlayerPawn.Value == null) return;
if (!player.PlayerPawn.Value.IsValid) return;
if (player.PlayerPawn.Value.ItemServices == null) return;
GiveNamedItem2.Invoke(player.PlayerPawn.Value.ItemServices.Handle, item, 0, 0, 0, 0, 0, 0); public void OnConfigParsed(WeaponPaintsConfig config)
}
public void OnConfigParsed(WeaponPaintsConfig config)
{ {
if (config.DatabaseHost.Length < 1 || config.DatabaseName.Length < 1 || config.DatabaseUser.Length < 1) if (config.DatabaseHost.Length < 1 || config.DatabaseName.Length < 1 || config.DatabaseUser.Length < 1)
{ {

View File

@@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.172" /> <PackageReference Include="CounterStrikeSharp.API" Version="1.0.168" />
<PackageReference Include="Dapper" Version="2.1.28" /> <PackageReference Include="Dapper" Version="2.1.28" />
<PackageReference Include="MySqlConnector" Version="2.3.5" /> <PackageReference Include="MySqlConnector" Version="2.3.5" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />

View File

@@ -14,11 +14,13 @@ namespace WeaponPaints
_config = config; _config = config;
} }
internal async Task GetKnifeFromDatabase(PlayerInfo player) public async Task GetKnifeFromDatabase(PlayerInfo player)
{ {
if (!_config.Additional.KnifeEnabled) return;
try try
{ {
if (!_config.Additional.KnifeEnabled || string.IsNullOrEmpty(player?.SteamId))
return;
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
string query = "SELECT `knife` FROM `wp_player_knife` WHERE `steamid` = @steamid"; string query = "SELECT `knife` FROM `wp_player_knife` WHERE `steamid` = @steamid";
string? playerKnife = await connection.QueryFirstOrDefaultAsync<string>(query, new { steamid = player.SteamId }); string? playerKnife = await connection.QueryFirstOrDefaultAsync<string>(query, new { steamid = player.SteamId });
@@ -28,54 +30,47 @@ namespace WeaponPaints
WeaponPaints.g_playersKnife[player.Slot] = playerKnife; WeaponPaints.g_playersKnife[player.Slot] = playerKnife;
} }
} }
catch (Exception e) catch (Exception ex)
{ {
Utility.Log(e.Message); Utility.Log($"An error occurred in GetKnifeFromDatabase: {ex.Message}");
return;
} }
} }
internal async Task GetGloveFromDatabase(PlayerInfo player) public async Task GetGloveFromDatabase(PlayerInfo player)
{ {
if (!_config.Additional.GloveEnabled) return;
try try
{ {
// Ensure proper disposal of resources using "using" statement if (!_config.Additional.GloveEnabled || string.IsNullOrEmpty(player?.SteamId))
return;
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
// Construct the SQL query with specific columns for better performance
string query = "SELECT `weapon_defindex` FROM `wp_player_gloves` WHERE `steamid` = @steamid"; string query = "SELECT `weapon_defindex` FROM `wp_player_gloves` WHERE `steamid` = @steamid";
// Execute the query and retrieve glove data
ushort? gloveData = await connection.QueryFirstOrDefaultAsync<ushort?>(query, new { steamid = player.SteamId }); ushort? gloveData = await connection.QueryFirstOrDefaultAsync<ushort?>(query, new { steamid = player.SteamId });
// Check if glove data is retrieved successfully
if (gloveData != null) if (gloveData != null)
{ {
// Update g_playersGlove dictionary with glove data
WeaponPaints.g_playersGlove[player.Slot] = gloveData.Value; WeaponPaints.g_playersGlove[player.Slot] = gloveData.Value;
} }
} }
catch (Exception e) catch (Exception ex)
{ {
// Log any exceptions occurred during database operation Utility.Log($"An error occurred in GetGloveFromDatabase: {ex.Message}");
Utility.Log("An error occurred while fetching glove data: " + e.Message);
} }
} }
internal async Task GetWeaponPaintsFromDatabase(PlayerInfo player) public async Task GetWeaponPaintsFromDatabase(PlayerInfo player)
{ {
if (!_config.Additional.SkinEnabled || player == null || player.SteamId == null) return;
try try
{ {
if (!_config.Additional.SkinEnabled || player == null || string.IsNullOrEmpty(player.SteamId))
return;
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
string query = "SELECT `weapon_defindex`, `weapon_paint_id`, `weapon_wear`, `weapon_seed` FROM `wp_player_skins` WHERE `steamid` = @steamid"; string query = "SELECT * FROM `wp_player_skins` WHERE `steamid` = @steamid";
var playerSkins = await connection.QueryAsync<dynamic>(query, new { steamid = player.SteamId });
var playerSkins = await connection.QueryAsync<dynamic>(query, new { steamid = player.SteamId }); if (playerSkins == null)
return;
if (playerSkins == null) return;
var weaponInfos = new ConcurrentDictionary<int, WeaponInfo>(); var weaponInfos = new ConcurrentDictionary<int, WeaponInfo>();
@@ -98,9 +93,9 @@ namespace WeaponPaints
WeaponPaints.gPlayerWeaponsInfo[player.Slot] = weaponInfos; WeaponPaints.gPlayerWeaponsInfo[player.Slot] = weaponInfos;
} }
catch (Exception e) catch (Exception ex)
{ {
Utility.Log($"Database error occurred: {e.Message}"); Utility.Log($"An error occurred in GetWeaponPaintsFromDatabase: {ex.Message}");
} }
} }
@@ -120,7 +115,6 @@ namespace WeaponPaints
} }
} }
internal async Task SyncGloveToDatabase(PlayerInfo player, int defindex) internal async Task SyncGloveToDatabase(PlayerInfo player, int defindex)
{ {
if (!_config.Additional.GloveEnabled || player == null || string.IsNullOrEmpty(player.SteamId)) return; if (!_config.Additional.GloveEnabled || player == null || string.IsNullOrEmpty(player.SteamId)) return;
@@ -146,35 +140,27 @@ namespace WeaponPaints
{ {
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
foreach (var weaponInfoPair in weaponsInfo) foreach (var weaponInfoPair in weaponsInfo)
{ {
int weaponDefIndex = weaponInfoPair.Key; int weaponDefIndex = weaponInfoPair.Key;
WeaponInfo weaponInfo = weaponInfoPair.Value; WeaponInfo weaponInfo = weaponInfoPair.Value;
int paintId = weaponInfo.Paint; int paintId = weaponInfo.Paint;
float wear = weaponInfo.Wear; float wear = weaponInfo.Wear;
int seed = weaponInfo.Seed; int seed = weaponInfo.Seed;
string query = "INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, `weapon_paint_id`, `weapon_wear`, `weapon_seed`) " + string query = "INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, `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"; "ON DUPLICATE KEY UPDATE `weapon_paint_id` = @paintId, `weapon_wear` = @wear, `weapon_seed` = @seed";
var parameters = new DynamicParameters(); var parameters = new { steamid = player.SteamId, weaponDefIndex, paintId, wear, seed };
parameters.Add("@steamid", player.SteamId); await connection.ExecuteAsync(query, parameters);
parameters.Add("@weaponDefIndex", weaponDefIndex); }
parameters.Add("@paintId", paintId); }
parameters.Add("@wear", wear); catch (Exception e)
parameters.Add("@seed", seed);
await connection.ExecuteAsync(query, parameters);
}
}
catch (Exception e)
{ {
Utility.Log($"Error syncing weapon paints to database: {e.Message}"); Utility.Log($"Error syncing weapon paints to database: {e.Message}");
} }
} }
} }
} }

View File

@@ -14,4 +14,4 @@
"wp_skin_menu_weapon_title": "Ieroču Izvēlne", "wp_skin_menu_weapon_title": "Ieroču Izvēlne",
"wp_skin_menu_skin_title": "Izvēlieties ādu {lime}{0}{default}", "wp_skin_menu_skin_title": "Izvēlieties ādu {lime}{0}{default}",
"wp_skin_menu_select": "Jūs esat izvēlējies {lime}{0}{default} kā savu ādu" "wp_skin_menu_select": "Jūs esat izvēlējies {lime}{0}{default} kā savu ādu"
} }

View File

@@ -14,4 +14,4 @@
"wp_skin_menu_weapon_title": "Menu Broni", "wp_skin_menu_weapon_title": "Menu Broni",
"wp_skin_menu_skin_title": "Wybierz skórkę dla {lime}{0}{default}", "wp_skin_menu_skin_title": "Wybierz skórkę dla {lime}{0}{default}",
"wp_skin_menu_select": "Wybrałeś {lime}{0}{default} jako swoją skórkę" "wp_skin_menu_select": "Wybrałeś {lime}{0}{default} jako swoją skórkę"
} }

View File

@@ -14,4 +14,4 @@
"wp_skin_menu_weapon_title": "Menu de Armas", "wp_skin_menu_weapon_title": "Menu de Armas",
"wp_skin_menu_skin_title": "Selecione uma skin para {lime}{0}{default}", "wp_skin_menu_skin_title": "Selecione uma skin para {lime}{0}{default}",
"wp_skin_menu_select": "Você escolheu {lime}{0}{default} como sua skin" "wp_skin_menu_select": "Você escolheu {lime}{0}{default} como sua skin"
} }

View File

@@ -14,4 +14,4 @@
"wp_skin_menu_weapon_title": "Menu de Armas", "wp_skin_menu_weapon_title": "Menu de Armas",
"wp_skin_menu_skin_title": "Selecione uma skin para {lime}{0}{default}", "wp_skin_menu_skin_title": "Selecione uma skin para {lime}{0}{default}",
"wp_skin_menu_select": "Você escolheu {lime}{0}{default} como sua skin" "wp_skin_menu_select": "Você escolheu {lime}{0}{default} como sua skin"
} }

View File

@@ -14,4 +14,4 @@
"wp_skin_menu_weapon_title": "Silah Menüsü", "wp_skin_menu_weapon_title": "Silah Menüsü",
"wp_skin_menu_skin_title": "{lime}{0}{default} için bir skin seçin", "wp_skin_menu_skin_title": "{lime}{0}{default} için bir skin seçin",
"wp_skin_menu_select": "{lime}{0}{default} olarak bir skin seçtiniz" "wp_skin_menu_select": "{lime}{0}{default} olarak bir skin seçtiniz"
} }

View File

@@ -14,4 +14,4 @@
"wp_skin_menu_weapon_title": "武器菜单", "wp_skin_menu_weapon_title": "武器菜单",
"wp_skin_menu_skin_title": "为 {lime}{0}{default} 选择皮肤", "wp_skin_menu_skin_title": "为 {lime}{0}{default} 选择皮肤",
"wp_skin_menu_select": "您已选择 {lime}{0}{default} 作为您的皮肤" "wp_skin_menu_select": "您已选择 {lime}{0}{default} 作为您的皮肤"
} }

File diff suppressed because one or more lines are too long