- Minor changes
- Escape kick reason @poggu suggestion
- Auto-updater for config
- Using UTC time
- Added expiring IP bans after x days (`ExpireOldIpBans` in config => value = days, 0 = disabled)
- Added exception message to database error
- Fixed? ungag/unmute/unsilence commands
- Updated css version to `178`
- Changed `css_adminhelp` command to use new file `admin_help.txt` as output
This commit is contained in:
Dawid Bepierszcz
2024-03-01 12:38:46 +01:00
parent 5bf966f9cd
commit 229b8d73a3
29 changed files with 802 additions and 815 deletions

View File

@@ -3,82 +3,80 @@ using Dapper;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
namespace CS2_SimpleAdmin
namespace CS2_SimpleAdmin;
public class AdminSQLManager
{
public class AdminSQLManager
private readonly Database _database;
// Unused for now
//public static readonly ConcurrentDictionary<string, ConcurrentBag<string>> _adminCache = new ConcurrentDictionary<string, ConcurrentBag<string>>();
public static readonly ConcurrentDictionary<SteamID, DateTime?> _adminCache = new ConcurrentDictionary<SteamID, DateTime?>();
//public static readonly ConcurrentDictionary<SteamID, DateTime?> _adminCacheTimestamps = new ConcurrentDictionary<SteamID, DateTime?>();
public AdminSQLManager(Database database)
{
private readonly Database _database;
_database = database;
}
// Unused for now
//public static readonly ConcurrentDictionary<string, ConcurrentBag<string>> _adminCache = new ConcurrentDictionary<string, ConcurrentBag<string>>();
public static readonly ConcurrentDictionary<SteamID, DateTime?> _adminCache = new ConcurrentDictionary<SteamID, DateTime?>();
public async Task<List<(List<string>, int)>> GetAdminFlags(string steamId)
{
DateTime now = DateTime.UtcNow;
//public static readonly ConcurrentDictionary<SteamID, DateTime?> _adminCacheTimestamps = new ConcurrentDictionary<SteamID, DateTime?>();
await using var connection = await _database.GetConnectionAsync();
public AdminSQLManager(Database database)
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();
if (activeFlags == null)
{
_database = database;
return new List<(List<string>, int)>();
}
/*
public async Task<List<dynamic>> GetAdminFlags(string steamId)
List<(List<string>, int)> filteredFlagsWithImmunity = new List<(List<string>, int)>();
foreach (dynamic flags in activeFlags)
{
if (_adminCache.ContainsKey(steamId))
if (flags is not IDictionary<string, object> flagsDict)
{
return _adminCache[steamId].Select(flag => (dynamic)flag).ToList();
continue;
}
else
if (!flagsDict.TryGetValue("flags", out var flagsValueObj) || !flagsDict.TryGetValue("immunity", out var immunityValueObj))
{
await using var connection = _database.GetConnection();
await connection.OpenAsync();
DateTime now = DateTime.Now;
string sql = "SELECT flags, ends FROM sa_admins WHERE player_steamid = @PlayerSteamID AND (ends IS NULL OR ends > @CurrentTime)";
List<dynamic> activeFlags = (await connection.QueryAsync(sql, new { PlayerSteamID = steamId, CurrentTime = now })).ToList();
_adminCache[steamId] = new List<string>();
foreach (var flags in activeFlags)
{
if (flags == null) continue;
string flagsValue = flags.flags.ToString();
_adminCache[steamId].Add(flagsValue);
}
continue;
}
return _adminCache[steamId].Select(flag => (dynamic)flag).ToList();
if (!(flagsValueObj is string flagsValue) || !int.TryParse(immunityValueObj.ToString(), out var immunityValue))
{
continue;
}
//Console.WriteLine($"Flags: {flagsValue}, Immunity: {immunityValue}");
filteredFlagsWithImmunity.Add((flagsValue.Split(',').ToList(), immunityValue));
}
*/
public async Task<List<(List<string>, int)>> GetAdminFlags(string steamId)
return filteredFlagsWithImmunity;
}
public async Task<List<(string, List<string>, int, DateTime?)>> GetAllPlayersFlags()
{
DateTime now = DateTime.UtcNow;
try
{
DateTime now = DateTime.Now;
await using var 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();
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();
if (activeFlags == null)
{
return new List<(List<string>, int)>();
return new List<(string, List<string>, int, DateTime?)>();
}
List<(List<string>, int)> filteredFlagsWithImmunity = new List<(List<string>, int)>();
/*
List<string> filteredFlags = new List<string>();
foreach (var flags in activeFlags)
{
if (flags == null) continue;
string flag = flags.flags.ToString();
if (flag != null)
{
filteredFlags.Add(flag);
}
}
*/
List<(string, List<string>, int, DateTime?)> filteredFlagsWithImmunity = new List<(string, List<string>, int, DateTime?)>();
foreach (dynamic flags in activeFlags)
{
@@ -87,226 +85,141 @@ namespace CS2_SimpleAdmin
continue;
}
if (!flagsDict.TryGetValue("flags", out var flagsValueObj) || !flagsDict.TryGetValue("immunity", out var immunityValueObj))
if (!flagsDict.TryGetValue("player_steamid", out var steamIdObj) ||
!flagsDict.TryGetValue("flags", out var flagsValueObj) ||
!flagsDict.TryGetValue("immunity", out var immunityValueObj) ||
!flagsDict.TryGetValue("ends", out var endsObj))
{
//Console.WriteLine("One or more required keys are missing.");
continue;
}
if (!(flagsValueObj is string flagsValue) || !int.TryParse(immunityValueObj.ToString(), out var immunityValue))
DateTime? ends = null;
if (endsObj != null) // Check if "ends" is not null
{
if (!DateTime.TryParse(endsObj.ToString(), out var parsedEnds))
{
//Console.WriteLine("Failed to parse 'ends' value.");
continue;
}
ends = parsedEnds;
}
if (!(steamIdObj is string steamId) ||
!(flagsValueObj is string flagsValue) ||
!int.TryParse(immunityValueObj.ToString(), out var immunityValue))
{
//Console.WriteLine("Failed to parse one or more values.");
continue;
}
//Console.WriteLine($"Flags: {flagsValue}, Immunity: {immunityValue}");
filteredFlagsWithImmunity.Add((flagsValue.Split(',').ToList(), immunityValue));
filteredFlagsWithImmunity.Add((steamId, flagsValue.Split(',').ToList(), immunityValue, ends));
}
/* Unused for now
bool shouldCache = activeFlags.Any(flags =>
{
if (flags?.ends == null)
{
return true;
}
if (flags.ends is DateTime endsTime)
{
return (endsTime - now).TotalHours > 1;
}
return false;
});
if (shouldCache)
{
List<string> flagsToCache = new List<string>();
foreach (var flags in activeFlags)
{
if (flags.ends == null || (DateTime.Now - (DateTime)flags.ends).TotalHours > 6)
{
if (flags == null) continue;
flagsToCache.Add(flags.flags.ToString());
}
}
_adminCache.AddOrUpdate(steamId, new ConcurrentBag<string>(flagsToCache), (_, existingBag) =>
{
foreach (var flag in flagsToCache)
{
existingBag.Add(flag);
}
return existingBag;
});
return flagsToCache.Cast<object>().ToList();
}
*/
return filteredFlagsWithImmunity;
//return filteredFlags.Cast<object>().ToList();
}
public async Task<List<(string, List<string>, int, DateTime?)>> GetAllPlayersFlags()
catch (Exception)
{
DateTime now = DateTime.Now;
return new List<(string, List<string>, int, DateTime?)>();
}
}
try
public async Task GiveAllFlags()
{
List<(string, List<string>, int, DateTime?)> allPlayers = await GetAllPlayersFlags();
foreach (var record in allPlayers)
{
string steamIdStr = record.Item1;
List<string> flags = record.Item2;
int immunity = record.Item3;
DateTime? ends = record.Item4;
if (!string.IsNullOrEmpty(steamIdStr) && SteamID.TryParse(steamIdStr, out var steamId) && steamId != null)
{
await using var 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();
if (activeFlags == null)
if (!_adminCache.ContainsKey(steamId))
{
return new List<(string, List<string>, int, DateTime?)>();
_adminCache.TryAdd(steamId, ends);
//_adminCacheTimestamps.Add(steamId, ends);
}
List<(string, List<string>, int, DateTime?)> filteredFlagsWithImmunity = new List<(string, List<string>, int, DateTime?)>();
foreach (dynamic flags in activeFlags)
{
if (flags is not IDictionary<string, object> flagsDict)
{
continue;
}
if (!flagsDict.TryGetValue("player_steamid", out var steamIdObj) ||
!flagsDict.TryGetValue("flags", out var flagsValueObj) ||
!flagsDict.TryGetValue("immunity", out var immunityValueObj) ||
!flagsDict.TryGetValue("ends", out var endsObj))
{
//Console.WriteLine("One or more required keys are missing.");
continue;
}
DateTime? ends = null;
if (endsObj != null) // Check if "ends" is not null
{
if (!DateTime.TryParse(endsObj.ToString(), out var parsedEnds))
{
//Console.WriteLine("Failed to parse 'ends' value.");
continue;
}
ends = parsedEnds;
}
if (!(steamIdObj is string steamId) ||
!(flagsValueObj is string flagsValue) ||
!int.TryParse(immunityValueObj.ToString(), out var immunityValue))
{
//Console.WriteLine("Failed to parse one or more values.");
continue;
}
filteredFlagsWithImmunity.Add((steamId, flagsValue.Split(',').ToList(), immunityValue, ends));
}
return filteredFlagsWithImmunity;
}
catch (Exception)
{
return new List<(string, List<string>, int, DateTime?)>();
}
}
public async Task GiveAllFlags()
{
List<(string, List<string>, int, DateTime?)> allPlayers = await GetAllPlayersFlags();
foreach (var record in allPlayers)
{
string steamIdStr = record.Item1;
List<string> flags = record.Item2;
int immunity = record.Item3;
DateTime? ends = record.Item4;
if (!string.IsNullOrEmpty(steamIdStr) && SteamID.TryParse(steamIdStr, out var steamId) && steamId != null)
{
if (!_adminCache.ContainsKey(steamId))
{
_adminCache.TryAdd(steamId, ends);
//_adminCacheTimestamps.Add(steamId, ends);
}
Helper.GivePlayerFlags(steamId, flags, (uint)immunity);
// Often need to call 2 times
Helper.GivePlayerFlags(steamId, flags, (uint)immunity);
}
}
}
public async Task DeleteAdminBySteamId(string playerSteamId, bool globalDelete = false)
{
if (string.IsNullOrEmpty(playerSteamId)) return;
//_adminCache.TryRemove(playerSteamId, out _);
await using var connection = await _database.GetConnectionAsync();
string sql = "";
if (globalDelete)
{
sql = "DELETE FROM sa_admins WHERE player_steamid = @PlayerSteamID";
}
else
{
sql = "DELETE FROM sa_admins WHERE player_steamid = @PlayerSteamID AND server_id = @ServerId";
}
await connection.ExecuteAsync(sql, new { PlayerSteamID = playerSteamId, ServerId = CS2_SimpleAdmin.ServerId });
}
public async Task AddAdminBySteamId(string playerSteamId, string playerName, string flags, int immunity = 0, int time = 0, bool globalAdmin = false)
{
if (string.IsNullOrEmpty(playerSteamId)) return;
flags = flags.Replace(" ", "");
DateTime now = DateTime.Now;
DateTime? futureTime;
if (time != 0)
futureTime = now.AddMinutes(time);
else
futureTime = null;
await using var 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)";
int? serverId = globalAdmin ? null : CS2_SimpleAdmin.ServerId;
await connection.ExecuteAsync(sql, new
{
playerSteamId,
playerName,
flags,
immunity,
ends = futureTime,
created = now,
serverid = serverId
});
}
public async Task DeleteOldAdmins()
{
try
{
await using var 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 });
}
catch (Exception)
{
if (CS2_SimpleAdmin._logger != null)
CS2_SimpleAdmin._logger.LogCritical("Unable to remove expired admins");
Helper.GivePlayerFlags(steamId, flags, (uint)immunity);
// Often need to call 2 times
Helper.GivePlayerFlags(steamId, flags, (uint)immunity);
}
}
}
}
public async Task DeleteAdminBySteamId(string playerSteamId, bool globalDelete = false)
{
if (string.IsNullOrEmpty(playerSteamId)) return;
//_adminCache.TryRemove(playerSteamId, out _);
await using var connection = await _database.GetConnectionAsync();
string sql = "";
if (globalDelete)
{
sql = "DELETE FROM sa_admins WHERE player_steamid = @PlayerSteamID";
}
else
{
sql = "DELETE FROM sa_admins WHERE player_steamid = @PlayerSteamID AND server_id = @ServerId";
}
await connection.ExecuteAsync(sql, new { PlayerSteamID = playerSteamId, ServerId = CS2_SimpleAdmin.ServerId });
}
public async Task AddAdminBySteamId(string playerSteamId, string playerName, string flags, int immunity = 0, int time = 0, bool globalAdmin = false)
{
if (string.IsNullOrEmpty(playerSteamId)) return;
flags = flags.Replace(" ", "");
DateTime now = DateTime.UtcNow;
DateTime? futureTime;
if (time != 0)
futureTime = now.AddMinutes(time);
else
futureTime = null;
await using var 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)";
int? serverId = globalAdmin ? null : CS2_SimpleAdmin.ServerId;
await connection.ExecuteAsync(sql, new
{
playerSteamId,
playerName,
flags,
immunity,
ends = futureTime,
created = now,
serverid = serverId
});
}
public async Task DeleteOldAdmins()
{
try
{
await using var 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 });
}
catch (Exception)
{
if (CS2_SimpleAdmin._logger != null)
CS2_SimpleAdmin._logger.LogCritical("Unable to remove expired admins");
}
}
}

