Compare commits

...

31 Commits

Author SHA1 Message Date
Dawid Bepierszcz
1109c0cf56 Merge pull request #148 from daffyyyy/main
1.6c
2024-02-11 04:00:07 +01:00
Dawid Bepierszcz
63869f4c94 Merge branch 'Nereziel:main' into main 2024-02-11 03:58:49 +01:00
Dawid Bepierszcz
fa284678e8 1.6c
- Fix for invalid players
2024-02-11 03:58:32 +01:00
Dawid Bepierszcz
558f3178f2 Update WeaponAction.cs 2024-02-10 15:34:34 +01:00
Dawid Bepierszcz
c5f9cc6429 Merge pull request #145 from daffyyyy/main
1.6b
2024-02-10 13:00:48 +01:00
Dawid Bepierszcz
4087d3d016 Merge branch 'Nereziel:main' into main 2024-02-10 13:00:04 +01:00
Dawid Bepierszcz
e7919bb468 Merge branch 'main' of https://github.com/daffyyyy/cs2-WeaponPaints 2024-02-10 12:59:45 +01:00
Dawid Bepierszcz
33bd83d0a1 1.6b
- Closing menu
2024-02-10 12:59:41 +01:00
Dawid Bepierszcz
73d989c0ce Merge pull request #144 from daffyyyy/main
1.6b
2024-02-10 12:25:38 +01:00
Dawid Bepierszcz
f1cecfc73e Merge branch 'Nereziel:main' into main 2024-02-10 12:24:35 +01:00
Dawid Bepierszcz
aae6f7e260 1.6b
- Minor changes
- Fixed tables creation
2024-02-10 12:23:56 +01:00
Dawid Bepierszcz
171d520cc0 Merge pull request #136 from daffyyyy/main
1.6a
2024-02-08 19:37:40 +01:00
Dawid Bepierszcz
deac9bab97 Merge branch 'Nereziel:main' into main 2024-02-08 19:35:57 +01:00
Dawid Bepierszcz
8a76530302 Merge branch 'main' of https://github.com/daffyyyy/cs2-WeaponPaints 2024-02-08 19:35:40 +01:00
Dawid Bepierszcz
d1cbecaecb 1.6a
- Major changes
- Better sql stuff
- Temp fix for crashes on skins reload
2024-02-08 19:35:29 +01:00
Dawid Bepierszcz
ebc932e47c Merge pull request #135 from daffyyyy/main
Updated min. css version
2024-02-08 10:53:34 +01:00
Dawid Bepierszcz
e258ed8c92 Merge branch 'Nereziel:main' into main 2024-02-08 10:53:08 +01:00
Dawid Bepierszcz
e44af369bb Merge branch 'main' of https://github.com/daffyyyy/cs2-WeaponPaints 2024-02-08 10:52:32 +01:00
Dawid Bepierszcz
47055ad6f7 Updated min. css version 2024-02-08 10:52:22 +01:00
Dawid Bepierszcz
d9166253b3 Merge pull request #134 from daffyyyy/main
1.5a
2024-02-08 10:51:44 +01:00
Dawid Bepierszcz
4e90506645 Merge branch 'Nereziel:main' into main 2024-02-08 10:50:08 +01:00
Dawid Bepierszcz
bd93936fab 1.5a
- Minor changes
- New skins
2024-02-08 10:49:53 +01:00
Dawid Bepierszcz
63403dfc8e new skins
New skins
2024-02-07 22:08:26 +01:00
Nereziel
b24a2bd04e Update README.md 2024-02-03 20:27:29 +01:00
Dawid Bepierszcz
dbc652a68c Merge pull request #129 from daffyyyy/main
1.4c
2024-02-03 17:26:12 +01:00
Dawid Bepierszcz
a59ce8f1a5 Merge branch 'main' of https://github.com/daffyyyy/cs2-WeaponPaints 2024-02-03 17:24:46 +01:00
Dawid Bepierszcz
baaa47d837 1.4c 2024-02-03 17:24:26 +01:00
Dawid Bepierszcz
7dcfea3e17 Merge branch 'Nereziel:main' into main 2024-02-03 17:23:44 +01:00
Dawid Bepierszcz
4eab8f0a87 Merge branch 'main' of https://github.com/daffyyyy/cs2-WeaponPaints 2024-02-03 17:23:16 +01:00
Dawid Bepierszcz
236c79c4b9 1.4c
- Minor changes
- Better loading skins
2024-02-03 17:23:12 +01:00
Nereziel
83084452df Update README.md 2024-02-03 16:51:13 +01:00
3323 changed files with 519 additions and 381 deletions

2
.gitignore vendored
View File

@@ -1,4 +1,4 @@
.vs/
bin/
obj/
website/getskins.php

View File

