Compare commits

..

20 Commits

Author SHA1 Message Date
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
3326 changed files with 921 additions and 1079 deletions

3
.gitignore vendored
View File

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

View File

@@ -8,50 +8,56 @@ namespace WeaponPaints
{ {
private void OnCommandRefresh(CCSPlayerController? player, CommandInfo command) private void OnCommandRefresh(CCSPlayerController? player, CommandInfo command)
{ {
if (!Config.AdditionalSetting.CommandWpEnabled || !Config.AdditionalSetting.SkinEnabled || !g_bCommandsAllowed) return; if (!Config.Additional.CommandWpEnabled || !Config.Additional.SkinEnabled || !g_bCommandsAllowed) return;
if (!Utility.IsPlayerValid(player)) 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; int playerIndex = (int)player!.Index;
PlayerInfo playerInfo = new PlayerInfo PlayerInfo playerInfo = new PlayerInfo
{ {
UserId = player.UserId, UserId = player.UserId,
Index = (int)player.Index, Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64, SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName, Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0] 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) || try
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
{ {
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds); if (!commandsCooldown.TryGetValue((int)player.UserId, out DateTime cooldownEndTime) ||
if (weaponSync != null) DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo));
if (Config.AdditionalSetting.KnifeEnabled)
{ {
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
if (weaponSync != null) 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) private void OnCommandWS(CCSPlayerController? player, CommandInfo command)
{ {
if (!Config.AdditionalSetting.SkinEnabled) return; if (!Config.Additional.SkinEnabled) return;
if (!Utility.IsPlayerValid(player)) return; if (!Utility.IsPlayerValid(player)) return;
if (!string.IsNullOrEmpty(Localizer["wp_info_website"])) if (!string.IsNullOrEmpty(Localizer["wp_info_website"]))
@@ -62,7 +68,7 @@ namespace WeaponPaints
{ {
player!.Print(Localizer["wp_info_refresh"]); player!.Print(Localizer["wp_info_refresh"]);
} }
if (!Config.AdditionalSetting.KnifeEnabled) return; if (!Config.Additional.KnifeEnabled) return;
if (!string.IsNullOrEmpty(Localizer["wp_info_knife"])) if (!string.IsNullOrEmpty(Localizer["wp_info_knife"]))
{ {
player!.Print(Localizer["wp_info_knife"]); player!.Print(Localizer["wp_info_knife"]);
@@ -71,19 +77,19 @@ namespace WeaponPaints
private void RegisterCommands() private void RegisterCommands()
{ {
AddCommand($"css_{Config.AdditionalSetting.CommandSkin}", "Skins info", (player, info) => AddCommand($"css_{Config.Additional.CommandSkin}", "Skins info", (player, info) =>
{ {
if (!Utility.IsPlayerValid(player)) return; if (!Utility.IsPlayerValid(player)) return;
OnCommandWS(player, info); OnCommandWS(player, info);
}); });
AddCommand($"css_{Config.AdditionalSetting.CommandRefresh}", "Skins refresh", (player, info) => AddCommand($"css_{Config.Additional.CommandRefresh}", "Skins refresh", (player, info) =>
{ {
if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return; if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return;
OnCommandRefresh(player, info); OnCommandRefresh(player, info);
}); });
if (Config.AdditionalSetting.CommandKillEnabled) if (Config.Additional.CommandKillEnabled)
{ {
AddCommand($"css_{Config.AdditionalSetting.CommandKill}", "kill yourself", (player, info) => AddCommand($"css_{Config.Additional.CommandKill}", "kill yourself", (player, info) =>
{ {
if (player == null || !Utility.IsPlayerValid(player) || player.PlayerPawn.Value == null || !player!.PlayerPawn.IsValid) return; if (player == null || !Utility.IsPlayerValid(player) || player.PlayerPawn.Value == null || !player!.PlayerPawn.IsValid) return;
@@ -94,7 +100,7 @@ namespace WeaponPaints
private void SetupKnifeMenu() private void SetupKnifeMenu()
{ {
if (!Config.AdditionalSetting.KnifeEnabled || !g_bCommandsAllowed) return; if (!Config.Additional.KnifeEnabled || !g_bCommandsAllowed) return;
var knivesOnly = weaponList var knivesOnly = weaponList
.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")) .Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet"))
@@ -115,7 +121,7 @@ namespace WeaponPaints
player!.Print(Localizer["wp_knife_menu_select", knifeName]); player!.Print(Localizer["wp_knife_menu_select", knifeName]);
} }
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_kill"]) && Config.AdditionalSetting.CommandKillEnabled) if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_kill"]) && Config.Additional.CommandKillEnabled)
{ {
player!.Print(Localizer["wp_knife_menu_kill"]); player!.Print(Localizer["wp_knife_menu_kill"]);
} }
@@ -124,7 +130,7 @@ namespace WeaponPaints
{ {
UserId = player.UserId, UserId = player.UserId,
Index = (int)player.Index, Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64, SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName, Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0] IpAddress = player?.IpAddress?.Split(":")[0]
}; };
@@ -145,7 +151,7 @@ namespace WeaponPaints
{ {
giveItemMenu.AddMenuOption(knifePair.Value, handleGive); giveItemMenu.AddMenuOption(knifePair.Value, handleGive);
} }
AddCommand($"css_{Config.AdditionalSetting.CommandKnife}", "Knife Menu", (player, info) => AddCommand($"css_{Config.Additional.CommandKnife}", "Knife Menu", (player, info) =>
{ {
if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return; if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return;
@@ -155,7 +161,7 @@ namespace WeaponPaints
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow)) DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
{ {
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds); commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
ChatMenus.OpenMenu(player, giveItemMenu); MenuManager.OpenChatMenu(player, giveItemMenu);
return; return;
} }
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"])) if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
@@ -212,25 +218,25 @@ namespace WeaponPaints
if (firstSkin != null && if (firstSkin != null &&
firstSkin.TryGetValue("weapon_defindex", out var weaponDefIndexObj) && firstSkin.TryGetValue("weapon_defindex", out var weaponDefIndexObj) &&
weaponDefIndexObj != null && weaponDefIndexObj != null &&
ushort.TryParse(weaponDefIndexObj.ToString(), out var weaponDefIndex) && int.TryParse(weaponDefIndexObj.ToString(), out var weaponDefIndex) &&
ushort.TryParse(selectedPaintID, out var paintID)) int.TryParse(selectedPaintID, out var paintID))
{ {
p!.Print(Localizer["wp_skin_menu_select", selectedSkin]); p!.Print(Localizer["wp_skin_menu_select", selectedSkin]);
if (!gPlayerWeaponsInfo[playerIndex].TryGetValue(weaponDefIndex, out _)) if (!gPlayerWeaponsInfo[playerIndex].ContainsKey(weaponDefIndex))
{ {
gPlayerWeaponsInfo[playerIndex][weaponDefIndex] = new WeaponInfo(); gPlayerWeaponsInfo[playerIndex][weaponDefIndex] = new WeaponInfo();
} }
gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Paint = paintID; gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Paint = paintID;
gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Wear = 0.00001f; gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Wear = 0.01f;
gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Seed = 0; gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Seed = 0;
PlayerInfo playerInfo = new PlayerInfo PlayerInfo playerInfo = new PlayerInfo
{ {
UserId = player.UserId, UserId = player.UserId,
Index = (int)player.Index, Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64, SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName, Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0] IpAddress = player?.IpAddress?.Split(":")[0]
}; };
@@ -238,7 +244,7 @@ namespace WeaponPaints
if (!Config.GlobalShare) if (!Config.GlobalShare)
{ {
if (weaponSync != null) if (weaponSync != null)
Task.Run(async () => await weaponSync.SyncWeaponPaintToDatabase(playerInfo, weaponDefIndex)); Task.Run(async () => await weaponSync.SyncWeaponPaintsToDatabase(playerInfo));
} }
} }
}; };
@@ -262,7 +268,7 @@ namespace WeaponPaints
} }
// Open the submenu for skin selection of the chosen weapon // Open the submenu for skin selection of the chosen weapon
ChatMenus.OpenMenu(player, skinSubMenu); MenuManager.OpenChatMenu(player, skinSubMenu);
} }
}; };
@@ -273,7 +279,7 @@ namespace WeaponPaints
weaponSelectionMenu.AddMenuOption(weaponName, handleWeaponSelection); weaponSelectionMenu.AddMenuOption(weaponName, handleWeaponSelection);
} }
// Command to open the weapon selection menu for players // Command to open the weapon selection menu for players
AddCommand($"css_{Config.AdditionalSetting.CommandSkinSelection}", "Skins selection menu", (player, info) => AddCommand($"css_{Config.Additional.CommandSkinSelection}", "Skins selection menu", (player, info) =>
{ {
if (!Utility.IsPlayerValid(player)) return; if (!Utility.IsPlayerValid(player)) return;
@@ -283,7 +289,7 @@ namespace WeaponPaints
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow)) DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
{ {
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds); commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
ChatMenus.OpenMenu(player, weaponSelectionMenu); MenuManager.OpenChatMenu(player, weaponSelectionMenu);
return; return;
} }
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"])) if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))

View File

@@ -3,13 +3,9 @@ using System.Text.Json.Serialization;
namespace WeaponPaints namespace WeaponPaints
{ {
public class AdditionalSetting public class Additional
{ {
[JsonPropertyName("SkinVisibilityFix")]
[JsonPropertyName("UseMetamodAlwaysLegacyModel")]
public bool UseMetamodAlwaysLegacyModel { get; set; } = false;
[JsonPropertyName("SkinVisibilityFix")]
public bool SkinVisibilityFix { get; set; } = true; public bool SkinVisibilityFix { get; set; } = true;
[JsonPropertyName("KnifeEnabled")] [JsonPropertyName("KnifeEnabled")]
@@ -18,13 +14,7 @@ namespace WeaponPaints
[JsonPropertyName("SkinEnabled")] [JsonPropertyName("SkinEnabled")]
public bool SkinEnabled { get; set; } = true; public bool SkinEnabled { get; set; } = true;
[JsonPropertyName("MusicKitEnabled")] [JsonPropertyName("CommandWpEnabled")]
public bool MusicKitEnabled { get; set; } = true;
[JsonPropertyName("NameTagEnabled")]
public bool NameTagEnabled { get; set; } = true;
[JsonPropertyName("CommandWpEnabled")]
public bool CommandWpEnabled { get; set; } = true; public bool CommandWpEnabled { get; set; } = true;
[JsonPropertyName("CommandKillEnabled")] [JsonPropertyName("CommandKillEnabled")]
@@ -56,7 +46,7 @@ namespace WeaponPaints
public class WeaponPaintsConfig : BasePluginConfig public class WeaponPaintsConfig : BasePluginConfig
{ {
public override int Version { get; set; } = 5; public override int Version { get; set; } = 4;
[JsonPropertyName("DatabaseHost")] [JsonPropertyName("DatabaseHost")]
public string DatabaseHost { get; set; } = ""; public string DatabaseHost { get; set; } = "";
@@ -85,8 +75,8 @@ namespace WeaponPaints
[JsonPropertyName("Website")] [JsonPropertyName("Website")]
public string Website { get; set; } = "example.com/skins"; public string Website { get; set; } = "example.com/skins";
[JsonPropertyName("AdditionalSetting")] [JsonPropertyName("Additional")]
public AdditionalSetting AdditionalSetting { get; set; } = new AdditionalSetting(); 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;
}
}
}
}

270
Events.cs
View File

@@ -1,7 +1,5 @@
using CounterStrikeSharp.API; using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Entities;
using System.Numerics;
namespace WeaponPaints namespace WeaponPaints
{ {
@@ -11,50 +9,52 @@ namespace WeaponPaints
{ {
CCSPlayerController? player = Utilities.GetPlayerFromSlot(playerSlot); CCSPlayerController? player = Utilities.GetPlayerFromSlot(playerSlot);
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || weaponSync == null || player.Connected == PlayerConnectedState.PlayerDisconnecting) return;
PlayerInfo playerInfo = new PlayerInfo PlayerInfo playerInfo = new PlayerInfo
{ {
UserId = player.UserId, UserId = player.UserId,
Index = (int)player.Index, Index = (int)player.Index,
SteamId = player.SteamID, SteamId = player.SteamID.ToString(),
Name = player?.PlayerName, Name = player.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0] IpAddress = player.IpAddress?.Split(":")[0]
}; };
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || weaponSync == null) return; if (!gPlayerWeaponsInfo.ContainsKey((int)player.Index))
Task.Run(async () =>
{ {
await weaponSync.GetPlayerDatabaseIndex(playerInfo); _ = Task.Run(async () =>
}); {
} if (Config.Additional.SkinEnabled)
await weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
if (Config.Additional.KnifeEnabled)
await weaponSync.GetKnifeFromDatabase(playerInfo);
});
}
}
private void OnClientDisconnect(int playerSlot) private void OnClientDisconnect(int playerSlot)
{ {
CCSPlayerController player = Utilities.GetPlayerFromSlot(playerSlot); CCSPlayerController player = Utilities.GetPlayerFromSlot(playerSlot);
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || player.UserId == null) return; if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || player.UserId == null)
return;
g_playersDatabaseIndex.TryRemove((int)player.Index, out _); if (Config.Additional.KnifeEnabled)
if (Config.AdditionalSetting.KnifeEnabled)
g_playersKnife.TryRemove((int)player.Index, out _); g_playersKnife.TryRemove((int)player.Index, out _);
if (Config.AdditionalSetting.SkinEnabled)
if (Config.Additional.SkinEnabled && gPlayerWeaponsInfo.TryGetValue((int)player.Index, out var innerDictionary))
{ {
if (gPlayerWeaponsInfo.TryRemove((int)player.Index, out var innerDictionary)) innerDictionary.Clear();
{ gPlayerWeaponsInfo.TryRemove((int)player.Index, out _);
innerDictionary.Clear();
}
}
if (Config.AdditionalSetting.MusicKitEnabled)
g_playersMusicKit.TryRemove((int)player.Index, out _);
if (commandsCooldown.ContainsKey((int)player.UserId))
{
commandsCooldown.Remove((int)player.UserId);
} }
commandsCooldown.Remove((int)player.UserId);
} }
private void OnEntityCreated(CEntityInstance entity) private void OnEntityCreated(CEntityInstance entity)
{ {
if (!Config.AdditionalSetting.SkinEnabled) return; if (!Config.Additional.SkinEnabled) return;
if (entity == null || !entity.IsValid || string.IsNullOrEmpty(entity.DesignerName)) return; if (entity == null || !entity.IsValid || string.IsNullOrEmpty(entity.DesignerName)) return;
string designerName = entity.DesignerName; string designerName = entity.DesignerName;
if (!weaponList.ContainsKey(designerName)) return; if (!weaponList.ContainsKey(designerName)) return;
@@ -94,108 +94,123 @@ namespace WeaponPaints
if (player == null || !player.IsValid) return HookResult.Continue; if (player == null || !player.IsValid) return HookResult.Continue;
/* /*
if (Config.AdditionalSetting.SkinVisibilityFix) if (Config.Additional.SkinVisibilityFix)
AddTimer(0.2f, () => RefreshSkins(player)); AddTimer(0.2f, () => RefreshSkins(player));
*/ */
return HookResult.Continue; return HookResult.Continue;
} }
/*
private HookResult OnItemPickup(EventItemPickup @event, GameEventInfo info) /*
{ private HookResult OnItemPickup(EventItemPickup @event, GameEventInfo info)
if (@event.Defindex == 42 || @event.Defindex == 59) {
{ if (@event.Defindex == 42 || @event.Defindex == 59)
CCSPlayerController? player = @event.Userid; {
if (player == null || !player.IsValid || !g_knifePickupCount.ContainsKey((int)player.Index) || player.IsBot || !g_playersKnife.ContainsKey((int)player.Index)) CCSPlayerController? player = @event.Userid;
return HookResult.Continue; 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_knifePickupCount[(int)player.Index] >= 2) return HookResult.Continue;
if (g_playersKnife.ContainsKey((int)player.Index) if (g_playersKnife.ContainsKey((int)player.Index)
&& &&
g_playersKnife[(int)player.Index] != "weapon_knife") g_playersKnife[(int)player.Index] != "weapon_knife")
{ {
g_knifePickupCount[(int)player.Index]++; g_knifePickupCount[(int)player.Index]++;
RemovePlayerKnife(player, true); RemovePlayerKnife(player, true);
if (!PlayerHasKnife(player) && Config.AdditionalSetting.GiveKnifeAfterRemove) if (!PlayerHasKnife(player) && Config.Additional.GiveKnifeAfterRemove)
AddTimer(0.3f, () => GiveKnifeToPlayer(player)); AddTimer(0.3f, () => GiveKnifeToPlayer(player));
} }
} }
return HookResult.Continue; return HookResult.Continue;
} }
*/ */
public HookResult OnPickup(CEntityIOOutput output, string name, CEntityInstance activator, CEntityInstance caller, CVariant value, float delay) public HookResult OnPickup(CEntityIOOutput output, string name, CEntityInstance activator, CEntityInstance caller, CVariant value, float delay)
{ {
CCSPlayerController? player = Utilities.GetEntityFromIndex<CCSPlayerPawn>((int)activator.Index).OriginalController.Value; CCSPlayerController? player = Utilities.GetEntityFromIndex<CCSPlayerPawn>((int)activator.Index).OriginalController.Value;
if (player == null || player.IsBot || player.IsHLTV) if (player == null || player.IsBot || player.IsHLTV ||
return HookResult.Continue; player.SteamID.ToString() == "" || !g_knifePickupCount.TryGetValue((int)player.Index, out var pickupCount) ||
!g_playersKnife.ContainsKey((int)player.Index))
if (player == null || !player.IsValid || player.SteamID.ToString() == "" || {
!g_knifePickupCount.ContainsKey((int)player.Index) || !g_playersKnife.ContainsKey((int)player.Index))
return HookResult.Continue; return HookResult.Continue;
}
CBasePlayerWeapon weapon = new(caller.Handle); CBasePlayerWeapon weapon = new(caller.Handle);
if (weapon.AttributeManager.Item.ItemDefinitionIndex != 42 && weapon.AttributeManager.Item.ItemDefinitionIndex != 59) if (weapon.AttributeManager.Item.ItemDefinitionIndex != 42 && weapon.AttributeManager.Item.ItemDefinitionIndex != 59)
{
return HookResult.Continue; return HookResult.Continue;
}
if (g_knifePickupCount[(int)player.Index] >= 2) return HookResult.Continue; if (pickupCount >= 2)
{
return HookResult.Continue;
}
if (g_playersKnife[(int)player.Index] != "weapon_knife") if (g_playersKnife[(int)player.Index] != "weapon_knife")
{ {
g_knifePickupCount[(int)player.Index]++; pickupCount++;
g_knifePickupCount[(int)player.Index] = pickupCount;
player.RemoveItemByDesignerName(weapon.DesignerName); player.RemoveItemByDesignerName(weapon.DesignerName);
if (Config.AdditionalSetting.GiveKnifeAfterRemove) if (Config.Additional.GiveKnifeAfterRemove)
{
AddTimer(0.2f, () => GiveKnifeToPlayer(player)); AddTimer(0.2f, () => GiveKnifeToPlayer(player));
}
} }
return HookResult.Continue; return HookResult.Continue;
} }
private void OnMapStart(string mapName)
{
if (!Config.AdditionalSetting.KnifeEnabled) return;
// TODO
// needed for now
AddTimer(2.0f, () =>
{
private void OnMapStart(string mapName)
{
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_t_default_melee \"\"");
NativeAPI.IssueServerCommand("mp_ct_default_melee \"\""); NativeAPI.IssueServerCommand("mp_ct_default_melee \"\"");
NativeAPI.IssueServerCommand("mp_equipment_reset_rounds 0"); NativeAPI.IssueServerCommand("mp_equipment_reset_rounds 0");
if (Config.GlobalShare) if (Config.GlobalShare)
GlobalShareConnect(); GlobalShareConnect();
weaponSync = new WeaponSynchronization(DatabaseConnectionString, Config, GlobalShareApi, GlobalShareServerId);
}); });
/*
g_hTimerCheckSkinsData = AddTimer(10.0f, () => g_hTimerCheckSkinsData = AddTimer(10.0f, () =>
{ {
List<CCSPlayerController> players = Utilities.GetPlayers(); List<CCSPlayerController> players = Utilities.GetPlayers();
HashSet<int> playerIndexes = new HashSet<int>(gPlayerWeaponsInfo.Keys);
foreach (CCSPlayerController player in players) foreach (CCSPlayerController player in players)
{ {
if (player.IsBot || player.IsHLTV || player.SteamID.ToString() == "") continue; if (player.IsBot || player.IsHLTV || player.SteamID.ToString() == "") continue;
//if (gPlayerWeaponsInfo.ContainsKey((int)player.Index)) continue; if (gPlayerWeaponsInfo.ContainsKey((int)player.Index)) continue;
if (playerIndexes.Contains((int)player.Index)) continue;
PlayerInfo playerInfo = new PlayerInfo PlayerInfo playerInfo = new PlayerInfo
{ {
UserId = player.UserId, UserId = player.UserId,
Index = (int)player.Index, Index = (int)player.Index,
SteamId = player?.SteamID, SteamId = player?.SteamID.ToString(),
Name = player?.PlayerName, Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0] IpAddress = player?.IpAddress?.Split(":")[0]
}; };
if (weaponSync != null)
_ = weaponSync.GetKnifeFromDatabase(playerInfo); if (Config.Additional.SkinEnabled && weaponSync != null)
} _ = weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
if (Config.Additional.KnifeEnabled && weaponSync != null)
_ = weaponSync.GetKnifeFromDatabase(playerInfo);
}
}, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE | CounterStrikeSharp.API.Modules.Timers.TimerFlags.REPEAT); }, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE | CounterStrikeSharp.API.Modules.Timers.TimerFlags.REPEAT);
*/
} }
private HookResult OnPlayerConnectFull(EventPlayerConnectFull @event, GameEventInfo info) private HookResult OnPlayerConnectFull(EventPlayerConnectFull @event, GameEventInfo info)
@@ -208,19 +223,22 @@ namespace WeaponPaints
{ {
UserId = player.UserId, UserId = player.UserId,
Index = (int)player.Index, Index = (int)player.Index,
SteamId = player?.SteamID, SteamId = player?.SteamID.ToString(),
Name = player?.PlayerName, Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0] IpAddress = player?.IpAddress?.Split(":")[0]
}; };
if (!g_playersDatabaseIndex.ContainsKey((int)player!.Index)) if (!gPlayerWeaponsInfo.ContainsKey((int)player!.Index))
{ {
Console.WriteLine($"[WeaponPaints] Retrying to retrieve player {player.PlayerName} skins"); Console.WriteLine($"[WeaponPaints] Retrying to retrieve player {player.PlayerName} skins");
Task.Run(async () => Task.Run(async () =>
{ {
await weaponSync.GetPlayerDatabaseIndex(playerInfo); if (Config.Additional.SkinEnabled)
}); await weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
} if (Config.Additional.KnifeEnabled)
await weaponSync.GetKnifeFromDatabase(playerInfo);
});
}
return HookResult.Continue; return HookResult.Continue;
} }
@@ -228,24 +246,13 @@ namespace WeaponPaints
private HookResult OnPlayerSpawn(EventPlayerSpawn @event, GameEventInfo info) private HookResult OnPlayerSpawn(EventPlayerSpawn @event, GameEventInfo info)
{ {
CCSPlayerController? player = @event.Userid; CCSPlayerController? player = @event.Userid;
if (player == null || !player.IsValid) if (player == null || !player.IsValid || !Config.Additional.KnifeEnabled || PlayerHasKnife(player))
{ {
return HookResult.Continue; return HookResult.Continue;
} }
if (Config.AdditionalSetting.KnifeEnabled && !PlayerHasKnife(player)) g_knifePickupCount[(int)player.Index] = 0;
{ GiveKnifeToPlayer(player);
g_knifePickupCount[(int)player.Index] = 0;
GiveKnifeToPlayer(player);
//AddTimer(0.1f, () => GiveKnifeToPlayer(player));
}
/*
if (Config.AdditionalSetting.SkinVisibilityFix)
{
AddTimer(0.3f, () => RefreshSkins(player));
}
*/
return HookResult.Continue; return HookResult.Continue;
} }
@@ -273,36 +280,51 @@ namespace WeaponPaints
{ {
try 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); var viewModels = GetPlayerViewModels(player);
if (viewModels == null || viewModels.Length == 0)
if (viewModels == null) continue; continue;
var viewModel = viewModels[0]; var viewModel = viewModels[0];
if (viewModel == null || viewModel.Value == null || viewModel.Value.Weapon == null || viewModel.Value.Weapon.Value == null) continue; if (viewModel == null || viewModel.Value == null || viewModel.Value.Weapon == null || viewModel.Value.Weapon.Value == null)
CBasePlayerWeapon weapon = viewModel.Value.Weapon.Value; continue;
if (weapon == null || !weapon.IsValid) continue; var weapon = viewModel.Value.Weapon.Value;
if (weapon == null || !weapon.IsValid)
continue;
var isKnife = viewModel.Value.VMName.Contains("knife"); if (viewModel.Value.VMName.Contains("knife"))
continue;
if (!isKnife) var sceneNode = viewModel.Value.CBodyComponent?.SceneNode;
if (sceneNode == null)
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 ( skeleton.ModelState.MeshGroupMask = 1;
viewModel.Value.CBodyComponent != null
&& viewModel.Value.CBodyComponent.SceneNode != null
&& weapon.CBodyComponent!.SceneNode!.GetSkeletonInstance().ModelState.MeshGroupMask != 2
)
{
weapon.CBodyComponent!.SceneNode!.GetSkeletonInstance().ModelState.MeshGroupMask = 2;
}
Utilities.SetStateChanged(viewModel.Value, "CBaseEntity", "m_CBodyComponent");
} }
else
{
if (skeleton.ModelState.MeshGroupMask != 2)
{
skeleton.ModelState.MeshGroupMask = 2;
}
}
Utilities.SetStateChanged(viewModel.Value, "CBaseEntity", "m_CBodyComponent");
} }
catch (Exception) catch (Exception)
{ } {
// Handle exceptions silently
}
} }
} }
@@ -312,18 +334,16 @@ namespace WeaponPaints
RegisterListener<Listeners.OnClientPutInServer>(OnClientPutInServer); RegisterListener<Listeners.OnClientPutInServer>(OnClientPutInServer);
RegisterListener<Listeners.OnClientDisconnect>(OnClientDisconnect); RegisterListener<Listeners.OnClientDisconnect>(OnClientDisconnect);
RegisterListener<Listeners.OnMapStart>(OnMapStart); RegisterListener<Listeners.OnMapStart>(OnMapStart);
RegisterListener<Listeners.OnTick>(OnTick);
if (!Config.AdditionalSetting.UseMetamodAlwaysLegacyModel) //RegisterEventHandler<EventPlayerConnectFull>(OnPlayerConnectFull);
RegisterListener<Listeners.OnTick>(OnTick);
RegisterEventHandler<EventPlayerConnectFull>(OnPlayerConnectFull);
RegisterEventHandler<EventPlayerSpawn>(OnPlayerSpawn); RegisterEventHandler<EventPlayerSpawn>(OnPlayerSpawn);
RegisterEventHandler<EventRoundStart>(OnRoundStart, HookMode.Pre); RegisterEventHandler<EventRoundStart>(OnRoundStart, HookMode.Pre);
RegisterEventHandler<EventRoundEnd>(OnRoundEnd); RegisterEventHandler<EventRoundEnd>(OnRoundEnd);
RegisterEventHandler<EventItemPurchase>(OnEventItemPurchasePost); //RegisterEventHandler<EventItemPurchase>(OnEventItemPurchasePost);
//RegisterEventHandler<EventItemPickup>(OnItemPickup); //RegisterEventHandler<EventItemPickup>(OnItemPickup);
HookEntityOutput("weapon_knife", "OnPlayerPickup", OnPickup, HookMode.Pre); HookEntityOutput("weapon_knife", "OnPlayerPickup", OnPickup, HookMode.Pre);
} }
/* WORKAROUND FOR CLIENTS WITHOUT STEAMID ON AUTHORIZATION */ /* WORKAROUND FOR CLIENTS WITHOUT STEAMID ON AUTHORIZATION */
@@ -334,15 +354,15 @@ namespace WeaponPaints
if (player == null || !player.IsValid || !player.EntityIndex.HasValue || player.IsHLTV) return HookResult.Continue; if (player == null || !player.IsValid || !player.EntityIndex.HasValue || player.IsHLTV) return HookResult.Continue;
int playerIndex = (int)player.EntityIndex.Value.Value; int playerIndex = (int)player.EntityIndex.Value.Value;
if (Config.AdditionalSetting.SkinEnabled && weaponSync != null) if (Config.Additional.SkinEnabled && weaponSync != null)
_ = weaponSync.GetWeaponPaintsFromDatabase(playerIndex); _ = weaponSync.GetWeaponPaintsFromDatabase(playerIndex);
if (Config.AdditionalSetting.KnifeEnabled && weaponSync != null) if (Config.Additional.KnifeEnabled && weaponSync != null)
_ = weaponSync.GetKnifeFromDatabase(playerIndex); _ = weaponSync.GetKnifeFromDatabase(playerIndex);
Task.Run(async () => Task.Run(async () =>
{ {
if (Config.AdditionalSetting.SkinEnabled && weaponSync != null) if (Config.Additional.SkinEnabled && weaponSync != null)
if (Config.AdditionalSetting.KnifeEnabled && weaponSync != null) if (Config.Additional.KnifeEnabled && weaponSync != null)
}); });
return HookResult.Continue; return HookResult.Continue;

