Compare commits

...

40 Commits

Author SHA1 Message Date
Nereziel
7c3fa6469b Merge pull request #99 from himenekocn/main
Add zh-cn.json
2023-12-15 20:13:36 +01:00
LynchMus
52962518fe Create zh-cn.json 2023-12-14 12:13:31 +08:00
Nereziel
7e12b89a9e fix logout 2023-12-13 20:02:01 +01:00
Nereziel
ae56b18a3c Merge pull request #97 from daffyyyy/some-changes
Fix for F
2023-12-13 19:52:59 +01:00
daffyyyy
c907911cd1 Fix for F 2023-12-13 19:49:47 +01:00
Nereziel
1aa486cd7d Merge branch 'main' of https://github.com/Nereziel/cs2-WeaponPaints 2023-12-13 19:42:43 +01:00
Nereziel
5e62c7c597 Update preview.png 2023-12-13 19:36:37 +01:00
Nereziel
819ac6233c Update README.md 2023-12-13 19:31:47 +01:00
Nereziel
ed24eb0dfc add config for darkmode
lazy to make toggle for player
2023-12-13 19:25:13 +01:00
Nereziel
1a9f7ad108 Merge pull request #91 from exababy/patch-1
Wear & Seed Support
2023-12-13 19:22:20 +01:00
Nereziel
6f1a29bb39 Merge pull request #96 from snowhp/main
pt-PT and pt-BR translations added
2023-12-13 08:28:33 +01:00
Nereziel
9e64cdcd43 Merge pull request #95 from exababy/patch-2
turkish language
2023-12-13 08:27:23 +01:00
Nereziel
da86756092 Merge pull request #94 from rcon420/patch-2
latvian lang added
2023-12-13 08:26:35 +01:00
Tiago Machado
22880070cd Merge pull request #1 from crashzk/patch-1
Update pt-BR.json
2023-12-12 23:02:44 +00:00
crashzk
208cbe1aef Update pt-BR.json 2023-12-12 19:53:34 -03:00
Tiago Machado
c0cf9210dc Create pt-BR.json 2023-12-12 22:00:51 +00:00
Tiago Machado
5f61254b4e Create pt-PT.json 2023-12-12 22:00:18 +00:00
Nilsu Derinder
6cd1bb3bf5 fix 2 2023-12-12 23:46:11 +03:00
Nilsu Derinder
4f94b831c2 fix 2023-12-12 23:40:53 +03:00
Nilsu Derinder
969d40b970 Button Update
the button will not work if the skin is not selected which fixes possible bugs in the plugin.
2023-12-12 23:33:05 +03:00
Nilsu Derinder
0cd36a7877 turkish language 2023-12-12 23:21:33 +03:00
rcon_password
a3306b5f8f latvian lang added
latvian lang added
2023-12-12 22:13:05 +02:00
Nereziel
379c2f797c Merge pull request #93 from daffyyyy/some-changes
CSS 121, languages and more
2023-12-12 20:55:21 +01:00
Nilsu Derinder
7f41607d54 Update & Fix
now selected wear appears 
and pulls the value from the database.
2023-12-12 22:44:08 +03:00
daffyyyy
fc42190701 CSS 121, languages and more 2023-12-12 20:09:39 +01:00
Nilsu Derinder
928c1e1466 bootstrap update 2023-12-11 18:46:34 +03:00
Nilsu Derinder
78649f5dcf Update
wear has been updated and settings have been moved into modal and added settings button
2023-12-11 11:32:40 +03:00
Nilsu Derinder
4e72f10326 Seed Update
seed was converted to box instead of range and only numbers can be entered.
2023-12-08 17:56:28 +03:00
Nilsu Derinder
3ddbf7e11e Advanced wear 2023-12-06 22:25:19 +03:00
Nilsu Derinder
ee770fd8c2 Seed support 2023-12-06 22:03:52 +03:00
Nilsu Derinder
72c5df53b5 fix 2023-12-06 20:50:39 +03:00
Nilsu Derinder
d0ed0f4c0b Wear Support 2023-12-06 19:42:18 +03:00
Nereziel
643beaad46 Merge pull request #90 from daffyyyy/some-changes
!skins thread-safe and checking version
2023-12-06 17:18:06 +01:00
daffyyyy
6d44e582be !skins thread-safe and checking version 2023-12-06 14:47:26 +01:00
Nereziel
813a9abcc8 Merge pull request #89 from daffyyyy/some-changes
Small fixes cssharp >= 101
2023-12-05 19:32:00 +01:00
daffyyyy
b0790729be Small fixes 2023-12-05 19:30:10 +01:00
Nereziel
74a6dff114 Merge pull request #88 from daffyyyy/some-changes
Update for cssharp 101
2023-12-04 21:03:07 +01:00
daffyyyy
e37f111f1b Update WeaponPaints.csproj 2023-12-04 21:01:36 +01:00
daffyyyy
5e6286b667 Update for cssharp 101 2023-12-04 21:00:24 +01:00
Nereziel
ed4da98a50 edit default fallback
+removed unused php
2023-12-03 21:25:04 +01:00
25 changed files with 589 additions and 268 deletions

View File