@@ -10,43 +10,49 @@ namespace WeaponPaints
{
if (!Config.Additional.CommandWpEnabled || !Config.Additional.SkinEnabled || !g_bCommandsAllowed) return;
if (!Utility.IsPlayerValid(player)) return;
if (player == null || player.Index <= 0) return;
if (player == null || !player.IsValid || player.UserId == null || player.IsBot) return;
int playerIndex = (int)player!.Index;
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
SteamId = player?.SteamID.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (player == null || player.UserId == null) return;
if (player == null || !player.IsValid || player.UserId == null || player.IsBot) return;
if (!commandsCooldown.TryGetValue((int)player.UserId, out DateTime cooldownEndTime) ||
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
try
{
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
if (weaponSync != null)
Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo));
if (Config.Additional.KnifeEnabled)
if (!commandsCooldown.TryGetValue((int)player.UserId, out DateTime cooldownEndTime) ||
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
{
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
if (weaponSync != null)
Task.Run(async () => await weaponSync.GetKnifeFromDatabase(playerInfo));
Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo));
if (Config.Additional.KnifeEnabled)
{
if (weaponSync != null)
Task.Run(async () => await weaponSync.GetKnifeFromDatabase(playerInfo));
RefreshWeapons(player);
RefreshWeapons(player);
}
if (!string.IsNullOrEmpty(Localizer["wp_command_refresh_done"]))
{
player!.Print(Localizer["wp_command_refresh_done"]);
}
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_refresh_done"]))
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_refresh_done"]);
player!.Print(Localizer["wp_command_cooldown"]);
}
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_cooldown"]);
}
catch (Exception) { }
}
private void OnCommandWS(CCSPlayerController? player, CommandInfo command)
@@ -101,44 +107,40 @@ namespace WeaponPaints
.ToDictionary(pair => pair.Key, pair => pair.Value);
var giveItemMenu = new ChatMenu(Localizer["wp_knife_menu_title"]);
var handleGive = (CCSPlayerController? player, ChatMenuOption option) =>
giveItemMenu.PostSelectAction = PostSelectAction.Close;
var handleGive = (CCSPlayerController player, ChatMenuOption option) =>
{
if (Utility.IsPlayerValid(player))
if (!Utility.IsPlayerValid(player)) return;
var knifeName = option.Text;
var knifeKey = knivesOnly.FirstOrDefault(x => x.Value == knifeName).Key;
if (!string.IsNullOrEmpty(knifeKey))
{
if (player == null) return;
var knifeName = option.Text;
var knifeKey = knivesOnly.FirstOrDefault(x => x.Value == knifeName).Key;
if (!string.IsNullOrEmpty(knifeKey))
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_select"]))
{
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_select"]))
{
player!.Print(Localizer["wp_knife_menu_select", knifeName]);
}
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_kill"]) && Config.Additional.CommandKillEnabled)
{
player!.Print(Localizer["wp_knife_menu_kill"]);
}
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
g_playersKnife[(int)player!.Index] = knifeKey;
if (player!.PawnIsAlive && g_bCommandsAllowed)
{
RefreshWeapons(player);
}
if (weaponSync != null)
Task.Run(async () => await weaponSync.SyncKnifeToDatabase(playerInfo, knifeKey));
player!.Print(Localizer["wp_knife_menu_select", knifeName]);
}
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_kill"]) && Config.Additional.CommandKillEnabled)
{
player!.Print(Localizer["wp_knife_menu_kill"]);
}
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player.SteamID.ToString(),
Name = player.PlayerName,
IpAddress = player.IpAddress?.Split(":")[0]
};
g_playersKnife[(int)player!.Index] = knifeKey;
if (g_bCommandsAllowed && (LifeState_t)player.LifeState == LifeState_t.LIFE_ALIVE)
RefreshKnife(player);
_ = weaponSync?.SyncKnifeToDatabase(playerInfo, knifeKey) ?? Task.CompletedTask;
}
};
foreach (var knifePair in knivesOnly)
@@ -155,7 +157,7 @@ namespace WeaponPaints
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
{
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
ChatMenus.OpenMenu(player, giveItemMenu);
MenuManager.OpenChatMenu(player, giveItemMenu);
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
@@ -187,17 +189,16 @@ namespace WeaponPaints
)?.ToList();
var skinSubMenu = new ChatMenu(Localizer["wp_skin_menu_skin_title", selectedWeapon]);
skinSubMenu.PostSelectAction = PostSelectAction.Close;
// Function to handle skin selection for the chosen weapon
var handleSkinSelection = (CCSPlayerController? p, ChatMenuOption opt) =>
var handleSkinSelection = (CCSPlayerController p, ChatMenuOption opt) =>
{
if (p == null || !p.IsValid || p.Index <= 0) return;
if (!Utility.IsPlayerValid(p)) return;
playerIndex = (int)p.Index;
if (p.AuthorizedSteamID == null) return;
string steamId = p.AuthorizedSteamID.SteamId64.ToString();
string steamId = p.SteamID.ToString();
var firstSkin = skinsList?.FirstOrDefault(skin =>
{
if (skin != null && skin.TryGetValue("weapon_name", out var weaponName))
@@ -228,13 +229,16 @@ namespace WeaponPaints
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
UserId = p.UserId,
Index = (int)p.Index,
SteamId = p.SteamID.ToString(),
Name = p.PlayerName,
IpAddress = p.IpAddress?.Split(":")[0]
};
if (g_bCommandsAllowed && (LifeState_t)p.LifeState == LifeState_t.LIFE_ALIVE)
RefreshWeapons(p);
if (!Config.GlobalShare)
{
if (weaponSync != null)
@@ -262,7 +266,7 @@ namespace WeaponPaints
}
// Open the submenu for skin selection of the chosen weapon
ChatMenus.OpenMenu(player, skinSubMenu);
MenuManager.OpenChatMenu(player, skinSubMenu);
}
};
@@ -283,7 +287,8 @@ namespace WeaponPaints
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
{
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
ChatMenus.OpenMenu(player, weaponSelectionMenu);
MenuManager.OpenChatMenu(player, weaponSelectionMenu);
weaponSelectionMenu.PostSelectAction = PostSelectAction.Close;
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))

View File

@@ -40,6 +40,7 @@ namespace WeaponPaints
[JsonPropertyName("GiveRandomSkin")]
public bool GiveRandomSkin { get; set; } = false;
[JsonPropertyName("GiveKnifeAfterRemove")]
public bool GiveKnifeAfterRemove { get; set; } = false;
}
@@ -78,5 +79,4 @@ namespace WeaponPaints
[JsonPropertyName("Additional")]
public Additional Additional { get; set; } = new Additional();
}
}
}

28
Database.cs Normal file
View File

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

147
Events.cs
View File