View File

@@ -4,8 +4,8 @@
{ {
public int Index { get; set; } public int Index { get; set; }
public int? UserId { get; set; } public int? UserId { get; set; }
public ulong? SteamId { get; set; } public string? SteamId { get; set; }
public string? Name { get; set; } public string? Name { get; set; }
public string? IpAddress { get; set; } public string? IpAddress { get; set; }
} }
} }

View File

@@ -23,7 +23,8 @@ Unfinished, unoptimized and not fully functional ugly demo weapon paints plugin
## CS2 Server ## CS2 Server
- Have working CounterStrikeSharp (**with RUNTIME!**) - Have working CounterStrikeSharp (**with RUNTIME!**)
- Download from Release and copy plugin to plugins - 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`** - In `addons/counterstrikesharp/configs/`**`core.json`** set **FollowCS2ServerGuidelines** to **`false`**
## Plugin Configuration ## Plugin Configuration
@@ -88,6 +89,7 @@ Disregard if the config is **`GlobalShare = true`**
## Known issues ## Known issues
- Issue on Windows servers, no knives are given. - 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 - Can cause incompatibility with plugins/maps which manipulates weapons and knives
## Troubleshooting ## Troubleshooting
@@ -100,6 +102,9 @@ Plugin is not loaded or configured with mysql credentials. Tables are auto-creat
**Knives are disappearing:** **Knives are disappearing:**
Set in config GiveKnifeAfterRemove to true Set in config GiveKnifeAfterRemove to true
**Knives are not changing for players:**
You can't change knife if you have your own equipped
</details> </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/) ### 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.Core;
using CounterStrikeSharp.API.Modules.Utils; using CounterStrikeSharp.API.Modules.Utils;
using Dapper; using Dapper;
using MySqlConnector;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Reflection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using MySqlConnector;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection;
namespace WeaponPaints namespace WeaponPaints
{ {
@@ -23,11 +23,13 @@ namespace WeaponPaints
Password = Config.DatabasePassword, Password = Config.DatabasePassword,
Database = Config.DatabaseName, Database = Config.DatabaseName,
Port = (uint)Config.DatabasePort, Port = (uint)Config.DatabasePort,
Pooling = true
}; };
return builder.ConnectionString; return builder.ConnectionString;
} }
internal static async void CheckDatabaseTables()
internal static async void CheckDatabaseTables()
{ {
try try
{ {
@@ -36,22 +38,15 @@ namespace WeaponPaints
using var transaction = await connection.BeginTransactionAsync(); using var transaction = await connection.BeginTransactionAsync();
// Minimal version for MySQL 5.6.5 try
string[] sqlCommands = new string[]
{
"CREATE TABLE IF NOT EXISTS `wp_users` (`id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `steamid` BIGINT UNSIGNED NOT NULL, `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `unique_steamid` (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
"CREATE TABLE IF NOT EXISTS `wp_users_items` (`user_id` INT UNSIGNED NOT NULL, `weapon` SMALLINT UNSIGNED NOT NULL, `paint` SMALLINT UNSIGNED NOT NULL, `wear` FLOAT NOT NULL DEFAULT 0.00001, `seed` SMALLINT UNSIGNED NOT NULL DEFAULT 0, `nametag` VARCHAR(20) DEFAULT NULL, `stattrack` INT UNSIGNED NOT NULL DEFAULT 0, `stattrack_enabled` SMALLINT NOT NULL DEFAULT 0, `quality` SMALLINT UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (`user_id`,`weapon`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
"CREATE TABLE IF NOT EXISTS `wp_users_knife` (`user_id` INT UNSIGNED NOT NULL, `knife` VARCHAR(32) DEFAULT NULL, PRIMARY KEY (`user_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
"CREATE TABLE IF NOT EXISTS `wp_users_music` (`user_id` INT UNSIGNED NOT NULL, `music` SMALLINT UNSIGNED DEFAULT NULL, PRIMARY KEY (`user_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"
};
try
{ {
foreach (string command in sqlCommands) 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";
await connection.ExecuteAsync(command, transaction: transaction);
}
await transaction.CommitAsync(); await connection.ExecuteAsync(createTable1, transaction: transaction);
await connection.ExecuteAsync(createTable2, transaction: transaction);
await transaction.CommitAsync();
} }
catch (Exception) catch (Exception)
{ {
@@ -71,15 +66,15 @@ namespace WeaponPaints
} }
internal static void LoadSkinsFromFile(string filePath) internal static void LoadSkinsFromFile(string filePath)
{ {
if (File.Exists(filePath)) try
{ {
string json = File.ReadAllText(filePath); string json = File.ReadAllText(filePath);
var deserializedSkins = JsonConvert.DeserializeObject<List<JObject>>(json); var deserializedSkins = JsonConvert.DeserializeObject<List<JObject>>(json);
WeaponPaints.skinsList = deserializedSkins ?? new List<JObject>(); WeaponPaints.skinsList = deserializedSkins ?? new List<JObject>();
} }
else catch (FileNotFoundException)
{ {
throw new FileNotFoundException("File not found.", filePath); throw;
} }
} }
@@ -120,11 +115,11 @@ namespace WeaponPaints
{ {
try try
{ {
HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION"); HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION").ConfigureAwait(false);
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
{ {
string remoteVersion = await response.Content.ReadAsStringAsync(); string remoteVersion = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
remoteVersion = remoteVersion.Trim(); remoteVersion = remoteVersion.Trim();
int comparisonResult = string.Compare(version, remoteVersion); int comparisonResult = string.Compare(version, remoteVersion);
@@ -147,9 +142,13 @@ namespace WeaponPaints
logger.LogWarning("Failed to check version"); logger.LogWarning("Failed to check version");
} }
} }
catch (HttpRequestException ex)
{
logger.LogError(ex, "Failed to connect to the version server.");
}
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex); logger.LogError(ex, "An error occurred while checking version.");
} }
} }
} }