@@ -10,32 +10,39 @@ namespace WeaponPaints
{
if (!Config.Additional.CommandWpEnabled || !Config.Additional.SkinEnabled || !g_bCommandsAllowed) return;
if (!Utility.IsPlayerValid(player)) return;
string temp = "";
if (player == null || player.Index <= 0) return;
int playerIndex = (int)player!.Index;
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (playerIndex != 0 && DateTime.UtcNow >= commandCooldown[playerIndex].AddSeconds(Config.CmdRefreshCooldownSeconds))
{
commandCooldown[playerIndex] = DateTime.UtcNow;
if (weaponSync != null)
Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerIndex));
Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo));
if (Config.Additional.KnifeEnabled)
{
if (weaponSync != null)
Task.Run(async () => await weaponSync.GetKnifeFromDatabase(playerIndex));
Task.Run(async () => await weaponSync.GetKnifeFromDatabase(playerInfo));
RefreshWeapons(player);
}
if (!string.IsNullOrEmpty(Config.Messages.SuccessRefreshCommand))
if (!string.IsNullOrEmpty(Localizer["wp_command_refresh_done"]))
{
temp = $" {Config.Prefix} {Config.Messages.SuccessRefreshCommand}";
player.PrintToChat(Utility.ReplaceTags(temp));
player!.Print(Localizer["wp_command_refresh_done"]);
}
return;
}
if (!string.IsNullOrEmpty(Config.Messages.CooldownRefreshCommand))
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
temp = $" {Config.Prefix} {Config.Messages.CooldownRefreshCommand}";
player.PrintToChat(Utility.ReplaceTags(temp));
player!.Print(Localizer["wp_command_cooldown"]);
}
}
@@ -44,22 +51,18 @@ namespace WeaponPaints
if (!Config.Additional.SkinEnabled) return;
if (!Utility.IsPlayerValid(player)) return;
string temp;
if (!string.IsNullOrEmpty(Config.Messages.WebsiteMessageCommand))
if (!string.IsNullOrEmpty(Localizer["wp_info_website"]))
{
temp = $" {Config.Prefix} {Config.Messages.WebsiteMessageCommand}";
player!.PrintToChat(Utility.ReplaceTags(temp));
player!.Print(Localizer["wp_info_website", Config.Website]);
}
if (!string.IsNullOrEmpty(Config.Messages.SynchronizeMessageCommand))
if (!string.IsNullOrEmpty(Localizer["wp_info_refresh"]))
{
temp = $" {Config.Prefix} {Config.Messages.SynchronizeMessageCommand}";
player!.PrintToChat(Utility.ReplaceTags(temp));
player!.Print(Localizer["wp_info_refresh"]);
}
if (!Config.Additional.KnifeEnabled) return;
if (!string.IsNullOrEmpty(Config.Messages.KnifeMessageCommand))
if (!string.IsNullOrEmpty(Localizer["wp_info_knife"]))
{
temp = $" {Config.Prefix} {Config.Messages.KnifeMessageCommand}";
player!.PrintToChat(Utility.ReplaceTags(temp));
player!.Print(Localizer["wp_info_knife"]);
}
}
@@ -94,37 +97,44 @@ namespace WeaponPaints
.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet"))
.ToDictionary(pair => pair.Key, pair => pair.Value);
var giveItemMenu = new ChatMenu(Utility.ReplaceTags($" {Config.Messages.KnifeMenuTitle}"));
var giveItemMenu = new ChatMenu(Localizer["wp_knife_menu_title"]);
var handleGive = (CCSPlayerController? player, ChatMenuOption option) =>
{
if (Utility.IsPlayerValid(player))
{
if (player == null) return;
var knifeName = option.Text;
var knifeKey = knivesOnly.FirstOrDefault(x => x.Value == knifeName).Key;
if (!string.IsNullOrEmpty(knifeKey))
{
string temp = "";
if (!string.IsNullOrEmpty(Config.Messages.ChosenKnifeMenu))
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_select"]))
{
temp = $" {Config.Prefix} {Config.Messages.ChosenKnifeMenu}".Replace("{KNIFE}", knifeName);
player!.PrintToChat(Utility.ReplaceTags(temp));
player!.Print(Localizer["wp_knife_menu_select", knifeName]);
}
if (!string.IsNullOrEmpty(Config.Messages.ChosenKnifeMenuKill) && Config.Additional.CommandKillEnabled)
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_kill"]) && Config.Additional.CommandKillEnabled)
{
temp = $" {Config.Prefix} {Config.Messages.ChosenKnifeMenuKill}";
player!.PrintToChat(Utility.ReplaceTags(temp));
player!.Print(Localizer["wp_knife_menu_kill"]);
}
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
g_playersKnife[(int)player!.Index] = knifeKey;
if (player!.PawnIsAlive && g_bCommandsAllowed)
{
RefreshWeapons(player);
}
if (weaponSync != null)
Task.Run(() => weaponSync.SyncKnifeToDatabase((int)player.Index, knifeKey));
Task.Run(async () => await weaponSync.SyncKnifeToDatabase(playerInfo, knifeKey));
}
}
};
@@ -143,10 +153,9 @@ namespace WeaponPaints
ChatMenus.OpenMenu(player, giveItemMenu);
return;
}
if (!string.IsNullOrEmpty(Config.Messages.CooldownRefreshCommand))
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
string temp = $" {Config.Prefix} {Config.Messages.CooldownRefreshCommand}";
player.PrintToChat(Utility.ReplaceTags(temp));
player!.Print(Localizer["wp_command_cooldown"]);
}
});
}
@@ -154,7 +163,7 @@ namespace WeaponPaints
private void SetupSkinsMenu()
{
var classNamesByWeapon = weaponList.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
var weaponSelectionMenu = new ChatMenu(Utility.ReplaceTags($" {Config.Messages.WeaponMenuTitle}"));
var weaponSelectionMenu = new ChatMenu(Localizer["wp_skin_menu_weapon_title"]);
// Function to handle skin selection for a specific weapon
var handleWeaponSelection = (CCSPlayerController? player, ChatMenuOption option) =>
@@ -172,7 +181,7 @@ namespace WeaponPaints
weaponName?.ToString() == selectedWeaponClassname
)?.ToList();
var skinSubMenu = new ChatMenu(Utility.ReplaceTags($" {Config.Messages.SkinMenuTitle}").Replace("{WEAPON}", selectedWeapon));
var skinSubMenu = new ChatMenu(Localizer["wp_skin_menu_skin_title", selectedWeapon]);
// Function to handle skin selection for the chosen weapon
var handleSkinSelection = (CCSPlayerController? p, ChatMenuOption opt) =>
@@ -201,8 +210,7 @@ namespace WeaponPaints
int.TryParse(weaponDefIndexObj.ToString(), out var weaponDefIndex) &&
int.TryParse(selectedPaintID, out var paintID))
{
string temp = $" {Config.Prefix} {Config.Messages.ChosenSkinMenu}".Replace("{SKIN}", selectedSkin);
p.PrintToChat(Utility.ReplaceTags(temp));
p!.Print(Localizer["wp_skin_menu_select", selectedSkin]);
if (!gPlayerWeaponsInfo[playerIndex].ContainsKey(weaponDefIndex))
{
@@ -210,16 +218,22 @@ namespace WeaponPaints
}
gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Paint = paintID;
gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Wear = 0.0f;
gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Wear = 0.01f;
gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Seed = 0;
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (!Config.GlobalShare)
{
if (weaponSync == null) return;
Task.Run(async () =>
{
await weaponSync.SyncWeaponPaintsToDatabase(p);
});
if (weaponSync != null)
Task.Run(async () => await weaponSync.SyncWeaponPaintsToDatabase(playerInfo));
}
}
};
@@ -265,10 +279,9 @@ namespace WeaponPaints
ChatMenus.OpenMenu(player, weaponSelectionMenu);
return;
}
if (!string.IsNullOrEmpty(Config.Messages.CooldownRefreshCommand))
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
string temp = $"{Config.Prefix} {Config.Messages.CooldownRefreshCommand}";
player.PrintToChat(Utility.ReplaceTags(temp));
player!.Print(Localizer["wp_command_cooldown"]);
}
});
}

View File

@@ -3,32 +3,6 @@ using System.Text.Json.Serialization;
namespace WeaponPaints
{
public class Messages
{
[JsonPropertyName("WebsiteMessageCommand")]
public string WebsiteMessageCommand { get; set; } = "Visit {WEBSITE} where you can change skins.";
[JsonPropertyName("SynchronizeMessageCommand")]
public string SynchronizeMessageCommand { get; set; } = "Type !wp to synchronize chosen skins.";
[JsonPropertyName("KnifeMessageCommand")]
public string KnifeMessageCommand { get; set; } = "Type !knife to open knife menu.";
[JsonPropertyName("CooldownRefreshCommand")]
public string CooldownRefreshCommand { get; set; } = "You can't refresh weapon paints right now.";
[JsonPropertyName("SuccessRefreshCommand")]
public string SuccessRefreshCommand { get; set; } = "Refreshing weapon paints.";
[JsonPropertyName("ChosenKnifeMenu")]
public string ChosenKnifeMenu { get; set; } = "You have chosen {KNIFE} as your knife.";
[JsonPropertyName("ChosenSkinMenu")]
public string ChosenSkinMenu { get; set; } = "You have chosen {SKIN} as your skin.";
[JsonPropertyName("ChosenKnifeMenuKill")]
public string ChosenKnifeMenuKill { get; set; } = "To correctly apply skin for knife, you need to type !kill.";
[JsonPropertyName("KnifeMenuTitle")]
public string KnifeMenuTitle { get; set; } = "Knife Menu.";
[JsonPropertyName("WeaponMenuTitle")]
public string WeaponMenuTitle { get; set; } = "Weapon Menu.";
[JsonPropertyName("SkinMenuTitle")]
public string SkinMenuTitle { get; set; } = "Select skin for {WEAPON}";
}
public class Additional
{
[JsonPropertyName("SkinVisibilityFix")]
@@ -66,6 +40,8 @@ namespace WeaponPaints
[JsonPropertyName("GiveRandomSkin")]
public bool GiveRandomSkin { get; set; } = false;
[JsonPropertyName("GiveKnifeAfterRemove")]
public bool GiveKnifeAfterRemove { get; set; } = false;
}
public class WeaponPaintsConfig : BasePluginConfig
@@ -99,9 +75,6 @@ namespace WeaponPaints
[JsonPropertyName("Website")]
public string Website { get; set; } = "example.com/skins";
[JsonPropertyName("Messages")]
public Messages Messages { get; set; } = new Messages();
[JsonPropertyName("Additional")]
public Additional Additional { get; set; } = new Additional();
}

126
Events.cs
View File