View File

@@ -1,113 +1,112 @@
using Dapper;
using Microsoft.Extensions.Logging;
namespace CS2_SimpleAdmin
namespace CS2_SimpleAdmin;
internal class BanManager
{
internal class BanManager
private readonly Database _database;
private readonly CS2_SimpleAdminConfig _config;
public BanManager(Database database, CS2_SimpleAdminConfig config)
{
private readonly Database _database;
private readonly CS2_SimpleAdminConfig _config;
_database = database;
_config = config;
}
public BanManager(Database database, CS2_SimpleAdminConfig config)
public async Task BanPlayer(PlayerInfo player, PlayerInfo issuer, string reason, int time = 0)
{
DateTime now = DateTime.UtcNow;
DateTime futureTime = now.AddMinutes(time);
await using var connection = await _database.GetConnectionAsync();
var sql = "INSERT INTO `sa_bans` (`player_steamid`, `player_name`, `player_ip`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `server_id`) " +
"VALUES (@playerSteamid, @playerName, @playerIp, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @serverid)";
await connection.ExecuteAsync(sql, new
{
_database = database;
_config = config;
playerSteamid = player.SteamId,
playerName = player.Name,
playerIp = _config.BanType == 1 ? player.IpAddress : null,
adminSteamid = issuer.SteamId == null ? "Console" : issuer.SteamId,
adminName = issuer.Name == null ? "Console" : issuer.Name,
banReason = reason,
duration = time,
ends = futureTime,
created = now,
serverid = CS2_SimpleAdmin.ServerId
});
}
public async Task AddBanBySteamid(string playerSteamId, PlayerInfo issuer, string reason, int time = 0)
{
if (string.IsNullOrEmpty(playerSteamId)) return;
DateTime now = DateTime.UtcNow;
DateTime futureTime = now.AddMinutes(time);
await using var connection = await _database.GetConnectionAsync();
var sql = "INSERT INTO `sa_bans` (`player_steamid`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `server_id`) " +
"VALUES (@playerSteamid, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @serverid)";
await connection.ExecuteAsync(sql, new
{
playerSteamid = playerSteamId,
adminSteamid = issuer.SteamId == null ? "Console" : issuer.SteamId,
adminName = issuer.Name == null ? "Console" : issuer.Name,
banReason = reason,
duration = time,
ends = futureTime,
created = now,
serverid = CS2_SimpleAdmin.ServerId
});
}
public async Task AddBanByIp(string playerIp, PlayerInfo issuer, string reason, int time = 0)
{
if (string.IsNullOrEmpty(playerIp)) return;
DateTime now = DateTime.UtcNow;
DateTime futureTime = now.AddMinutes(time);
await using var connection = await _database.GetConnectionAsync();
var sql = "INSERT INTO `sa_bans` (`player_ip`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `server_id`) " +
"VALUES (@playerIp, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @serverid)";
await connection.ExecuteAsync(sql, new
{
playerIp,
adminSteamid = issuer.SteamId == null ? "Console" : issuer.SteamId,
adminName = issuer.Name == null ? "Console" : issuer.Name,
banReason = reason,
duration = time,
ends = futureTime,
created = now,
serverid = CS2_SimpleAdmin.ServerId
});
}
public async Task<bool> IsPlayerBanned(PlayerInfo player)
{
if (player.SteamId == null && player.IpAddress == null)
{
return false;
}
public async Task BanPlayer(PlayerInfo player, PlayerInfo issuer, string reason, int time = 0)
{
DateTime now = DateTime.Now;
DateTime futureTime = now.AddMinutes(time);
await using var connection = await _database.GetConnectionAsync();
var sql = "INSERT INTO `sa_bans` (`player_steamid`, `player_name`, `player_ip`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `server_id`) " +
"VALUES (@playerSteamid, @playerName, @playerIp, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @serverid)";
await connection.ExecuteAsync(sql, new
{
playerSteamid = player.SteamId,
playerName = player.Name,
playerIp = _config.BanType == 1 ? player.IpAddress : null,
adminSteamid = issuer.SteamId == null ? "Console" : issuer.SteamId,
adminName = issuer.Name == null ? "Console" : issuer.Name,
banReason = reason,
duration = time,
ends = futureTime,
created = now,
serverid = CS2_SimpleAdmin.ServerId
});
}
public async Task AddBanBySteamid(string playerSteamId, PlayerInfo issuer, string reason, int time = 0)
{
if (string.IsNullOrEmpty(playerSteamId)) return;
DateTime now = DateTime.Now;
DateTime futureTime = now.AddMinutes(time);
await using var connection = await _database.GetConnectionAsync();
var sql = "INSERT INTO `sa_bans` (`player_steamid`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `server_id`) " +
"VALUES (@playerSteamid, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @serverid)";
await connection.ExecuteAsync(sql, new
{
playerSteamid = playerSteamId,
adminSteamid = issuer.SteamId == null ? "Console" : issuer.SteamId,
adminName = issuer.Name == null ? "Console" : issuer.Name,
banReason = reason,
duration = time,
ends = futureTime,
created = now,
serverid = CS2_SimpleAdmin.ServerId
});
}
public async Task AddBanByIp(string playerIp, PlayerInfo issuer, string reason, int time = 0)
{
if (string.IsNullOrEmpty(playerIp)) return;
DateTime now = DateTime.Now;
DateTime futureTime = now.AddMinutes(time);
await using var connection = await _database.GetConnectionAsync();
var sql = "INSERT INTO `sa_bans` (`player_ip`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `server_id`) " +
"VALUES (@playerIp, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @serverid)";
await connection.ExecuteAsync(sql, new
{
playerIp,
adminSteamid = issuer.SteamId == null ? "Console" : issuer.SteamId,
adminName = issuer.Name == null ? "Console" : issuer.Name,
banReason = reason,
duration = time,
ends = futureTime,
created = now,
serverid = CS2_SimpleAdmin.ServerId
});
}
public async Task<bool> IsPlayerBanned(PlayerInfo player)
{
if (player.SteamId == null && player.IpAddress == null)
{
return false;
}
#if DEBUG
if (CS2_SimpleAdmin._logger != null)
CS2_SimpleAdmin._logger.LogCritical($"IsPlayerBanned for {player.Name}");
if (CS2_SimpleAdmin._logger != null)
CS2_SimpleAdmin._logger.LogCritical($"IsPlayerBanned for {player.Name}");
#endif
int banCount = 0;
int banCount = 0;
DateTime currentTime = DateTime.Now;
DateTime currentTime = DateTime.Now;
try
{
string sql = @"
try
{
string sql = @"
UPDATE sa_bans
SET player_ip = CASE WHEN player_ip IS NULL THEN @PlayerIP ELSE player_ip END,
player_name = CASE WHEN player_name IS NULL THEN @PlayerName ELSE player_name END
@@ -120,72 +119,107 @@ namespace CS2_SimpleAdmin
AND status = 'ACTIVE'
AND (duration = 0 OR ends > @CurrentTime);";
await using var connection = await _database.GetConnectionAsync();
await using var connection = await _database.GetConnectionAsync();
var parameters = new
{
PlayerSteamID = player.SteamId,
PlayerIP = !string.IsNullOrEmpty(player.IpAddress) ? player.IpAddress : (object)DBNull.Value,
PlayerName = !string.IsNullOrEmpty(player.Name) ? player.Name : string.Empty,
CurrentTime = currentTime
};
banCount = await connection.ExecuteScalarAsync<int>(sql, parameters);
}
catch (Exception)
var parameters = new
{
return false;
}
PlayerSteamID = player.SteamId,
PlayerIP = _config.BanType == 0 || string.IsNullOrEmpty(player.IpAddress) ? null : player.IpAddress,
PlayerName = !string.IsNullOrEmpty(player.Name) ? player.Name : string.Empty,
CurrentTime = currentTime
};
return banCount > 0;
banCount = await connection.ExecuteScalarAsync<int>(sql, parameters);
}
catch (Exception)
{
return false;
}
public async Task<int> GetPlayerBans(PlayerInfo player)
return banCount > 0;
}
public async Task<int> GetPlayerBans(PlayerInfo player)
{
string sql = "SELECT COUNT(*) FROM sa_bans WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP)";
int banCount;
await using var connection = await _database.GetConnectionAsync();
if (!string.IsNullOrEmpty(player.IpAddress))
{
string sql = "SELECT COUNT(*) FROM sa_bans WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP)";
int banCount;
banCount = await connection.ExecuteScalarAsync<int>(sql, new { PlayerSteamID = player.SteamId, PlayerIP = player.IpAddress });
}
else
{
banCount = await connection.ExecuteScalarAsync<int>(sql, new { PlayerSteamID = player.SteamId, PlayerIP = DBNull.Value });
}
return banCount;
}
public async Task UnbanPlayer(string playerPattern)
{
if (playerPattern == null || playerPattern.Length <= 1)
{
return;
}
await using var connection = await _database.GetConnectionAsync();
string sqlUnban = "UPDATE sa_bans SET status = 'UNBANNED' WHERE player_steamid = @pattern OR player_name = @pattern OR player_ip = @pattern AND status = 'ACTIVE'";
await connection.ExecuteAsync(sqlUnban, new { pattern = playerPattern });
}
public async Task ExpireOldBans()
{
try
{
DateTime currentTime = DateTime.UtcNow;
await using var connection = await _database.GetConnectionAsync();
if (!string.IsNullOrEmpty(player.IpAddress))
{
banCount = await connection.ExecuteScalarAsync<int>(sql, new { PlayerSteamID = player.SteamId, PlayerIP = player.IpAddress });
}
else
{
banCount = await connection.ExecuteScalarAsync<int>(sql, new { PlayerSteamID = player.SteamId, PlayerIP = DBNull.Value });
}
return banCount;
}
public async Task UnbanPlayer(string playerPattern)
{
if (playerPattern == null || playerPattern.Length <= 1)
{
return;
}
/*
string sql = "";
await using var connection = await _database.GetConnectionAsync();
string sqlUnban = "UPDATE sa_bans SET status = 'UNBANNED' WHERE player_steamid = @pattern OR player_name = @pattern OR player_ip = @pattern AND status = 'ACTIVE'";
await connection.ExecuteAsync(sqlUnban, new { pattern = playerPattern });
sql = "UPDATE sa_bans SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND `duration` > 0 AND ends <= @CurrentTime";
await connection.ExecuteAsync(sql, new { CurrentTime = DateTime.UtcNow });
*/
string sql = @"
UPDATE sa_bans
SET
status = 'EXPIRED'
WHERE
status = 'ACTIVE'
AND
`duration` > 0
AND
ends <= @currentTime";
await connection.ExecuteAsync(sql, new { currentTime });
if (_config.ExpireOldIpBans > 0)
{
DateTime ipBansTime = currentTime.AddDays(-_config.ExpireOldIpBans);
sql = @"
UPDATE sa_bans
SET
player_ip = NULL
WHERE
status = 'ACTIVE'
AND
ends <= @ipBansTime";
await connection.ExecuteAsync(sql, new { ipBansTime });
}
}
public async Task ExpireOldBans()
catch (Exception)
{
try
{
await using var connection = await _database.GetConnectionAsync();
string sql = "UPDATE sa_bans SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND `duration` > 0 AND ends <= @CurrentTime";
await connection.ExecuteAsync(sql, new { CurrentTime = DateTime.Now });
}
catch (Exception)
{
if (CS2_SimpleAdmin._logger != null)
CS2_SimpleAdmin._logger.LogCritical("Unable to remove expired bans");
}
CS2_SimpleAdmin._logger?.LogCritical("Unable to remove expired bans");
}
}
}
}