View File

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

View File

@@ -19,14 +19,14 @@ namespace WeaponPaints
if (isKnife && !g_playersKnife.ContainsKey(playerIndex) || isKnife && g_playersKnife[playerIndex] == "weapon_knife") return; if (isKnife && !g_playersKnife.ContainsKey(playerIndex) || isKnife && g_playersKnife[playerIndex] == "weapon_knife") return;
ushort weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex; int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex;
if (isKnife) if (isKnife)
{ {
weapon.AttributeManager.Item.EntityQuality = 3; weapon.AttributeManager.Item.EntityQuality = 3;
} }
if (_config.AdditionalSetting.GiveRandomSkin && if (_config.Additional.GiveRandomSkin &&
!gPlayerWeaponsInfo[playerIndex].ContainsKey(weaponDefIndex)) !gPlayerWeaponsInfo[playerIndex].ContainsKey(weaponDefIndex))
{ {
// Random skins // Random skins
@@ -35,12 +35,23 @@ namespace WeaponPaints
weapon.AttributeManager.Item.ItemIDHigh = weapon.AttributeManager.Item.ItemIDLow >> 32; weapon.AttributeManager.Item.ItemIDHigh = weapon.AttributeManager.Item.ItemIDLow >> 32;
weapon.FallbackPaintKit = GetRandomPaint(weaponDefIndex); weapon.FallbackPaintKit = GetRandomPaint(weaponDefIndex);
weapon.FallbackSeed = 0; weapon.FallbackSeed = 0;
weapon.FallbackWear = 0.00001f; weapon.FallbackWear = 0.000001f;
if (!isKnife && weapon.CBodyComponent != null && weapon.CBodyComponent.SceneNode != null) if (!isKnife && weapon.CBodyComponent != null && weapon.CBodyComponent.SceneNode != null)
{ {
if (weapon.CBodyComponent!.SceneNode!.GetSkeletonInstance().ModelState.MeshGroupMask != 2) var skeleton = GetSkeletonInstance(weapon.CBodyComponent.SceneNode);
int[] array = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 };
int fallbackPaintKit = weapon.FallbackPaintKit;
if (array.Contains(fallbackPaintKit))
{ {
weapon.CBodyComponent!.SceneNode!.GetSkeletonInstance().ModelState.MeshGroupMask = 2; skeleton.ModelState.MeshGroupMask = 1;
}
else
{
if (skeleton.ModelState.MeshGroupMask != 2)
{
skeleton.ModelState.MeshGroupMask = 2;
}
} }
} }
return; return;
@@ -56,44 +67,59 @@ namespace WeaponPaints
weapon.FallbackSeed = weaponInfo.Seed; weapon.FallbackSeed = weaponInfo.Seed;
weapon.FallbackWear = weaponInfo.Wear; weapon.FallbackWear = weaponInfo.Wear;
if (!isKnife && weapon.CBodyComponent != null && weapon.CBodyComponent.SceneNode != null) if (!isKnife && weapon.CBodyComponent != null && weapon.CBodyComponent.SceneNode != null)
{ {
if (weapon.CBodyComponent!.SceneNode!.GetSkeletonInstance().ModelState.MeshGroupMask != 2) var skeleton = GetSkeletonInstance(weapon.CBodyComponent.SceneNode);
int[] array = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 };
int fallbackPaintKit = weapon.FallbackPaintKit;
if (array.Contains(fallbackPaintKit))
{ {
weapon.CBodyComponent!.SceneNode!.GetSkeletonInstance().ModelState.MeshGroupMask = 2; skeleton.ModelState.MeshGroupMask = 1;
} }
} else
{
} if (skeleton.ModelState.MeshGroupMask != 2)
{
skeleton.ModelState.MeshGroupMask = 2;
}
}
}
}
internal static void GiveKnifeToPlayer(CCSPlayerController? player) internal static void GiveKnifeToPlayer(CCSPlayerController? player)
{ {
if (!_config.AdditionalSetting.KnifeEnabled || player == null || !player.IsValid) return; if (!_config.Additional.KnifeEnabled || player == null || !player.IsValid) return;
string knifeToGive;
if (g_playersKnife.TryGetValue((int)player.Index, out var knife)) if (g_playersKnife.TryGetValue((int)player.Index, out var knife))
{ {
player.GiveNamedItem(knife); knifeToGive = knife;
} }
else if (_config.AdditionalSetting.GiveRandomKnife) else if (_config.Additional.GiveRandomKnife)
{ {
var knifeTypes = weaponList.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")).ToDictionary(pair => pair.Key, pair => pair.Value); var knifeTypes = weaponList.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")).ToList();
if (knifeTypes.Count == 0)
{
Utility.Log("No valid knife types found.");
return;
}
Random random = new(); Random random = new();
int index = random.Next(knifeTypes.Count); int index = random.Next(knifeTypes.Count);
var randomKnifeClass = knifeTypes.Keys.ElementAt(index); knifeToGive = knifeTypes[index].Key;
player.GiveNamedItem(randomKnifeClass);
} }
else else
{ {
var defaultKnife = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife"; knifeToGive = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife";
player.GiveNamedItem(defaultKnife);
} }
player.GiveNamedItem(knifeToGive);
} }
internal static bool PlayerHasKnife(CCSPlayerController? player) internal static bool PlayerHasKnife(CCSPlayerController? player)
{ {
if (!_config.AdditionalSetting.KnifeEnabled) return false; if (!_config.Additional.KnifeEnabled) return false;
if (player == null || !player.IsValid || player.PlayerPawn == null || !player.PlayerPawn.IsValid || !player.PawnIsAlive) if (player == null || !player.IsValid || player.PlayerPawn == null || !player.PlayerPawn.IsValid || !player.PawnIsAlive)
{ {
@@ -120,6 +146,7 @@ namespace WeaponPaints
internal void RefreshPlayerKnife(CCSPlayerController? player) internal void RefreshPlayerKnife(CCSPlayerController? player)
{ {
return;
if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return; if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return;
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) return; if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) return;
@@ -175,7 +202,7 @@ namespace WeaponPaints
} }
} }
} }
/*
internal void RefreshSkins(CCSPlayerController? player) internal void RefreshSkins(CCSPlayerController? player)
{ {
return; return;
@@ -185,68 +212,71 @@ namespace WeaponPaints
AddTimer(0.25f, () => NativeAPI.IssueClientCommand((int)player.Index - 1, "slot2")); AddTimer(0.25f, () => NativeAPI.IssueClientCommand((int)player.Index - 1, "slot2"));
AddTimer(0.38f, () => NativeAPI.IssueClientCommand((int)player.Index - 1, "slot1")); AddTimer(0.38f, () => NativeAPI.IssueClientCommand((int)player.Index - 1, "slot1"));
} }
*/
internal void RefreshWeapons(CCSPlayerController? player) internal void RefreshWeapons(CCSPlayerController? player)
{ {
if (player == null || !player.IsValid || player.PlayerPawn.Value == null || !player.PawnIsAlive) return; if (player == null || !player.IsValid || player.PlayerPawn?.Value == null || !player.PawnIsAlive)
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) return; return;
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null)
return;
var weapons = player.PlayerPawn.Value.WeaponServices.MyWeapons; var weapons = player.PlayerPawn.Value.WeaponServices.MyWeapons;
if (weapons != null && weapons.Count > 0) if (weapons == null || weapons.Count == 0)
return;
var itemServices = new CCSPlayer_ItemServices(player.PlayerPawn.Value.ItemServices.Handle);
foreach (var weapon in weapons)
{ {
CCSPlayer_ItemServices service = new(player.PlayerPawn.Value.ItemServices.Handle); if (weapon == null || !weapon.IsValid || weapon.Value == null || !weapon.Value.IsValid || weapon.Index <= 0 || !weapon.Value.DesignerName.Contains("weapon_"))
continue;
foreach (var weapon in weapons) try
{ {
if (weapon != null && weapon.IsValid && weapon.Value != null && weapon.Value.IsValid) string? weaponByDefindex = null;
if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet"))
{ {
if (weapon.Index <= 0 || !weapon.Value.DesignerName.Contains("weapon_")) continue; player.RemoveItemByDesignerName(weapon.Value.DesignerName, false);
//if (weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 42 || weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 59) GiveKnifeToPlayer(player);
try }
else
{
if (weaponDefindex.TryGetValue(weapon.Value.AttributeManager.Item.ItemDefinitionIndex, out weaponByDefindex) && weaponByDefindex != null)
{ {
if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet")) int clip1 = weapon.Value.Clip1;
int reservedAmmo = weapon.Value.ReserveAmmo[0];
player.RemoveItemByDesignerName(weapon.Value.DesignerName, false);
var newWeapon = new CBasePlayerWeapon(player.GiveNamedItem(weaponByDefindex));
Server.NextFrame(() =>
{ {
player.RemoveItemByDesignerName(weapon.Value.DesignerName, true); try
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; if (newWeapon != null)
try
{ {
newWeapon.Clip1 = clip1; newWeapon.Clip1 = clip1;
newWeapon.ReserveAmmo[0] = reservedAmmo; newWeapon.ReserveAmmo[0] = reservedAmmo;
} }
catch (Exception) }
{ } catch (Exception ex)
}); {
} Logger.LogWarning("Error setting weapon properties: " + ex.Message);
}
});
} }
catch (Exception ex) else
{ {
Logger.LogWarning("Refreshing weapons exception"); Logger.LogWarning("Unable to find weapon by defindex.");
Console.WriteLine("[WeaponPaints] Refreshing weapons exception");
Console.WriteLine(ex.Message);
} }
} }
} }
catch (Exception ex)
/* {
if (Config.AdditionalSetting.SkinVisibilityFix) Logger.LogWarning("Refreshing weapons exception: " + ex.Message);
RefreshSkins(player); }
*/
} }
} }
@@ -259,13 +289,11 @@ namespace WeaponPaints
if (weapons != null && weapons.Count > 0) if (weapons != null && weapons.Count > 0)
{ {
CCSPlayer_ItemServices service = new CCSPlayer_ItemServices(player.PlayerPawn.Value.ItemServices.Handle); CCSPlayer_ItemServices service = new CCSPlayer_ItemServices(player.PlayerPawn.Value.ItemServices.Handle);
//var dropWeapon = VirtualFunction.CreateVoid<nint, nint>(service.Handle, GameData.GetOffset("CCSPlayer_ItemServices_DropActivePlayerWeapon"));
foreach (var weapon in weapons) foreach (var weapon in weapons)
{ {
if (weapon != null && weapon.IsValid && weapon.Value != null && weapon.Value.IsValid) if (weapon != null && weapon.IsValid && weapon.Value != null && weapon.Value.IsValid)
{ {
//if (weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 42 || weapon.Value.AttributeManager.Item.ItemDefinitionIndex == 59)
if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet")) if (weapon.Value.DesignerName.Contains("knife") || weapon.Value.DesignerName.Contains("bayonet"))
{ {
if (!force) if (!force)
@@ -297,28 +325,31 @@ namespace WeaponPaints
} }
private static int GetRandomPaint(int defindex) private static int GetRandomPaint(int defindex)
{ {
if (skinsList == null || skinsList.Count == 0)
return 0;
if (skinsList != null) Random rnd = new Random();
{
Random rnd = new Random(); // Filter weapons by the provided defindex
// Filter weapons by the provided defindex var filteredWeapons = skinsList.Where(w => w["weapon_defindex"]?.ToString() == defindex.ToString()).ToList();
var filteredWeapons = skinsList.FindAll(w => w["weapon_defindex"]?.ToString() == defindex.ToString());
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; return 0;
} }
private static CSkeletonInstance GetSkeletonInstance(CGameSceneNode node)
{
Func<nint, nint> GetSkeletonInstance = VirtualFunction.Create<nint, nint>(node.Handle, 8);
return new CSkeletonInstance(GetSkeletonInstance(node.Handle));
}
private static unsafe CHandle<CBaseViewModel>[]? GetPlayerViewModels(CCSPlayerController player) private static unsafe CHandle<CBaseViewModel>[]? GetPlayerViewModels(CCSPlayerController player)
{ {
if (player.PlayerPawn.Value == null || player.PlayerPawn.Value.ViewModelServices == null) return null; if (player.PlayerPawn.Value == null || player.PlayerPawn.Value.ViewModelServices == null) return null;
@@ -339,5 +370,6 @@ namespace WeaponPaints
return values; return values;
} }
} }
} }

View File

@@ -2,12 +2,8 @@
{ {
public class WeaponInfo public class WeaponInfo
{ {
public ushort Paint { get; set; } public int Paint { get; set; }
public ushort Seed { get; set; } public int Seed { get; set; }
public float Wear { get; set; } public float Wear { get; set; }
public string? NameTag { get; set; } }
public ushort Quality { get; set; }
public uint StatTrack { get; set; }
public bool StatTrackEnabled { get; set; }
}
} }

View File

@@ -4,12 +4,13 @@ using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Cvars; using CounterStrikeSharp.API.Modules.Cvars;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using MySqlConnector;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System.Collections.Concurrent; using System.Collections.Concurrent;
namespace WeaponPaints; namespace WeaponPaints;
[MinimumApiVersion(155)] [MinimumApiVersion(163)]
public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig> public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig>
{ {
internal static readonly Dictionary<string, string> weaponList = new() internal static readonly Dictionary<string, string> weaponList = new()
@@ -36,6 +37,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{"weapon_negev", "Negev"}, {"weapon_negev", "Negev"},
{"weapon_sawedoff", "Sawed-Off"}, {"weapon_sawedoff", "Sawed-Off"},
{"weapon_tec9", "Tec-9"}, {"weapon_tec9", "Tec-9"},
{"weapon_taser", "Zeus x27"},
{"weapon_hkp2000", "P2000"}, {"weapon_hkp2000", "P2000"},
{"weapon_mp7", "MP7"}, {"weapon_mp7", "MP7"},
{"weapon_mp9", "MP9"}, {"weapon_mp9", "MP9"},
@@ -67,72 +69,15 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{ "weapon_knife_cord", "Paracord Knife" }, { "weapon_knife_cord", "Paracord Knife" },
{ "weapon_knife_canis", "Survival Knife" }, { "weapon_knife_canis", "Survival Knife" },
{ "weapon_knife_outdoor", "Nomad Knife" }, { "weapon_knife_outdoor", "Nomad Knife" },
{ "weapon_knife_skeleton", "Skeleton Knife" } { "weapon_knife_skeleton", "Skeleton Knife" },
{ "weapon_knife_kukri", "Kukri Knife" }
}; };
public static Dictionary<int, string> WeaponDefindex { get; } = new Dictionary<int, string>
{
{ 1, "weapon_deagle" },
{ 2, "weapon_elite" },
{ 3, "weapon_fiveseven" },
{ 4, "weapon_glock" },
{ 7, "weapon_ak47" },
{ 8, "weapon_aug" },
{ 9, "weapon_awp" },
{ 10, "weapon_famas" },
{ 11, "weapon_g3sg1" },
{ 13, "weapon_galilar" },
{ 14, "weapon_m249" },
{ 16, "weapon_m4a1" },
{ 17, "weapon_mac10" },
{ 19, "weapon_p90" },
{ 23, "weapon_mp5sd" },
{ 24, "weapon_ump45" },
{ 25, "weapon_xm1014" },
{ 26, "weapon_bizon" },
{ 27, "weapon_mag7" },
{ 28, "weapon_negev" },
{ 29, "weapon_sawedoff" },
{ 30, "weapon_tec9" },
{ 32, "weapon_hkp2000" },
{ 33, "weapon_mp7" },
{ 34, "weapon_mp9" },
{ 35, "weapon_nova" },
{ 36, "weapon_p250" },
{ 38, "weapon_scar20" },
{ 39, "weapon_sg556" },
{ 40, "weapon_ssg08" },
{ 60, "weapon_m4a1_silencer" },
{ 61, "weapon_usp_silencer" },
{ 63, "weapon_cz75a" },
{ 64, "weapon_revolver" },
{ 500, "weapon_bayonet" },
{ 503, "weapon_knife_css" },
{ 505, "weapon_knife_flip" },
{ 506, "weapon_knife_gut" },
{ 507, "weapon_knife_karambit" },
{ 508, "weapon_knife_m9_bayonet" },
{ 509, "weapon_knife_tactical" },
{ 512, "weapon_knife_falchion" },
{ 514, "weapon_knife_survival_bowie" },
{ 515, "weapon_knife_butterfly" },
{ 516, "weapon_knife_push" },
{ 517, "weapon_knife_cord" },
{ 518, "weapon_knife_canis" },
{ 519, "weapon_knife_ursus" },
{ 520, "weapon_knife_gypsy_jackknife" },
{ 521, "weapon_knife_outdoor" },
{ 522, "weapon_knife_stiletto" },
{ 523, "weapon_knife_widowmaker" },
{ 525, "weapon_knife_skeleton" }
};
internal static WeaponPaintsConfig _config = new WeaponPaintsConfig(); internal static WeaponPaintsConfig _config = new WeaponPaintsConfig();
internal static IStringLocalizer? _localizer; internal static IStringLocalizer? _localizer;
internal static Dictionary<int, int> g_knifePickupCount = new Dictionary<int, int>(); internal static Dictionary<int, int> g_knifePickupCount = new Dictionary<int, int>();
internal static ConcurrentDictionary<int, int> g_playersDatabaseIndex = new ConcurrentDictionary<int, int>(); internal static ConcurrentDictionary<int, string> g_playersKnife = new ConcurrentDictionary<int, string>();
internal static ConcurrentDictionary<int, string> g_playersKnife = new ConcurrentDictionary<int, string>(); internal static ConcurrentDictionary<int, ConcurrentDictionary<int, WeaponInfo>> gPlayerWeaponsInfo = new ConcurrentDictionary<int, ConcurrentDictionary<int, WeaponInfo>>();
internal static ConcurrentDictionary<int, int?> g_playersMusicKit = new ConcurrentDictionary<int, int?>();
internal static ConcurrentDictionary<int, ConcurrentDictionary<ushort, WeaponInfo>> gPlayerWeaponsInfo = new ConcurrentDictionary<int, ConcurrentDictionary<ushort, WeaponInfo>>();
internal static List<JObject> skinsList = new List<JObject>(); internal static List<JObject> skinsList = new List<JObject>();
internal static WeaponSynchronization? weaponSync; internal static WeaponSynchronization? weaponSync;
internal bool g_bCommandsAllowed = true; internal bool g_bCommandsAllowed = true;
@@ -140,13 +85,72 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
internal Uri GlobalShareApi = new("https://weaponpaints.fun/api.php"); internal Uri GlobalShareApi = new("https://weaponpaints.fun/api.php");
internal int GlobalShareServerId = 0; internal int GlobalShareServerId = 0;
internal static Dictionary<int, DateTime> commandsCooldown = new Dictionary<int, DateTime>(); internal static Dictionary<int, DateTime> commandsCooldown = new Dictionary<int, DateTime>();
private string DatabaseConnectionString = string.Empty; internal static Database? _database;
private CounterStrikeSharp.API.Modules.Timers.Timer? g_hTimerCheckSkinsData = null; //private CounterStrikeSharp.API.Modules.Timers.Timer? g_hTimerCheckSkinsData = null;
public WeaponPaintsConfig Config { get; set; } = new(); public static Dictionary<int, string> weaponDefindex { get; } = new Dictionary<int, string>
{
{ 1, "weapon_deagle" },
{ 2, "weapon_elite" },
{ 3, "weapon_fiveseven" },
{ 4, "weapon_glock" },
{ 7, "weapon_ak47" },
{ 8, "weapon_aug" },
{ 9, "weapon_awp" },
{ 10, "weapon_famas" },
{ 11, "weapon_g3sg1" },
{ 13, "weapon_galilar" },
{ 14, "weapon_m249" },
{ 16, "weapon_m4a1" },
{ 17, "weapon_mac10" },
{ 19, "weapon_p90" },
{ 23, "weapon_mp5sd" },
{ 24, "weapon_ump45" },
{ 25, "weapon_xm1014" },
{ 26, "weapon_bizon" },
{ 27, "weapon_mag7" },
{ 28, "weapon_negev" },
{ 29, "weapon_sawedoff" },
{ 30, "weapon_tec9" },
{ 31, "weapon_taser" },
{ 32, "weapon_hkp2000" },
{ 33, "weapon_mp7" },
{ 34, "weapon_mp9" },
{ 35, "weapon_nova" },
{ 36, "weapon_p250" },
{ 38, "weapon_scar20" },
{ 39, "weapon_sg556" },
{ 40, "weapon_ssg08" },
{ 60, "weapon_m4a1_silencer" },
{ 61, "weapon_usp_silencer" },
{ 63, "weapon_cz75a" },
{ 64, "weapon_revolver" },
{ 500, "weapon_bayonet" },
{ 503, "weapon_knife_css" },
{ 505, "weapon_knife_flip" },
{ 506, "weapon_knife_gut" },
{ 507, "weapon_knife_karambit" },
{ 508, "weapon_knife_m9_bayonet" },
{ 509, "weapon_knife_tactical" },
{ 512, "weapon_knife_falchion" },
{ 514, "weapon_knife_survival_bowie" },
{ 515, "weapon_knife_butterfly" },
{ 516, "weapon_knife_push" },
{ 517, "weapon_knife_cord" },
{ 518, "weapon_knife_canis" },
{ 519, "weapon_knife_ursus" },
{ 520, "weapon_knife_gypsy_jackknife" },
{ 521, "weapon_knife_outdoor" },
{ 522, "weapon_knife_stiletto" },
{ 523, "weapon_knife_widowmaker" },
{ 525, "weapon_knife_skeleton" },
{ 526, "weapon_knife_kukri" }
};
public WeaponPaintsConfig Config { get; set; } = new();
public override string ModuleAuthor => "Nereziel & daffyy"; public override string ModuleAuthor => "Nereziel & daffyy";
public override string ModuleDescription => "Skin and knife selector, standalone and web-based"; public override string ModuleDescription => "Skin and knife selector, standalone and web-based";
public override string ModuleName => "WeaponPaints"; public override string ModuleName => "WeaponPaints";
public override string ModuleVersion => "1.5.0"; public override string ModuleVersion => "1.6a";
public static WeaponPaintsConfig GetWeaponPaintsConfig() public static WeaponPaintsConfig GetWeaponPaintsConfig()
{ {
@@ -155,46 +159,37 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
public override void Load(bool hotReload) public override void Load(bool hotReload)
{ {
if (!Config.GlobalShare) if (hotReload && weaponSync != null)
{
DatabaseConnectionString = Utility.BuildDatabaseConnectionString();
Utility.TestDatabaseConnection();
}
if (hotReload)
{ {
OnMapStart(string.Empty); OnMapStart(string.Empty);
List<CCSPlayerController> players = Utilities.GetPlayers(); foreach (var player in Utilities.GetPlayers())
foreach (CCSPlayerController player in players)
{ {
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || player.SteamID.ToString() == "") continue; if (weaponSync == null || player is null || !player.IsValid || !player.PawnIsAlive || player.IsBot || player.IsHLTV || player.Connected != PlayerConnectedState.PlayerConnected)
if (g_playersDatabaseIndex.ContainsKey((int)player.Index)) continue; continue;
PlayerInfo playerInfo = new PlayerInfo g_knifePickupCount[(int)player.Index] = 0;
gPlayerWeaponsInfo.TryRemove((int)player.Index, out _);
g_playersKnife.TryRemove((int)player.Index, out _);
PlayerInfo playerInfo = new PlayerInfo
{ {
UserId = player.UserId, UserId = player.UserId,
Index = (int)player.Index, Index = (int)player.Index,
SteamId = player?.SteamID, SteamId = player?.SteamID.ToString(),
Name = player?.PlayerName, Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0] IpAddress = player?.IpAddress?.Split(":")[0]
}; };
if (weaponSync != null)
{
_ = weaponSync!.GetPlayerDatabaseIndex(playerInfo);
}
g_knifePickupCount[(int)player!.Index] = 0;
}
/*
RegisterListeners();
RegisterCommands();
*/
}
if (Config.AdditionalSetting.KnifeEnabled) if (Config.Additional.SkinEnabled)
_ = weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
if (Config.Additional.KnifeEnabled)
_ = weaponSync.GetKnifeFromDatabase(playerInfo);
}
}
if (Config.Additional.KnifeEnabled)
SetupKnifeMenu(); SetupKnifeMenu();
if (Config.AdditionalSetting.SkinEnabled) if (Config.Additional.SkinEnabled)
SetupSkinsMenu(); SetupSkinsMenu();
RegisterListeners(); RegisterListeners();
@@ -209,37 +204,32 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{ {
if (config.DatabaseHost.Length < 1 || config.DatabaseName.Length < 1 || config.DatabaseUser.Length < 1) if (config.DatabaseHost.Length < 1 || config.DatabaseName.Length < 1 || config.DatabaseUser.Length < 1)
{ {
// maybe more spam to get attention? Logger.LogError("You need to setup Database credentials in config!");
for (int i = 1; i <= 30; i++) throw new Exception("[WeaponPaints] You need to setup Database credentials in config!");
{ }
Console.WriteLine("[WeaponPaints] You need to setup Database credentials in config!"); /*
} DatabaseConnectionString = Utility.BuildDatabaseConnectionString();
Logger.LogError("You need to setup Database credentials in config!"); Utility.TestDatabaseConnection();
throw new Exception("[WeaponPaints] You need to setup Database credentials in config!"); */
}
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);
} }
else
{
// maybe more spam to get attention?
for (int i = 1; i <= 30; i++)
{
Console.WriteLine("[WeaponPaints] GLOBAL SHARE IS NOT SUPPORTED NOW !!");
}
Logger.LogError("GLOBAL SHARE IS NOT SUPPORTED NOW !!");
throw new Exception("[WeaponPaints] GLOBAL SHARE IS NOT SUPPORTED NOW !!");
}
Config = config; Config = config;
_config = config; _config = config;
_localizer = Localizer; _localizer = Localizer;
/* Utility.Config = config;
* GLOBAL SHARE IS NOT SUPPORTED NOW!
*/
if (Config.GlobalShare)
Config.GlobalShare = false;
Utility.Config = config;
Utility.ShowAd(ModuleVersion); Utility.ShowAd(ModuleVersion);
Task.Run(async () => await Utility.CheckVersion(ModuleVersion, Logger)); Task.Run(async () => await Utility.CheckVersion(ModuleVersion, Logger));
} }
@@ -273,7 +263,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
Task<string> responseBodyTask = response.Content.ReadAsStringAsync(); Task<string> responseBodyTask = response.Content.ReadAsStringAsync();
responseBodyTask.Wait(); responseBodyTask.Wait();
string responseBody = responseBodyTask.Result; string responseBody = responseBodyTask.Result;
GlobalShareServerId = Int32.Parse(responseBody); GlobalShareServerId = int.Parse(responseBody);
} }
else else
{ {

View File

@@ -9,9 +9,9 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <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="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" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup> </ItemGroup>

View File

@@ -1,7 +1,4 @@
using CounterStrikeSharp.API.Core; using Dapper;
using CounterStrikeSharp.API.Modules.Entities;
using Dapper;
using MySqlConnector;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System.Collections.Concurrent; using System.Collections.Concurrent;
@@ -10,75 +7,32 @@ namespace WeaponPaints
internal class WeaponSynchronization internal class WeaponSynchronization
{ {
private readonly WeaponPaintsConfig _config; private readonly WeaponPaintsConfig _config;
private readonly string _databaseConnectionString; private readonly Database _database;
private readonly Uri _globalShareApi; private readonly Uri _globalShareApi;
private readonly int _globalShareServerId; private readonly int _globalShareServerId;
internal WeaponSynchronization(string databaseConnectionString, WeaponPaintsConfig config, Uri globalShareApi, int globalShareServerId) internal WeaponSynchronization(Database database, WeaponPaintsConfig config, Uri globalShareApi, int globalShareServerId)
{ {
_databaseConnectionString = databaseConnectionString; _database = database;
_config = config; _config = config;
_globalShareApi = globalShareApi; _globalShareApi = globalShareApi;
_globalShareServerId = globalShareServerId; _globalShareServerId = globalShareServerId;
} }
internal async Task GetPlayerDatabaseIndex(PlayerInfo player)
internal async Task GetKnifeFromDatabase(PlayerInfo player)
{ {
if (player.SteamId == null || player.Index == 0) return; if (!_config.Additional.KnifeEnabled) return;
try
{
using (var connection = new MySqlConnection(_databaseConnectionString))
{
await connection.OpenAsync();
string query = "SELECT `id` FROM `wp_users` WHERE `steamid` = @steamid";
int? databaseIndex = await connection.QueryFirstOrDefaultAsync<int?>(query, new { steamid = player.SteamId });
if (databaseIndex != null)
{
WeaponPaints.g_playersDatabaseIndex[player.Index] = (int)databaseIndex;
}
else
{
string insertQuery = "INSERT INTO `wp_users` (`steamid`) VALUES (@steamid)";
await connection.ExecuteAsync(insertQuery, new { steamid = player.SteamId });
Console.WriteLine("SQL Insert Query: " + insertQuery);
databaseIndex = await connection.QueryFirstOrDefaultAsync<int?>(query, new { steamid = player.SteamId });
WeaponPaints.g_playersDatabaseIndex[(int)player.Index] = (int)databaseIndex;
}
await connection.CloseAsync();
if (databaseIndex != null)
{
if (_config.AdditionalSetting.SkinEnabled)
await GetWeaponPaintsFromDatabase(player);
if (_config.AdditionalSetting.KnifeEnabled)
await GetKnifeFromDatabase(player);
if (_config.AdditionalSetting.MusicKitEnabled)
await GetMusicKitFromDatabase(player);
}
}
}
catch (Exception e)
{
Utility.Log("GetPlayerDatabaseIndex: " + e.Message);
return;
}
}
internal async Task GetKnifeFromDatabase(PlayerInfo player)
{
if (!_config.AdditionalSetting.KnifeEnabled) return;
if (player.SteamId == null || player.Index == 0) return; if (player.SteamId == null || player.Index == 0) return;
try try
{ {
if (_config.GlobalShare) if (_config.GlobalShare)
{ {
var values = new Dictionary<string, string> var values = new Dictionary<string, string>
{ {
{ "server_id", _globalShareServerId.ToString() }, { "server_id", _globalShareServerId.ToString() },
{ "steamid", player.SteamId.ToString()! }, { "steamid", player.SteamId },
{ "knife", "1" } { "knife", "1" }
}; };
UriBuilder builder = new UriBuilder(_globalShareApi); UriBuilder builder = new UriBuilder(_globalShareApi);
builder.Query = string.Join("&", values.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}")); builder.Query = string.Join("&", values.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}"));
@@ -109,86 +63,44 @@ namespace WeaponPaints
return; return;
} }
if (!WeaponPaints.g_playersDatabaseIndex.TryGetValue(player.Index, out _))
{
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 query = "SELECT `knife` FROM `wp_users_knife` WHERE `user_id` = @userId"; string? playerKnife = await connection.QueryFirstOrDefaultAsync<string>(query, new { steamid = player.SteamId });
string? PlayerKnife = await connection.QueryFirstOrDefaultAsync<string>(query, new { userId = WeaponPaints.g_playersDatabaseIndex[player.Index] });
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) catch (Exception e)
{ {
Utility.Log("GetKnifeFromDatabase: " + e.Message); Utility.Log(e.Message);
return; return;
} }
} }
internal async Task GetMusicKitFromDatabase(PlayerInfo player)
{
if (!_config.AdditionalSetting.MusicKitEnabled) return;
if (player.SteamId == null || player.Index == 0) return;
if (!WeaponPaints.g_playersDatabaseIndex.TryGetValue(player.Index, out _))
{
return;
}
try
{
using (var connection = new MySqlConnection(_databaseConnectionString))
{
await connection.OpenAsync();
string query = "SELECT `music` FROM `wp_users_music` WHERE `user_id` = @userId";
int? PlayerMusitKit = await connection.QueryFirstOrDefaultAsync<int?>(query, new { userId = WeaponPaints.g_playersDatabaseIndex[player.Index] });
if (PlayerMusitKit != null)
{
WeaponPaints.g_playersMusicKit[player.Index] = PlayerMusitKit;
}
else
{
return;
}
await connection.CloseAsync();
}
}
catch (Exception e)
{
Utility.Log("GetMusicKitFromDatabase: " + e.Message);
return;
}
}
internal async Task GetWeaponPaintsFromDatabase(PlayerInfo player) internal async Task GetWeaponPaintsFromDatabase(PlayerInfo player)
{ {
if (!_config.AdditionalSetting.SkinEnabled) return; if (!_config.Additional.SkinEnabled) return;
if (player.SteamId == null || player.Index == 0) return; if (player.SteamId == null || player.Index == 0) return;
if (!WeaponPaints.gPlayerWeaponsInfo.TryGetValue(player.Index, out _)) if (!WeaponPaints.gPlayerWeaponsInfo.TryGetValue(player.Index, out _))
{ {
WeaponPaints.gPlayerWeaponsInfo[player.Index] = new ConcurrentDictionary<ushort, WeaponInfo>(); WeaponPaints.gPlayerWeaponsInfo[player.Index] = new ConcurrentDictionary<int, WeaponInfo>();
} }
try
try
{ {
if (_config.GlobalShare) if (_config.GlobalShare)
{ {
var values = new Dictionary<string, string> var values = new Dictionary<string, string>
{ {
{ "server_id", _globalShareServerId.ToString() }, { "server_id", _globalShareServerId.ToString() },
{ "steamid", player.SteamId.ToString()! }, { "steamid", player.SteamId },
{ "skins", "1" } { "skins", "1" }
}; };
UriBuilder builder = new UriBuilder(_globalShareApi); UriBuilder builder = new UriBuilder(_globalShareApi);
builder.Query = string.Join("&", values.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}")); builder.Query = string.Join("&", values.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}"));
@@ -206,20 +118,19 @@ namespace WeaponPaints
{ {
foreach (var weapon in jsonArray) foreach (var weapon in jsonArray)
{ {
ushort? weaponDefIndex = weapon["weapon_defindex"]?.Value<ushort>(); int? weaponDefIndex = weapon["weapon_defindex"]?.Value<int>();
ushort? weaponPaintId = weapon["weapon_paint_id"]?.Value<ushort>(); int? weaponPaintId = weapon["weapon_paint_id"]?.Value<int>();
float? weaponWear = weapon["weapon_wear"]?.Value<float>(); float? weaponWear = weapon["weapon_wear"]?.Value<float>();
ushort? weaponSeed = weapon["weapon_seed"]?.Value<ushort>(); int? weaponSeed = weapon["weapon_seed"]?.Value<int>();
if (weaponDefIndex != null && weaponPaintId != null && weaponWear != null && weaponSeed != null) if (weaponDefIndex != null && weaponPaintId != null && weaponWear != null && weaponSeed != null)
{ {
WeaponInfo weaponInfo = new WeaponInfo WeaponInfo weaponInfo = new WeaponInfo
{ {
Paint = weaponPaintId.Value, Paint = weaponPaintId.Value,
Seed = weaponSeed.Value, Seed = weaponSeed.Value,
Wear = weaponWear.Value, Wear = weaponWear.Value
NameTag = null };
};
WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex.Value] = weaponInfo; WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex.Value] = weaponInfo;
} }
} }
@@ -233,99 +144,78 @@ namespace WeaponPaints
} }
} }
if (!WeaponPaints.g_playersDatabaseIndex.TryGetValue(player.Index, out _)) await using (var connection = await _database.GetConnectionAsync())
{
return;
}
using (var connection = new MySqlConnection(_databaseConnectionString))
{ {
await connection.OpenAsync(); string query = "SELECT * FROM `wp_player_skins` WHERE `steamid` = @steamid";
string query = "SELECT `weapon`, `paint`, `wear`, `seed`, `nametag` FROM `wp_users_items` WHERE `user_id` = @userId"; var playerSkins = await connection.QueryAsync(query, new { steamid = player.SteamId });
IEnumerable<dynamic> PlayerSkins = await connection.QueryAsync<dynamic>(query, new { userId = WeaponPaints.g_playersDatabaseIndex[player.Index] });
if (PlayerSkins != null && PlayerSkins.Any()) 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
{ {
ushort weaponDefIndex = row.weapon ?? default(ushort); Paint = weaponPaintId,
ushort weaponPaintId = row.paint ?? default(ushort); Seed = weaponSeed,
float weaponWear = row.wear ?? default(float); Wear = weaponWear
ushort weaponSeed = row.seed ?? default(ushort); };
string weaponNameTag = row.nametag; WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex] = weaponInfo;
WeaponInfo weaponInfo = new WeaponInfo
{
Paint = weaponPaintId,
Seed = weaponSeed,
Wear = weaponWear,
NameTag = weaponNameTag
};
WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex] = weaponInfo;
});
} }
else
{
return;
}
await connection.CloseAsync();
} }
} }
catch (Exception e) catch (Exception e)
{
Utility.Log("GetWeaponPaintsFromDatabase: " + e.Message);
return;
}
}
internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife)
{
if (!_config.AdditionalSetting.KnifeEnabled) return;
if(player == null || player.Index <= 0) return;
try
{
if (!WeaponPaints.g_playersDatabaseIndex.TryGetValue(player.Index, out _))
return;
using var connection = new MySqlConnection(_databaseConnectionString);
await connection.OpenAsync();
string query = "INSERT INTO `wp_users_knife` (`user_id`, `knife`) VALUES(@userId, @newKnife) ON DUPLICATE KEY UPDATE `knife` = @newKnife";
await connection.ExecuteAsync(query, new { userId = WeaponPaints.g_playersDatabaseIndex[player.Index], newKnife = knife });
await connection.CloseAsync();
}
catch (Exception e)
{ {
Utility.Log(e.Message); Utility.Log(e.Message);
return; return;
} }
} }
internal async Task SyncWeaponPaintToDatabase(PlayerInfo player, ushort weaponDefIndex)
internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife)
{ {
if (!_config.AdditionalSetting.SkinEnabled) return; if (!_config.Additional.KnifeEnabled) return;
if (player == null || player.Index <= 0) return; if (player.SteamId == null || player.Index == 0) return;
if (!WeaponPaints.g_playersDatabaseIndex.TryGetValue(player.Index, out var playerDatabaseIndex)) try
return; {
await using var connection = await _database.GetConnectionAsync();
if (!WeaponPaints.gPlayerWeaponsInfo.TryGetValue(player.Index, out var playerSavedWeapons)) string query = "INSERT INTO `wp_player_knife` (`steamid`, `knife`) VALUES(@steamid, @newKnife) ON DUPLICATE KEY UPDATE `knife` = @newKnife";
return; await connection.ExecuteAsync(query, new { steamid = player.SteamId, newKnife = knife });
}
if (!playerSavedWeapons.TryGetValue(weaponDefIndex, out var weaponInfo)) catch (Exception e)
return; {
Utility.Log(e.Message);
}
}
internal async Task SyncWeaponPaintsToDatabase(PlayerInfo player)
{
if (player == null || player.Index <= 0 || player.SteamId == null) return;
using var connection = new MySqlConnection(_databaseConnectionString); await using var connection = await _database.GetConnectionAsync();
string querySql = @"
INSERT INTO `wp_users_items` if (!WeaponPaints.gPlayerWeaponsInfo.ContainsKey(player.Index))
(`user_id`, `weapon`, `paint`, `wear`, `seed`) return;
VALUES
(@userId, @weaponDefIndex, @paintId, @wear, @seed) foreach (var weaponInfoPair in WeaponPaints.gPlayerWeaponsInfo[player.Index])
ON DUPLICATE KEY UPDATE {
paint = @paintId, int weaponDefIndex = weaponInfoPair.Key;
wear = @wear, WeaponInfo weaponInfo = weaponInfoPair.Value;
seed = @seed";
var queryParams = new { weaponDefIndex, userId = playerDatabaseIndex, paintId = weaponInfo.Paint, wear = weaponInfo.Wear, seed = weaponInfo.Seed }; int paintId = weaponInfo.Paint;
await connection.ExecuteAsync(querySql, queryParams); float wear = weaponInfo.Wear;
await connection.CloseAsync(); int seed = weaponInfo.Seed;
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 { steamid = player.SteamId, weaponDefIndex, paintId, wear, seed };
await connection.ExecuteAsync(updateSql, updateParams);
}
} }
} }
} }