@@ -9,46 +9,47 @@ namespace WeaponPaints
{
CCSPlayerController? player = Utilities.GetPlayerFromSlot(playerSlot);
if (player is null || !player.IsValid || player.IsBot || player.IsHLTV || player.SteamID.ToString().Length != 17 ||
weaponSync == null || player.Connected == PlayerConnectedState.PlayerDisconnecting) return;
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player.SteamID.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
Name = player.PlayerName,
IpAddress = player.IpAddress?.Split(":")[0]
};
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || weaponSync == null) return;
Task.Run(async () =>
if (!gPlayerWeaponsInfo.ContainsKey((int)player.Index))
{
if (Config.Additional.SkinEnabled)
await weaponSync.GetKnifeFromDatabase(playerInfo);
});
_ = Task.Run(async () =>
{
if (Config.Additional.SkinEnabled)
await weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
//if (Config.Additional.KnifeEnabled && weaponSync != null)
//_ = weaponSync.GetKnifeFromDatabase(playerIndex);
if (Config.Additional.KnifeEnabled)
await weaponSync.GetKnifeFromDatabase(playerInfo);
});
}
}
private void OnClientDisconnect(int playerSlot)
{
CCSPlayerController player = Utilities.GetPlayerFromSlot(playerSlot);
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || player.UserId == null) return;
if (player is null || !player.IsValid || !player.UserId.HasValue || player.IsBot || player.IsHLTV || player.SteamID.ToString().Length != 17) return;
if (Config.Additional.KnifeEnabled)
g_playersKnife.TryRemove((int)player.Index, out _);
if (Config.Additional.SkinEnabled)
if (Config.Additional.SkinEnabled && gPlayerWeaponsInfo.TryGetValue((int)player.Index, out var innerDictionary))
{
if (gPlayerWeaponsInfo.TryRemove((int)player.Index, out var innerDictionary))
{
innerDictionary.Clear();
}
}
if (commandsCooldown.ContainsKey((int)player.UserId))
{
commandsCooldown.Remove((int)player.UserId);
innerDictionary.Clear();
gPlayerWeaponsInfo.TryRemove((int)player.Index, out _);
}
commandsCooldown.Remove((int)player.UserId);
}
private void OnEntityCreated(CEntityInstance entity)
@@ -73,7 +74,8 @@ namespace WeaponPaints
if (weapon.OwnerEntity.Value == null) return;
if (weapon.OwnerEntity.Index <= 0) return;
int weaponOwner = (int)weapon.OwnerEntity.Index;
var pawn = new CBasePlayerPawn(NativeAPI.GetEntityFromIndex(weaponOwner));
CBasePlayerPawn? pawn = Utilities.GetEntityFromIndex<CCSPlayerPawn>((int)weaponOwner);
//var pawn = new CBasePlayerPawn(NativeAPI.GetEntityFromIndex(weaponOwner));
if (!pawn.IsValid) return;
var playerIndex = (int)pawn.Controller.Index;
@@ -109,7 +111,6 @@ namespace WeaponPaints
if (player == null || !player.IsValid || !g_knifePickupCount.ContainsKey((int)player.Index) || player.IsBot || !g_playersKnife.ContainsKey((int)player.Index))
return HookResult.Continue;
if (g_knifePickupCount[(int)player.Index] >= 2) return HookResult.Continue;
if (g_playersKnife.ContainsKey((int)player.Index)
@@ -132,26 +133,34 @@ namespace WeaponPaints
{
CCSPlayerController? player = Utilities.GetEntityFromIndex<CCSPlayerPawn>((int)activator.Index).OriginalController.Value;
if (player == null || player.IsBot || player.IsHLTV)
return HookResult.Continue;
if (player == null || !player.IsValid || player.SteamID.ToString() == "" ||
!g_knifePickupCount.ContainsKey((int)player.Index) || !g_playersKnife.ContainsKey((int)player.Index))
if (player == null || player.IsBot || player.IsHLTV ||
player.SteamID.ToString().Length != 17 || !g_knifePickupCount.TryGetValue((int)player.Index, out var pickupCount) ||
!g_playersKnife.ContainsKey((int)player.Index))
{
return HookResult.Continue;
}
CBasePlayerWeapon weapon = new(caller.Handle);
if (weapon.AttributeManager.Item.ItemDefinitionIndex != 42 && weapon.AttributeManager.Item.ItemDefinitionIndex != 59)
{
return HookResult.Continue;
}
if (g_knifePickupCount[(int)player.Index] >= 2) return HookResult.Continue;
if (pickupCount >= 2)
{
return HookResult.Continue;
}
if (g_playersKnife[(int)player.Index] != "weapon_knife")
{
g_knifePickupCount[(int)player.Index]++;
pickupCount++;
g_knifePickupCount[(int)player.Index] = pickupCount;
player.RemoveItemByDesignerName(weapon.DesignerName);
if (Config.Additional.GiveKnifeAfterRemove)
{
AddTimer(0.2f, () => GiveKnifeToPlayer(player));
}
}
return HookResult.Continue;
@@ -159,22 +168,24 @@ namespace WeaponPaints
private void OnMapStart(string mapName)
{
if (!Config.Additional.KnifeEnabled) return;
if (!Config.Additional.KnifeEnabled && !Config.Additional.SkinEnabled) return;
if (_database != null)
weaponSync = new WeaponSynchronization(_database, Config, GlobalShareApi, GlobalShareServerId);
// TODO
// needed for now
AddTimer(2.0f, () =>
{
NativeAPI.IssueServerCommand("mp_t_default_melee \"\"");
NativeAPI.IssueServerCommand("mp_ct_default_melee \"\"");
NativeAPI.IssueServerCommand("mp_equipment_reset_rounds 0");
if (Config.GlobalShare)
GlobalShareConnect();
weaponSync = new WeaponSynchronization(DatabaseConnectionString, Config, GlobalShareApi, GlobalShareServerId);
});
/*
g_hTimerCheckSkinsData = AddTimer(10.0f, () =>
{
List<CCSPlayerController> players = Utilities.GetPlayers();
@@ -199,6 +210,7 @@ namespace WeaponPaints
_ = weaponSync.GetKnifeFromDatabase(playerInfo);
}
}, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE | CounterStrikeSharp.API.Modules.Timers.TimerFlags.REPEAT);
*/
}
private HookResult OnPlayerConnectFull(EventPlayerConnectFull @event, GameEventInfo info)
@@ -234,24 +246,13 @@ namespace WeaponPaints
private HookResult OnPlayerSpawn(EventPlayerSpawn @event, GameEventInfo info)
{
CCSPlayerController? player = @event.Userid;
if (player == null || !player.IsValid)
if (player == null || !player.IsValid || !Config.Additional.KnifeEnabled || PlayerHasKnife(player))
{
return HookResult.Continue;
}
if (Config.Additional.KnifeEnabled && !PlayerHasKnife(player))
{
g_knifePickupCount[(int)player.Index] = 0;
GiveKnifeToPlayer(player);
//AddTimer(0.1f, () => GiveKnifeToPlayer(player));
}
/*
if (Config.Additional.SkinVisibilityFix)
{
AddTimer(0.3f, () => RefreshSkins(player));
}
*/
g_knifePickupCount[(int)player.Index] = 0;
GiveKnifeToPlayer(player);
return HookResult.Continue;
}
@@ -279,36 +280,51 @@ namespace WeaponPaints
{
try
{
if (player == null || !player.IsValid || !player.PawnIsAlive || player.IsBot || player.IsHLTV) continue;
if (player is null || !player.IsValid || !player.PawnIsAlive || player.IsBot || player.IsHLTV || player.Connected != PlayerConnectedState.PlayerConnected)
continue;
var viewModels = GetPlayerViewModels(player);
if (viewModels == null) continue;
if (viewModels == null || viewModels.Length == 0)
continue;
var viewModel = viewModels[0];
if (viewModel == null || viewModel.Value == null || viewModel.Value.Weapon == null || viewModel.Value.Weapon.Value == null) continue;
CBasePlayerWeapon weapon = viewModel.Value.Weapon.Value;
if (viewModel == null || viewModel.Value == null || viewModel.Value.Weapon == null || viewModel.Value.Weapon.Value == null)
continue;
if (weapon == null || !weapon.IsValid) continue;
var weapon = viewModel.Value.Weapon.Value;
if (weapon == null || !weapon.IsValid)
continue;
var isKnife = viewModel.Value.VMName.Contains("knife");
if (viewModel.Value.VMName.Contains("knife"))
continue;
if (!isKnife)
var sceneNode = viewModel.Value.CBodyComponent?.SceneNode;
if (sceneNode == null)
continue;
var skeleton = GetSkeletonInstance(sceneNode);
if (skeleton == null)
continue;
int[] knifePaintKits = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 };
if (knifePaintKits.Contains(weapon.FallbackPaintKit))
{
if (
viewModel.Value.CBodyComponent != null
&& viewModel.Value.CBodyComponent.SceneNode != null
)
skeleton.ModelState.MeshGroupMask = 1;
}
else
{
if (skeleton.ModelState.MeshGroupMask != 2)
{
var skeleton = GetSkeletonInstance(viewModel.Value.CBodyComponent.SceneNode);
skeleton.ModelState.MeshGroupMask = 2;
}
Utilities.SetStateChanged(viewModel.Value, "CBaseEntity", "m_CBodyComponent");
}
Utilities.SetStateChanged(viewModel.Value, "CBaseEntity", "m_CBodyComponent");
}
catch (Exception)
{ }
{
// Handle exceptions silently
}
}
}
@@ -320,16 +336,15 @@ namespace WeaponPaints
RegisterListener<Listeners.OnMapStart>(OnMapStart);
RegisterListener<Listeners.OnTick>(OnTick);
RegisterEventHandler<EventPlayerConnectFull>(OnPlayerConnectFull);
//RegisterEventHandler<EventPlayerConnectFull>(OnPlayerConnectFull);
RegisterEventHandler<EventPlayerSpawn>(OnPlayerSpawn);
RegisterEventHandler<EventRoundStart>(OnRoundStart, HookMode.Pre);
RegisterEventHandler<EventRoundEnd>(OnRoundEnd);
RegisterEventHandler<EventItemPurchase>(OnEventItemPurchasePost);
//RegisterEventHandler<EventItemPurchase>(OnEventItemPurchasePost);
//RegisterEventHandler<EventItemPickup>(OnItemPickup);
HookEntityOutput("weapon_knife", "OnPlayerPickup", OnPickup, HookMode.Pre);
}
/* WORKAROUND FOR CLIENTS WITHOUT STEAMID ON AUTHORIZATION */
/*private HookResult OnPlayerConnectFull(EventPlayerConnectFull @event, GameEventInfo info)
{

View File

@@ -8,4 +8,4 @@
public string? Name { get; set; }
public string? IpAddress { get; set; }
}
}
}

View File

@@ -23,7 +23,8 @@ Unfinished, unoptimized and not fully functional ugly demo weapon paints plugin
## CS2 Server
- Have working CounterStrikeSharp (**with RUNTIME!**)
- Download from Release and copy plugin to plugins
- Setup `addons/counterstrikesharp/configs/`**`plugins/WeaponPaints/WeaponPaints.json`** set **`GlobalShare`** to **`true`** for global, or include database credentials
- Run server with plugin, **it will generate config if installed correctly!**
- Edit `addons/counterstrikesharp/configs/`**`plugins/WeaponPaints/WeaponPaints.json`** set **`GlobalShare`** to **`true`** for global, or include database credentials
- In `addons/counterstrikesharp/configs/`**`core.json`** set **FollowCS2ServerGuidelines** to **`false`**
## Plugin Configuration
@@ -88,6 +89,7 @@ Disregard if the config is **`GlobalShare = true`**
## Known issues
- Issue on Windows servers, no knives are given.
- You can't change knife if it's equpied in cs2 inventory
- Can cause incompatibility with plugins/maps which manipulates weapons and knives
## Troubleshooting
@@ -100,6 +102,9 @@ Plugin is not loaded or configured with mysql credentials. Tables are auto-creat
**Knives are disappearing:**
Set in config GiveKnifeAfterRemove to true
**Knives are not changing for players:**
You can't change knife if you have your own equipped
</details>
### Use this plugin at your own risk! Using this may lead to GSLT ban or something else Valve come with. [Valve Server guidelines](https://blog.counter-strike.net/index.php/server_guidelines/)

View File

@@ -1,11 +1,11 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Utils;
using Dapper;
using MySqlConnector;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Reflection;
using Microsoft.Extensions.Logging;
using MySqlConnector;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection;
namespace WeaponPaints
{
@@ -23,27 +23,44 @@ namespace WeaponPaints
Password = Config.DatabasePassword,
Database = Config.DatabaseName,
Port = (uint)Config.DatabasePort,
Pooling = true
};
return builder.ConnectionString;
}
internal static async void CheckDatabaseTables()
internal static async Task CheckDatabaseTables()
{
if (WeaponPaints._database is null) return;
try
{
using var connection = new MySqlConnection(BuildDatabaseConnectionString());
await connection.OpenAsync();
await using var connection = await WeaponPaints._database.GetConnectionAsync();
using var transaction = await connection.BeginTransactionAsync();
await using var transaction = await connection.BeginTransactionAsync();
try
{
string createTable1 = "CREATE TABLE IF NOT EXISTS `wp_player_skins` (`steamid` varchar(64) NOT NULL, `weapon_defindex` int(6) NOT NULL, `weapon_paint_id` int(6) NOT NULL, `weapon_wear` float NOT NULL DEFAULT 0.000001, `weapon_seed` int(16) NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci";
string createTable2 = "CREATE TABLE IF NOT EXISTS `wp_player_knife` (`steamid` varchar(64) NOT NULL, `knife` varchar(64) NOT NULL, UNIQUE (`steamid`)) ENGINE = InnoDB";
string[] createTableQueries = new[]
{
@"CREATE TABLE IF NOT EXISTS `wp_player_skins` (
`steamid` varchar(64) NOT NULL,
`weapon_defindex` int(6) NOT NULL,
`weapon_paint_id` int(6) NOT NULL,
`weapon_wear` float NOT NULL DEFAULT 0.000001,
`weapon_seed` int(16) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci",
@"CREATE TABLE IF NOT EXISTS `wp_player_knife` (
`steamid` varchar(64) NOT NULL,
`knife` varchar(64) NOT NULL,
UNIQUE (`steamid`)
) ENGINE = InnoDB"
};
await connection.ExecuteAsync(createTable1, transaction: transaction);
await connection.ExecuteAsync(createTable2, transaction: transaction);
foreach (var query in createTableQueries)
{
await connection.ExecuteAsync(query, transaction: transaction);
}
await transaction.CommitAsync();
}
@@ -55,25 +72,29 @@ namespace WeaponPaints
}
catch (Exception ex)
{
throw new Exception("[WeaponPaints] Unknown mysql exception! " + ex.Message);
throw new Exception("[WeaponPaints] Unknown MySQL exception! " + ex.Message);
}
}
internal static bool IsPlayerValid(CCSPlayerController? player)
{
return (player != null && player.IsValid && !player.IsBot && !player.IsHLTV && player.AuthorizedSteamID != null);
if (player is null) return false;
return (player is not null && player.IsValid && !player.IsBot && !player.IsHLTV
&& WeaponPaints.weaponSync != null && player.Connected == PlayerConnectedState.PlayerConnected);
}
internal static void LoadSkinsFromFile(string filePath)
{
if (File.Exists(filePath))
try
{
string json = File.ReadAllText(filePath);
var deserializedSkins = JsonConvert.DeserializeObject<List<JObject>>(json);
WeaponPaints.skinsList = deserializedSkins ?? new List<JObject>();
}
else
catch (FileNotFoundException)
{
throw new FileNotFoundException("File not found.", filePath);
throw;
}
}
@@ -114,11 +135,11 @@ namespace WeaponPaints
{
try
{
HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION");
HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
string remoteVersion = await response.Content.ReadAsStringAsync();
string remoteVersion = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
remoteVersion = remoteVersion.Trim();
int comparisonResult = string.Compare(version, remoteVersion);
@@ -141,9 +162,13 @@ namespace WeaponPaints
logger.LogWarning("Failed to check version");
}
}
catch (HttpRequestException ex)
{
logger.LogError(ex, "Failed to connect to the version server.");
}
catch (Exception ex)
{
Console.WriteLine(ex);
logger.LogError(ex, "An error occurred while checking version.");
}
}
}
@@ -163,6 +188,7 @@ namespace WeaponPaints
Console.WriteLine(" ");
}
/*(
internal static void TestDatabaseConnection()
{
try
@@ -181,5 +207,6 @@ namespace WeaponPaints
}
CheckDatabaseTables();
}
*/
}
}