View File

@@ -1,208 +1,164 @@
using CounterStrikeSharp.API.Core;
using Dapper;
using Dapper;
using Microsoft.Extensions.Logging;
namespace CS2_SimpleAdmin
namespace CS2_SimpleAdmin;
internal class MuteManager
{
internal class MuteManager
private readonly Database _database;
public MuteManager(Database database)
{
private readonly Database _database;
_database = database;
}
public MuteManager(Database database)
public async Task MutePlayer(PlayerInfo player, PlayerInfo issuer, string reason, int time = 0, int type = 0)
{
if (player == null || player.SteamId == null) return;
await using var connection = await _database.GetConnectionAsync();
DateTime now = DateTime.UtcNow;
DateTime futureTime = now.AddMinutes(time);
string muteType = "GAG";
if (type == 1)
muteType = "MUTE";
else if (type == 2)
muteType = "SILENCE";
var sql = "INSERT INTO `sa_mutes` (`player_steamid`, `player_name`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `type`, `server_id`) " +
"VALUES (@playerSteamid, @playerName, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @type, @serverid)";
await connection.ExecuteAsync(sql, new
{
_database = database;
playerSteamid = player.SteamId,
playerName = player.Name,
adminSteamid = issuer.SteamId == null ? "Console" : issuer.SteamId,
adminName = issuer.SteamId == null ? "Console" : issuer.Name,
banReason = reason,
duration = time,
ends = futureTime,
created = now,
type = muteType,
serverid = CS2_SimpleAdmin.ServerId
});
}
public async Task AddMuteBySteamid(string playerSteamId, PlayerInfo issuer, string reason, int time = 0, int type = 0)
{
if (string.IsNullOrEmpty(playerSteamId)) return;
await using var connection = await _database.GetConnectionAsync();
DateTime now = DateTime.UtcNow;
DateTime futureTime = now.AddMinutes(time);
string muteType = "GAG";
if (type == 1)
muteType = "MUTE";
else if (type == 2)
muteType = "SILENCE";
var sql = "INSERT INTO `sa_mutes` (`player_steamid`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `type`, `server_id`) " +
"VALUES (@playerSteamid, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @type, @serverid)";
await connection.ExecuteAsync(sql, new
{
playerSteamid = playerSteamId,
adminSteamid = issuer.SteamId == null ? "Console" : issuer.SteamId,
adminName = issuer.Name == null ? "Console" : issuer.Name,
banReason = reason,
duration = time,
ends = futureTime,
created = now,
type = muteType,
serverid = CS2_SimpleAdmin.ServerId
});
}
public async Task<List<dynamic>> IsPlayerMuted(string steamId)
{
if (string.IsNullOrEmpty(steamId))
{
return new List<dynamic>();
}
public async Task MutePlayer(PlayerInfo player, PlayerInfo issuer, string reason, int time = 0, int type = 0)
{
if (player == null || player.SteamId == null) return;
await using var connection = await _database.GetConnectionAsync();
DateTime now = DateTime.Now;
DateTime futureTime = now.AddMinutes(time);
string muteType = "GAG";
if (type == 1)
muteType = "MUTE";
else if (type == 2)
muteType = "SILENCE";
var sql = "INSERT INTO `sa_mutes` (`player_steamid`, `player_name`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `type`, `server_id`) " +
"VALUES (@playerSteamid, @playerName, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @type, @serverid)";
await connection.ExecuteAsync(sql, new
{
playerSteamid = player.SteamId,
playerName = player.Name,
adminSteamid = issuer.SteamId == null ? "Console" : issuer.SteamId,
adminName = issuer.SteamId == null ? "Console" : issuer.Name,
banReason = reason,
duration = time,
ends = futureTime,
created = now,
type = muteType,
serverid = CS2_SimpleAdmin.ServerId
});
}
public async Task AddMuteBySteamid(string playerSteamId, PlayerInfo issuer, string reason, int time = 0, int type = 0)
{
if (string.IsNullOrEmpty(playerSteamId)) return;
await using var connection = await _database.GetConnectionAsync();
DateTime now = DateTime.Now;
DateTime futureTime = now.AddMinutes(time);
string muteType = "GAG";
if (type == 1)
muteType = "MUTE";
else if (type == 2)
muteType = "SILENCE";
var sql = "INSERT INTO `sa_mutes` (`player_steamid`, `admin_steamid`, `admin_name`, `reason`, `duration`, `ends`, `created`, `type`, `server_id`) " +
"VALUES (@playerSteamid, @adminSteamid, @adminName, @banReason, @duration, @ends, @created, @type, @serverid)";
await connection.ExecuteAsync(sql, new
{
playerSteamid = playerSteamId,
adminSteamid = issuer.SteamId == null ? "Console" : issuer.SteamId,
adminName = issuer.Name == null ? "Console" : issuer.Name,
banReason = reason,
duration = time,
ends = futureTime,
created = now,
type = muteType,
serverid = CS2_SimpleAdmin.ServerId
});
}
public async Task<List<dynamic>> IsPlayerMuted(string steamId)
{
if (string.IsNullOrEmpty(steamId))
{
return new List<dynamic>();
}
#if DEBUG
if (CS2_SimpleAdmin._logger != null)
CS2_SimpleAdmin._logger.LogCritical($"IsPlayerMuted for {steamId}");
if (CS2_SimpleAdmin._logger != null)
CS2_SimpleAdmin._logger.LogCritical($"IsPlayerMuted for {steamId}");
#endif
try
{
await using var connection = await _database.GetConnectionAsync();
DateTime currentTime = DateTime.Now;
string sql = "SELECT * FROM sa_mutes WHERE player_steamid = @PlayerSteamID AND status = 'ACTIVE' AND (duration = 0 OR ends > @CurrentTime)";
var parameters = new { PlayerSteamID = steamId, CurrentTime = currentTime };
var activeMutes = (await connection.QueryAsync(sql, parameters)).ToList();
return activeMutes;
}
catch (Exception)
{
return new List<dynamic>();
}
}
public async Task<int> GetPlayerMutes(string steamId)
try
{
await using var connection = await _database.GetConnectionAsync();
DateTime currentTime = DateTime.Now;
string sql = "SELECT * FROM sa_mutes WHERE player_steamid = @PlayerSteamID AND status = 'ACTIVE' AND (duration = 0 OR ends > @CurrentTime)";
int muteCount;
string sql = "SELECT COUNT(*) FROM sa_mutes WHERE player_steamid = @PlayerSteamID";
muteCount = await connection.ExecuteScalarAsync<int>(sql, new { PlayerSteamID = steamId });
return muteCount;
var parameters = new { PlayerSteamID = steamId, CurrentTime = currentTime };
var activeMutes = (await connection.QueryAsync(sql, parameters)).ToList();
return activeMutes;
}
public async Task UnmutePlayer(string playerPattern, int type = 0)
catch (Exception)
{
if (playerPattern == null || playerPattern.Length <= 1)
{
return;
}
await using var connection = await _database.GetConnectionAsync();
if (type == 2)
{
string _unbanSql = "UPDATE sa_mutes SET status = 'UNMUTED' WHERE (player_steamid = @pattern OR player_name = @pattern) AND status = 'ACTIVE'";
await connection.ExecuteAsync(_unbanSql, new { pattern = playerPattern });
return;
}
string muteType = "GAG";
if (type == 1)
{
muteType = "MUTE";
}
else if (type == 2)
muteType = "SILENCE";
string sqlUnban = "UPDATE sa_mutes SET status = 'UNMUTED' WHERE (player_steamid = @pattern OR player_name = @pattern) AND type = @muteType AND status = 'ACTIVE'";
await connection.ExecuteAsync(sqlUnban, new { pattern = playerPattern, muteType });
}
public async Task ExpireOldMutes()
{
try
{
await using var connection = await _database.GetConnectionAsync();
string sql = "UPDATE sa_mutes SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND `duration` > 0 AND ends <= @CurrentTime";
await connection.ExecuteAsync(sql, new { CurrentTime = DateTime.Now });
}
catch (Exception)
{
if (CS2_SimpleAdmin._logger != null)
CS2_SimpleAdmin._logger.LogCritical("Unable to remove expired mutes");
}
}
public async Task CheckMute(PlayerInfo player)
{
if (player.UserId == null || player.SteamId == null) return;
string steamId = player.SteamId;
List<dynamic> activeMutes = await IsPlayerMuted(steamId);
if (activeMutes.Count > 0)
{
foreach (var mute in activeMutes)
{
string muteType = mute.type;
TimeSpan duration = mute.ends - mute.created;
int durationInSeconds = (int)duration.TotalSeconds;
if (muteType == "GAG")
{
if (CS2_SimpleAdmin.TagsDetected)
NativeAPI.IssueServerCommand($"css_tag_mute {player!.SteamId}");
/*
CCSPlayerController currentPlayer = player;
if (mute.duration == 0 || durationInSeconds >= 1800) continue;
await Task.Delay(TimeSpan.FromSeconds(durationInSeconds));
if (currentPlayer != null && currentPlayer.IsValid)
{
NativeAPI.IssueServerCommand($"css_tag_unmute {currentPlayer.Index.ToString()}");
await UnmutePlayer(currentPlayer.AuthorizedSteamID.SteamId64.ToString(), 0);
}
*/
}
else
{
// Mic mute
}
}
}
return new List<dynamic>();
}
}
}
public async Task<int> GetPlayerMutes(string steamId)
{
await using var connection = await _database.GetConnectionAsync();
int muteCount;
string sql = "SELECT COUNT(*) FROM sa_mutes WHERE player_steamid = @PlayerSteamID";
muteCount = await connection.ExecuteScalarAsync<int>(sql, new { PlayerSteamID = steamId });
return muteCount;
}
public async Task UnmutePlayer(string playerPattern, int type = 0)
{
if (playerPattern == null || playerPattern.Length <= 1)
{
return;
}
await using var connection = await _database.GetConnectionAsync();
if (type == 2)
{
string _unbanSql = "UPDATE sa_mutes SET status = 'UNMUTED' WHERE (player_steamid = @pattern OR player_name = @pattern) AND status = 'ACTIVE'";
await connection.ExecuteAsync(_unbanSql, new { pattern = playerPattern });
return;
}
string muteType = "GAG";
if (type == 1)
{
muteType = "MUTE";
}
else if (type == 2)
muteType = "SILENCE";
string sqlUnban = "UPDATE sa_mutes SET status = 'UNMUTED' WHERE (player_steamid = @pattern OR player_name = @pattern) AND type = @muteType AND status = 'ACTIVE'";
await connection.ExecuteAsync(sqlUnban, new { pattern = playerPattern, muteType });
}
public async Task ExpireOldMutes()
{
try
{
await using var connection = await _database.GetConnectionAsync();
string sql = "UPDATE sa_mutes SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND `duration` > 0 AND ends <= @CurrentTime";
await connection.ExecuteAsync(sql, new { CurrentTime = DateTime.Now });
}
catch (Exception)
{
if (CS2_SimpleAdmin._logger != null)
CS2_SimpleAdmin._logger.LogCritical("Unable to remove expired mutes");
}
}
}