View File

@@ -1,66 +1,29 @@
<?php <?php
/**
* Class DataBase
*
* This class handles database operations using PDO.
*/
class DataBase { class DataBase {
/**
* @var PDO The PDO instance for database connection.
*/
private $PDO; private $PDO;
/**
* Constructor method to initialize the database connection.
*/
public function __construct() { public function __construct() {
try { try {
// Establish a connection to the database using PDO $this->PDO = new PDO("mysql:host=".DB_HOST."; port=".DB_PORT."; dbname=".DB_NAME, DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->PDO = new PDO(
"mysql:host=".DB_HOST.";port=".DB_PORT.";dbname=".DB_NAME,
DB_USER,
DB_PASS
);
// Set the connection to use utf8 encoding
$this->PDO->exec("SET NAMES utf8");
} }
catch(PDOException $ex) { catch(PDOException $ex)
// Display error message if connection fails {
echo "<div style='display: flex; flex-direction: column;align-items: center;justify-content: center;text-align: center;'><h2>Problem with database!</h2>"; echo "<div style='display: flex; flex-direction: column;align-items: center;justify-content: center;text-align: center;'><h2>Problem with database!</h2>";
die("<pre style='padding: 10px;text-wrap: balance; border: 2px solid #ed6bd3;background: #252525; color: #ed6bd3; width: 50%;'>" . $ex . "</pre>"); die("<pre style='padding: 10px;text-wrap: balance; border: 2px solid #ed6bd3;background: #252525; color: #ed6bd3; width: 50%;'>" . $ex . "</pre>");
} }
} }
public function select($query, $bindings = []) {
/**
* Perform a SELECT query on the database.
*
* @param string $query The SQL query to execute.
* @param array $bindings An associative array of parameters and their values.
* @return array|false Returns an array of rows as associative arrays or false if no results are found.
*/
public function select($query, $bindings = array()) {
// Prepare and execute the SQL query
$STH = $this->PDO->prepare($query); $STH = $this->PDO->prepare($query);
$STH->execute($bindings); $STH->execute($bindings);
// Fetch the results as associative arrays
$result = $STH->fetchAll(PDO::FETCH_ASSOC); $result = $STH->fetchAll(PDO::FETCH_ASSOC);
if ($result === false) { $result ??= false;
$result = array(); // Set $result to an empty array if no results found return $result;
}
return $result;
} }
/** public function query($query, $bindings = []){
* Perform a non-query SQL statement on the database.
*
* @param string $query The SQL query to execute.
* @param array $bindings An associative array of parameters and their values.
* @return bool Returns true on success or false on failure.
*/
public function query($query, $bindings = array()) {
// Prepare and execute the SQL query
$STH = $this->PDO->prepare($query); $STH = $this->PDO->prepare($query);
return $STH->execute($bindings); return $STH->execute($bindings);
} }
}
}

