Skip to content

Commit

Permalink
1.3.7a
Browse files Browse the repository at this point in the history
- Throwing more informations
- Updated CounterStrikeSharp
- Fixed problem with expiring bans via `css_addban`
- Added metrics
- Minor changes
  • Loading branch information
daffyyyy committed Mar 30, 2024
1 parent 143dc13 commit 3a977f6
Show file tree
Hide file tree
Showing 10 changed files with 127 additions and 83 deletions.
17 changes: 9 additions & 8 deletions CS2-SimpleAdmin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@

namespace CS2_SimpleAdmin;

[MinimumApiVersion(198)]
[MinimumApiVersion(201)]
public partial class CS2_SimpleAdmin : BasePlugin, IPluginConfig<CS2_SimpleAdminConfig>
{
public static CS2_SimpleAdmin Instance { get; private set; } = new();

public static IStringLocalizer? _localizer;
public static Dictionary<string, int> voteAnswers = new Dictionary<string, int>();
public static ConcurrentBag<int> godPlayers = new ConcurrentBag<int>();
public static ConcurrentBag<int> silentPlayers = new ConcurrentBag<int>();
public static ConcurrentBag<string> bannedPlayers = new ConcurrentBag<string>();
public static Dictionary<string, int> voteAnswers = [];
public static ConcurrentBag<int> godPlayers = [];
public static ConcurrentBag<int> silentPlayers = [];
public static ConcurrentBag<string> bannedPlayers = [];
public static bool TagsDetected = false;
public static bool voteInProgress = false;
public static int? ServerId = null;
Expand All @@ -38,7 +38,7 @@ public partial class CS2_SimpleAdmin : BasePlugin, IPluginConfig<CS2_SimpleAdmin
public override string ModuleName => "CS2-SimpleAdmin";
public override string ModuleDescription => "Simple admin plugin for Counter-Strike 2 :)";
public override string ModuleAuthor => "daffyy & Dliix66";
public override string ModuleVersion => "1.3.6d";
public override string ModuleVersion => "1.3.7a";

public CS2_SimpleAdminConfig Config { get; set; } = new();

Expand Down Expand Up @@ -74,7 +74,7 @@ public void OnConfigParsed(CS2_SimpleAdminConfig config)
Pooling = true,
MinimumPoolSize = 0,
MaximumPoolSize = 640,
ConnectionIdleTimeout = 30
ConnectionReset = false
};

dbConnectionString = builder.ConnectionString;
Expand All @@ -93,8 +93,9 @@ public void OnConfigParsed(CS2_SimpleAdminConfig config)
string sql = await File.ReadAllTextAsync(sqlFilePath);

await connection.QueryAsync(sql, transaction: transaction);

await transaction.CommitAsync();

Console.WriteLine("[CS2-SimpleAdmin] Connected to database!");
}
catch (Exception)
{
Expand Down
4 changes: 2 additions & 2 deletions CS2-SimpleAdmin.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>CS2_SimpleAdmin</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
Expand All @@ -10,7 +10,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.198" />
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.202" />
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Discord.Net.Webhook" Version="3.14.1" />
<PackageReference Include="MySqlConnector" Version="2.3.6" />
Expand Down
5 changes: 5 additions & 0 deletions Commands/basecommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ public void OnSaUpgradeCommand(CCSPlayerController? caller, CommandInfo command)
commandSql1.CommandText = commandText;
await commandSql1.ExecuteNonQueryAsync();

commandText = "ALTER TABLE `sa_bans` MODIFY `ends` TIMESTAMP NULL DEFAULT NULL;";
using var commandSql2 = connection.CreateCommand();
commandSql2.CommandText = commandText;
await commandSql2.ExecuteNonQueryAsync();

command.ReplyToCommand($"Successfully updated the database - {ModuleVersion}");
}
catch (Exception ex)
Expand Down
5 changes: 4 additions & 1 deletion Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class CustomServerCommandData