View File

@@ -1,139 +1,137 @@
using System.Collections.Concurrent;
namespace CS2_SimpleAdmin
namespace CS2_SimpleAdmin;
public enum PenaltyType
{
public enum PenaltyType
{
Mute,
Gag,
Silence
}
Mute,
Gag,
Silence
}
public class PlayerPenaltyManager
{
private static ConcurrentDictionary<int, Dictionary<PenaltyType, List<(DateTime EndDateTime, int Duration)>>> penalties =
new ConcurrentDictionary<int, Dictionary<PenaltyType, List<(DateTime, int)>>>();
public class PlayerPenaltyManager
{
private static ConcurrentDictionary<int, Dictionary<PenaltyType, List<(DateTime EndDateTime, int Duration)>>> penalties =
new ConcurrentDictionary<int, Dictionary<PenaltyType, List<(DateTime, int)>>>();
// Add a penalty for a player
public void AddPenalty(int slot, PenaltyType penaltyType, DateTime endDateTime, int durationSeconds)
// Add a penalty for a player
public void AddPenalty(int slot, PenaltyType penaltyType, DateTime endDateTime, int durationSeconds)
{
if (!penalties.ContainsKey(slot))
{
if (!penalties.ContainsKey(slot))
{
penalties[slot] = new Dictionary<PenaltyType, List<(DateTime, int)>>();
}
if (!penalties[slot].ContainsKey(penaltyType))
{
penalties[slot][penaltyType] = new List<(DateTime, int)>();
}
penalties[slot][penaltyType].Add((endDateTime, durationSeconds));
penalties[slot] = new Dictionary<PenaltyType, List<(DateTime, int)>>();
}
public bool IsPenalized(int slot, PenaltyType penaltyType)
if (!penalties[slot].ContainsKey(penaltyType))
{
//Console.WriteLine($"Checking penalties for player with slot {slot} and penalty type {penaltyType}");
penalties[slot][penaltyType] = new List<(DateTime, int)>();
}
if (penalties.TryGetValue(slot, out var penaltyDict) && penaltyDict.TryGetValue(penaltyType, out var penaltiesList))
penalties[slot][penaltyType].Add((endDateTime, durationSeconds));
}
public bool IsPenalized(int slot, PenaltyType penaltyType)
{
//Console.WriteLine($"Checking penalties for player with slot {slot} and penalty type {penaltyType}");
if (penalties.TryGetValue(slot, out var penaltyDict) && penaltyDict.TryGetValue(penaltyType, out var penaltiesList))
{
//Console.WriteLine($"Found penalties for player with slot {slot} and penalty type {penaltyType}");
DateTime now = DateTime.Now;
// Check if any active penalties exist
foreach (var penalty in penaltiesList.ToList())
{
//Console.WriteLine($"Found penalties for player with slot {slot} and penalty type {penaltyType}");
DateTime now = DateTime.Now;
// Check if any active penalties exist
foreach (var penalty in penaltiesList.ToList())
// Check if the penalty is still active
if (penalty.Duration > 0 && now >= penalty.EndDateTime.AddSeconds(penalty.Duration))
{
// Check if the penalty is still active
if (penalty.Duration > 0 && now >= penalty.EndDateTime.AddSeconds(penalty.Duration))
//Console.WriteLine($"Removing expired penalty for player with slot {slot} and penalty type {penaltyType}");
penaltiesList.Remove(penalty); // Remove expired penalty
if (penaltiesList.Count == 0)
{
//Console.WriteLine($"Removing expired penalty for player with slot {slot} and penalty type {penaltyType}");
penaltiesList.Remove(penalty); // Remove expired penalty
if (penaltiesList.Count == 0)
{
//Console.WriteLine($"No more penalties of type {penaltyType} for player with slot {slot}. Removing penalty type.");
penaltyDict.Remove(penaltyType); // Remove penalty type if no more penalties exist
}
}
else if (penalty.Duration == 0 || now < penalty.EndDateTime)
{
//Console.WriteLine($"Player with slot {slot} is penalized for type {penaltyType}");
// Return true if there's an active penalty
return true;
//Console.WriteLine($"No more penalties of type {penaltyType} for player with slot {slot}. Removing penalty type.");
penaltyDict.Remove(penaltyType); // Remove penalty type if no more penalties exist
}
}
// Return false if no active penalties are found
//Console.WriteLine($"Player with slot {slot} is not penalized for type {penaltyType}");
return false;
else if (penalty.Duration == 0 || now < penalty.EndDateTime)
{
//Console.WriteLine($"Player with slot {slot} is penalized for type {penaltyType}");
// Return true if there's an active penalty
return true;
}
}
// Return false if no penalties of the specified type were found for the player
//Console.WriteLine($"No penalties found for player with slot {slot} and penalty type {penaltyType}");
// Return false if no active penalties are found
//Console.WriteLine($"Player with slot {slot} is not penalized for type {penaltyType}");
return false;
}
// Get the end datetime and duration of penalties for a player and penalty type
public List<(DateTime EndDateTime, int Duration)> GetPlayerPenalties(int slot, PenaltyType penaltyType)
// Return false if no penalties of the specified type were found for the player
//Console.WriteLine($"No penalties found for player with slot {slot} and penalty type {penaltyType}");
return false;
}
// Get the end datetime and duration of penalties for a player and penalty type
public List<(DateTime EndDateTime, int Duration)> GetPlayerPenalties(int slot, PenaltyType penaltyType)
{
if (penalties.TryGetValue(slot, out Dictionary<PenaltyType, List<(DateTime EndDateTime, int Duration)>>? penaltyDict) &&
penaltyDict.TryGetValue(penaltyType, out List<(DateTime EndDateTime, int Duration)>? penaltiesList) && penaltiesList != null)
{
if (penalties.TryGetValue(slot, out Dictionary<PenaltyType, List<(DateTime EndDateTime, int Duration)>>? penaltyDict) &&
penaltyDict.TryGetValue(penaltyType, out List<(DateTime EndDateTime, int Duration)>? penaltiesList) && penaltiesList != null)
return penaltiesList;
}
return new List<(DateTime EndDateTime, int Duration)>();
}
public bool IsSlotInPenalties(int slot)
{
return penalties.ContainsKey(slot);
}
// Remove all penalties for a player slot
public void RemoveAllPenalties(int slot)
{
if (penalties.ContainsKey(slot))
{
penalties.TryRemove(slot, out _);
}
}
// Remove all penalties
public void RemoveAllPenalties()
{
penalties.Clear();
}
// Remove all penalties of a selected type from a specific player
public void RemovePenaltiesByType(int slot, PenaltyType penaltyType)
{
if (penalties.TryGetValue(slot, out Dictionary<PenaltyType, List<(DateTime EndDateTime, int Duration)>>? penaltyDict) &&
penaltyDict.ContainsKey(penaltyType))
{
penaltyDict.Remove(penaltyType);
}
}
// Remove all expired penalties for all players and penalty types
public void RemoveExpiredPenalties()
{
DateTime now = DateTime.Now;
foreach (var kvp in penalties.ToList()) // Use ToList to avoid modification while iterating
{
var playerSlot = kvp.Key;
var penaltyDict = kvp.Value;
// Remove expired penalties for the player
foreach (var penaltiesList in penaltyDict.Values)
{
return penaltiesList;
penaltiesList.RemoveAll(p => p.Duration > 0 && now >= p.EndDateTime.AddSeconds(p.Duration));
}
return new List<(DateTime EndDateTime, int Duration)>();
}
public bool IsSlotInPenalties(int slot)
{
return penalties.ContainsKey(slot);
}
// Remove all penalties for a player slot
public void RemoveAllPenalties(int slot)
{
if (penalties.ContainsKey(slot))
// Remove player slot if no penalties left
if (penaltyDict.Count == 0)
{
penalties.TryRemove(slot, out _);
}
}
// Remove all penalties
public void RemoveAllPenalties()
{
penalties.Clear();
}
// Remove all penalties of a selected type from a specific player
public void RemovePenaltiesByType(int slot, PenaltyType penaltyType)
{
if (penalties.TryGetValue(slot, out Dictionary<PenaltyType, List<(DateTime EndDateTime, int Duration)>>? penaltyDict) &&
penaltyDict.ContainsKey(penaltyType))
{
penaltyDict.Remove(penaltyType);
}
}
// Remove all expired penalties for all players and penalty types
public void RemoveExpiredPenalties()
{
DateTime now = DateTime.Now;
foreach (var kvp in penalties.ToList()) // Use ToList to avoid modification while iterating
{
var playerSlot = kvp.Key;
var penaltyDict = kvp.Value;
// Remove expired penalties for the player
foreach (var penaltiesList in penaltyDict.Values)
{
penaltiesList.RemoveAll(p => p.Duration > 0 && now >= p.EndDateTime.AddSeconds(p.Duration));
}
// Remove player slot if no penalties left
if (penaltyDict.Count == 0)
{
penalties.TryRemove(playerSlot, out _);
}
penalties.TryRemove(playerSlot, out _);
}
}
}
}
}