View File

@@ -1,71 +0,0 @@
<?php
// Set security headers to enhance security
header("X-Frame-Options: SAMEORIGIN");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");
header("Referrer-Policy: no-referrer-when-downgrade");
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://code.jquery.com; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; img-src 'self' data: https://cdn.jsdelivr.net https://steamcommunity-a.akamaihd.net https://raw.githubusercontent.com;");
// Include necessary classes and files
require 'class/config.php';
require 'class/database.php';
require 'steamauth/steamauth.php';
require 'class/utils.php';
// Create a database instance
$db = new DataBase();
// Check if the user is logged in
if (isset($_SESSION['steamid'])) {
// Insert or update user's Steam ID in the database
$steamid = $_SESSION['steamid'];
$db->query("INSERT INTO `wp_users` (`steamid`) VALUES ('{$steamid}') ON DUPLICATE KEY UPDATE `updated_at` = CURRENT_TIMESTAMP");
// Get user's database index
$userInfoQuery = $db->select("SELECT `id` FROM `wp_users` WHERE `steamid` = :steamid", ["steamid" => $steamid]);
$_SESSION['userDbIndex'] = $userDbIndex = (int)$userInfoQuery[0]['id'];
// Get weapons and skins information
$weapons = UtilsClass::getWeaponsFromArray();
$skins = UtilsClass::skinsFromJson();
// Retrieve user's selected skins and knife
$querySelected = $db->select("SELECT `weapon`, `paint`, `wear`, `seed`, `nametag` FROM `wp_users_items` WHERE `user_id` = :user_id", ["user_id" => $userDbIndex]);
$selectedSkins = UtilsClass::getSelectedSkins($querySelected);
$selectedKnifeResult = $db->select("SELECT `knife` FROM `wp_users_knife` WHERE `user_id` = :user_id", ["user_id" => $userDbIndex]);
// Determine user's selected knife or set default knife
if (!empty($selectedKnifeResult)) {
$selectedKnife = $selectedKnifeResult[0]['knife'];
} else {
$selectedKnife = "weapon_knife";
}
$knifes = UtilsClass::getKnifeTypes();
// Handle form submission
if (isset($_POST['forma'])) {
$ex = explode("-", $_POST['forma']);
// Handle knife selection
if ($ex[0] == "knife") {
$db->query("INSERT INTO `wp_users_knife` (`user_id`, `knife`) VALUES(:user_id, :knife) ON DUPLICATE KEY UPDATE `knife` = :knife", ["user_id" => $userDbIndex, "knife" => $knifes[$ex[1]]['weapon_name']]);
} else {
// Handle skin selection
if (array_key_exists($ex[1], $skins[$ex[0]]) && isset($_POST['wear']) && $_POST['wear'] >= 0.00 && $_POST['wear'] <= 1.00 && isset($_POST['seed'])) {
$wear = floatval($_POST['wear']); // wear
$seed = intval($_POST['seed']); // seed
// Check if the skin is already selected and update or insert accordingly
if (array_key_exists($ex[0], $selectedSkins)) {
$db->query("UPDATE wp_users_items SET paint = :weapon_paint_id, wear = :weapon_wear, seed = :weapon_seed WHERE user_id = :user_id AND weapon = :weapon_defindex", ["user_id" => $userDbIndex, "weapon_defindex" => $ex[0], "weapon_paint_id" => $ex[1], "weapon_wear" => $wear, "weapon_seed" => $seed]);
} else {
$db->query("INSERT INTO wp_users_items (`user_id`, `weapon`, `paint`, `wear`, `seed`) VALUES (:user_id, :weapon_defindex, :weapon_paint_id, :weapon_wear, :weapon_seed)", ["user_id" => $userDbIndex, "weapon_defindex" => $ex[0], "weapon_paint_id" => $ex[1], "weapon_wear" => $wear, "weapon_seed" => $seed]);
}
}
}
// Redirect to the same page after form submission
header("Location: {$_SERVER['PHP_SELF']}");
}
}
?>