View File

@@ -1 +1 @@
1.4b
1.6a

View File

@@ -11,7 +11,7 @@ namespace WeaponPaints
{
internal static void ChangeWeaponAttributes(CBasePlayerWeapon? weapon, CCSPlayerController? player, bool isKnife = false)
{
if (player == null || weapon == null || !weapon.IsValid || !Utility.IsPlayerValid(player)) return;
if (player is null || weapon is null || !weapon.IsValid || !Utility.IsPlayerValid(player)) return;
int playerIndex = (int)player.Index;
@@ -21,7 +21,6 @@ namespace WeaponPaints
int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex;
if (isKnife)
{
weapon.AttributeManager.Item.EntityQuality = 3;
@@ -40,9 +39,19 @@ namespace WeaponPaints
if (!isKnife && weapon.CBodyComponent != null && weapon.CBodyComponent.SceneNode != null)
{
var skeleton = GetSkeletonInstance(weapon.CBodyComponent.SceneNode);
if (skeleton.ModelState.MeshGroupMask != 2)
int[] array = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 };
int fallbackPaintKit = weapon.FallbackPaintKit;
if (array.Contains(fallbackPaintKit))
{
skeleton.ModelState.MeshGroupMask = 2;
skeleton.ModelState.MeshGroupMask = 1;
}
else
{
if (skeleton.ModelState.MeshGroupMask != 2)
{
skeleton.ModelState.MeshGroupMask = 2;
}
}
}
return;
@@ -61,9 +70,18 @@ namespace WeaponPaints
if (!isKnife && weapon.CBodyComponent != null && weapon.CBodyComponent.SceneNode != null)
{
var skeleton = GetSkeletonInstance(weapon.CBodyComponent.SceneNode);
if (skeleton.ModelState.MeshGroupMask != 2)
int[] array = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 };
int fallbackPaintKit = weapon.FallbackPaintKit;
if (array.Contains(fallbackPaintKit))
{
skeleton.ModelState.MeshGroupMask = 2;
skeleton.ModelState.MeshGroupMask = 1;
}
else
{
if (skeleton.ModelState.MeshGroupMask != 2)
{
skeleton.ModelState.MeshGroupMask = 2;
}
}
}
}
@@ -72,25 +90,31 @@ namespace WeaponPaints
{
if (!_config.Additional.KnifeEnabled || player == null || !player.IsValid) return;
string knifeToGive;
if (g_playersKnife.TryGetValue((int)player.Index, out var knife))
{
player.GiveNamedItem(knife);
knifeToGive = knife;
}
else if (_config.Additional.GiveRandomKnife)
{
var knifeTypes = weaponList.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")).ToDictionary(pair => pair.Key, pair => pair.Value);
var knifeTypes = weaponList.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")).ToList();
if (knifeTypes.Count == 0)
{
Utility.Log("No valid knife types found.");
return;
}
Random random = new();
int index = random.Next(knifeTypes.Count);
var randomKnifeClass = knifeTypes.Keys.ElementAt(index);
player.GiveNamedItem(randomKnifeClass);
knifeToGive = knifeTypes[index].Key;
}
else
{
var defaultKnife = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife";
player.GiveNamedItem(defaultKnife);
knifeToGive = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife";
}
player.GiveNamedItem(knifeToGive);
}
internal static bool PlayerHasKnife(CCSPlayerController? player)
@@ -120,8 +144,10 @@ namespace WeaponPaints
return false;
}
/*
internal void RefreshPlayerKnife(CCSPlayerController? player)
{
return;
if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return;
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) return;
@@ -177,7 +203,9 @@ namespace WeaponPaints
}
}
}
*/
/*
internal void RefreshSkins(CCSPlayerController? player)
{
return;
@@ -187,138 +215,180 @@ namespace WeaponPaints
AddTimer(0.25f, () => NativeAPI.IssueClientCommand((int)player.Index - 1, "slot2"));
AddTimer(0.38f, () => NativeAPI.IssueClientCommand((int)player.Index - 1, "slot1"));
}
*/
internal void RefreshWeapons(CCSPlayerController? player)
{
if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return;
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) return;
if (player == null || !player.IsValid || player.PlayerPawn?.Value == null || (LifeState_t)player.LifeState != LifeState_t.LIFE_ALIVE)
return;
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null)
return;
var weapons = player.PlayerPawn.Value.WeaponServices.MyWeapons;
if (weapons == null || weapons.Count == 0)
return;
// Dictionary to store weapons and their ammo
if (weapons != null && weapons.Count > 0)
{
//Dictionary<string, (int, int)> weaponsWithAmmo = new Dictionary<string, (int, int)>();
Dictionary<string, List<(int, int)>> weaponsWithAmmo = new Dictionary<string, List<(int, int)>>();
bool bomb = false;
bool defuser = player.PawnHasDefuser;
bool healthshot = false;
// Iterate through each weapon
foreach (var weapon in weapons)
{
if (weapon == null || !weapon.IsValid || weapon.Value == null ||
!weapon.Value.IsValid || !weapon.Value.DesignerName.Contains("weapon_"))
continue;
try
{
string? weaponByDefindex = null;
CCSWeaponBaseVData? weaponData = weapon.Value.As<CCSWeaponBase>().VData;
if (weaponData != null)
{
if (weaponData.GearSlot == gear_slot_t.GEAR_SLOT_C4)
bomb = true;
if (weaponData.Name.Equals("weapon_healtshot"))
healthshot = true;
if (weaponData.GearSlot == gear_slot_t.GEAR_SLOT_GRENADES || weaponData.GearSlot == gear_slot_t.GEAR_SLOT_UTILITY || weaponData.GearSlot == gear_slot_t.GEAR_SLOT_BOOSTS)
{
int clip1 = weapon.Value.Clip1;
int reservedAmmo = weapon.Value.ReserveAmmo[0];
weaponsWithAmmo.Add(weapon.Value.DesignerName, new List<(int, int)>() { (clip1, reservedAmmo) });
}
}
if (!weapon.Value.DesignerName.Contains("knife") && weaponDefindex.TryGetValue(weapon.Value.AttributeManager.Item.ItemDefinitionIndex, out weaponByDefindex) && weaponByDefindex != null)
{
int clip1 = weapon.Value.Clip1;
int reservedAmmo = weapon.Value.ReserveAmmo[0];
if (!weaponsWithAmmo.ContainsKey(weaponByDefindex))
{
weaponsWithAmmo.Add(weaponByDefindex, new List<(int, int)>());
}
weaponsWithAmmo[weaponByDefindex].Add((clip1, reservedAmmo));
}
}
catch (Exception ex)
{
Logger.LogWarning(ex.Message);
continue;
}
}
player.RemoveWeapons();
AddTimer(0.2f, () =>
{
if (bomb)
player.GiveNamedItem("weapon_c4");
if (defuser)
{
var itemServ = player.PlayerPawn?.Value?.ItemServices;
if (itemServ != null)
{
var items = new CCSPlayer_ItemServices(itemServ.Handle);
items.HasDefuser = true;
}
}
if (healthshot)
player.GiveNamedItem("weapon_healtshot");
GiveKnifeToPlayer(player);
foreach (var entry in weaponsWithAmmo)
{
foreach (var ammo in entry.Value)
{
var newWeapon = new CBasePlayerWeapon(player.GiveNamedItem(entry.Key));
Server.NextFrame(() =>
{
try
{
if (newWeapon != null)
{
newWeapon.Clip1 = ammo.Item1;
newWeapon.ReserveAmmo[0] = ammo.Item2;
}
}
catch (Exception ex)
{
Logger.LogWarning("Error setting weapon properties: " + ex.Message);
}
});
}
}
});
}
}
internal void RefreshKnife(CCSPlayerController? player)
{
if (player == null || !player.IsValid || player.PlayerPawn?.Value == null || (LifeState_t)player.LifeState != LifeState_t.LIFE_ALIVE)
return;
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null)
return;
var weapons = player.PlayerPawn.Value.WeaponServices.MyWeapons;
if (weapons != null && weapons.Count > 0)
{
CCSPlayer_ItemServices service = new(player.PlayerPawn.Value.ItemServices.Handle);
foreach (var weapon in weapons)
{
if (weapon != null && weapon.IsValid && weapon.Value != null && weapon.Value.IsValid)
if (weapon != null && weapon.IsValid && weapon.Value != null && weapon.Value.IsValid && weapon.Index > 0)
{
if (weapon.Index <= 0 || !weapon.Value.DesignerName.Contains("weapon_")) continue;
//if (weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 42 || weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 59)
try
{
if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet"))
CCSWeaponBaseVData? weaponData = weapon.Value.As<CCSWeaponBase>().VData;
if (weapon.Value.DesignerName.Contains("knife") || weaponData?.GearSlot == gear_slot_t.GEAR_SLOT_KNIFE)
{
player.RemoveItemByDesignerName(weapon.Value.DesignerName, true);
GiveKnifeToPlayer(player);
}
else
{
if (!weaponDefindex.ContainsKey(weapon.Value.AttributeManager.Item.ItemDefinitionIndex)) continue;
int clip1, reservedAmmo;
clip1 = weapon.Value.Clip1;
reservedAmmo = weapon.Value.ReserveAmmo[0];
string weaponByDefindex = weaponDefindex[weapon.Value.AttributeManager.Item.ItemDefinitionIndex];
player.RemoveItemByDesignerName(weapon.Value.DesignerName, true);
CBasePlayerWeapon newWeapon = new(player.GiveNamedItem(weaponByDefindex));
Server.NextFrame(() =>
{
if (newWeapon == null) return;
try
{
newWeapon.Clip1 = clip1;
newWeapon.ReserveAmmo[0] = reservedAmmo;
}
catch (Exception)
{ }
});
RefreshWeapons(player);
break;
}
}
catch (Exception ex)
{
Logger.LogWarning("Refreshing weapons exception");
Console.WriteLine("[WeaponPaints] Refreshing weapons exception");
Console.WriteLine(ex.Message);
}
}
}
/*
if (Config.Additional.SkinVisibilityFix)
RefreshSkins(player);
*/
}
}
internal void RemovePlayerKnife(CCSPlayerController? player, bool force = false)
{
if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return;
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) return;
var weapons = player.PlayerPawn.Value.WeaponServices.MyWeapons;
if (weapons != null && weapons.Count > 0)
{
CCSPlayer_ItemServices service = new CCSPlayer_ItemServices(player.PlayerPawn.Value.ItemServices.Handle);
//var dropWeapon = VirtualFunction.CreateVoid<nint, nint>(service.Handle, GameData.GetOffset("CCSPlayer_ItemServices_DropActivePlayerWeapon"));
foreach (var weapon in weapons)
{
if (weapon != null && weapon.IsValid && weapon.Value != null && weapon.Value.IsValid)
{
//if (weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 42 || weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 59)
if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet"))
{
if (!force)
{
if ((int)weapon.Index <= 0) return;
int weaponEntityIndex = (int)weapon.Index;
NativeAPI.IssueClientCommand((int)player.Index - 1, "slot3");
AddTimer(0.35f, () => service.DropActivePlayerWeapon(weapon.Value));
AddTimer(1.0f, () =>
{
CEntityInstance? knife = Utilities.GetEntityFromIndex<CEntityInstance>(weaponEntityIndex);
if (knife != null && knife.IsValid)
{
knife.Remove();
}
});
}
else
{
weapon.Value.Remove();
}
break;
Logger.LogWarning($"Cannot remove knife: {ex.Message}");
}
}
}
}
}
private static int GetRandomPaint(int defindex)
{
if (skinsList == null || skinsList.Count == 0)
return 0;
if (skinsList != null)
{
Random rnd = new Random();
// Filter weapons by the provided defindex
var filteredWeapons = skinsList.FindAll(w => w["weapon_defindex"]?.ToString() == defindex.ToString());
Random rnd = new Random();
// Filter weapons by the provided defindex
var filteredWeapons = skinsList.Where(w => w["weapon_defindex"]?.ToString() == defindex.ToString()).ToList();
if (filteredWeapons.Count == 0)
return 0;
var randomWeapon = filteredWeapons[rnd.Next(filteredWeapons.Count)];
if (int.TryParse(randomWeapon["paint"]?.ToString(), out int paintValue))
return paintValue;
if (filteredWeapons.Count > 0)
{
var randomWeapon = filteredWeapons[rnd.Next(filteredWeapons.Count)];
if (int.TryParse(randomWeapon["paint"]?.ToString(), out int paintValue))
{
return paintValue;
}
else
{
return 0;
}
}
}
return 0;
}

