Skip to content

Commit

Permalink
Merge pull request #231 from daffyyyy/main
Browse files Browse the repository at this point in the history
2.4a
  • Loading branch information
daffyyyy authored Apr 2, 2024
2 parents f99c9b2 + d6de0ce commit 36046fe
Show file tree
Hide file tree
Showing 9 changed files with 110 additions and 111 deletions.
3 changes: 3 additions & 0 deletions Commands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ private void OnCommandRefresh(CCSPlayerController? player, CommandInfo command)

if (weaponSync != null)
{
_ = Task.Run(async () => await weaponSync.GetPlayerData(playerInfo));
/*
if (Config.Additional.SkinEnabled)
{
_ = Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo));
Expand All @@ -53,6 +55,7 @@ private void OnCommandRefresh(CCSPlayerController? player, CommandInfo command)
{
_ = Task.Run(async () => await weaponSync.GetMusicFromDatabase(playerInfo));
}
*/

RefreshGloves(player);
RefreshWeapons(player);
Expand Down
14 changes: 10 additions & 4 deletions Events.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ public HookResult OnClientFullConnect(EventPlayerConnectFull @event, GameEventIn

try
{
_ = Task.Run(async () => await weaponSync.GetPlayerData(playerInfo));
/*
if (Config.Additional.SkinEnabled)
{
_ = Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo));
Expand All @@ -47,6 +49,7 @@ public HookResult OnClientFullConnect(EventPlayerConnectFull @event, GameEventIn
{
_ = Task.Run(async () => await weaponSync.GetMusicFromDatabase(playerInfo));
}
*/
}
catch (Exception)
{
Expand Down Expand Up @@ -102,7 +105,6 @@ public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo
private void GivePlayerWeaponSkin(CCSPlayerController player, CBasePlayerWeapon weapon)
{
if (!Config.Additional.SkinEnabled) return;
if (player is null || weapon is null || !weapon.IsValid || !Utility.IsPlayerValid(player)) return;
if (!gPlayerWeaponsInfo.ContainsKey(player.Slot)) return;

bool isKnife = weapon.DesignerName.Contains("knife") || weapon.DesignerName.Contains("bayonet");
Expand Down Expand Up @@ -214,6 +216,7 @@ private HookResult OnPlayerSpawn(EventPlayerSpawn @event, GameEventInfo info)

GivePlayerMusicKit(player);
GivePlayerAgent(player);

Server.NextFrame(() =>
{
RefreshGloves(player);
Expand Down Expand Up @@ -266,7 +269,7 @@ public void OnEntitySpawned(CEntityInstance entity)
Server.NextFrame(() =>
{
var weapon = new CBasePlayerWeapon(entity.Handle);
if (weapon == null || !weapon.IsValid || weapon.OwnerEntity.Value == null) return;
if (weapon == null || !weapon.IsValid) return;

try
{
Expand Down Expand Up @@ -326,10 +329,13 @@ private void RegisterListeners()
RegisterListener<Listeners.OnMapStart>(OnMapStart);

RegisterEventHandler<EventPlayerSpawn>(OnPlayerSpawn);
RegisterEventHandler<EventRoundStart>(OnRoundStart, HookMode.Pre);
RegisterEventHandler<EventRoundStart>(OnRoundStart);
RegisterEventHandler<EventRoundEnd>(OnRoundEnd);
RegisterListener<Listeners.OnEntitySpawned>(OnEntitySpawned);
RegisterListener<Listeners.OnTick>(OnTick);

if (Config.Additional.ShowSkinImage)
RegisterListener<Listeners.OnTick>(OnTick);

//VirtualFunctions.GiveNamedItemFunc.Hook(OnGiveNamedItemPost, HookMode.Post);
}
}
Expand Down
1 change: 1 addition & 0 deletions PlayerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public static class PlayerExtensions
public static void Print(this CCSPlayerController controller, string message)
{
if (WeaponPaints._localizer == null) return;

StringBuilder _message = new(WeaponPaints._localizer["wp_prefix"]);
_message.Append(message);
controller.PrintToChat(_message.ToString());
Expand Down
125 changes: 44 additions & 81 deletions Utility.cs
Original file line number Diff line number Diff line change
@@ -1,34 +1,16 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Translations;
using Dapper;
using Microsoft.Extensions.Logging;
using MySqlConnector;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection;

namespace WeaponPaints
{
internal static class Utility
{
internal static WeaponPaintsConfig? Config { get; set; }

internal static string BuildDatabaseConnectionString()
{
if (Config == null) return string.Empty;
var builder = new MySqlConnectionStringBuilder
{
Server = Config.DatabaseHost,
UserID = Config.DatabaseUser,
Password = Config.DatabasePassword,
Database = Config.DatabaseName,
Port = (uint)Config.DatabasePort,
Pooling = true
};

return builder.ConnectionString;
}

internal static async Task CheckDatabaseTables()
{
if (WeaponPaints._database is null) return;
Expand All @@ -41,37 +23,37 @@ internal static async Task CheckDatabaseTables()

try
{
string[] createTableQueries = new[]
{
string[] createTableQueries =
[
@"CREATE TABLE IF NOT EXISTS `wp_player_skins` (
`steamid` varchar(18) 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",
@"CREATE TABLE IF NOT EXISTS `wp_player_knife` (
@"CREATE TABLE IF NOT EXISTS `wp_player_knife` (
`steamid` varchar(18) NOT NULL,
`knife` varchar(64) NOT NULL,
UNIQUE (`steamid`)
) ENGINE = InnoDB",
@"CREATE TABLE IF NOT EXISTS `wp_player_gloves` (
@"CREATE TABLE IF NOT EXISTS `wp_player_gloves` (
`steamid` varchar(18) NOT NULL,
`weapon_defindex` int(11) NOT NULL,
UNIQUE (`steamid`)
) ENGINE=InnoDB",
@"CREATE TABLE IF NOT EXISTS `wp_player_agents` (
@"CREATE TABLE IF NOT EXISTS `wp_player_agents` (
`steamid` varchar(18) NOT NULL,
`agent_ct` varchar(64) DEFAULT NULL,
`agent_t` varchar(64) DEFAULT NULL,
UNIQUE (`steamid`)
) ENGINE=InnoDB",
@"CREATE TABLE IF NOT EXISTS `wp_player_music` (
@"CREATE TABLE IF NOT EXISTS `wp_player_music` (
`steamid` varchar(64) NOT NULL,
`music_id` int(11) NOT NULL,
UNIQUE (`steamid`)
) ENGINE=InnoDB",
};
];

foreach (var query in createTableQueries)
{
Expand Down Expand Up @@ -99,7 +81,7 @@ internal static bool IsPlayerValid(CCSPlayerController? player)
return (player.IsValid && !player.IsBot && !player.IsHLTV && player.UserId.HasValue);
}

internal static void LoadSkinsFromFile(string filePath)
internal static void LoadSkinsFromFile(string filePath, ILogger logger)
{
try
{
Expand All @@ -109,11 +91,11 @@ internal static void LoadSkinsFromFile(string filePath)
}
catch (FileNotFoundException)
{
throw;
logger?.LogError("Not found \"skins.json\" file");
}
}

internal static void LoadGlovesFromFile(string filePath)
internal static void LoadGlovesFromFile(string filePath, ILogger logger)
{
try
{
Expand All @@ -123,11 +105,11 @@ internal static void LoadGlovesFromFile(string filePath)
}
catch (FileNotFoundException)
{
throw;
logger?.LogError("Not found \"gloves.json\" file");
}
}

internal static void LoadAgentsFromFile(string filePath)
internal static void LoadAgentsFromFile(string filePath, ILogger logger)
{
try
{
Expand All @@ -137,11 +119,11 @@ internal static void LoadAgentsFromFile(string filePath)
}
catch (FileNotFoundException)
{
throw;
logger?.LogError("Not found \"agents.json\" file");
}
}

internal static void LoadMusicFromFile(string filePath)
internal static void LoadMusicFromFile(string filePath, ILogger logger)
{
try
{
Expand All @@ -151,7 +133,7 @@ internal static void LoadMusicFromFile(string filePath)
}
catch (FileNotFoundException)
{
throw;
logger?.LogError("Not found \"music.json\" file");
}
}

Expand All @@ -165,69 +147,50 @@ internal static void Log(string message)

internal static string ReplaceTags(string message)
{
if (message.Contains('{'))
{
string modifiedValue = message;
if (Config != null)
{
modifiedValue = modifiedValue.Replace("{WEBSITE}", Config.Website);
}
foreach (FieldInfo field in typeof(ChatColors).GetFields())
{
string pattern = $"{{{field.Name}}}";
if (message.Contains(pattern, StringComparison.OrdinalIgnoreCase))
{
modifiedValue = modifiedValue.Replace(pattern, field.GetValue(null)!.ToString(), StringComparison.OrdinalIgnoreCase);
}
}
return modifiedValue;
}

return message;
return message.ReplaceColorTags();
}

internal static async Task CheckVersion(string version, ILogger logger)
{
using (HttpClient client = new HttpClient())
using HttpClient client = new();

try
{
try
HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION").ConfigureAwait(false);

if (response.IsSuccessStatusCode)
{
HttpResponseMessage response = await client.GetAsync("https://raw.githubusercontent.com/Nereziel/cs2-WeaponPaints/main/VERSION").ConfigureAwait(false);
string remoteVersion = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
remoteVersion = remoteVersion.Trim();

if (response.IsSuccessStatusCode)
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)
{
string remoteVersion = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
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");
}
logger.LogInformation("Probably dev version detected");
}
else
{
logger.LogWarning("Failed to check version");
logger.LogInformation("Plugin is up to date");
}
}
catch (HttpRequestException ex)
else
{
logger.LogError(ex, "Failed to connect to the version server.");
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred while checking version.");
logger.LogWarning("Failed to check version");
}
}
catch (HttpRequestException ex)
{
logger.LogError(ex, "Failed to connect to the version server.");
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred while checking version.");
}
}

internal static void ShowAd(string moduleVersion)
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.3c
2.4a
2 changes: 1 addition & 1 deletion WeaponAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal static void GiveKnifeToPlayer(CCSPlayerController? player)

if (PlayerHasKnife(player)) return;

string knifeToGive = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife";
//string knifeToGive = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife";
player.GiveNamedItem(CsItem.Knife);
}

Expand Down
16 changes: 10 additions & 6 deletions WeaponPaints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

namespace WeaponPaints;

[MinimumApiVersion(195)]
[MinimumApiVersion(201)]
public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig>
{
internal static WeaponPaints Instance { get; private set; } = new();
Expand Down Expand Up @@ -160,7 +160,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
public override string ModuleAuthor => "Nereziel & daffyy";
public override string ModuleDescription => "Skin, gloves, agents and knife selector, standalone and web-based";
public override string ModuleName => "WeaponPaints";
public override string ModuleVersion => "2.3c";
public override string ModuleVersion => "2.4a";

public static WeaponPaintsConfig GetWeaponPaintsConfig()
{
Expand Down Expand Up @@ -200,6 +200,9 @@ public override void Load(bool hotReload)
IpAddress = player?.IpAddress?.Split(":")[0]
};

_ = Task.Run(async () => await weaponSync.GetPlayerData(playerInfo));

/*
if (Config.Additional.SkinEnabled)
{
_ = Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo));
Expand All @@ -220,13 +223,14 @@ public override void Load(bool hotReload)
{
_ = Task.Run(async () => await weaponSync.GetMusicFromDatabase(playerInfo));
}
*/
}
}

Utility.LoadSkinsFromFile(ModuleDirectory + "/skins.json");
Utility.LoadGlovesFromFile(ModuleDirectory + "/gloves.json");
Utility.LoadAgentsFromFile(ModuleDirectory + "/agents.json");
Utility.LoadMusicFromFile(ModuleDirectory + "/music.json");
Utility.LoadSkinsFromFile(ModuleDirectory + "/skins.json", Logger);
Utility.LoadGlovesFromFile(ModuleDirectory + "/gloves.json", Logger);
Utility.LoadAgentsFromFile(ModuleDirectory + "/agents.json", Logger);
Utility.LoadMusicFromFile(ModuleDirectory + "/music.json", Logger);

if (Config.Additional.KnifeEnabled)
SetupKnifeMenu();
Expand Down
Loading

0 comments on commit 36046fe

Please sign in to comment.