View File

@@ -1,112 +1,99 @@
<?php <?php
/**
* Class UtilsClass
*
* Provides utility methods for handling skin and weapon data.
*/
class UtilsClass class UtilsClass
{ {
/** public static function skinsFromJson(): array
* Retrieve skins data from the JSON file.
*
* @return array An associative array containing skin data.
*/
public static function skinsFromJson()
{ {
$skins = array(); $skins = [];
$jsonFilePath = __DIR__ . "/../data/skins.json"; $json = json_decode(file_get_contents(__DIR__ . "/../data/skins.json"), true);
if (file_exists($jsonFilePath) && is_readable($jsonFilePath)) { foreach ($json as $skin) {
$json = json_decode(file_get_contents($jsonFilePath), true); $skins[(int) $skin['weapon_defindex']][(int) $skin['paint']] = [
'weapon_name' => $skin['weapon_name'],
foreach ($json as $skin) { 'paint_name' => $skin['paint_name'],
$skins[(int) $skin['weapon_defindex']][(int) $skin['paint']] = array( 'image_url' => $skin['image'],
'weapon_name' => $skin['weapon_name'], ];
'paint_name' => $skin['paint_name'],
'image_url' => $skin['image'],
);
}
} else {
// Handle file not found or unreadable error
// You can throw an exception or log an error message
} }
return $skins; return $skins;
} }
/**
* Retrieve weapons data from the skin data array.
*
* @return array An associative array containing weapon data.
*/
public static function getWeaponsFromArray() public static function getWeaponsFromArray()
{ {
$weapons = array(); $weapons = [];
$skinsData = self::skinsFromJson(); $temp = self::skinsFromJson();
foreach ($skinsData as $key => $value) { foreach ($temp as $key => $value) {
$weapons[$key] = array( if (key_exists($key, $weapons))
continue;
$weapons[$key] = [
'weapon_name' => $value[0]['weapon_name'], 'weapon_name' => $value[0]['weapon_name'],
'paint_name' => $value[0]['paint_name'], 'paint_name' => $value[0]['paint_name'],
'image_url' => $value[0]['image_url'], 'image_url' => $value[0]['image_url'],
); ];
} }
return $weapons; return $weapons;
} }
/**
* Retrieve knife types from the weapon data array.
*
* @return array An associative array containing knife types data.
*/
public static function getKnifeTypes() public static function getKnifeTypes()
{ {
$knifes = array(); $knifes = [];
$weaponsData = self::getWeaponsFromArray(); $temp = self::getWeaponsFromArray();
$allowedKnifeKeys = array( foreach ($temp as $key => $weapon) {
500, 503, 505, 506, 507, 508, 509, 512, 514, 515, if (
516, 517, 518, 519, 520, 521, 522, 523, 525 !in_array($key, [
); 500,
503,
505,
506,
507,
508,
509,
512,
514,
515,
516,
517,
518,
519,
520,
521,
522,
523,
525,
526
])
)
continue;
foreach ($weaponsData as $key => $weapon) { $knifes[$key] = [
if (in_array($key, $allowedKnifeKeys)) { 'weapon_name' => $weapon['weapon_name'],
$knifes[$key] = array( 'paint_name' => rtrim(explode("|", $weapon['paint_name'])[0]),
'weapon_name' => $weapon['weapon_name'], 'image_url' => $weapon['image_url'],
'paint_name' => rtrim(explode("|", $weapon['paint_name'])[0]), ];
'image_url' => $weapon['image_url'], $knifes[0] = [
); 'weapon_name' => "weapon_knife",
} 'paint_name' => "Default knife",
'image_url' => "https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/website/img/skins/weapon_knife.png",
];
} }
// Add default knife
$knifes[0] = array(
'weapon_name' => "weapon_knife",
'paint_name' => "Default knife",
'image_url' => "https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/website/img/skins/weapon_knife.png",
);
ksort($knifes); ksort($knifes);
return $knifes; return $knifes;
} }
/** public static function getSelectedSkins(array $temp)
* Retrieve selected skins data from the database result.
*
* @param array $temp An array containing the selected skins data.
* @return array An associative array containing selected skins data.
*/
public static function getSelectedSkins($temp)
{ {
$selected = array(); $selected = [];
foreach ($temp as $weapon) { foreach ($temp as $weapon) {
$selected[$weapon['weapon']] = array( $selected[$weapon['weapon_defindex']] = [
'weapon_paint_id' => $weapon['paint'], 'weapon_paint_id' => $weapon['weapon_paint_id'],
'weapon_seed' => $weapon['seed'], 'weapon_seed' => $weapon['weapon_seed'],
'weapon_wear' => $weapon['wear'], 'weapon_wear' => $weapon['weapon_wear'],
); ];
} }
return $selected; return $selected;

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

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