View File

@@ -4,12 +4,13 @@ using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Cvars;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using MySqlConnector;
using Newtonsoft.Json.Linq;
using System.Collections.Concurrent;
namespace WeaponPaints;
[MinimumApiVersion(144)]
[MinimumApiVersion(163)]
public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig>
{
internal static readonly Dictionary<string, string> weaponList = new()
@@ -36,6 +37,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{"weapon_negev", "Negev"},
{"weapon_sawedoff", "Sawed-Off"},
{"weapon_tec9", "Tec-9"},
{"weapon_taser", "Zeus x27"},
{"weapon_hkp2000", "P2000"},
{"weapon_mp7", "MP7"},
{"weapon_mp9", "MP9"},
@@ -67,7 +69,8 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{ "weapon_knife_cord", "Paracord Knife" },
{ "weapon_knife_canis", "Survival Knife" },
{ "weapon_knife_outdoor", "Nomad Knife" },
{ "weapon_knife_skeleton", "Skeleton Knife" }
{ "weapon_knife_skeleton", "Skeleton Knife" },
{ "weapon_knife_kukri", "Kukri Knife" }
};
internal static WeaponPaintsConfig _config = new WeaponPaintsConfig();
@@ -82,8 +85,9 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
internal Uri GlobalShareApi = new("https://weaponpaints.fun/api.php");
internal int GlobalShareServerId = 0;
internal static Dictionary<int, DateTime> commandsCooldown = new Dictionary<int, DateTime>();
private string DatabaseConnectionString = string.Empty;
private CounterStrikeSharp.API.Modules.Timers.Timer? g_hTimerCheckSkinsData = null;
internal static Database? _database;
//private CounterStrikeSharp.API.Modules.Timers.Timer? g_hTimerCheckSkinsData = null;
public static Dictionary<int, string> weaponDefindex { get; } = new Dictionary<int, string>
{
{ 1, "weapon_deagle" },
@@ -108,6 +112,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{ 28, "weapon_negev" },
{ 29, "weapon_sawedoff" },
{ 30, "weapon_tec9" },
{ 31, "weapon_taser" },
{ 32, "weapon_hkp2000" },
{ 33, "weapon_mp7" },
{ 34, "weapon_mp9" },
@@ -138,14 +143,15 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{ 521, "weapon_knife_outdoor" },
{ 522, "weapon_knife_stiletto" },
{ 523, "weapon_knife_widowmaker" },
{ 525, "weapon_knife_skeleton" }
{ 525, "weapon_knife_skeleton" },
{ 526, "weapon_knife_kukri" }
};
public WeaponPaintsConfig Config { get; set; } = new();
public override string ModuleAuthor => "Nereziel & daffyy";
public override string ModuleDescription => "Skin and knife selector, standalone and web-based";
public override string ModuleName => "WeaponPaints";
public override string ModuleVersion => "1.4b";
public override string ModuleVersion => "1.6c";
public static WeaponPaintsConfig GetWeaponPaintsConfig()
{
@@ -154,22 +160,19 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
public override void Load(bool hotReload)
{
if (!Config.GlobalShare)
{
DatabaseConnectionString = Utility.BuildDatabaseConnectionString();
Utility.TestDatabaseConnection();
}
if (hotReload)
if (hotReload && weaponSync != null)
{
OnMapStart(string.Empty);
List<CCSPlayerController> players = Utilities.GetPlayers();
foreach (CCSPlayerController player in players)
foreach (var player in Utilities.GetPlayers())
{
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || player.SteamID.ToString() == "") continue;
if (gPlayerWeaponsInfo.ContainsKey((int)player.Index)) continue;
if (weaponSync == null || player is null || !player.IsValid || player.SteamID.ToString().Length != 17 || !player.PawnIsAlive || player.IsBot ||
player.IsHLTV || player.Connected != PlayerConnectedState.PlayerConnected)
continue;
g_knifePickupCount[(int)player.Index] = 0;
gPlayerWeaponsInfo.TryRemove((int)player.Index, out _);
g_playersKnife.TryRemove((int)player.Index, out _);
PlayerInfo playerInfo = new PlayerInfo
{
@@ -180,19 +183,12 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (Config.Additional.SkinEnabled && weaponSync != null)
if (Config.Additional.SkinEnabled)
_ = weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
if (Config.Additional.KnifeEnabled && weaponSync != null)
if (Config.Additional.KnifeEnabled)
_ = weaponSync.GetKnifeFromDatabase(playerInfo);
g_knifePickupCount[(int)player!.Index] = 0;
}
/*
RegisterListeners();
RegisterCommands();
*/
}
if (Config.Additional.KnifeEnabled)
SetupKnifeMenu();
if (Config.Additional.SkinEnabled)
@@ -213,6 +209,25 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
Logger.LogError("You need to setup Database credentials in config!");
throw new Exception("[WeaponPaints] You need to setup Database credentials in config!");
}
/*
DatabaseConnectionString = Utility.BuildDatabaseConnectionString();
Utility.TestDatabaseConnection();
*/
var builder = new MySqlConnectionStringBuilder
{
Server = config.DatabaseHost,
UserID = config.DatabaseUser,
Password = config.DatabasePassword,
Database = config.DatabaseName,
Port = (uint)config.DatabasePort,
Pooling = true
};
_database = new(builder.ConnectionString);
_ = Utility.CheckDatabaseTables();
}
Config = config;
@@ -253,7 +268,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
Task<string> responseBodyTask = response.Content.ReadAsStringAsync();
responseBodyTask.Wait();
string responseBody = responseBodyTask.Result;
GlobalShareServerId = Int32.Parse(responseBody);
GlobalShareServerId = int.Parse(responseBody);
}
else
{

View File

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

View File

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

View File

@@ -11,4 +11,4 @@
"wp_skin_menu_weapon_title": "Ieroču Izvēlne",
"wp_skin_menu_skin_title": "Izvēlies skinu ierocim: {lime}{0}{default}",
"wp_skin_menu_select": "Tu esi izvēlējies {lime}{0}{default} kā savu skinu"
}
}

View File

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

View File

@@ -11,4 +11,4 @@
"wp_skin_menu_weapon_title": "Menu de Armas",
"wp_skin_menu_skin_title": "Escolhe a skin para {lime}{0}{default}",
"wp_skin_menu_select": "Tu escolheste {lime}{0}{default} como a tua skin"
}
}

View File

@@ -11,4 +11,4 @@
"wp_skin_menu_weapon_title": "Silah Menüsü",
"wp_skin_menu_skin_title": "Select skin for {lime}{0}{default}",
"wp_skin_menu_select": "Teniniz olarak {lime}{0}{default} seçtiniz"
}
}

View File

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

View File

@@ -62,7 +62,8 @@ class UtilsClass
521,
522,
523,
525
525,
526
])
)
continue;

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

Some files were not shown because too many files have changed in this diff Show More