Merge pull request #324 from daffyyyy/main

2.9a
This commit is contained in:
Dawid Bepierszcz
2024-10-19 20:26:29 +02:00
committed by GitHub
8 changed files with 814 additions and 541 deletions

View File

@@ -1,7 +1,9 @@
using CounterStrikeSharp.API.Core; using System.Collections.Concurrent;
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 CounterStrikeSharp.API.Modules.Timers; using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Modules.Utils;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace WeaponPaints; namespace WeaponPaints;
@@ -150,6 +152,11 @@ public partial class WeaponPaints
{ {
if (!Utility.IsPlayerValid(player)) return; if (!Utility.IsPlayerValid(player)) return;
var playerKnives = GPlayersKnife.GetOrAdd(player.Slot, new ConcurrentDictionary<CsTeam, string>());
var teamsToCheck = player.TeamNum < 2
? new[] { CsTeam.Terrorist, CsTeam.CounterTerrorist }
: [player.Team];
var knifeName = option.Text; var knifeName = option.Text;
var knifeKey = knivesOnly.FirstOrDefault(x => x.Value == knifeName).Key; var knifeKey = knivesOnly.FirstOrDefault(x => x.Value == knifeName).Key;
if (string.IsNullOrEmpty(knifeKey)) return; if (string.IsNullOrEmpty(knifeKey)) return;
@@ -173,13 +180,17 @@ public partial class WeaponPaints
IpAddress = player.IpAddress?.Split(":")[0] IpAddress = player.IpAddress?.Split(":")[0]
}; };
GPlayersKnife[player.Slot] = knifeKey; foreach (var team in teamsToCheck)
{
// Attempt to get the existing knives
playerKnives[team] = knifeKey;
}
if (_gBCommandsAllowed && (LifeState_t)player.LifeState == LifeState_t.LIFE_ALIVE) if (_gBCommandsAllowed && (LifeState_t)player.LifeState == LifeState_t.LIFE_ALIVE)
RefreshWeapons(player); RefreshWeapons(player);
if (WeaponSync != null) if (WeaponSync != null)
_ = Task.Run(async () => await WeaponSync.SyncKnifeToDatabase(playerInfo, knifeKey)); _ = Task.Run(async () => await WeaponSync.SyncKnifeToDatabase(playerInfo, knifeKey, teamsToCheck));
}; };
foreach (var knifePair in knivesOnly) foreach (var knifePair in knivesOnly)
{ {
@@ -229,7 +240,7 @@ public partial class WeaponPaints
var selectedWeapon = option.Text; var selectedWeapon = option.Text;
if (!classNamesByWeapon.TryGetValue(selectedWeapon, out var selectedWeaponClassname)) return; if (!classNamesByWeapon.TryGetValue(selectedWeapon, out var selectedWeaponClassname)) return;
var skinsForSelectedWeapon = SkinsList?.Where(skin => var skinsForSelectedWeapon = SkinsList.Where(skin =>
skin.TryGetValue("weapon_name", out var weaponName) && skin.TryGetValue("weapon_name", out var weaponName) &&
weaponName?.ToString() == selectedWeaponClassname weaponName?.ToString() == selectedWeaponClassname
)?.ToList(); )?.ToList();
@@ -241,8 +252,7 @@ public partial class WeaponPaints
{ {
if (!Utility.IsPlayerValid(p)) return; if (!Utility.IsPlayerValid(p)) return;
var steamId = p.SteamID.ToString(); var firstSkin = SkinsList.FirstOrDefault(skin =>
var firstSkin = SkinsList?.FirstOrDefault(skin =>
{ {
if (skin.TryGetValue("weapon_name", out var weaponName)) if (skin.TryGetValue("weapon_name", out var weaponName))
{ {
@@ -259,29 +269,38 @@ public partial class WeaponPaints
!int.TryParse(weaponDefIndexObj.ToString(), out var weaponDefIndex) || !int.TryParse(weaponDefIndexObj.ToString(), out var weaponDefIndex) ||
!int.TryParse(selectedPaintId, out var paintId)) return; !int.TryParse(selectedPaintId, out var paintId)) return;
{ {
if (Config.Additional.ShowSkinImage && SkinsList != null) if (Config.Additional.ShowSkinImage)
{ {
var foundSkin = SkinsList.FirstOrDefault(skin => var foundSkin = SkinsList.FirstOrDefault(skin =>
((int?)skin?["weapon_defindex"] ?? 0) == weaponDefIndex && ((int?)skin["weapon_defindex"] ?? 0) == weaponDefIndex &&
((int?)skin?["paint"] ?? 0) == paintId && ((int?)skin["paint"] ?? 0) == paintId &&
skin?["image"] != null skin["image"] != null
); );
var image = foundSkin?["image"]?.ToString() ?? ""; var image = foundSkin?["image"]?.ToString() ?? "";
_playerWeaponImage[p.Slot] = image; _playerWeaponImage[p.Slot] = image;
AddTimer(2.0f, () => _playerWeaponImage.Remove(p.Slot), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); AddTimer(2.0f, () => _playerWeaponImage.Remove(p.Slot), TimerFlags.STOP_ON_MAPCHANGE);
} }
p.Print(Localizer["wp_skin_menu_select", selectedSkin]); p.Print(Localizer["wp_skin_menu_select", selectedSkin]);
var playerSkins = GPlayerWeaponsInfo.GetOrAdd(p.Slot, new ConcurrentDictionary<CsTeam, ConcurrentDictionary<int, WeaponInfo>>());
if (!GPlayerWeaponsInfo[p.Slot].TryGetValue(weaponDefIndex, out var value)) var teamsToCheck = p.TeamNum < 2
? new[] { CsTeam.Terrorist, CsTeam.CounterTerrorist }
: [p.Team];
foreach (var team in teamsToCheck)
{ {
value = new WeaponInfo(); // Ensure there's an entry for the team in playerSkins
GPlayerWeaponsInfo[p.Slot][weaponDefIndex] = value; var teamWeapons = playerSkins.GetOrAdd(team, _ => new ConcurrentDictionary<int, WeaponInfo>());
}
// Attempt to get or add the existing WeaponInfo
var value = teamWeapons.GetOrAdd(weaponDefIndex, _ => new WeaponInfo());
// Update the properties of WeaponInfo
value.Paint = paintId; value.Paint = paintId;
value.Wear = 0.01f; value.Wear = 0.01f;
value.Seed = 0; value.Seed = 0;
}
PlayerInfo playerInfo = new PlayerInfo PlayerInfo playerInfo = new PlayerInfo
{ {
@@ -372,6 +391,11 @@ public partial class WeaponPaints
var selectedPaintName = option.Text; var selectedPaintName = option.Text;
var playerGloves = GPlayersGlove.GetOrAdd(player.Slot, new ConcurrentDictionary<CsTeam, ushort>());
var teamsToCheck = player.TeamNum < 2
? new[] { CsTeam.Terrorist, CsTeam.CounterTerrorist }
: [player.Team];
var selectedGlove = GlovesList.FirstOrDefault(g => g.ContainsKey("paint_name") && g["paint_name"]?.ToString() == selectedPaintName); var selectedGlove = GlovesList.FirstOrDefault(g => g.ContainsKey("paint_name") && g["paint_name"]?.ToString() == selectedPaintName);
var image = selectedGlove?["image"]?.ToString() ?? ""; var image = selectedGlove?["image"]?.ToString() ?? "";
if (selectedGlove == null || if (selectedGlove == null ||
@@ -397,15 +421,32 @@ public partial class WeaponPaints
if (paint != 0) if (paint != 0)
{ {
GPlayersGlove[player.Slot] = (ushort)weaponDefindex; // Ensure that player weapons info exists for the player
if (!GPlayerWeaponsInfo.ContainsKey(player.Slot))
{
GPlayerWeaponsInfo[player.Slot] = new ConcurrentDictionary<CsTeam, ConcurrentDictionary<int, WeaponInfo>>();
}
if (!GPlayerWeaponsInfo[player.Slot].ContainsKey(weaponDefindex)) // Ensure teams are initialized
foreach (var team in teamsToCheck)
{
if (!GPlayerWeaponsInfo[player.Slot].ContainsKey(team))
{
GPlayerWeaponsInfo[player.Slot][team] = new ConcurrentDictionary<int, WeaponInfo>();
}
// Update the glove for the player in the specified team
playerGloves[team] = (ushort)weaponDefindex;
// Check if the glove information already exists for the player
if (!GPlayerWeaponsInfo[player.Slot][team].ContainsKey(weaponDefindex))
{ {
WeaponInfo weaponInfo = new() WeaponInfo weaponInfo = new()
{ {
Paint = paint Paint = paint
}; };
GPlayerWeaponsInfo[player.Slot][weaponDefindex] = weaponInfo; GPlayerWeaponsInfo[player.Slot][team][weaponDefindex] = weaponInfo;
}
} }
} }
else else
@@ -413,28 +454,30 @@ public partial class WeaponPaints
GPlayersGlove.TryRemove(player.Slot, out _); GPlayersGlove.TryRemove(player.Slot, out _);
} }
if (!string.IsNullOrEmpty(Localizer["wp_glove_menu_select"]))
{
player.Print(Localizer["wp_glove_menu_select", selectedPaintName]);
}
if (WeaponSync == null) return; if (WeaponSync == null) return;
_ = Task.Run(async () => _ = Task.Run(async () =>
{ {
await WeaponSync.SyncGloveToDatabase(playerInfo, weaponDefindex); // Sync glove to database for all teams
foreach (var team in teamsToCheck)
{
await WeaponSync.SyncGloveToDatabase(playerInfo, (ushort)weaponDefindex, teamsToCheck);
if (!GPlayerWeaponsInfo[playerInfo.Slot].TryGetValue(weaponDefindex, out var value)) // Check if the weapon info exists for the glove
if (!GPlayerWeaponsInfo[playerInfo.Slot][team].TryGetValue(weaponDefindex, out var value))
{ {
value = new WeaponInfo(); value = new WeaponInfo();
GPlayerWeaponsInfo[playerInfo.Slot][weaponDefindex] = value; GPlayerWeaponsInfo[playerInfo.Slot][team][weaponDefindex] = value;
} }
// Update weapon info
value.Paint = paint; value.Paint = paint;
value.Wear = 0.00f; value.Wear = 0.00f;
value.Seed = 0; value.Seed = 0;
// Sync weapon paints to database
await WeaponSync.SyncWeaponPaintsToDatabase(playerInfo); await WeaponSync.SyncWeaponPaintsToDatabase(playerInfo);
}
}); });
AddTimer(0.1f, () => GivePlayerGloves(player)); AddTimer(0.1f, () => GivePlayerGloves(player));
@@ -597,6 +640,11 @@ public partial class WeaponPaints
var selectedPaintName = option.Text; var selectedPaintName = option.Text;
var playerMusic = GPlayersMusic.GetOrAdd(player.Slot, new ConcurrentDictionary<CsTeam, ushort>());
var teamsToCheck = player.TeamNum < 2
? new[] { CsTeam.Terrorist, CsTeam.CounterTerrorist }
: [player.Team]; // Corrected array initializer
var selectedMusic = MusicList.FirstOrDefault(g => g.ContainsKey("name") && g["name"]?.ToString() == selectedPaintName); var selectedMusic = MusicList.FirstOrDefault(g => g.ContainsKey("name") && g["name"]?.ToString() == selectedPaintName);
if (selectedMusic != null) if (selectedMusic != null)
{ {
@@ -607,7 +655,7 @@ public partial class WeaponPaints
if (Config.Additional.ShowSkinImage) if (Config.Additional.ShowSkinImage)
{ {
_playerWeaponImage[player.Slot] = image; _playerWeaponImage[player.Slot] = image;
AddTimer(2.0f, () => _playerWeaponImage.Remove(player.Slot), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); AddTimer(2.0f, () => _playerWeaponImage.Remove(player.Slot), TimerFlags.STOP_ON_MAPCHANGE);
} }
PlayerInfo playerInfo = new PlayerInfo PlayerInfo playerInfo = new PlayerInfo
@@ -622,11 +670,17 @@ public partial class WeaponPaints
if (paint != 0) if (paint != 0)
{ {
GPlayersMusic[player.Slot] = (ushort)paint; foreach (var team in teamsToCheck)
{
playerMusic[team] = (ushort)paint;
}
} }
else else
{ {
GPlayersMusic[player.Slot] = 0; foreach (var team in teamsToCheck)
{
playerMusic[team] = 0;
}
} }
if (!string.IsNullOrEmpty(Localizer["wp_music_menu_select"])) if (!string.IsNullOrEmpty(Localizer["wp_music_menu_select"]))
@@ -638,11 +692,9 @@ public partial class WeaponPaints
{ {
_ = Task.Run(async () => _ = Task.Run(async () =>
{ {
await WeaponSync.SyncMusicToDatabase(playerInfo, (ushort)paint); await WeaponSync.SyncMusicToDatabase(playerInfo, (ushort)paint, teamsToCheck);
}); });
} }
//RefreshGloves(player);
} }
else else
{ {
@@ -656,7 +708,10 @@ public partial class WeaponPaints
IpAddress = player.IpAddress?.Split(":")[0] IpAddress = player.IpAddress?.Split(":")[0]
}; };
GPlayersMusic[player.Slot] = 0; foreach (var team in teamsToCheck)
{
playerMusic[team] = 0;
}
if (!string.IsNullOrEmpty(Localizer["wp_music_menu_select"])) if (!string.IsNullOrEmpty(Localizer["wp_music_menu_select"]))
{ {
@@ -667,7 +722,7 @@ public partial class WeaponPaints
{ {
_ = Task.Run(async () => _ = Task.Run(async () =>
{ {
await WeaponSync.SyncMusicToDatabase(playerInfo, 0); await WeaponSync.SyncMusicToDatabase(playerInfo, 0, teamsToCheck);
}); });
} }
} }
@@ -716,6 +771,11 @@ public partial class WeaponPaints
var selectedPaintName = option.Text; var selectedPaintName = option.Text;
var playerPins = GPlayersPin.GetOrAdd(player.Slot, new ConcurrentDictionary<CsTeam, ushort>());
var teamsToCheck = player.TeamNum < 2
? new[] { CsTeam.Terrorist, CsTeam.CounterTerrorist }
: [player.Team];
var selectedPin = PinsList.FirstOrDefault(g => g.ContainsKey("name") && g["name"]?.ToString() == selectedPaintName); var selectedPin = PinsList.FirstOrDefault(g => g.ContainsKey("name") && g["name"]?.ToString() == selectedPaintName);
if (selectedPin != null) if (selectedPin != null)
{ {
@@ -741,11 +801,17 @@ public partial class WeaponPaints
if (paint != 0) if (paint != 0)
{ {
GPlayersPin[player.Slot] = (ushort)paint; foreach (var team in teamsToCheck)
{
playerPins[team] = (ushort)paint; // Set pin for each team
}
} }
else else
{ {
GPlayersPin[player.Slot] = 0; foreach (var team in teamsToCheck)
{
playerPins[team] = 0; // Set pin for each team
}
} }
if (!string.IsNullOrEmpty(Localizer["wp_pins_menu_select"])) if (!string.IsNullOrEmpty(Localizer["wp_pins_menu_select"]))
@@ -759,7 +825,7 @@ public partial class WeaponPaints
{ {
_ = Task.Run(async () => _ = Task.Run(async () =>
{ {
await WeaponSync.SyncPinToDatabase(playerInfo, (ushort)paint); await WeaponSync.SyncPinToDatabase(playerInfo, (ushort)paint, teamsToCheck);
}); });
} }
} }
@@ -775,7 +841,10 @@ public partial class WeaponPaints
IpAddress = player.IpAddress?.Split(":")[0] IpAddress = player.IpAddress?.Split(":")[0]
}; };
GPlayersPin[player.Slot] = 0; foreach (var team in teamsToCheck)
{
playerPins[team] = 0; // Set music for each team
}
if (!string.IsNullOrEmpty(Localizer["wp_pins_menu_select"])) if (!string.IsNullOrEmpty(Localizer["wp_pins_menu_select"]))
{ {
@@ -788,7 +857,7 @@ public partial class WeaponPaints
{ {
_ = Task.Run(async () => _ = Task.Run(async () =>
{ {
await WeaponSync.SyncPinToDatabase(playerInfo, 0); await WeaponSync.SyncPinToDatabase(playerInfo, 0, teamsToCheck);
}); });
} }
} }

View File

@@ -81,7 +81,7 @@ namespace WeaponPaints
return HookResult.Continue; return HookResult.Continue;
if (WeaponSync != null) if (WeaponSync != null)
_ = Task.Run(async () => await WeaponSync.SyncStatTrakToDatabase(playerInfo, weaponInfos)); _ = Task.Run(async () => await WeaponSync.SyncStatTrakToDatabase(playerInfo));
if (Config.Additional.SkinEnabled) if (Config.Additional.SkinEnabled)
{ {
@@ -253,10 +253,14 @@ namespace WeaponPaints
private HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info) private HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info)
{ {
CCSPlayerController? player = @event.Attacker; CCSPlayerController? player = @event.Attacker;
CCSPlayerController? victim = @event.Userid;
if (player is null || !player.IsValid) if (player is null || !player.IsValid)
return HookResult.Continue; return HookResult.Continue;
if (victim == null || victim == player)
return HookResult.Continue;
if (!GPlayerWeaponsInfo.TryGetValue(player.Slot, out _)) return HookResult.Continue; if (!GPlayerWeaponsInfo.TryGetValue(player.Slot, out _)) return HookResult.Continue;
CBasePlayerWeapon? weapon = player.PlayerPawn.Value?.WeaponServices?.ActiveWeapon.Value; CBasePlayerWeapon? weapon = player.PlayerPawn.Value?.WeaponServices?.ActiveWeapon.Value;
@@ -265,7 +269,7 @@ namespace WeaponPaints
int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex; int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex;
if (!GPlayerWeaponsInfo[player.Slot].TryGetValue(weaponDefIndex, out var weaponInfo) || weaponInfo.Paint == 0) if (!GPlayerWeaponsInfo[player.Slot][player.Team].TryGetValue(weaponDefIndex, out var weaponInfo) || weaponInfo.Paint == 0)
return HookResult.Continue; return HookResult.Continue;
if (!weaponInfo.StatTrak) return HookResult.Continue; if (!weaponInfo.StatTrak) return HookResult.Continue;

View File

@@ -24,58 +24,65 @@ namespace WeaponPaints
{ {
string[] createTableQueries = string[] createTableQueries =
[ [
""" @"
CREATE TABLE IF NOT EXISTS `wp_player_skins` ( CREATE TABLE IF NOT EXISTS `wp_player_skins` (
`steamid` varchar(18) NOT NULL, `steamid` varchar(18) NOT NULL,
`weapon_team` int(1) 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,
`weapon_nametag` VARCHAR(128) DEFAULT NULL, `weapon_nametag` VARCHAR(128) DEFAULT NULL,
`weapon_stattrak` tinyint(1) NOT NULL, `weapon_stattrak` tinyint(1) NOT NULL DEFAULT 0,
`weapon_stattrak_count` int(10) NOT NULL, `weapon_stattrak_count` int(10) NOT NULL DEFAULT 0,
`weapon_sticker_0` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0;0;0' COMMENT 'id;schema;x;y;wear;scale;rotation', `weapon_sticker_0` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0;0;0' COMMENT 'id;schema;x;y;wear;scale;rotation',
`weapon_sticker_1` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0;0;0' COMMENT 'id;schema;x;y;wear;scale;rotation', `weapon_sticker_1` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0;0;0' COMMENT 'id;schema;x;y;wear;scale;rotation',
`weapon_sticker_2` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0;0;0' COMMENT 'id;schema;x;y;wear;scale;rotation', `weapon_sticker_2` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0;0;0' COMMENT 'id;schema;x;y;wear;scale;rotation',
`weapon_sticker_3` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0;0;0' COMMENT 'id;schema;x;y;wear;scale;rotation', `weapon_sticker_3` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0;0;0' COMMENT 'id;schema;x;y;wear;scale;rotation',
`weapon_sticker_4` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0;0;0' COMMENT 'id;schema;x;y;wear;scale;rotation', `weapon_sticker_4` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0;0;0' COMMENT 'id;schema;x;y;wear;scale;rotation',
`weapon_keychain`VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0' COMMENT 'id;x;y;z;seed' `weapon_keychain` VARCHAR(128) NOT NULL DEFAULT '0;0;0;0;0' COMMENT 'id;x;y;z;seed',
) ENGINE=InnoDB UNIQUE (`steamid`, `weapon_team`, `weapon_defindex`) -- Add unique constraint here
""", ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;",
@"CREATE TABLE IF NOT EXISTS `wp_player_knife` (
@"
CREATE TABLE IF NOT EXISTS `wp_player_knife` (
`steamid` varchar(18) NOT NULL, `steamid` varchar(18) NOT NULL,
`weapon_team` int(1) NOT NULL,
`knife` varchar(64) NOT NULL, `knife` varchar(64) NOT NULL,
UNIQUE (`steamid`) UNIQUE (`steamid`, `weapon_team`) -- Unique constraint
) ENGINE = InnoDB", ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;",
"""
@"
CREATE TABLE IF NOT EXISTS `wp_player_gloves` ( CREATE TABLE IF NOT EXISTS `wp_player_gloves` (
`steamid` varchar(18) NOT NULL, `steamid` varchar(18) NOT NULL,
`weapon_team` int(1) NOT NULL,
`weapon_defindex` int(11) NOT NULL, `weapon_defindex` int(11) NOT NULL,
UNIQUE (`steamid`) UNIQUE (`steamid`, `weapon_team`) -- Unique constraint
) ENGINE=InnoDB ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;",
""",
""" @"
CREATE TABLE IF NOT EXISTS `wp_player_agents` ( CREATE TABLE IF NOT EXISTS `wp_player_agents` (
`steamid` varchar(18) NOT NULL, `steamid` varchar(18) NOT NULL,
`agent_ct` varchar(64) DEFAULT NULL, `agent_ct` varchar(64) DEFAULT NULL,
`agent_t` varchar(64) DEFAULT NULL, `agent_t` varchar(64) DEFAULT NULL,
UNIQUE (`steamid`) UNIQUE (`steamid`) -- Unique constraint
) ENGINE=InnoDB ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;",
""",
""" @"
CREATE TABLE IF NOT EXISTS `wp_player_music` ( CREATE TABLE IF NOT EXISTS `wp_player_music` (
`steamid` varchar(64) NOT NULL, `steamid` varchar(64) NOT NULL,
`weapon_team` int(1) NOT NULL,
`music_id` int(11) NOT NULL, `music_id` int(11) NOT NULL,
UNIQUE (`steamid`) UNIQUE (`steamid`, `weapon_team`) -- Unique constraint
) ENGINE=InnoDB ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;",
""",
""" @"
CREATE TABLE IF NOT EXISTS `wp_player_pins` ( CREATE TABLE IF NOT EXISTS `wp_player_pins` (
`steamid` varchar(64) NOT NULL, `steamid` varchar(64) NOT NULL,
`weapon_team` int(1) NOT NULL,
`id` int(11) NOT NULL, `id` int(11) NOT NULL,
UNIQUE (`steamid`) UNIQUE (`steamid`, `weapon_team`) -- Unique constraint
) ENGINE=InnoDB ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;"
""",
]; ];
foreach (var query in createTableQueries) foreach (var query in createTableQueries)

View File

@@ -1 +1 @@
2.8c 2.9a

View File

@@ -3,6 +3,7 @@ using System.Runtime.InteropServices;
using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Capabilities; using CounterStrikeSharp.API.Core.Capabilities;
using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions; using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions;
using CounterStrikeSharp.API.Modules.Utils;
using MenuManager; using MenuManager;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@@ -72,12 +73,12 @@ public partial class WeaponPaints
}; };
public static IStringLocalizer? _localizer; public static IStringLocalizer? _localizer;
internal static readonly ConcurrentDictionary<int, string> GPlayersKnife = new(); internal static readonly ConcurrentDictionary<int, ConcurrentDictionary<CsTeam, string>> GPlayersKnife = new();
internal static readonly ConcurrentDictionary<int, ushort> GPlayersGlove = new(); internal static readonly ConcurrentDictionary<int, ConcurrentDictionary<CsTeam, ushort>> GPlayersGlove = new();
internal static readonly ConcurrentDictionary<int, ushort> GPlayersMusic = new(); internal static readonly ConcurrentDictionary<int, ConcurrentDictionary<CsTeam, ushort>> GPlayersMusic = new();
internal static readonly ConcurrentDictionary<int, ushort> GPlayersPin = new(); internal static readonly ConcurrentDictionary<int, ConcurrentDictionary<CsTeam, ushort>> GPlayersPin = new();
public static readonly ConcurrentDictionary<int, (string? CT, string? T)> GPlayersAgent = new(); public static readonly ConcurrentDictionary<int, (string? CT, string? T)> GPlayersAgent = new();
internal static readonly ConcurrentDictionary<int, ConcurrentDictionary<int, WeaponInfo>> GPlayerWeaponsInfo = new(); internal static readonly ConcurrentDictionary<int, ConcurrentDictionary<CsTeam, ConcurrentDictionary<int, WeaponInfo>>> GPlayerWeaponsInfo = new();
internal static List<JObject> SkinsList = []; internal static List<JObject> SkinsList = [];
internal static List<JObject> PinsList = []; internal static List<JObject> PinsList = [];
internal static List<JObject> GlovesList = []; internal static List<JObject> GlovesList = [];

View File

@@ -20,11 +20,12 @@ namespace WeaponPaints
bool isKnife = weapon.DesignerName.Contains("knife") || weapon.DesignerName.Contains("bayonet"); bool isKnife = weapon.DesignerName.Contains("knife") || weapon.DesignerName.Contains("bayonet");
if (isKnife && !GPlayersKnife.ContainsKey(player.Slot) || isKnife && GPlayersKnife[player.Slot] == "weapon_knife") return; if (isKnife && !GPlayersKnife.ContainsKey(player.Slot) ||
isKnife && GPlayersKnife[player.Slot][player.Team] == "weapon_knife") return;
if (isKnife) if (isKnife)
{ {
var newDefIndex = WeaponDefindex.FirstOrDefault(x => x.Value == GPlayersKnife[player.Slot]); var newDefIndex = WeaponDefindex.FirstOrDefault(x => x.Value == GPlayersKnife[player.Slot][player.Team]);
if (newDefIndex.Key == 0) return; if (newDefIndex.Key == 0) return;
if (weapon.AttributeManager.Item.ItemDefinitionIndex != newDefIndex.Key) if (weapon.AttributeManager.Item.ItemDefinitionIndex != newDefIndex.Key)
@@ -47,7 +48,7 @@ namespace WeaponPaints
bool isLegacyModel; bool isLegacyModel;
if (_config.Additional.GiveRandomSkin && if (_config.Additional.GiveRandomSkin &&
!GPlayerWeaponsInfo[player.Slot].ContainsKey(weaponDefIndex)) !GPlayerWeaponsInfo[player.Slot][player.Team].ContainsKey(weaponDefIndex))
{ {
// Random skins // Random skins
weapon.FallbackPaintKit = GetRandomPaint(weaponDefIndex); weapon.FallbackPaintKit = GetRandomPaint(weaponDefIndex);
@@ -80,7 +81,7 @@ namespace WeaponPaints
return; return;
} }
if (!GPlayerWeaponsInfo[player.Slot].TryGetValue(weaponDefIndex, out var value) || value.Paint == 0) return; if (!GPlayerWeaponsInfo[player.Slot][player.Team].TryGetValue(weaponDefIndex, out var value) || value.Paint == 0) return;
var weaponInfo = value; var weaponInfo = value;
//Log($"Apply on {weapon.DesignerName}({weapon.AttributeManager.Item.ItemDefinitionIndex}) paint {gPlayerWeaponPaints[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]} seed {gPlayerWeaponSeed[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]} wear {gPlayerWeaponWear[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]}"); //Log($"Apply on {weapon.DesignerName}({weapon.AttributeManager.Item.ItemDefinitionIndex}) paint {gPlayerWeaponPaints[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]} seed {gPlayerWeaponSeed[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]} wear {gPlayerWeaponWear[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]}");
@@ -131,7 +132,8 @@ namespace WeaponPaints
{ {
int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex; int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex;
if (!GPlayerWeaponsInfo.TryGetValue(player.Slot, out var playerWeapons) || if (!GPlayerWeaponsInfo.TryGetValue(player.Slot, out var playerWeapons) ||
!playerWeapons.TryGetValue(weaponDefIndex, out var weaponInfo) || !playerWeapons.TryGetValue(player.Team, out var weaponInfoDict) ||
!weaponInfoDict.TryGetValue(weaponDefIndex, out var weaponInfo) ||
weaponInfo.Stickers.Count <= 0) return; weaponInfo.Stickers.Count <= 0) return;
float wearIncrement = 0.001f; float wearIncrement = 0.001f;
@@ -155,7 +157,7 @@ namespace WeaponPaints
int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex; int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex;
if (!GPlayerWeaponsInfo.TryGetValue(player.Slot, out var playerWeapons) || if (!GPlayerWeaponsInfo.TryGetValue(player.Slot, out var playerWeapons) ||
!playerWeapons.TryGetValue(weaponDefIndex, out var weaponInfo)) !playerWeapons[player.Team].TryGetValue(weaponDefIndex, out var weaponInfo))
{ {
return; return;
} }
@@ -197,7 +199,7 @@ namespace WeaponPaints
int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex; int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex;
if (!GPlayerWeaponsInfo.TryGetValue(player.Slot, out var playerWeaponsInfo) || if (!GPlayerWeaponsInfo.TryGetValue(player.Slot, out var playerWeaponsInfo) ||
!playerWeaponsInfo.TryGetValue(weaponDefIndex, out var value) || !playerWeaponsInfo[player.Team].TryGetValue(weaponDefIndex, out var value) ||
value.KeyChain == null) return; value.KeyChain == null) return;
var keyChain = value.KeyChain; var keyChain = value.KeyChain;
@@ -263,8 +265,6 @@ namespace WeaponPaints
if (player.Team is CsTeam.None or CsTeam.Spectator) if (player.Team is CsTeam.None or CsTeam.Spectator)
return; return;
int playerTeam = player.TeamNum;
Dictionary<string, List<(int, int)>> weaponsWithAmmo = []; Dictionary<string, List<(int, int)>> weaponsWithAmmo = [];
foreach (var weapon in weapons) foreach (var weapon in weapons)
@@ -376,11 +376,12 @@ namespace WeaponPaints
if (!player.PawnIsAlive) if (!player.PawnIsAlive)
return; return;
if (!GPlayersGlove.TryGetValue(player.Slot, out var gloveInfo) || gloveInfo == 0) return; if (!GPlayersGlove.TryGetValue(player.Slot, out var gloveInfo) ||
!gloveInfo.TryGetValue(player.Team, out var gloveId) || gloveId == 0) return;
WeaponInfo weaponInfo = GPlayerWeaponsInfo[player.Slot][gloveInfo]; WeaponInfo weaponInfo = GPlayerWeaponsInfo[player.Slot][player.Team][gloveId];
item.ItemDefinitionIndex = gloveInfo; item.ItemDefinitionIndex = gloveId;
item.ItemIDLow = 16384 & 0xFFFFFFFF; item.ItemIDLow = 16384 & 0xFFFFFFFF;
item.ItemIDHigh = 16384; item.ItemIDHigh = 16384;
@@ -472,21 +473,24 @@ namespace WeaponPaints
private static void GivePlayerMusicKit(CCSPlayerController player) private static void GivePlayerMusicKit(CCSPlayerController player)
{ {
if (!GPlayersMusic.TryGetValue(player.Slot, out var value)) return; if (GPlayersMusic.TryGetValue(player.Slot, out var musicInfo) || musicInfo == null ||
!musicInfo.TryGetValue(player.Team, out var musicId) || musicId == 0) return;
if (player.InventoryServices == null) return; if (player.InventoryServices == null) return;
player.InventoryServices.MusicID = value; player.InventoryServices.MusicID = musicId;
Utilities.SetStateChanged(player, "CCSPlayerController", "m_pInventoryServices"); Utilities.SetStateChanged(player, "CCSPlayerController", "m_pInventoryServices");
player.MusicKitID = value; player.MusicKitID = musicId;
Utilities.SetStateChanged(player, "CCSPlayerController", "m_iMusicKitID"); Utilities.SetStateChanged(player, "CCSPlayerController", "m_iMusicKitID");
} }
private static void GivePlayerPin(CCSPlayerController player) private static void GivePlayerPin(CCSPlayerController player)
{ {
if (!GPlayersPin.TryGetValue(player.Slot, out var pin)) return; if (!GPlayersPin.TryGetValue(player.Slot, out var pinInfo) ||
!pinInfo.TryGetValue(player.Team, out var pinId)) return;
if (player.InventoryServices == null) return; if (player.InventoryServices == null) return;
player.InventoryServices.Rank[5] = pin > 0 ? (MedalRank_t)pin : MedalRank_t.MEDAL_RANK_NONE; player.InventoryServices.Rank[5] = pinId > 0 ? (MedalRank_t)pinId : MedalRank_t.MEDAL_RANK_NONE;
Utilities.SetStateChanged(player, "CCSPlayerController", "m_pInventoryServices"); Utilities.SetStateChanged(player, "CCSPlayerController", "m_pInventoryServices");
} }

View File

@@ -16,7 +16,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, gloves, agents and knife selector, standalone and web-based"; public override string ModuleDescription => "Skin, gloves, agents and knife selector, standalone and web-based";
public override string ModuleName => "WeaponPaints"; public override string ModuleName => "WeaponPaints";
public override string ModuleVersion => "2.8c"; public override string ModuleVersion => "2.9a";
public override void Load(bool hotReload) public override void Load(bool hotReload)
{ {
@@ -26,18 +26,19 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{ {
OnMapStart(string.Empty); OnMapStart(string.Empty);
GPlayerWeaponsInfo.Clear();
GPlayersKnife.Clear();
GPlayersGlove.Clear();
GPlayersAgent.Clear();
GPlayersPin.Clear();
GPlayersMusic.Clear();
foreach (var player in Enumerable foreach (var player in Enumerable
.OfType<CCSPlayerController>(Utilities.GetPlayers().TakeWhile(player => WeaponSync != null)) .OfType<CCSPlayerController>(Utilities.GetPlayers().TakeWhile(_ => WeaponSync != null))
.Where(player => player.IsValid && .Where(player => player.IsValid &&
!string.IsNullOrEmpty(player.IpAddress) && player is !string.IsNullOrEmpty(player.IpAddress) && player is
{ IsBot: false, Connected: PlayerConnectedState.PlayerConnected })) { IsBot: false, Connected: PlayerConnectedState.PlayerConnected }))
{ {
GPlayerWeaponsInfo.TryRemove(player.Slot, out _);
GPlayersKnife.TryRemove(player.Slot, out _);
GPlayersGlove.TryRemove(player.Slot, out _);
GPlayersAgent.TryRemove(player.Slot, out _);
GPlayersPin.TryRemove(player.Slot, out _);
var playerInfo = new PlayerInfo var playerInfo = new PlayerInfo
{ {
UserId = player.UserId, UserId = player.UserId,

View File

@@ -1,12 +1,13 @@
using Dapper; using Dapper;
using MySqlConnector; using MySqlConnector;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using CounterStrikeSharp.API.Modules.Utils;
namespace WeaponPaints namespace WeaponPaints;
internal class WeaponSynchronization
{ {
internal class WeaponSynchronization
{
private readonly WeaponPaintsConfig _config; private readonly WeaponPaintsConfig _config;
private readonly Database _database; private readonly Database _database;
@@ -49,12 +50,36 @@ namespace WeaponPaints
if (!_config.Additional.KnifeEnabled || string.IsNullOrEmpty(player?.SteamId)) if (!_config.Additional.KnifeEnabled || string.IsNullOrEmpty(player?.SteamId))
return; return;
const string query = "SELECT `knife` FROM `wp_player_knife` WHERE `steamid` = @steamid"; const string query = "SELECT `knife`, `weapon_team` FROM `wp_player_knife` WHERE `steamid` = @steamid";
var playerKnife = connection.QueryFirstOrDefault<string>(query, new { steamid = player.SteamId }); var rows = connection.Query<dynamic>(query, new { steamid = player.SteamId }); // Retrieve all records for the player
if (!string.IsNullOrEmpty(playerKnife)) foreach (var row in rows)
{ {
WeaponPaints.GPlayersKnife[player.Slot] = playerKnife; // Check if knife is null or empty
if (string.IsNullOrEmpty(row.knife)) continue;
// Determine the weapon team based on the query result
CsTeam weaponTeam = (int)row.weapon_team switch
{
0 => CsTeam.None,
2 => CsTeam.Terrorist,
_ => CsTeam.CounterTerrorist
};
// Get or create entries for the players slot
var playerKnives = WeaponPaints.GPlayersKnife.GetOrAdd(player.Slot, _ => new ConcurrentDictionary<CsTeam, string>());
if (weaponTeam == CsTeam.None)
{
// Assign knife to both teams if weaponTeam is None
playerKnives[CsTeam.Terrorist] = row.knife;
playerKnives[CsTeam.CounterTerrorist] = row.knife;
}
else
{
// Assign knife to the specific team
playerKnives[weaponTeam] = row.knife;
}
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -70,17 +95,40 @@ namespace WeaponPaints
if (!_config.Additional.GloveEnabled || string.IsNullOrEmpty(player?.SteamId)) if (!_config.Additional.GloveEnabled || string.IsNullOrEmpty(player?.SteamId))
return; return;
const string query = "SELECT `weapon_defindex` FROM `wp_player_gloves` WHERE `steamid` = @steamid"; const string query = "SELECT `weapon_defindex`, `weapon_team` FROM `wp_player_gloves` WHERE `steamid` = @steamid";
var gloveData = connection.QueryFirstOrDefault<ushort?>(query, new { steamid = player.SteamId }); var rows = connection.Query<dynamic>(query, new { steamid = player.SteamId }); // Retrieve all records for the player
if (gloveData != null) foreach (var row in rows)
{ {
WeaponPaints.GPlayersGlove[player.Slot] = gloveData.Value; // Check if weapon_defindex is null
if (row.weapon_defindex == null) continue;
// Determine the weapon team based on the query result
var playerGloves = WeaponPaints.GPlayersGlove.GetOrAdd(player.Slot, _ => new ConcurrentDictionary<CsTeam, ushort>());
CsTeam weaponTeam = (int)row.weapon_team switch
{
0 => CsTeam.None,
2 => CsTeam.Terrorist,
_ => CsTeam.CounterTerrorist
};
// Get or create entries for the players slot
if (weaponTeam == CsTeam.None)
{
// Assign glove ID to both teams if weaponTeam is None
playerGloves[CsTeam.Terrorist] = (ushort)row.weapon_defindex;
playerGloves[CsTeam.CounterTerrorist] = (ushort)row.weapon_defindex;
}
else
{
// Assign glove ID to the specific team
playerGloves[weaponTeam] = (ushort)row.weapon_defindex;
}
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Utility.Log($"An error occurred in GetGloveFromDatabase: {ex.Message}"); Utility.Log($"An error occurred in GetGlovesFromDatabase: {ex.Message}");
} }
} }
@@ -119,7 +167,10 @@ namespace WeaponPaints
if (!_config.Additional.SkinEnabled || player == null || string.IsNullOrEmpty(player.SteamId)) if (!_config.Additional.SkinEnabled || player == null || string.IsNullOrEmpty(player.SteamId))
return; return;
var weaponInfos = new ConcurrentDictionary<int, WeaponInfo>(); var playerWeapons = WeaponPaints.GPlayerWeaponsInfo.GetOrAdd(player.Slot,
_ => new ConcurrentDictionary<CsTeam, ConcurrentDictionary<int, WeaponInfo>>());
// var weaponInfos = new ConcurrentDictionary<int, WeaponInfo>();
const string query = "SELECT * FROM `wp_player_skins` WHERE `steamid` = @steamid"; const string query = "SELECT * FROM `wp_player_skins` WHERE `steamid` = @steamid";
var playerSkins = connection.Query<dynamic>(query, new { steamid = player.SteamId }); var playerSkins = connection.Query<dynamic>(query, new { steamid = player.SteamId });
@@ -134,6 +185,14 @@ namespace WeaponPaints
bool weaponStatTrak = row?.weapon_stattrak ?? false; bool weaponStatTrak = row?.weapon_stattrak ?? false;
int weaponStatTrakCount = row?.weapon_stattrak_count ?? 0; int weaponStatTrakCount = row?.weapon_stattrak_count ?? 0;
CsTeam weaponTeam = row?.weapon_team switch
{
null => CsTeam.None,
0 => CsTeam.None,
2 => CsTeam.Terrorist,
_ => CsTeam.CounterTerrorist
};
string[]? keyChainParts = row?.weapon_keychain?.ToString().Split(';'); string[]? keyChainParts = row?.weapon_keychain?.ToString().Split(';');
KeyChainInfo keyChainInfo = new KeyChainInfo(); KeyChainInfo keyChainInfo = new KeyChainInfo();
@@ -209,10 +268,27 @@ namespace WeaponPaints
weaponInfo.Stickers.Add(stickerInfo); weaponInfo.Stickers.Add(stickerInfo);
} }
weaponInfos[weaponDefIndex] = weaponInfo; if (weaponTeam == CsTeam.None)
{
// Get or create entries for both teams
var terroristWeapons = playerWeapons.GetOrAdd(CsTeam.Terrorist, _ => new ConcurrentDictionary<int, WeaponInfo>());
var counterTerroristWeapons = playerWeapons.GetOrAdd(CsTeam.CounterTerrorist, _ => new ConcurrentDictionary<int, WeaponInfo>());
// Add weaponInfo to both team weapon dictionaries
terroristWeapons[weaponDefIndex] = weaponInfo;
counterTerroristWeapons[weaponDefIndex] = weaponInfo;
}
else
{
// Add to the specific team
var teamWeapons = playerWeapons.GetOrAdd(weaponTeam, _ => new ConcurrentDictionary<int, WeaponInfo>());
teamWeapons[weaponDefIndex] = weaponInfo;
} }
WeaponPaints.GPlayerWeaponsInfo[player.Slot] = weaponInfos; // weaponInfos[weaponDefIndex] = weaponInfo;
}
// WeaponPaints.GPlayerWeaponsInfo[player.Slot][weaponTeam] = weaponInfos;
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -227,12 +303,36 @@ namespace WeaponPaints
if (!_config.Additional.MusicEnabled || string.IsNullOrEmpty(player?.SteamId)) if (!_config.Additional.MusicEnabled || string.IsNullOrEmpty(player?.SteamId))
return; return;
const string query = "SELECT `music_id` FROM `wp_player_music` WHERE `steamid` = @steamid"; const string query = "SELECT `music_id`, `weapon_team` FROM `wp_player_music` WHERE `steamid` = @steamid";
var musicData = connection.QueryFirstOrDefault<ushort?>(query, new { steamid = player.SteamId }); var rows = connection.Query<dynamic>(query, new { steamid = player.SteamId }); // Retrieve all records for the player
if (musicData != null) foreach (var row in rows)
{ {
WeaponPaints.GPlayersMusic[player.Slot] = musicData.Value; // Check if music_id is null
if (row.music_id == null) continue;
// Determine the weapon team based on the query result
CsTeam weaponTeam = (int)row.weapon_team switch
{
0 => CsTeam.None,
2 => CsTeam.Terrorist,
_ => CsTeam.CounterTerrorist
};
// Get or create entries for the players slot
var playerMusic = WeaponPaints.GPlayersMusic.GetOrAdd(player.Slot, _ => new ConcurrentDictionary<CsTeam, ushort>());
if (weaponTeam == CsTeam.None)
{
// Assign music ID to both teams if weaponTeam is None
playerMusic[CsTeam.Terrorist] = row.music_id.Value;
playerMusic[CsTeam.CounterTerrorist] = row.music_id.Value;
}
else
{
// Assign music ID to the specific team
playerMusic[weaponTeam] = row.music_id.Value;
}
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -248,12 +348,36 @@ namespace WeaponPaints
if (string.IsNullOrEmpty(player?.SteamId)) if (string.IsNullOrEmpty(player?.SteamId))
return; return;
const string query = "SELECT `id` FROM `wp_player_pins` WHERE `steamid` = @steamid"; const string query = "SELECT `id`, `weapon_team` FROM `wp_player_pins` WHERE `steamid` = @steamid";
var pinData = connection.QueryFirstOrDefault<ushort?>(query, new { steamid = player.SteamId }); var rows = connection.Query<dynamic>(query, new { steamid = player.SteamId }); // Retrieve all records for the player
if (pinData != null) foreach (var row in rows)
{ {
WeaponPaints.GPlayersPin[player.Slot] = pinData.Value; // Check if id is null
if (row.id == null) continue;
// Determine the weapon team based on the query result
CsTeam weaponTeam = (int)row.weapon_team switch
{
0 => CsTeam.None,
2 => CsTeam.Terrorist,
_ => CsTeam.CounterTerrorist
};
// Get or create entries for the players slot
var playerPins = WeaponPaints.GPlayersPin.GetOrAdd(player.Slot, _ => new ConcurrentDictionary<CsTeam, ushort>());
if (weaponTeam == CsTeam.None)
{
// Assign pin ID to both teams if weaponTeam is None
playerPins[CsTeam.Terrorist] = (ushort)row.id;
playerPins[CsTeam.CounterTerrorist] = (ushort)row.id;
}
else
{
// Assign pin ID to the specific team
playerPins[weaponTeam] = (ushort)row.id;
}
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -262,16 +386,21 @@ namespace WeaponPaints
} }
} }
internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife) internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife, CsTeam[] teams)
{ {
if (!_config.Additional.KnifeEnabled || string.IsNullOrEmpty(player.SteamId) || string.IsNullOrEmpty(knife)) return; if (!_config.Additional.KnifeEnabled || string.IsNullOrEmpty(player.SteamId) || string.IsNullOrEmpty(knife) || teams.Length == 0) return;
const string query = "INSERT INTO `wp_player_knife` (`steamid`, `knife`) VALUES(@steamid, @newKnife) ON DUPLICATE KEY UPDATE `knife` = @newKnife"; const string query = "INSERT INTO `wp_player_knife` (`steamid`, `weapon_team`, `knife`) VALUES(@steamid, @team, @newKnife) ON DUPLICATE KEY UPDATE `knife` = @newKnife";
try try
{ {
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
await connection.ExecuteAsync(query, new { steamid = player.SteamId, newKnife = knife });
// Loop through each team and insert/update accordingly
foreach (var team in teams)
{
await connection.ExecuteAsync(query, new { steamid = player.SteamId, team, newKnife = knife });
}
} }
catch (Exception e) catch (Exception e)
{ {
@@ -279,18 +408,36 @@ namespace WeaponPaints
} }
} }
internal async Task SyncGloveToDatabase(PlayerInfo player, int defindex) internal async Task SyncGloveToDatabase(PlayerInfo player, ushort gloveDefIndex, CsTeam[] teams)
{ {
if (!_config.Additional.GloveEnabled || string.IsNullOrEmpty(player.SteamId)) return; // Check if the necessary conditions are met
if (!_config.Additional.GloveEnabled || string.IsNullOrEmpty(player.SteamId) || teams.Length == 0)
return;
const string query = @"
INSERT INTO `wp_player_gloves` (`steamid`, `weapon_team`, `weapon_defindex`)
VALUES(@steamid, @team, @gloveDefIndex)
ON DUPLICATE KEY UPDATE `weapon_defindex` = @gloveDefIndex";
try try
{ {
// Get a database connection
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
const string query = "INSERT INTO `wp_player_gloves` (`steamid`, `weapon_defindex`) VALUES(@steamid, @weapon_defindex) ON DUPLICATE KEY UPDATE `weapon_defindex` = @weapon_defindex";
await connection.ExecuteAsync(query, new { steamid = player.SteamId, weapon_defindex = defindex }); // Loop through each team and insert/update accordingly
foreach (var team in teams)
{
// Execute the SQL command for each team
await connection.ExecuteAsync(query, new {
steamid = player.SteamId,
team = (int)team, // Cast the CsTeam enum to int for insertion
gloveDefIndex
});
}
} }
catch (Exception e) catch (Exception e)
{ {
// Log any exceptions that occur
Utility.Log($"Error syncing glove to database: {e.Message}"); Utility.Log($"Error syncing glove to database: {e.Message}");
} }
} }
@@ -320,56 +467,73 @@ namespace WeaponPaints
internal async Task SyncWeaponPaintsToDatabase(PlayerInfo player) internal async Task SyncWeaponPaintsToDatabase(PlayerInfo player)
{ {
if (string.IsNullOrEmpty(player.SteamId) || !WeaponPaints.GPlayerWeaponsInfo.TryGetValue(player.Slot, out var weaponsInfo)) if (string.IsNullOrEmpty(player.SteamId) || !WeaponPaints.GPlayerWeaponsInfo.TryGetValue(player.Slot, out var teamWeaponInfos))
return; return;
try try
{ {
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
// Loop through each team (Terrorist and CounterTerrorist)
foreach (var (teamId, weaponsInfo) in teamWeaponInfos)
{
foreach (var (weaponDefIndex, weaponInfo) in weaponsInfo) foreach (var (weaponDefIndex, weaponInfo) in weaponsInfo)
{ {
var paintId = weaponInfo.Paint; var paintId = weaponInfo.Paint;
var wear = weaponInfo.Wear; var wear = weaponInfo.Wear;
var seed = weaponInfo.Seed; var seed = weaponInfo.Seed;
const string queryCheckExistence = "SELECT COUNT(*) FROM `wp_player_skins` WHERE `steamid` = @steamid AND `weapon_defindex` = @weaponDefIndex"; // Prepare the queries to check and update/insert weapon skin data
const string queryCheckExistence = "SELECT COUNT(*) FROM `wp_player_skins` WHERE `steamid` = @steamid AND `weapon_defindex` = @weaponDefIndex AND `weapon_team` = @weaponTeam";
var existingRecordCount = await connection.ExecuteScalarAsync<int>(queryCheckExistence, new { steamid = player.SteamId, weaponDefIndex = weaponDefIndex }); var existingRecordCount = await connection.ExecuteScalarAsync<int>(
queryCheckExistence,
new { steamid = player.SteamId, weaponDefIndex, weaponTeam = teamId }
);
string query; string query;
object parameters; object parameters;
if (existingRecordCount > 0) if (existingRecordCount > 0)
{ {
query = "UPDATE `wp_player_skins` SET `weapon_paint_id` = @paintId, `weapon_wear` = @wear, `weapon_seed` = @seed WHERE `steamid` = @steamid AND `weapon_defindex` = @weaponDefIndex"; // Update existing record
parameters = new { steamid = player.SteamId, weaponDefIndex = weaponDefIndex, paintId, wear, seed }; query = "UPDATE `wp_player_skins` SET `weapon_paint_id` = @paintId, `weapon_wear` = @wear, `weapon_seed` = @seed " +
"WHERE `steamid` = @steamid AND `weapon_defindex` = @weaponDefIndex AND `weapon_team` = @weaponTeam";
parameters = new { steamid = player.SteamId, weaponDefIndex, weaponTeam = (int)teamId, paintId, wear, seed };
} }
else else
{ {
query = "INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, `weapon_paint_id`, `weapon_wear`, `weapon_seed`) " + // Insert new record
"VALUES (@steamid, @weaponDefIndex, @paintId, @wear, @seed)"; query = "INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, `weapon_team`, `weapon_paint_id`, `weapon_wear`, `weapon_seed`) " +
parameters = new { steamid = player.SteamId, weaponDefIndex = weaponDefIndex, paintId, wear, seed }; "VALUES (@steamid, @weaponDefIndex, @weaponTeam, @paintId, @wear, @seed)";
parameters = new { steamid = player.SteamId, weaponDefIndex, weaponTeam = (int)teamId, paintId, wear, seed };
} }
await connection.ExecuteAsync(query, parameters); await connection.ExecuteAsync(query, parameters);
} }
} }
}
catch (Exception e) catch (Exception e)
{ {
Utility.Log($"Error syncing weapon paints to database: {e.Message}"); Utility.Log($"Error syncing weapon paints to database: {e.Message}");
} }
} }
internal async Task SyncMusicToDatabase(PlayerInfo player, ushort music) internal async Task SyncMusicToDatabase(PlayerInfo player, ushort music, CsTeam[] teams)
{ {
if (!_config.Additional.MusicEnabled || string.IsNullOrEmpty(player.SteamId)) return; if (!_config.Additional.MusicEnabled || string.IsNullOrEmpty(player.SteamId)) return;
const string query = "INSERT INTO `wp_player_music` (`steamid`, `weapon_team`, `music_id`) VALUES(@steamid, @team, @newMusic) ON DUPLICATE KEY UPDATE `music_id` = @newMusic";
try try
{ {
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
const string query = "INSERT INTO `wp_player_music` (`steamid`, `music_id`) VALUES(@steamid, @newMusic) ON DUPLICATE KEY UPDATE `music_id` = @newMusic";
await connection.ExecuteAsync(query, new { steamid = player.SteamId, newMusic = music }); // Loop through each team and insert/update accordingly
foreach (var team in teams)
{
await connection.ExecuteAsync(query, new { steamid = player.SteamId, team, newMusic = music });
}
} }
catch (Exception e) catch (Exception e)
{ {
@@ -377,15 +541,21 @@ namespace WeaponPaints
} }
} }
internal async Task SyncPinToDatabase(PlayerInfo player, ushort pin) internal async Task SyncPinToDatabase(PlayerInfo player, ushort pin, CsTeam[] teams)
{ {
if (!_config.Additional.PinsEnabled || string.IsNullOrEmpty(player.SteamId)) return; if (!_config.Additional.PinsEnabled || string.IsNullOrEmpty(player.SteamId)) return;
const string query = "INSERT INTO `wp_player_pins` (`steamid`, `weapon_team`, `id`) VALUES(@steamid, @team, @newPin) ON DUPLICATE KEY UPDATE `id` = @newPin";
try try
{ {
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
const string query = "INSERT INTO `wp_player_pins` (`steamid`, `id`) VALUES(@steamid, @newPin) ON DUPLICATE KEY UPDATE `id` = @newPin";
await connection.ExecuteAsync(query, new { steamid = player.SteamId, newPin = pin }); // Loop through each team and insert/update accordingly
foreach (var team in teams)
{
await connection.ExecuteAsync(query, new { steamid = player.SteamId, team, newPin = pin });
}
} }
catch (Exception e) catch (Exception e)
{ {
@@ -393,15 +563,9 @@ namespace WeaponPaints
} }
} }
internal async Task SyncStatTrakToDatabase(PlayerInfo player, ConcurrentDictionary<int,WeaponInfo> weaponInfos) internal async Task SyncStatTrakToDatabase(PlayerInfo player)
{ {
if (WeaponPaints.WeaponSync == null || weaponInfos.IsEmpty) return; if (WeaponPaints.WeaponSync == null || WeaponPaints.GPlayerWeaponsInfo.IsEmpty) return;
var statTrakWeapons = weaponInfos
.Where(w => w.Value is { StatTrak: true, StatTrakCount: > 0 })
.ToDictionary(w => w.Key, w => w.Value.StatTrakCount);
if (statTrakWeapons.Count == 0) return;
if (string.IsNullOrEmpty(player.SteamId)) if (string.IsNullOrEmpty(player.SteamId))
return; return;
@@ -411,22 +575,46 @@ namespace WeaponPaints
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
await using var transaction = await connection.BeginTransactionAsync(); await using var transaction = await connection.BeginTransactionAsync();
// Check if player's slot exists in GPlayerWeaponsInfo
if (!WeaponPaints.GPlayerWeaponsInfo.TryGetValue(player.Slot, out var teamWeaponsInfo))
return;
// Iterate through each team in the player's weapon info
foreach (var teamInfo in teamWeaponsInfo)
{
// Retrieve weaponInfos for the current team
var weaponInfos = teamInfo.Value;
// Get StatTrak weapons for the current team
var statTrakWeapons = weaponInfos
.Where(w => w.Value is { StatTrak: true, StatTrakCount: > 0 })
.ToDictionary(w => w.Key, w => w.Value.StatTrakCount);
// Check if there are StatTrak weapons to sync
if (statTrakWeapons.Count == 0) continue;
// Get the current team ID
int weaponTeam = (int)teamInfo.Key;
// Sync StatTrak values for the current team
foreach (var (defindex, statTrakCount) in statTrakWeapons) foreach (var (defindex, statTrakCount) in statTrakWeapons)
{ {
const string query = @" const string query = @"
INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, `weapon_stattrak_count`) INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, `weapon_stattrak_count`, `weapon_team`)
VALUES (@steamid, @weaponDefIndex, @StatTrakCount) VALUES (@steamid, @weaponDefIndex, @StatTrakCount, @weaponTeam)
ON DUPLICATE KEY UPDATE `weapon_stattrak_count` = @StatTrakCount"; ON DUPLICATE KEY UPDATE `weapon_stattrak_count` = @StatTrakCount";
var parameters = new var parameters = new
{ {
steamid = player.SteamId, steamid = player.SteamId,
weaponDefIndex = defindex, weaponDefIndex = defindex,
StatTrakCount = statTrakCount StatTrakCount = statTrakCount,
weaponTeam
}; };
await connection.ExecuteAsync(query, parameters, transaction); await connection.ExecuteAsync(query, parameters, transaction);
} }
}
await transaction.CommitAsync(); await transaction.CommitAsync();
} }
@@ -435,5 +623,4 @@ namespace WeaponPaints
Utility.Log($"Error syncing stattrak to database: {e.Message}"); Utility.Log($"Error syncing stattrak to database: {e.Message}");
} }
} }
}
} }