@@ -12,12 +12,25 @@ namespace WeaponPaints
CCSPlayerController? player = Utilities.GetPlayerFromIndex(playerIndex);
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV) return;
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (Config.Additional.SkinEnabled && weaponSync != null)
_ = weaponSync.GetWeaponPaintsFromDatabase(playerIndex);
if (Config.Additional.KnifeEnabled && weaponSync != null)
_ = weaponSync.GetKnifeFromDatabase(playerIndex);
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || weaponSync == null) return;
Task.Run(async () =>
{
if (Config.Additional.SkinEnabled)
await weaponSync.GetKnifeFromDatabase(playerInfo);
});
//if (Config.Additional.KnifeEnabled && weaponSync != null)
//_ = weaponSync.GetKnifeFromDatabase(playerIndex);
}
private void OnClientDisconnect(int playerSlot)
@@ -32,7 +45,7 @@ namespace WeaponPaints
gPlayerWeaponsInfo.Remove((int)player.Index);
}
private void OnEntitySpawned(CEntityInstance entity)
private void OnEntityCreated(CEntityInstance entity)
{
if (!Config.Additional.SkinEnabled) return;
var designerName = entity.DesignerName;
@@ -44,6 +57,7 @@ namespace WeaponPaints
{
isKnife = true;
}
Server.NextFrame(() =>
{
try
@@ -81,23 +95,65 @@ namespace WeaponPaints
{
if (@event.Defindex == 42 || @event.Defindex == 59)
{
Server.PrintToChatAll("test1");
CCSPlayerController? player = @event.Userid;
if (!Utility.IsPlayerValid(player) || !player.PawnIsAlive || g_knifePickupCount[(int)player.Index] >= 2) 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;
Server.PrintToChatAll("test2");
if (g_knifePickupCount[(int)player.Index] >= 2) return HookResult.Continue;
Server.PrintToChatAll("test3");
if (g_playersKnife.ContainsKey((int)player.Index)
&&
g_playersKnife[(int)player.Index] != "weapon_knife")
{
Server.PrintToChatAll("usuwam noz");
g_knifePickupCount[(int)player.Index]++;
RemovePlayerKnife(player, true);
AddTimer(0.3f, () => GiveKnifeToPlayer(player));
if (!PlayerHasKnife(player) && Config.Additional.GiveKnifeAfterRemove)
AddTimer(0.3f, () => GiveKnifeToPlayer(player));
}
}
return HookResult.Continue;
}
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;
if (player == null || player.IsBot || player.IsHLTV)
return HookResult.Continue;
if (player == null || !player.IsValid || player.AuthorizedSteamID == null ||
!g_knifePickupCount.ContainsKey((int)player.Index) || !g_playersKnife.ContainsKey((int)player.Index))
return HookResult.Continue;
CBasePlayerWeapon weapon = new(caller.Handle);
if (weapon.AttributeManager.Item.ItemDefinitionIndex != 42 && weapon.AttributeManager.Item.ItemDefinitionIndex != 59)
return HookResult.Continue;
if (g_knifePickupCount[(int)player.Index] >= 2) return HookResult.Continue;
if (g_playersKnife[(int)player.Index] != "weapon_knife")
{
g_knifePickupCount[(int)player.Index]++;
weapon.Remove();
if (!PlayerHasKnife(player) && Config.Additional.GiveKnifeAfterRemove)
AddTimer(0.2f, () => GiveKnifeToPlayer(player));
}
return HookResult.Continue;
}
private void OnMapStart(string mapName)
{
if (!Config.Additional.KnifeEnabled) return;
@@ -105,12 +161,15 @@ namespace WeaponPaints
// needed for now
AddTimer(2.0f, () =>
{
NativeAPI.IssueServerCommand("mp_t_default_melee \"\"");
NativeAPI.IssueServerCommand("mp_ct_default_melee \"\"");
NativeAPI.IssueServerCommand("mp_equipment_reset_rounds 0");
if (Config.GlobalShare)
GlobalShareConnect();
weaponSync = new WeaponSynchronization(DatabaseConnectionString, Config, GlobalShareApi, GlobalShareServerId);
});
g_hTimerCheckSkinsData = AddTimer(10.0f, () =>
@@ -119,13 +178,22 @@ namespace WeaponPaints
foreach (CCSPlayerController player in players)
{
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || player.AuthorizedSteamID == null) continue;
if (player.IsBot || player.IsHLTV || player.AuthorizedSteamID == null) continue;
if (gPlayerWeaponsInfo.ContainsKey((int)player.Index)) continue;
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (Config.Additional.SkinEnabled && weaponSync != null)
_ = weaponSync.GetWeaponPaintsFromDatabase((int)player.Index);
_ = weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
if (Config.Additional.KnifeEnabled && weaponSync != null)
_ = weaponSync.GetKnifeFromDatabase((int)player.Index);
_ = weaponSync.GetKnifeFromDatabase(playerInfo);
}
}, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE | CounterStrikeSharp.API.Modules.Timers.TimerFlags.REPEAT);
}
@@ -133,16 +201,28 @@ namespace WeaponPaints
private HookResult OnPlayerConnectFull(EventPlayerConnectFull @event, GameEventInfo info)
{
CCSPlayerController? player = @event.Userid;
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV) return HookResult.Continue;
if (!gPlayerWeaponsInfo.ContainsKey((int)player.Index))
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || weaponSync == null) return HookResult.Continue;
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (!gPlayerWeaponsInfo.ContainsKey((int)player!.Index))
{
Console.WriteLine($"[WeaponPaints] Retrying to retrieve player {player.PlayerName} skins");
if (Config.Additional.SkinEnabled && weaponSync != null)
_ = weaponSync.GetWeaponPaintsFromDatabase((int)player.Index);
if (Config.Additional.KnifeEnabled && weaponSync != null)
_ = weaponSync.GetKnifeFromDatabase((int)player.Index);
Task.Run(async () =>
{
if (Config.Additional.SkinEnabled)
await weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
if (Config.Additional.KnifeEnabled)
await weaponSync.GetKnifeFromDatabase(playerInfo);
});
}
return HookResult.Continue;
@@ -151,7 +231,7 @@ namespace WeaponPaints
private HookResult OnPlayerSpawn(EventPlayerSpawn @event, GameEventInfo info)
{
CCSPlayerController? player = @event.Userid;
if (player == null || !player.IsValid)
if (player == null || !player.IsValid || player.IsBot)
{
return HookResult.Continue;
}
@@ -159,8 +239,7 @@ namespace WeaponPaints
if (Config.Additional.KnifeEnabled)
{
g_knifePickupCount[(int)player.Index] = 0;
if (!PlayerHasKnife(player))
GiveKnifeToPlayer(player);
AddTimer(0.1f, () => GiveKnifeToPlayer(player));
}
if (Config.Additional.SkinVisibilityFix)
@@ -190,7 +269,7 @@ namespace WeaponPaints
private void RegisterListeners()
{
RegisterListener<Listeners.OnEntitySpawned>(OnEntitySpawned);
RegisterListener<Listeners.OnEntityCreated>(OnEntityCreated);
RegisterListener<Listeners.OnClientAuthorized>(OnClientAuthorized);
RegisterListener<Listeners.OnClientDisconnect>(OnClientDisconnect);
RegisterListener<Listeners.OnMapStart>(OnMapStart);
@@ -200,7 +279,8 @@ namespace WeaponPaints
RegisterEventHandler<EventRoundStart>(OnRoundStart, HookMode.Pre);
RegisterEventHandler<EventRoundEnd>(OnRoundEnd);
RegisterEventHandler<EventItemPurchase>(OnEventItemPurchasePost);
RegisterEventHandler<EventItemPickup>(OnItemPickup);
//RegisterEventHandler<EventItemPickup>(OnItemPickup);
HookEntityOutput("weapon_knife", "OnPlayerPickup", OnPickup, HookMode.Pre);
}
/* WORKAROUND FOR CLIENTS WITHOUT STEAMID ON AUTHORIZATION */

14
PlayerExtensions.cs Normal file
View File

@@ -0,0 +1,14 @@
using CounterStrikeSharp.API.Core;
using System.Text;
namespace WeaponPaints;
public static class PlayerExtensions
{
public static void Print(this CCSPlayerController controller, string message)
{
StringBuilder _message = new(WeaponPaints._localizer["wp_prefix"]);
_message.Append(message);
controller.PrintToChat(_message.ToString());
}
}

11
PlayerInfo.cs Normal file
View File

@@ -0,0 +1,11 @@
namespace WeaponPaints
{
public class PlayerInfo
{
public int Index { get; set; }
public int? UserId { get; set; }
public string? SteamId { get; set; }
public string? Name { get; set; }
public string? IpAddress { get; set; }
}
}

1
PluginServices.cs Normal file
View File

@@ -0,0 +1 @@


View File

@@ -9,18 +9,19 @@ Unfinished, unoptimized and not fully functional ugly demo weapon paints plugin
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/E1E2G0P2O) or [![Donate on Steam](https://github.com/Nereziel/cs2-WeaponPaints/assets/32937653/a0d53822-4ca7-4caf-83b4-e1a9b5f8c94e)](https://steamcommunity.com/tradeoffer/new/?partner=41515647&token=gW2W-nXE)
## Features
- Changes only paint, seed and wear on weapons and knives;
- MySQL based or global website at [weaponpaints.fun](https://weaponpaints.fun/), so you dont need MySQL/Website;
- Data sync on player connect;
- Added command **`!wp`** to refresh skins; ***(with cooldown in second can be configured)***
- Added command **`!ws`** to show website;
- Added command **`!knife`** to show menu with knives;
- Knife change is now limited to have these cvars empty **`mp_t_default_melee ""`** and **`mp_ct_default_melee ""`**;
- Changes only paint, seed and wear on weapons and knives
- MySQL based or global website at [weaponpaints.fun](https://weaponpaints.fun/), so you dont need MySQL/Website
- Data sync on player connect
- Added command **`!wp`** to refresh skins ***(with cooldown in second can be configured)***
- Added command **`!ws`** to show website
- Added command **`!knife`** to show menu with knives
- Knife change is now limited to have these cvars empty **`mp_t_default_melee ""`** and **`mp_ct_default_melee ""`**
- Translations support, submit a PR if you want to share your translation
## CS2 Server
- Compile and copy plugin to plugins, [more info here](https://docs.cssharp.dev/guides/hello-world-plugin/);
- Setup **`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`**;
- Compile and copy plugin to plugins, [more info here](https://docs.cssharp.dev/guides/hello-world-plugin/)
- Setup **`addons/counterstrikesharp/configs/plugins/WeaponPaints/WeaponPaints.json`** set **`GlobalShare`** to **`true`** for global, or include database credentials
- in **`addons/counterstrikesharp/configs/core.json`** set **FollowCS2ServerGuidelines** to **`false`**
## Plugin Configuration
<details>
@@ -69,12 +70,17 @@ Unfinished, unoptimized and not fully functional ugly demo weapon paints plugin
</details>
## Web install
Disregard if the config is **`GlobalShare = true`**;
- Requires PHP >= 7.4; ***(Tested on php ver **`8.2.3`** and nginx webserver)***
- Copy website to web server; ***(Folder `img` not needed)***
- Get [Steam API Key](https://steamcommunity.com/dev/apikey);
- Fill in database credentials and api key in `class/config.php`;
- Visit website and login via steam;
Disregard if the config is **`GlobalShare = true`**
- Requires PHP >= 7.4 ***(Tested on php ver **`8.2.3`** and nginx webserver)***
- Copy website to web server ***(Folder `img` not needed)***
- Get [Steam API Key](https://steamcommunity.com/dev/apikey)
- Fill in database credentials and api key in `class/config.php`
- Visit website and login via steam
## Web Features
- Basic website
- Steam login/logout
- Change knife, paint, seed and wear
## Known issues
- Issue on Windows servers, no knives are given.

View File

@@ -5,6 +5,7 @@ using MySqlConnector;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Reflection;
using Microsoft.Extensions.Logging;
namespace WeaponPaints
{
@@ -38,7 +39,7 @@ namespace WeaponPaints
try
{
string createTable1 = "CREATE TABLE IF NOT EXISTS `wp_player_skins` (`steamid` varchar(64) NOT NULL, `weapon_defindex` int(6) NOT NULL, `weapon_paint_id` int(6) NOT NULL, `weapon_wear` float NOT NULL DEFAULT 0.0001, `weapon_seed` int(16) NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci";
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(createTable1, transaction: transaction);
@@ -107,6 +108,46 @@ namespace WeaponPaints
return message;
}
internal static async Task CheckVersion(string version, ILogger logger)
{
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION");
if (response.IsSuccessStatusCode)
{
string remoteVersion = await response.Content.ReadAsStringAsync();
remoteVersion = remoteVersion.Trim();
int comparisonResult = string.Compare(version, remoteVersion);
if (comparisonResult < 0)
{
logger.LogWarning("Plugin is outdated! Check https://github.com/Nereziel/cs2-WeaponPaints");
}
else if (comparisonResult > 0)
{
logger.LogInformation("Probably dev version detected");
}
else
{
logger.LogInformation("Plugin is up to date");
}
}
else
{
logger.LogWarning("Failed to check version");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
internal static void ShowAd(string moduleVersion)
{
Console.WriteLine(" ");

1
VERSION Normal file
View File

@@ -0,0 +1 @@
1.3f

View File

@@ -2,6 +2,7 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using Microsoft.Extensions.Logging;
namespace WeaponPaints
{
@@ -19,6 +20,11 @@ namespace WeaponPaints
int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex;
if (isKnife)
{
weapon.AttributeManager.Item.EntityQuality = 3;
}
if (_config.Additional.GiveRandomSkin &&
!gPlayerWeaponsInfo[playerIndex].ContainsKey(weaponDefIndex))
{
@@ -28,7 +34,7 @@ namespace WeaponPaints
weapon.AttributeManager.Item.ItemIDHigh = weapon.AttributeManager.Item.ItemIDLow >> 32;
weapon.FallbackPaintKit = GetRandomPaint(weaponDefIndex);
weapon.FallbackSeed = 0;
weapon.FallbackWear = 0.0f;
weapon.FallbackWear = 0.000001f;
if (!isKnife && weapon.CBodyComponent != null && weapon.CBodyComponent.SceneNode != null)
{
var skeleton = GetSkeletonInstance(weapon.CBodyComponent.SceneNode);
@@ -81,7 +87,7 @@ namespace WeaponPaints
{
if (!_config.Additional.KnifeEnabled) return false;
if (player == null || !player.IsValid || !player.PlayerPawn.IsValid)
if (player == null || !player.IsValid || player.PlayerPawn == null || !player.PlayerPawn.IsValid || !player.PawnIsAlive)
{
return false;
}
@@ -221,6 +227,7 @@ namespace WeaponPaints
}
catch (Exception ex)
{
Logger.LogWarning("Refreshing weapons exception");
Console.WriteLine("[WeaponPaints] Refreshing weapons exception");
Console.WriteLine(ex.Message);
}
@@ -240,6 +247,7 @@ namespace WeaponPaints
if (weapons != null && weapons.Count > 0)
{
CCSPlayer_ItemServices service = new CCSPlayer_ItemServices(player.PlayerPawn.Value.ItemServices.Handle);
//var dropWeapon = VirtualFunction.CreateVoid<nint, nint>(service.Handle, GameData.GetOffset("CCSPlayer_ItemServices_DropActivePlayerWeapon"));
foreach (var weapon in weapons)
{
@@ -277,10 +285,10 @@ namespace WeaponPaints
}
private static int GetRandomPaint(int defindex)
{
Random rnd = new Random();
if (WeaponPaints.skinsList != null)
if (skinsList != null)
{
Random rnd = new Random();
// Filter weapons by the provided defindex
var filteredWeapons = skinsList.FindAll(w => w["weapon_defindex"]?.ToString() == defindex.ToString());

View File

@@ -3,10 +3,12 @@ using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Cvars;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Localization;
namespace WeaponPaints;
[MinimumApiVersion(90)]
[MinimumApiVersion(121)]
public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig>
{
internal static readonly Dictionary<string, string> weaponList = new()
@@ -68,6 +70,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
};
internal static WeaponPaintsConfig _config = new WeaponPaintsConfig();
internal static IStringLocalizer? _localizer;
internal static Dictionary<int, int> g_knifePickupCount = new Dictionary<int, int>();
internal static Dictionary<int, string> g_playersKnife = new();
internal static Dictionary<int, Dictionary<int, WeaponInfo>> gPlayerWeaponsInfo = new Dictionary<int, Dictionary<int, WeaponInfo>>();
@@ -76,7 +79,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
//internal static List<int> g_changedKnife = new();
internal bool g_bCommandsAllowed = true;
internal Uri GlobalShareApi = new Uri("https://weaponpaints.fun/api.php");
internal Uri GlobalShareApi = new("https://weaponpaints.fun/api.php");
internal int GlobalShareServerId = 0;
private DateTime[] commandCooldown = new DateTime[Server.MaxPlayers];
private string DatabaseConnectionString = string.Empty;
@@ -142,7 +145,8 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
public override string ModuleAuthor => "Nereziel & daffyy";
public override string ModuleDescription => "Skin and knife selector, standalone and web-based";
public override string ModuleName => "WeaponPaints";
public override string ModuleVersion => "1.3c";
public override string ModuleVersion => "1.3g";
public static WeaponPaintsConfig GetWeaponPaintsConfig()
{
return _config;
@@ -156,22 +160,37 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
Utility.TestDatabaseConnection();
}
weaponSync = new WeaponSynchronization(DatabaseConnectionString, Config, GlobalShareApi, GlobalShareServerId);
if (hotReload)
{
OnMapStart(string.Empty);
Task.Run(async () =>
{
for (int i = 1; i <= Server.MaxPlayers; i++)
{
if (Config.Additional.SkinEnabled && weaponSync != null)
await weaponSync.GetWeaponPaintsFromDatabase(i);
if (Config.Additional.KnifeEnabled && weaponSync != null)
await weaponSync.GetKnifeFromDatabase(i);
}
});
List<CCSPlayerController> players = Utilities.GetPlayers();
foreach (CCSPlayerController player in players)
{
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV || player.AuthorizedSteamID == null) continue;
if (gPlayerWeaponsInfo.ContainsKey((int)player.Index)) continue;
PlayerInfo playerInfo = new PlayerInfo
{
UserId = player.UserId,
Index = (int)player.Index,
SteamId = player?.AuthorizedSteamID?.SteamId64.ToString(),
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (Config.Additional.SkinEnabled && weaponSync != null)
_ = weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
if (Config.Additional.KnifeEnabled && weaponSync != null)
_ = weaponSync.GetKnifeFromDatabase(playerInfo);
g_knifePickupCount[(int)player!.Index] = 0;
}
/*
RegisterListeners();
RegisterCommands();
*/
}
if (Config.Additional.KnifeEnabled)
@@ -191,14 +210,18 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{
if (config.DatabaseHost.Length < 1 || config.DatabaseName.Length < 1 || config.DatabaseUser.Length < 1)
{
Logger.LogError("You need to setup Database credentials in config!");
throw new Exception("[WeaponPaints] You need to setup Database credentials in config!");
}
}
Config = config;
_config = config;
_localizer = Localizer;
Utility.Config = config;
Utility.ShowAd(ModuleVersion);
Task.Run(async () => await Utility.CheckVersion(ModuleVersion, Logger));
}
public override void Unload(bool hotReload)
@@ -234,9 +257,12 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
}
else
{
Logger.LogError("Unable to retrieve serverid from GlobalShare!");
throw new Exception("[WeaponPaints] Unable to retrieve serverid from GlobalShare!");
}
}
Logger.LogInformation("GlobalShare ONLINE!");
Console.WriteLine("[WeaponPaints] GlobalShare ONLINE");
}
}

View File

@@ -5,12 +5,17 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CounterStrikeSharp.API" Version="*" />
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.121" />
<PackageReference Include="Dapper" Version="2.1.24" />
<PackageReference Include="MySqlConnector" Version="2.3.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<None Update="lang\**\*.*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View File

@@ -1,6 +1,4 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using Dapper;
using Dapper;
using MySqlConnector;
using Newtonsoft.Json.Linq;
@@ -21,24 +19,21 @@ namespace WeaponPaints
_globalShareServerId = globalShareServerId;
}
internal async Task GetKnifeFromDatabase(int playerIndex)
internal async Task GetKnifeFromDatabase(PlayerInfo player)
{
if (!_config.Additional.KnifeEnabled) return;
if (player.SteamId == null || player.Index == 0) return;
try
{
CCSPlayerController player = Utilities.GetPlayerFromIndex(playerIndex);
if (!Utility.IsPlayerValid(player)) return;
if (player.AuthorizedSteamID == null) return;
string steamId = player.AuthorizedSteamID.SteamId64.ToString();
if (_config.GlobalShare)
{
var values = new Dictionary<string, string>
{
{ "server_id", _globalShareServerId.ToString() },
{ "steamid", steamId },
{ "steamid", player.SteamId },
{ "knife", "1" }
};
UriBuilder builder = new UriBuilder(_globalShareApi);
builder.Query = string.Join("&", values.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}"));
@@ -53,7 +48,7 @@ namespace WeaponPaints
string result = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(result))
{
WeaponPaints.g_playersKnife[playerIndex] = result;
WeaponPaints.g_playersKnife[player.Index] = result;
}
else
{
@@ -72,10 +67,11 @@ namespace WeaponPaints
{
await connection.OpenAsync();
string query = "SELECT `knife` FROM `wp_player_knife` WHERE `steamid` = @steamid";
string? PlayerKnife = await connection.QueryFirstOrDefaultAsync<string>(query, new { steamid = steamId });
string? PlayerKnife = await connection.QueryFirstOrDefaultAsync<string>(query, new { steamid = player.SteamId });
if (PlayerKnife != null)
{
WeaponPaints.g_playersKnife[playerIndex] = PlayerKnife;
WeaponPaints.g_playersKnife[player.Index] = PlayerKnife;
}
else
{
@@ -91,20 +87,14 @@ namespace WeaponPaints
}
}
internal async Task GetWeaponPaintsFromDatabase(int playerIndex)
internal async Task GetWeaponPaintsFromDatabase(PlayerInfo player)
{
if (!_config.Additional.SkinEnabled) return;
if (player.SteamId == null || player.Index == 0) return;
CCSPlayerController player = Utilities.GetPlayerFromIndex(playerIndex);
if (!Utility.IsPlayerValid(player)) return;
if (player.AuthorizedSteamID == null) return;
string steamId = player.AuthorizedSteamID.SteamId64.ToString();
if (!WeaponPaints.gPlayerWeaponsInfo.TryGetValue(playerIndex, out _))
if (!WeaponPaints.gPlayerWeaponsInfo.TryGetValue(player.Index, out _))
{
WeaponPaints.gPlayerWeaponsInfo[playerIndex] = new Dictionary<int, WeaponInfo>();
WeaponPaints.gPlayerWeaponsInfo[player.Index] = new Dictionary<int, WeaponInfo>();
}
try
{
@@ -113,7 +103,7 @@ namespace WeaponPaints
var values = new Dictionary<string, string>
{
{ "server_id", _globalShareServerId.ToString() },
{ "steamid", steamId },
{ "steamid", player.SteamId },
{ "skins", "1" }
};
UriBuilder builder = new UriBuilder(_globalShareApi);
@@ -146,7 +136,7 @@ namespace WeaponPaints
Seed = weaponSeed.Value,
Wear = weaponWear.Value
};
WeaponPaints.gPlayerWeaponsInfo[playerIndex][weaponDefIndex.Value] = weaponInfo;
WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex.Value] = weaponInfo;
}
}
}
@@ -164,7 +154,7 @@ namespace WeaponPaints
await connection.OpenAsync();
string query = "SELECT * FROM `wp_player_skins` WHERE `steamid` = @steamid";
IEnumerable<dynamic> PlayerSkins = await connection.QueryAsync<dynamic>(query, new { steamid = steamId });
IEnumerable<dynamic> PlayerSkins = await connection.QueryAsync<dynamic>(query, new { steamid = player.SteamId });
if (PlayerSkins != null && PlayerSkins.AsList().Count > 0)
{
@@ -181,7 +171,7 @@ namespace WeaponPaints
Seed = weaponSeed,
Wear = weaponWear
};
WeaponPaints.gPlayerWeaponsInfo[playerIndex][weaponDefIndex] = weaponInfo;
WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex] = weaponInfo;
});
}
else
@@ -198,20 +188,17 @@ namespace WeaponPaints
}
}
internal async Task SyncKnifeToDatabase(int playerIndex, string knife)
internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife)
{
if (!_config.Additional.KnifeEnabled) return;
try
{
CCSPlayerController player = Utilities.GetPlayerFromIndex(playerIndex);
if (player == null || !player.IsValid) return;
if (player.AuthorizedSteamID == null) return;
string steamId = player.AuthorizedSteamID.SteamId64.ToString();
if (player.SteamId == null || player.Index == 0) return;
using var connection = new MySqlConnection(_databaseConnectionString);
await connection.OpenAsync();
string query = "INSERT INTO `wp_player_knife` (`steamid`, `knife`) VALUES(@steamid, @newKnife) ON DUPLICATE KEY UPDATE `knife` = @newKnife";
await connection.ExecuteAsync(query, new { steamid = steamId, newKnife = knife });
await connection.ExecuteAsync(query, new { steamid = player.SteamId, newKnife = knife });
await connection.CloseAsync();
}
catch (Exception e)
@@ -220,21 +207,17 @@ namespace WeaponPaints
return;
}
}
internal async Task SyncWeaponPaintsToDatabase(CCSPlayerController? player)
internal async Task SyncWeaponPaintsToDatabase(PlayerInfo player)
{
if (player == null || !Utility.IsPlayerValid(player)) return;
int playerIndex = (int)player.Index;
if (player.AuthorizedSteamID == null) return;
string steamId = player.AuthorizedSteamID.SteamId64.ToString();
if (player == null || player.Index <= 0 || player.SteamId == null) return;
using var connection = new MySqlConnection(_databaseConnectionString);
await connection.OpenAsync();
if (!WeaponPaints.gPlayerWeaponsInfo.ContainsKey(playerIndex))
if (!WeaponPaints.gPlayerWeaponsInfo.ContainsKey(player.Index))
return;
foreach (var weaponInfoPair in WeaponPaints.gPlayerWeaponsInfo[playerIndex])
foreach (var weaponInfoPair in WeaponPaints.gPlayerWeaponsInfo[player.Index])
{
int weaponDefIndex = weaponInfoPair.Key;
WeaponInfo weaponInfo = weaponInfoPair.Value;
@@ -247,7 +230,7 @@ namespace WeaponPaints
"`weapon_wear` = @wear, `weapon_seed` = @seed WHERE `steamid` = @steamid " +
"AND `weapon_defindex` = @weaponDefIndex";
var updateParams = new { paintId, wear, seed, steamid = steamId, weaponDefIndex };
var updateParams = new { paintId, wear, seed, steamid = player.SteamId, weaponDefIndex };
int rowsAffected = await connection.ExecuteAsync(updateSql, updateParams);
if (rowsAffected == 0)

14
lang/en.json Normal file
View File

@@ -0,0 +1,14 @@
{
"wp_prefix": "{lightblue}[WeaponPaints] {default}",
"wp_info_website": "Visit {lime}{0}{default} where you can change skins",
"wp_info_refresh": "Type {lime}!wp{default} to synchronize chosen skins",
"wp_info_knife": "Type {lime}!knife{default} to open knife menu",
"wp_command_cooldown": "{lightred}You can't refresh weapon paints right now",
"wp_command_refresh_done": "{lime}Refreshing weapon paints",
"wp_knife_menu_select": "You have chosen {lime}{0}{default} as your knife",
"wp_knife_menu_kill": "To correctly apply skin for knife, you need to type {lime}!kill{default}",
"wp_knife_menu_title": "Knife Menu",
"wp_skin_menu_weapon_title": "Weapon Menu",
"wp_skin_menu_skin_title": "Select skin for {lime}{0}{default}",
"wp_skin_menu_select": "You have chosen {lime}{0}{default} as your skin"
}

14
lang/lv.json Normal file
View File

@@ -0,0 +1,14 @@
{
"wp_prefix": "{lightblue}[Ieroču Ādiņas] {default}",
"wp_info_website": "Apmeklē {lime}{0}{default} kur tu vari nomainīt skinus",
"wp_info_refresh": "Raksti {lime}!wp{default} lai sinhronizētu izvēlētos skinus",
"wp_info_knife": "Raksti {lime}!knife{default} lai atvērtu nažu izvēlni",
"wp_command_cooldown": "{lightred} Tu šobrīd nevari atjaunot ieroču skinus...",
"wp_command_refresh_done": "{lime}Izvēlētie skini tiek atjaunoti",
"wp_knife_menu_select": "Tu esi izvēlējies {lime}{0}{default} nazi",
"wp_knife_menu_kill": "Lai pareizi atjaunotu naža skinu, ieraksti čatā {lime}!kill{default}",
"wp_knife_menu_title": "Nažu Izvēlne",
"wp_skin_menu_weapon_title": "Ieroču Izvēlne",
"wp_skin_menu_skin_title": "Izvēlies skinu ierocim: {lime}{0}{default}",
"wp_skin_menu_select": "Tu esi izvēlējies {lime}{0}{default} kā savu skinu"
}

14
lang/pl.json Normal file
View File

@@ -0,0 +1,14 @@
{
"wp_prefix": "{lightblue}[WeaponPaints] {default}",
"wp_info_website": "Odwiedź {lime}{0}{default} gdzie będziesz mógł ustawić skiny",
"wp_info_refresh": "Wpisz {lime}!wp{default} aby zsynchronizować swoje skiny",
"wp_info_knife": "Wpisz {lime}!knife{default} aby wy<77>wietlić menu no<6E>y",
"wp_command_cooldown": "{lightred}Odczekaj chwilę przed wykonaniem tej komendy...",
"wp_command_refresh_done": "{lime}Pomyslnie zsynchronizowano twoje skiny",
"wp_knife_menu_select": "Wybrałeś {lime}{0}{default} jako swój nóż",
"wp_knife_menu_kill": "Do prawidłowego zastosowania noża użyj {lime}!kill{default}",
"wp_knife_menu_title": "Menu noży",
"wp_skin_menu_weapon_title": "Menu broni",
"wp_skin_menu_skin_title": "Wybierz skin dla {lime}{0}{default}",
"wp_skin_menu_select": "Wybrałeś {lime}{0}{default} jako swój skin"
}

14
lang/pt-BR.json Normal file
View File

@@ -0,0 +1,14 @@
{
"wp_prefix": "{lightblue}[WeaponPaints] {default}",
"wp_info_website": "Visite {lime}{0}{default} para mudar suas skins e faca",
"wp_info_refresh": "Digite {lime}!wp{default} para sincronizar as suas skins",
"wp_info_knife": "Digite {lime}!knife{default} para abrir o menu de facas",
"wp_command_cooldown": "{lightred}Você não pode atualizar as skins das armas agora",
"wp_command_refresh_done": "{lime}Sincronizando as suas skins",
"wp_knife_menu_select": "Você escolheu {lime}{0}{default} como sua faca",
"wp_knife_menu_kill": "Para aplicar corretamente a skin da faca, você precisa digitar {lime}!kill{default}",
"wp_knife_menu_title": "Menu de Facas",
"wp_skin_menu_weapon_title": "Menu de Armas",
"wp_skin_menu_skin_title": "Selecionou a skin para {lime}{0}{default}",
"wp_skin_menu_select": "Você escolheu {lime}{0}{default} como sua skin"
}

14
lang/pt-PT.json Normal file
View File

@@ -0,0 +1,14 @@
{
"wp_prefix": "{lightblue}[WeaponPaints] {default}",
"wp_info_website": "Visita {lime}{0}{default} onde podes mudar as tuas skins",
"wp_info_refresh": "Digita {lime}!wp{default} para sincronizar as tuas skins",
"wp_info_knife": "Digita {lime}!knife{default} para abrir o menu de facas",
"wp_command_cooldown": "{lightred}Tu não podes sincronizar agora as tuas skins",
"wp_command_refresh_done": "{lime}Sincronizando as tuas skins",
"wp_knife_menu_select": "Tu escolheste {lime}{0}{default} como a tua faca",
"wp_knife_menu_kill": "Para aplicar corretamente a skins para a tua faca, digita {lime}!kill{default}",
"wp_knife_menu_title": "Menu Facas",
"wp_skin_menu_weapon_title": "Menu de Armas",
"wp_skin_menu_skin_title": "Escolhe a skin para {lime}{0}{default}",
"wp_skin_menu_select": "Tu escolheste {lime}{0}{default} como a tua skin"
}

14
lang/ru.json Normal file
View File

@@ -0,0 +1,14 @@
{
"wp_prefix": "{lightblue}[WeaponPaints] {default}",
"wp_info_website": "Посетите сайт {lime}{0},{default} чтобы выбрать скин",
"wp_info_refresh": "Наберите в чат {lime}!wp{default} для синхронизации выбранных скинов",
"wp_info_knife": "Наберите в чат {lime}!knife,{default} чтобы выбрать нож",
"wp_command_cooldown": "{lightred}Вы не можете выбрать оружие прямо сейчас",
"wp_command_refresh_done": "{lime}Обновление скинов для оружия",
"wp_knife_menu_select": "Вы выбрали {lime}{0}{default} скин для ножа",
"wp_knife_menu_kill": "Чтобы правильно применить скин для ножа, набери в чат {lime}!kill{default}",
"wp_knife_menu_title": "Меню ножей",
"wp_skin_menu_weapon_title": "Меню оружия",
"wp_skin_menu_skin_title": "Выберите скин для {lime}{0}{default}",
"wp_skin_menu_select": "Вы выбрали {lime}{0}{default} скина для оружия"
}

14
lang/tr.json Normal file
View File

@@ -0,0 +1,14 @@
{
"wp_prefix": "{lightblue}[WeaponPaints] {default}",
"wp_info_website": "Görünümleri değiştirebileceğiniz {lime}{0}{default} adresini ziyaret edin",
"wp_info_refresh": "Seçilen kaplamyı senkronize etmek için {lime}!wp{default} yazın",
"wp_info_knife": "Bıçak menüsünü açmak için {lime}!knife{default} yazın",
"wp_command_cooldown": "{lightred}Şu anda silah kaplamasını yenileyemezsiniz",
"wp_command_refresh_done": "{lime}Silah kaplaması yenileniyor",
"wp_knife_menu_select": "Bıçağınız olarak {lime}{0}{default} seçtiniz",
"wp_knife_menu_kill": "Bıçak için doğru şekilde kaplama uygulamak için {lime}!kill{default} yazmanız gerekir",
"wp_knife_menu_title": "Bıçak Menüsü",
"wp_skin_menu_weapon_title": "Silah Menüsü",
"wp_skin_menu_skin_title": "Select skin for {lime}{0}{default}",
"wp_skin_menu_select": "Teniniz olarak {lime}{0}{default} seçtiniz"
}

14
lang/zh-cn.json Normal file
View File

@@ -0,0 +1,14 @@
{
"wp_prefix": "{lightblue}[武器皮肤] {default}",
"wp_info_website": "在线访问 {lime}{0}{default} 更改你的武器皮肤",
"wp_info_refresh": "输入 {lime}!wp{default} 进行在线皮肤同步",
"wp_info_knife": "输入 {lime}!knife{default} 打开刀菜单",
"wp_command_cooldown": "{lightred}皮肤同步刷新冷却中",
"wp_command_refresh_done": "{lime}刷新武器皮肤中",
"wp_knife_menu_select": "你选择了 {lime}{0}{default} 作为你的刀",
"wp_knife_menu_kill": "如需完全应用皮肤到刀上, 你需要输入 {lime}!kill{default} 自杀来进行刷新",
"wp_knife_menu_title": "刀菜单",
"wp_skin_menu_weapon_title": "武器菜单",
"wp_skin_menu_skin_title": "选择 {lime}{0}{default} 的皮肤",
"wp_skin_menu_select": "你选择了 {lime}{0}{default} 作为你的皮肤"
}

View File

@@ -5,6 +5,8 @@ define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASS', '');
define('WEB_STYLE_DARK', true);
define('STEAM_API_KEY', '');
define('STEAM_DOMAIN_NAME', '');
define('STEAM_LOGOUT_PAGE', '');

View File

@@ -1,73 +0,0 @@
<?php
$weapons = array (
"weapon_deagle" => 1,
"weapon_elite" => 2,
"weapon_fiveseven" => 3,
"weapon_glock" => 4,
"weapon_ak47" => 7,
"weapon_aug" => 8,
"weapon_awp" => 9,
"weapon_famas" => 10,
"weapon_g3sg1" => 10,
"weapon_galilar" => 13,
"weapon_m249" => 14,
"weapon_m4a1" => 16,
"weapon_mac10" => 17,
"weapon_p90" => 19,
"weapon_mp5sd" => 23,
"weapon_ump45" => 24,
"weapon_xm1014" => 25,
"weapon_bizon" => 26,
"weapon_mag7" => 27,
"weapon_negev" => 28,
"weapon_sawedoff" => 29,
"weapon_tec9" => 30,
"weapon_hkp2000" => 32,
"weapon_mp7" => 33,
"weapon_mp9" => 34,
"weapon_nova" => 35,
"weapon_p250" => 36,
"weapon_scar20" => 38,
"weapon_sg556" => 39,
"weapon_ssg08" => 40,
"weapon_m4a1_silencer" => 60,
"weapon_usp_silencer" => 61,
"weapon_cz75a" => 63,
"weapon_revolver" => 64,
"weapon_bayonet" => 500,
"weapon_knife_css" => 503,
"weapon_knife_flip" => 505,
"weapon_knife_gut" => 506,
"weapon_knife_karambit" => 507,
"weapon_knife_m9_bayonet" => 508,
"weapon_knife_tactical" => 509,
"weapon_knife_falchion" => 512,
"weapon_knife_survival_bowie"=> 514,
"weapon_knife_butterfly" => 515,
"weapon_knife_push" => 516,
"weapon_knife_cord" => 517,
"weapon_knife_canis" => 518,
"weapon_knife_ursus" => 519,
"weapon_knife_gypsy_jackknife" => 520,
"weapon_knife_outdoor" => 521,
"weapon_knife_stiletto" => 522,
"weapon_knife_widowmaker" => 523,
"weapon_knife_skeleton" => 525);
$json = json_decode(file_get_contents('skins.json'));
echo "<pre>";
foreach($json as $skin)
{
if(!str_contains($skin->weapon->id, "weapon_")) continue;
$name = $skin->name;
$name = str_replace("'","\'",$name);
$weapon = $skin->weapon->id;
$image = $skin->image;
$paint = $skin->paint_index;
echo "('{$weapon}', {$weapons[$weapon]}, {$paint}, '{$image}', '{$name}')";
echo ",<br>";
}
//print_r($json);
echo "</pre>";
?>

View File

@@ -4,14 +4,15 @@ require_once 'class/database.php';
require_once 'steamauth/steamauth.php';
require_once 'class/utils.php';
$db = new DataBase();
if (isset($_SESSION['steamid'])) {
$steamid = $_SESSION['steamid'];
include('steamauth/userInfo.php');
$steamid = $steamprofile['steamid'];
$weapons = UtilsClass::getWeaponsFromArray();
$skins = UtilsClass::skinsFromJson();
$querySelected = $query3 = $db->select("SELECT `weapon_defindex`, `weapon_paint_id` FROM `wp_player_skins` WHERE `wp_player_skins`.`steamid` = :steamid", ["steamid" => $steamid]);
$querySelected = $query3 = $db->select("SELECT `weapon_defindex`, `weapon_paint_id`, `weapon_wear` FROM `wp_player_skins` WHERE `wp_player_skins`.`steamid` = :steamid", ["steamid" => $steamid]);
$selectedSkins = UtilsClass::getSelectedSkins($querySelected);
$selectedKnife = $db->select("SELECT * FROM `wp_player_knife` WHERE `wp_player_knife`.`steamid` = :steamid", ["steamid" => $steamid])[0];
$knifes = UtilsClass::getKnifeTypes();
@@ -22,31 +23,30 @@ if (isset($_SESSION['steamid'])) {
if ($ex[0] == "knife") {
$db->query("INSERT INTO `wp_player_knife` (`steamid`, `knife`) VALUES(:steamid, :knife) ON DUPLICATE KEY UPDATE `knife` = :knife", ["steamid" => $steamid, "knife" => $knifes[$ex[1]]['weapon_name']]);
} else {
if (!is_int($ex[1]))
header("Location: index.php");
if (array_key_exists($ex[1], $skins[$ex[0]])) {
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
if (array_key_exists($ex[0], $selectedSkins)) {
$db->query("UPDATE wp_player_skins SET weapon_paint_id = :weapon_paint_id WHERE steamid = :steamid AND weapon_defindex = :weapon_defindex", ["steamid" => $steamid, "weapon_defindex" => $ex[0], "weapon_paint_id" => $ex[1]]);
$db->query("UPDATE wp_player_skins SET weapon_paint_id = :weapon_paint_id, weapon_wear = :weapon_wear, weapon_seed = :weapon_seed WHERE steamid = :steamid AND weapon_defindex = :weapon_defindex", ["steamid" => $steamid, "weapon_defindex" => $ex[0], "weapon_paint_id" => $ex[1], "weapon_wear" => $wear, "weapon_seed" => $seed]);
} else {
$db->query("INSERT INTO wp_player_skins (`steamid`, `weapon_defindex`, `weapon_paint_id`) VALUES (:steamid, :weapon_defindex, :weapon_paint_id)", ["steamid" => $steamid, "weapon_defindex" => $ex[0], "weapon_paint_id" => $ex[1]]);
$db->query("INSERT INTO wp_player_skins (`steamid`, `weapon_defindex`, `weapon_paint_id`, `weapon_wear`, `weapon_seed`) VALUES (:steamid, :weapon_defindex, :weapon_paint_id, :weapon_wear, :weapon_seed)", ["steamid" => $steamid, "weapon_defindex" => $ex[0], "weapon_paint_id" => $ex[1], "weapon_wear" => $wear, "weapon_seed" => $seed]);
}
}
}
header("Location: index.php");
header("Location: {$_SERVER['PHP_SELF']}");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<html lang="en"<?php if(WEB_STYLE_DARK) echo 'data-bs-theme="dark"'?>>
<head>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style.css">
<title>CS2 Simple Weapon Paints</title>
</head>
@@ -59,9 +59,9 @@ if (isset($_SESSION['steamid'])) {
loginbutton("rectangle");
echo "</h2></div>";
} else {
echo "<div class='bg-primary'>Your current weapon skin loadout<form action='' method='get'><button class='btn btn-secondary' name='logout' type='submit'>Logout</button></form></div>";
echo "<div class='bg-primary'><h2>Your current weapon skin loadout <a class='btn btn-danger' href='{$_SERVER['PHP_SELF']}?logout'>Logout</a></h2> </div>";
echo "<div class='card-group mt-2'>";
?>
?>
<div class="col-sm-2">
<div class="card text-center mb-3 border border-primary">
@@ -132,14 +132,132 @@ if (isset($_SESSION['steamid'])) {
}
?>
</select>
</form>
<br></br>
<?php
$selectedSkinInfo = isset($selectedSkins[$defindex]) ? $selectedSkins[$defindex] : null;
$steamid = $_SESSION['steamid'];
$defindex = $defindex; // get defindex here, correct if not
$queryCheck = $db->select("SELECT 1 FROM `wp_player_skins` WHERE `steamid` = :steamid AND `weapon_defindex` = :defindex", ["steamid" => $steamid, "defindex" => $defindex]);
$hasSkinData = !empty($queryCheck);
if ($selectedSkinInfo && $hasSkinData) :
?>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#weaponModal<?php echo $defindex ?>">
Settings
</button>
<?php else : ?>
<button type="button" class="btn btn-primary" onclick="showSkinSelectionAlert()">
Settings
</button>
<script>
function showSkinSelectionAlert() {
alert("You need to select a skin first.");
}
</script>
<?php endif; ?>
</div>
<?php
// wear value
$queryWear = $db->select("SELECT `weapon_wear` FROM `wp_player_skins` WHERE `steamid` = :steamid AND `weapon_defindex` = :weapon_defindex", ["steamid" => $steamid, "weapon_defindex" => $defindex]);
$selectedSkinInfo = isset($selectedSkins[$defindex]) ? $selectedSkins[$defindex] : null;
$initialWearValue = isset($selectedSkinInfo['weapon_wear']) ? $selectedSkinInfo['weapon_wear'] : (isset($queryWear[0]['weapon_wear']) ? $queryWear[0]['weapon_wear'] : 0);
// seed value
$querySeed = $db->select("SELECT `weapon_seed` FROM `wp_player_skins` WHERE `steamid` = :steamid AND `weapon_defindex` = :weapon_defindex", ["steamid" => $steamid, "weapon_defindex" => $defindex]);
$selectedSkinInfo = isset($selectedSkins[$defindex]) ? $selectedSkins[$defindex] : null;
$initialSeedValue = isset($selectedSkinInfo['weapon_seed']) ? $selectedSkinInfo['weapon_seed'] : (isset($querySeed[0]['weapon_seed']) ? $querySeed[0]['weapon_seed'] : 0);
?>
<div class="modal fade" id="weaponModal<?php echo $defindex ?>" tabindex="-1" role="dialog" aria-labelledby="weaponModalLabel<?php echo $defindex ?>" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class='card-title item-name'>
<?php
if (array_key_exists($defindex, $selectedSkins)) {
echo "{$skins[$defindex][$selectedSkins[$defindex]]["paint_name"]} Settings";
} else {
echo "{$default["paint_name"]} Settings";
}
?>
</h5>
</div>
<div class="modal-body">
<div class="form-group">
<select class="form-select" id="wearSelect<?php echo $defindex ?>" name="wearSelect" onchange="updateWearValue<?php echo $defindex ?>(this.value)">
<option disabled>Select Wear</option>
<option value="0.00" <?php echo ($initialWearValue == 0.00) ? 'selected' : ''; ?>>Factory New</option>
<option value="0.07" <?php echo ($initialWearValue == 0.07) ? 'selected' : ''; ?>>Minimal Wear</option>
<option value="0.15" <?php echo ($initialWearValue == 0.15) ? 'selected' : ''; ?>>Field-Tested</option>
<option value="0.38" <?php echo ($initialWearValue == 0.38) ? 'selected' : ''; ?>>Well-Worn</option>
<option value="0.45" <?php echo ($initialWearValue == 0.45) ? 'selected' : ''; ?>>Battle-Scarred</option>
</select>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="wear">Wear:</label>
<input type="text" value="<?php echo $initialWearValue; ?>" class="form-control" id="wear<?php echo $defindex ?>" name="wear">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="seed">Seed:</label>
<input type="text" value="<?php echo $initialSeedValue; ?>" class="form-control" id="seed<?php echo $defindex ?>" name="seed" oninput="validateSeed(this)">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger">Use</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
// wear
function updateWearValue<?php echo $defindex ?>(selectedValue) {
var wearInputElement = document.getElementById("wear<?php echo $defindex ?>");
wearInputElement.value = selectedValue;
}
function validateWear(inputElement) {
inputElement.value = inputElement.value.replace(/[^0-9]/g, '');
}
// seed
function validateSeed(input) {
// Check entered value
var inputValue = input.value.replace(/[^0-9]/g, ''); // Just get the numbers
if (inputValue === "") {
input.value = 0; // Set to 0 if empty or no numbers
} else {
var numericValue = parseInt(inputValue);
numericValue = Math.min(1000, Math.max(1, numericValue)); // Interval control
input.value = numericValue;
}
}
</script>
<?php } ?>
<?php } ?>
</div>
</div>
<div class="container">
<footer class="d-flex flex-wrap justify-content-between align-items-center py-3 my-4 border-top">
<div class="col-md-4 d-flex align-items-center">
<span class="mb-3 mb-md-0 text-body-secondary">© 2023 <a href="https://github.com/Nereziel/cs2-WeaponPaints">Nereziel/cs2-WeaponPaints</a></span>
</div>
</footer>
</div>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

After

Width:  |  Height:  |  Size: 126 KiB