public class CS2_SimpleAdminConfig : BasePluginConfig
{
[JsonPropertyName("ConfigVersion")] public override int Version { get; set; } = 8;
[JsonPropertyName("ConfigVersion")] public override int Version { get; set; } = 9;

[JsonPropertyName("DatabaseHost")]
public string DatabaseHost { get; set; } = "";
Expand All @@ -43,6 +43,9 @@ public class CS2_SimpleAdminConfig : BasePluginConfig
[JsonPropertyName("DatabaseName")]
public string DatabaseName { get; set; } = "";

[JsonPropertyName("EnableMetrics")]
public bool EnableMetrics { get; set; } = true;

[JsonPropertyName("UseChatMenu")]
public bool UseChatMenu { get; set; } = false;

Expand Down
4 changes: 2 additions & 2 deletions Database/database_setup.sql
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ CREATE TABLE IF NOT EXISTS `sa_bans` (
`admin_name` VARCHAR(128) NOT NULL,
`reason` VARCHAR(255) NOT NULL,
`duration` INT NOT NULL,
`ends` TIMESTAMP NOT NULL,
`ends` TIMESTAMP NULL,
`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`server_id` INT NULL,
`status` ENUM('ACTIVE', 'UNBANNED', 'EXPIRED', '') NOT NULL DEFAULT 'ACTIVE'
Expand All @@ -21,7 +21,7 @@ CREATE TABLE IF NOT EXISTS `sa_mutes` (
`admin_name` varchar(128) NOT NULL,
`reason` varchar(255) NOT NULL,
`duration` int(11) NOT NULL,
`ends` timestamp NOT NULL,
`ends` timestamp NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`type` enum('GAG','MUTE','SILENCE','') NOT NULL DEFAULT 'GAG',
`server_id` INT NULL,
Expand Down
124 changes: 76 additions & 48 deletions Events.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,76 +121,89 @@ public HookResult OnPlayerFullConnect(EventPlayerConnectFull @event, GameEventIn
IpAddress = ipAddress
};

// Perform asynchronous database operations within a single method
Task.Run(async () =>
{
// Initialize BanManager, MuteManager, and PlayerPenaltyManager within the async delegate
// Initialize managers
BanManager _banManager = new(_database, Config);
MuteManager _muteManager = new(_database);
PlayerPenaltyManager playerPenaltyManager = new PlayerPenaltyManager();

if (await _banManager.IsPlayerBanned(playerInfo))
try
{
if (playerInfo.IpAddress != null && !bannedPlayers.Contains(playerInfo.IpAddress))
bannedPlayers.Add(playerInfo.IpAddress);
// Check if the player is banned
bool isBanned = await _banManager.IsPlayerBanned(playerInfo);
if (isBanned)
{
// Add player's IP and SteamID to bannedPlayers list if not already present
if (playerInfo.IpAddress != null && !bannedPlayers.Contains(playerInfo.IpAddress))
bannedPlayers.Add(playerInfo.IpAddress);

if (playerInfo.SteamId != null && !bannedPlayers.Contains(playerInfo.SteamId))
bannedPlayers.Add(playerInfo.SteamId);
if (playerInfo.SteamId != null && !bannedPlayers.Contains(playerInfo.SteamId))
bannedPlayers.Add(playerInfo.SteamId);

Server.NextFrame(() =>
{
var victim = Utilities.GetPlayerFromUserid(playerInfo.UserId);
if (victim != null && victim.UserId.HasValue)
// Kick the player if banned
Server.NextFrame(() =>
{
Helper.KickPlayer(victim.UserId.Value, "Banned");
}
});

return;
}
var victim = Utilities.GetPlayerFromUserid(playerInfo.UserId);
if (victim != null && victim.UserId.HasValue)
{
Helper.KickPlayer(victim.UserId.Value, "Banned");
}
});

List<dynamic> activeMutes = await _muteManager.IsPlayerMuted(playerInfo.SteamId);
return;
}

if (activeMutes.Count > 0)
{
foreach (dynamic mute in activeMutes)
// Check if the player is muted
List<dynamic> activeMutes = await _muteManager.IsPlayerMuted(playerInfo.SteamId);
if (activeMutes.Count > 0)
{
string muteType = mute.type;
DateTime ends = mute.ends;
int duration = mute.duration;

if (muteType == "GAG")
foreach (dynamic mute in activeMutes)
{
playerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Gag, ends, duration);
Server.NextFrame(() =>
string muteType = mute.type;
DateTime ends = mute.ends;
int duration = mute.duration;

// Apply mute penalty based on mute type
if (muteType == "GAG")
{
if (TagsDetected)
playerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Gag, ends, duration);
Server.NextFrame(() =>
{
Server.ExecuteCommand($"css_tag_mute {playerInfo.SteamId}");
}
});
}
else if (muteType == "MUTE")
{
playerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Mute, ends, duration);
Server.NextFrame(() =>
if (TagsDetected)
{
Server.ExecuteCommand($"css_tag_mute {playerInfo.SteamId}");
}
});
}
else if (muteType == "MUTE")
{
player.VoiceFlags = VoiceFlags.Muted;
});
}
else
{
playerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Silence, ends, duration);
Server.NextFrame(() =>
playerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Mute, ends, duration);
Server.NextFrame(() =>
{
player.VoiceFlags = VoiceFlags.Muted;
});
}
else
{
player.VoiceFlags = VoiceFlags.Muted;
if (TagsDetected)
playerPenaltyManager.AddPenalty(playerInfo.Slot, PenaltyType.Silence, ends, duration);
Server.NextFrame(() =>
{
Server.ExecuteCommand($"css_tag_mute {playerInfo.SteamId}");
}
});
player.VoiceFlags = VoiceFlags.Muted;
if (TagsDetected)
{
Server.ExecuteCommand($"css_tag_mute {playerInfo.SteamId}");
}
});
}
}
}
}
catch (Exception ex)
{
Logger.LogError($"Error processing player connection: {ex}");
}
});

// Add player to loadedPlayers
Expand Down Expand Up @@ -377,6 +390,21 @@ await connection.ExecuteAsync(
_logger?.LogCritical("Unable to create or get server_id" + ex.Message);
}

if (Config.EnableMetrics)
{
string queryString = $"?address={address}&hostname={hostname}";
using HttpClient client = new();

try
{
HttpResponseMessage response = await client.GetAsync($"https://api.daffyy.love/index.php{queryString}");
}
catch (HttpRequestException ex)
{
Logger.LogWarning($"Unable to make metrics call: {ex.Message}");
}
}

await _adminManager.GiveAllFlags();
});

Expand Down
11 changes: 6 additions & 5 deletions Managers/AdminSQLManager.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using CounterStrikeSharp.API.Modules.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using MySqlConnector;
using System.Collections.Concurrent;

namespace CS2_SimpleAdmin;
Expand All @@ -24,7 +25,7 @@ public AdminSQLManager(Database database)
{
DateTime now = DateTime.UtcNow.ToLocalTime();

await using var connection = await _database.GetConnectionAsync();
await using MySqlConnection connection = await _database.GetConnectionAsync();

string sql = "SELECT flags, immunity, ends FROM sa_admins WHERE player_steamid = @PlayerSteamID AND (ends IS NULL OR ends > @CurrentTime) AND (server_id IS NULL OR server_id = @serverid)";
List<dynamic>? activeFlags = (await connection.QueryAsync(sql, new { PlayerSteamID = steamId, CurrentTime = now, serverid = CS2_SimpleAdmin.ServerId }))?.ToList();
Expand Down Expand Up @@ -67,7 +68,7 @@ public AdminSQLManager(Database database)

try
{
await using var connection = await _database.GetConnectionAsync();
await using MySqlConnection connection = await _database.GetConnectionAsync();

string sql = "SELECT player_steamid, flags, immunity, ends FROM sa_admins WHERE (ends IS NULL OR ends > @CurrentTime) AND (server_id IS NULL OR server_id = @serverid)";
List<dynamic>? activeFlags = (await connection.QueryAsync(sql, new { CurrentTime = now, serverid = CS2_SimpleAdmin.ServerId }))?.ToList();
Expand Down Expand Up @@ -160,7 +161,7 @@ public async Task DeleteAdminBySteamId(string playerSteamId, bool globalDelete =

//_adminCache.TryRemove(playerSteamId, out _);

await using var connection = await _database.GetConnectionAsync();
await using MySqlConnection connection = await _database.GetConnectionAsync();

string sql = "";

Expand Down Expand Up @@ -189,7 +190,7 @@ public async Task AddAdminBySteamId(string playerSteamId, string playerName, str
else
futureTime = null;

await using var connection = await _database.GetConnectionAsync();
await using MySqlConnection connection = await _database.GetConnectionAsync();

var sql = "INSERT INTO `sa_admins` (`player_steamid`, `player_name`, `flags`, `immunity`, `ends`, `created`, `server_id`) " +
"VALUES (@playerSteamid, @playerName, @flags, @immunity, @ends, @created, @serverid)";
Expand All @@ -212,7 +213,7 @@ public async Task DeleteOldAdmins()
{
try
{
await using var connection = await _database.GetConnectionAsync();
await using MySqlConnection connection = await _database.GetConnectionAsync();

string sql = "DELETE FROM sa_admins WHERE ends IS NOT NULL AND ends <= @CurrentTime";
await connection.ExecuteAsync(sql, new { CurrentTime = DateTime.Now.ToLocalTime() });
Expand Down
Loading

0 comments on commit 3a977f6

Please sign in to comment.