Skip to content
This repository has been archived by the owner on Oct 22, 2024. It is now read-only.

Commit

Permalink
Patch v4.3.0
Browse files Browse the repository at this point in the history
  • Loading branch information
K4ryuu committed May 16, 2024
1 parent 1fde50a commit b04c61f
Show file tree
Hide file tree
Showing 18 changed files with 218 additions and 114 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
-- 2023.05.16 - V4.3.0

- feat: Added connect and disconnect messages with variables (if you need some other variable let me know)
- fix: Add current points to round summary
- fix: Error log on round start because of team balance
- fix: Enumeration problems on getting k4players
- fix: AutoTeamBalance error logs
- remove: Removed round summary translations. Now the regular gain/loss is used instead
- remove: CallbackAnonymizer removed since that bug was fixed in CSS
- remove: Debug logs on fetch

-- 2023.05.11 - V4.2.1

- fix: Toplist placements is now fetched every 5 minutes instead of the mistake 5 seconds
Expand Down
1 change: 1 addition & 0 deletions K4-SharedApi/src/K4-SharedApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace K4SharedApi
{
public interface IPlayerAPI
{
int TopPlacement { get; }
bool IsLoaded { get; }
bool IsValid { get; }
bool IsPlayer { get; }
Expand Down
Binary file modified K4-SharedApi/src/K4-SharedApi.dll
Binary file not shown.
1 change: 0 additions & 1 deletion K4-System/src/Module/Interfaces/IModuleRank.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using CounterStrikeSharp.API.Core;
using static K4System.ModuleRank;

namespace K4System;
Expand Down
26 changes: 8 additions & 18 deletions K4-System/src/Module/Rank/RankCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,25 @@ public void Initialize_Commands()

commands.RankCommands.ForEach(commandString =>
{
plugin.AddCommand($"css_{commandString}", "Check the current rank and points", plugin.CallbackAnonymizer(OnCommandRank));
plugin.AddCommand($"css_{commandString}", "Check the current rank and points", OnCommandRank);
});

commands.RanksCommands.ForEach(commandString =>
{
plugin.AddCommand($"css_{commandString}", "Check the available ranks and their data", plugin.CallbackAnonymizer(OnCommandRanks));
plugin.AddCommand($"css_{commandString}", "Check the available ranks and their data", OnCommandRanks);
});

commands.TopCommands.ForEach(commandString =>
{
plugin.AddCommand($"css_{commandString}", "Check the top players by points", plugin.CallbackAnonymizer(OnCommandTop));
plugin.AddCommand($"css_{commandString}", "Check the top players by points", OnCommandTop);
});


plugin.AddCommand("css_setpoints", "SEt the targeted player's points", plugin.CallbackAnonymizer(OnCommandSetPoints));
plugin.AddCommand("css_givepoints", "Give points the targeted player", plugin.CallbackAnonymizer(OnCommandGivePoints));
plugin.AddCommand("css_removepoints", "Remove points from the targeted player", plugin.CallbackAnonymizer(OnCommandRemovePoints));
plugin.AddCommand("css_toggletag", "Toggles the tag assigned by permissions", plugin.CallbackAnonymizer(OnCommandToggleTag));
plugin.AddCommand("css_togglepointmsg", "Toggles the chat messages of points modifications", plugin.CallbackAnonymizer(OnCommandTogglePointMessages));
plugin.AddCommand("css_setpoints", "SEt the targeted player's points", OnCommandSetPoints);
plugin.AddCommand("css_givepoints", "Give points the targeted player", OnCommandGivePoints);
plugin.AddCommand("css_removepoints", "Remove points from the targeted player", OnCommandRemovePoints);
plugin.AddCommand("css_toggletag", "Toggles the tag assigned by permissions", OnCommandToggleTag);
plugin.AddCommand("css_togglepointmsg", "Toggles the chat messages of points modifications", OnCommandTogglePointMessages);
}

public void OnCommandTogglePointMessages(CCSPlayerController? player, CommandInfo info)
Expand Down Expand Up @@ -202,25 +202,15 @@ public void OnCommandTop(CCSPlayerController? player, CommandInfo info)

Task.Run(async () =>
{
Console.WriteLine("Saving all players data");
await plugin.SaveAllPlayersDataAsync();
Console.WriteLine("Fetching top data");
List<(int points, string name)>? rankData = await FetchTopDataAsync(printCount);
Console.WriteLine("Fetched top data, waiting tick to print to chat.");
Server.NextFrame(() =>
{
Console.WriteLine("Printing top data to chat.");
if (!k4player.IsValid || !k4player.IsPlayer)
return;
Console.WriteLine("Player is valid and is player.");
if (rankData?.Count > 0)
{
for (int i = 0; i < rankData.Count; i++)
Expand Down
69 changes: 43 additions & 26 deletions K4-System/src/Module/Rank/RankEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace K4System
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using K4System.Models;
using Microsoft.Extensions.Logging;

public partial class ModuleRank : IModuleRank
{
Expand Down Expand Up @@ -152,47 +153,63 @@ public void Initialize_Events()

plugin.RegisterEventHandler((EventRoundPrestart @event, GameEventInfo info) =>
{
if (Config.RankSettings.RankBasedTeamBalance)
try
{
int team1Size = plugin.K4Players.Count(p => p.Controller.Team == CsTeam.Terrorist);
int team2Size = plugin.K4Players.Count(p => p.Controller.Team == CsTeam.CounterTerrorist);
if (Math.Abs(team1Size - team2Size) > 1)
if (Config.RankSettings.RankBasedTeamBalance)
{
var team1Players = plugin.K4Players.Where(p => p.Controller.Team == CsTeam.Terrorist).ToList();
var team2Players = plugin.K4Players.Where(p => p.Controller.Team == CsTeam.CounterTerrorist).ToList();
List<K4Player> players = plugin.K4Players.Where(p => p.IsValid && p.IsPlayer).ToList();
var team1RankPoints = team1Players.Select(p => p.rankData?.Points ?? 0).Sum();
var team2RankPoints = team2Players.Select(p => p.rankData?.Points ?? 0).Sum();
int team1Size = players.Count(p => p?.Controller?.Team == CsTeam.Terrorist);
int team2Size = players.Count(p => p?.Controller?.Team == CsTeam.CounterTerrorist);
while (Math.Abs(team1RankPoints - team2RankPoints) > Config.RankSettings.RankBasedTeamBalanceMaxDifference)
if (Math.Abs(team1Size - team2Size) > 1)
{
if (team1RankPoints > team2RankPoints)
{
var playerToSwitch = team1Players.OrderByDescending(p => p.rankData?.Points ?? 0).First();
team1Players.Remove(playerToSwitch);
team2Players.Add(playerToSwitch);
playerToSwitch.Controller.ChangeTeam(CsTeam.CounterTerrorist);
}
else
var team1Players = players.Where(p => p?.Controller?.Team == CsTeam.Terrorist).ToList();
var team2Players = players.Where(p => p?.Controller?.Team == CsTeam.CounterTerrorist).ToList();
var team1RankPoints = team1Players.Select(p => p?.rankData?.Points ?? 0).Sum();
var team2RankPoints = team2Players.Select(p => p?.rankData?.Points ?? 0).Sum();
while (Math.Abs(team1RankPoints - team2RankPoints) > Config.RankSettings.RankBasedTeamBalanceMaxDifference)
{
var playerToSwitch = team2Players.OrderByDescending(p => p.rankData?.Points ?? 0).First();
team2Players.Remove(playerToSwitch);
team1Players.Add(playerToSwitch);
playerToSwitch.Controller.ChangeTeam(CsTeam.Terrorist);
if (team1RankPoints > team2RankPoints)
{
var playerToSwitch = team1Players.OrderByDescending(p => p?.rankData?.Points ?? 0).FirstOrDefault();
if (playerToSwitch != null)
{
team1Players.Remove(playerToSwitch);
team2Players.Add(playerToSwitch);
playerToSwitch.Controller?.ChangeTeam(CsTeam.CounterTerrorist);
}
}
else
{
var playerToSwitch = team2Players.OrderByDescending(p => p?.rankData?.Points ?? 0).FirstOrDefault();
if (playerToSwitch != null)
{
team2Players.Remove(playerToSwitch);
team1Players.Add(playerToSwitch);
playerToSwitch.Controller?.ChangeTeam(CsTeam.Terrorist);
}
}
team1RankPoints = team1Players.Select(p => p?.rankData?.Points ?? 0).Sum();
team2RankPoints = team2Players.Select(p => p?.rankData?.Points ?? 0).Sum();
}
team1RankPoints = team1Players.Select(p => p.rankData?.Points ?? 0).Sum();
team2RankPoints = team2Players.Select(p => p.rankData?.Points ?? 0).Sum();
Server.PrintToChatAll($" {plugin.Localizer["k4.general.prefix"]} {plugin.Localizer["k4.ranks.rank.teamsbalanced"]}");
}
Server.PrintToChatAll($" {plugin.Localizer["k4.general.prefix"]} {plugin.Localizer["k4.ranks.rank.teamsbalanced"]}");
}
}
catch (Exception ex)
{
plugin.Logger.LogError($"Error balancing teams: {ex.Message}\n{ex.StackTrace}");
}
return HookResult.Continue;
}, HookMode.Post);


plugin.RegisterEventHandler((EventBombPlanted @event, GameEventInfo info) =>
{
ModifyPlayerPointsConnector(@event.Userid, Config.PointSettings.BombPlant, "k4.phrases.bombplanted");
Expand Down
51 changes: 3 additions & 48 deletions K4-System/src/Module/Rank/RankFunctions.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
namespace K4System
{
using MySqlConnector;

using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Admin;
using CounterStrikeSharp.API.Modules.Utils;
using Microsoft.Extensions.Logging;
using System.Data;
using K4SharedApi;
using K4System.Models;
using Dapper;
using MaxMind.GeoIP2;
using MaxMind.GeoIP2.Exceptions;

public partial class ModuleRank : IModuleRank
{
Expand Down Expand Up @@ -66,14 +60,12 @@ public void BeforeRoundEnd(int winnerTeam)
{
if (playerData.RoundPoints > 0)
{
k4player.Controller.PrintToChat($" {plugin.Localizer["k4.general.prefix"]} {plugin.Localizer["k4.ranks.summarypoints.gain", playerData.RoundPoints]}");
k4player.Controller.PrintToChat($" {plugin.Localizer["k4.general.prefix"]} {plugin.Localizer["k4.ranks.points.gain", playerData.Points, playerData.RoundPoints, plugin.Localizer["k4.phrases.roundsummary"]]}");
}
else if (playerData.RoundPoints < 0)
{
k4player.Controller.PrintToChat($" {plugin.Localizer["k4.general.prefix"]} {plugin.Localizer["k4.ranks.summarypoints.loss", Math.Abs(playerData.RoundPoints)]}");
k4player.Controller.PrintToChat($" {plugin.Localizer["k4.general.prefix"]} {plugin.Localizer["k4.ranks.points.loss", playerData.Points, Math.Abs(playerData.RoundPoints), plugin.Localizer["k4.phrases.roundsummary"]]}");
}
else
k4player.Controller.PrintToChat($" {plugin.Localizer["k4.general.prefix"]} {plugin.Localizer["k4.ranks.summarypoints.nochange"]}");
}

playerData.RoundPoints = 0;
Expand Down Expand Up @@ -274,49 +266,12 @@ public void SetPlayerClanTag(K4Player k4player)

if (Config.RankSettings.CountryTagEnabled)
{
string countryTag = GetPlayerCountryCode(k4player.Controller);
string countryTag = plugin.GetPlayerCountryCode(k4player.Controller);
tag = tag.Length > 0 ? $"{countryTag} | {tag}" : countryTag;
}

if (tag.Length > 0)
k4player.ClanTag = tag;
}

public string GetPlayerCountryCode(CCSPlayerController player)
{
string? playerIp = player.IpAddress;

if (playerIp == null)
return "??";

string[] parts = playerIp.Split(':');
string realIP = parts.Length == 2 ? parts[0] : playerIp;

string filePath = Path.Combine(plugin.ModuleDirectory, "GeoLite2-Country.mmdb");
if (!File.Exists(filePath))
{
Logger.LogError($"GeoLite2-Country.mmdb not found in {filePath}. Download it from https://github.com/P3TERX/GeoLite.mmdb/releases and place it in the same directory as the plugin.");
return "??";
}

using (DatabaseReader reader = new DatabaseReader(filePath))
{
try
{
MaxMind.GeoIP2.Responses.CountryResponse response = reader.Country(realIP);
return response.Country.IsoCode ?? "??";
}
catch (AddressNotFoundException)
{
Logger.LogError($"The address {realIP} is not in the database.");
return "??";
}
catch (GeoIP2Exception ex)
{
Logger.LogError($"Error: {ex.Message}");
return "??";
}
}
}
}
}
2 changes: 1 addition & 1 deletion K4-System/src/Module/Stat/StatCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public void Initialize_Commands()

commands.StatCommands.ForEach(commandString =>
{
plugin.AddCommand($"css_{commandString}", "Check your statistics", plugin.CallbackAnonymizer(OnCommandStats));
plugin.AddCommand($"css_{commandString}", "Check your statistics", OnCommandStats);
});
}

Expand Down
2 changes: 1 addition & 1 deletion K4-System/src/Module/Time/TimeCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public void Initialize_Commands()

commands.TimeCommands.ForEach(commandString =>
{
plugin.AddCommand($"css_{commandString}", "Check your playtime", plugin.CallbackAnonymizer(OnCommandTime));
plugin.AddCommand($"css_{commandString}", "Check your playtime", OnCommandTime);
});
}

Expand Down
11 changes: 6 additions & 5 deletions K4-System/src/Module/Utils/UtilsCommands.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
namespace K4System
{
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Admin;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Utils;
using K4System.Models;
Expand All @@ -13,10 +11,13 @@ public void Initialize_Commands()
{
CommandSettings commands = Config.CommandSettings;

commands.AdminListCommands.ForEach(commandString =>
if (Config.UtilSettings.AdminListEnable)
{
plugin.AddCommand($"css_{commandString}", "Check online admins", plugin.CallbackAnonymizer(OnCommandAdmins));
});
commands.AdminListCommands.ForEach(commandString =>
{
plugin.AddCommand($"css_{commandString}", "Check online admins", OnCommandAdmins);
});
}
}

public void OnCommandAdmins(CCSPlayerController? player, CommandInfo info)
Expand Down
63 changes: 63 additions & 0 deletions K4-System/src/Module/Utils/UtilsEvents.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@

namespace K4System
{
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using K4System.Models;

public partial class ModuleUtils : IModuleUtils
{
public void Initialize_Events()
{
if (Config.UtilSettings.ConnectMessageEnable)
{
plugin.RegisterEventHandler((EventPlayerActivate @event, GameEventInfo info) =>
{
K4Player? k4player = plugin.GetK4Player(@event.Userid);
if (k4player is null || !k4player.IsValid || !k4player.IsPlayer)
return HookResult.Continue;
Server.PrintToChatAll(ReplacePlaceholders(k4player, plugin.ApplyPrefixColors(Config.UtilSettings.ConnectMessage)));
return HookResult.Continue;
});
}

if (Config.UtilSettings.DisconnectMessageEnable)
{
plugin.RegisterEventHandler((EventPlayerDisconnect @event, GameEventInfo info) =>
{
K4Player? k4player = plugin.GetK4Player(@event.Userid);
if (k4player is null || !k4player.IsValid || !k4player.IsPlayer)
return HookResult.Continue;
Server.PrintToChatAll(ReplacePlaceholders(k4player, plugin.ApplyPrefixColors(Config.UtilSettings.DisconnectMessage)));
return HookResult.Continue;
});
}
}

public string ReplacePlaceholders(K4Player k4player, string text)
{
Dictionary<string, string> placeholders = new Dictionary<string, string>
{
{ "{name}", k4player.PlayerName },
{ "{steamid}", k4player.SteamID.ToString() },
{ "{clantag}", k4player.ClanTag },
{ "{rank}", k4player.rankData?.Rank.Name ?? "Unranked" },
{ "{country}", plugin.GetPlayerCountryCode(k4player.Controller) },
{ "{points}", k4player.rankData?.Points.ToString() ?? "0" },
{ "{topplacement}", k4player.rankData?.TopPlacement.ToString() ?? "0" },
{ "{playtime}", k4player.timeData?.TimeFields["all"].ToString() ?? "0" },
};

foreach (var placeholder in placeholders)
{
text = text.Replace(placeholder.Key, placeholder.Value);
}

return text;
}
}
}
11 changes: 11 additions & 0 deletions K4-System/src/Plugin/PluginAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ public PlayerAPIHandler(CCSPlayerController player, Plugin plugin)
public bool IsPlayer => _player?.IsPlayer == true;
public CCSPlayerController Controller => _player?.Controller ?? throw new Exception("K4-SharedAPI > Controller > Player is not valid or is not a player.");

public int TopPlacement
{
get
{
if (_player is null || !_player.IsValid || !_player.IsPlayer || _player.rankData is null)
throw new Exception("K4-SharedAPI > TopPlacement (get) > Player is not valid or is not a player.");

return _player.rankData.TopPlacement;
}
}

public int Points
{
get
Expand Down
Loading

0 comments on commit b04c61f

Please sign in to comment.