test
This commit is contained in:
Dawid Bepierszcz
2024-02-12 13:00:38 +01:00
parent 6a182fff9d
commit bda704e843
21 changed files with 3012 additions and 2663 deletions

312
Managers/AdminSQLManager.cs Normal file
View File

@@ -0,0 +1,312 @@
using CounterStrikeSharp.API.Modules.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
namespace CS2_SimpleAdmin
{
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)
{
_database = database;
}
/*
public async Task<List<dynamic>> GetAdminFlags(string steamId)
{
if (_adminCache.ContainsKey(steamId))
{
return _adminCache[steamId].Select(flag => (dynamic)flag).ToList();
}
else
{
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);
}
}
return _adminCache[steamId].Select(flag => (dynamic)flag).ToList();
}
*/
public async Task<List<(List<string>, int)>> GetAdminFlags(string steamId)
{
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();
if (activeFlags == null)
{
return new List<(List<string>, int)>();
}
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);
}
}
*/
foreach (dynamic flags in activeFlags)
{
if (flags is not IDictionary<string, object> flagsDict)
{
continue;
}
if (!flagsDict.TryGetValue("flags", out var flagsValueObj) || !flagsDict.TryGetValue("immunity", out var immunityValueObj))
{
continue;
}
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));
}
/* 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()
{
DateTime now = DateTime.Now;
try
{
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)
{
return new List<(string, List<string>, int, DateTime?)>();
}
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");
}
}
}
}

177
Managers/BanManager.cs Normal file
View File

@@ -0,0 +1,177 @@
using Dapper;
using Microsoft.Extensions.Logging;
namespace CS2_SimpleAdmin
{
internal class BanManager
{
private readonly Database _database;
private readonly CS2_SimpleAdminConfig _config;
public BanManager(Database database, CS2_SimpleAdminConfig config)
{
_database = database;
_config = config;
}
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}");
#endif
DateTime currentTimeUtc = DateTime.UtcNow;
string sql = "SELECT COUNT(*) FROM sa_bans WHERE (player_steamid = @PlayerSteamID OR player_ip = @PlayerIP) AND status = 'ACTIVE' AND (duration = 0 OR ends > @CurrentTime)";
int banCount = 0;
try
{
await using var connection = await _database.GetConnectionAsync();
var parameters = new
{
PlayerSteamID = player.SteamId,
PlayerIP = !string.IsNullOrEmpty(player.IpAddress) ? player.IpAddress : (object)DBNull.Value,
CurrentTime = currentTimeUtc
};
banCount = await connection.ExecuteScalarAsync<int>(sql, parameters);
}
catch (Exception)
{
return false;
}
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))
{
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
{
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");
}
}
}
}

208
Managers/MuteManager.cs Normal file
View File

@@ -0,0 +1,208 @@
using CounterStrikeSharp.API.Core;
using Dapper;
using Microsoft.Extensions.Logging;
namespace CS2_SimpleAdmin
{
public class MuteManager
{
private readonly Database _database;
public MuteManager(Database database)
{
_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.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}");
#endif
try
{
await using var connection = await _database.GetConnectionAsync();
DateTime currentTimeUtc = DateTime.UtcNow;
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 = currentTimeUtc };
var activeMutes = (await connection.QueryAsync(sql, parameters)).ToList();
return activeMutes;
}
catch (Exception)
{
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");
}
}
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
}
}
}
}
}
}

View File

@@ -0,0 +1,139 @@
using System.Collections.Concurrent;
namespace CS2_SimpleAdmin
{
public enum PenaltyType
{
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)>>>();
// Add a penalty for a player
public void AddPenalty(int slot, PenaltyType penaltyType, DateTime endDateTime, int durationSeconds)
{
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));
}
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())
{
// 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($"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;
}
}
// Return false if no active penalties are found
//Console.WriteLine($"Player with slot {slot} is not penalized for type {penaltyType}");
return false;
}
// 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)
{
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)
{
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 _);
}
}
}
}
}