Skip to content

Commit

Permalink
1.6.9a
Browse files Browse the repository at this point in the history
- Added `IsAdminSilent` to api
- Fixed disabling noclip via admin menu
- Fixed (?) hibernation problem
- Added discord webhook fire when adding ban or mute for offline player
- Updated css and mysqlconnector
  • Loading branch information
daffyyyy committed Nov 22, 2024
1 parent 70a62d4 commit b2ebe13
Show file tree
Hide file tree
Showing 17 changed files with 175 additions and 41 deletions.
5 changes: 5 additions & 0 deletions CS2-SimpleAdmin/Api/CS2_SimpleAdminApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,9 @@ public void LogCommand(CCSPlayerController? caller, CommandInfo command)
{
Helper.LogCommand(caller, command);
}

public bool IsAdminSilent(CCSPlayerController player)
{
return CS2_SimpleAdmin.SilentPlayers.Contains(player.Slot);
}
}
24 changes: 16 additions & 8 deletions CS2-SimpleAdmin/CS2-SimpleAdmin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@

namespace CS2_SimpleAdmin;

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

public override string ModuleName => "CS2-SimpleAdmin" + (Helper.IsDebugBuild ? " (DEBUG)" : " (RELEASE)");
public override string ModuleDescription => "Simple admin plugin for Counter-Strike 2 :)";
public override string ModuleAuthor => "daffyy & Dliix66";
public override string ModuleVersion => "1.6.8a";
public override string ModuleVersion => "1.6.9a";

public override void Load(bool hotReload)
{
Expand All @@ -36,10 +36,11 @@ public override void Load(bool hotReload)
AddTimer(2.0f, () =>
{
if (Database == null) return;

var playerManager = new PlayerManager();

Helper.GetValidPlayers().ForEach(player =>
{
var playerManager = new PlayerManager();
playerManager.LoadPlayerData(player);
});
});
Expand All @@ -56,9 +57,14 @@ public override void OnAllPluginsLoaded(bool hotReload)
{
AddTimer(3.0f, () => ReloadAdmins(null));

MenuApi = MenuCapability.Get();
if (MenuApi == null)
Logger.LogError("MenuManager Core not found...");
try
{
MenuApi = MenuCapability.Get();
}
catch (Exception ex)
{
Logger.LogError("Unable to load required plugins ... \n{exception}", ex.Message);
}

RegisterCommands.InitializeCommands();
}
Expand Down Expand Up @@ -88,9 +94,11 @@ public void OnConfigParsed(CS2_SimpleAdminConfig config)
DbConnectionString = builder.ConnectionString;
Database = new Database.Database(DbConnectionString);

if (!Database.CheckDatabaseConnection())
if (!Database.CheckDatabaseConnection(out var exception))
{
Logger.LogError("Unable connect to database!");
if (exception != null)
Logger.LogError("Problem with database connection! \n{exception}", exception);

Unload(false);
return;
}
Expand Down
4 changes: 2 additions & 2 deletions CS2-SimpleAdmin/CS2-SimpleAdmin.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.286" />
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.287" />
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="MySqlConnector" Version="2.4.0-beta.2" />
<PackageReference Include="MySqlConnector" Version="2.4.0" />
<PackageReference Include="Newtonsoft.Json" Version="*" />
</ItemGroup>

Expand Down
2 changes: 2 additions & 0 deletions CS2-SimpleAdmin/Commands/basebans.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@ public void OnAddBanCommand(CCSPlayerController? caller, CommandInfo command)
{
await BanManager.AddBanBySteamid(steamid, adminInfo, reason, time);
});

Helper.SendDiscordPenaltyMessage(caller, steamid, reason, time, PenaltyType.Ban, _localizer);

command.ReplyToCommand($"Player with steamid {steamid} is not online. Ban has been added offline.");
}
Expand Down
8 changes: 4 additions & 4 deletions CS2-SimpleAdmin/Commands/basecommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -375,14 +375,14 @@ public void ReloadAdmins(CCSPlayerController? caller)
var adminsFile = await File.ReadAllTextAsync(Instance.ModuleDirectory + "/data/admins.json");
var groupsFile = await File.ReadAllTextAsync(Instance.ModuleDirectory + "/data/groups.json");

await Server.NextFrameAsync(() =>
await Server.NextWorldUpdateAsync(() =>
{
if (!string.IsNullOrEmpty(adminsFile))
AddTimer(0.5f, () => AdminManager.LoadAdminData(ModuleDirectory + "/data/admins.json"));
AddTimer(1.0f, () => AdminManager.LoadAdminData(ModuleDirectory + "/data/admins.json"));
if (!string.IsNullOrEmpty(groupsFile))
AddTimer(1.0f, () => AdminManager.LoadAdminGroups(ModuleDirectory + "/data/groups.json"));
AddTimer(1.5f, () => AdminManager.LoadAdminGroups(ModuleDirectory + "/data/groups.json"));
if (!string.IsNullOrEmpty(adminsFile))
AddTimer(1.5f, () => AdminManager.LoadAdminData(ModuleDirectory + "/data/admins.json"));
AddTimer(2.0f, () => AdminManager.LoadAdminData(ModuleDirectory + "/data/admins.json"));
});
});

Expand Down
6 changes: 6 additions & 0 deletions CS2-SimpleAdmin/Commands/basecomms.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ public void OnAddGagCommand(CCSPlayerController? caller, CommandInfo command)
await MuteManager.AddMuteBySteamid(steamid, adminInfo, reason, time);
});

Helper.SendDiscordPenaltyMessage(caller, steamid, reason, time, PenaltyType.Gag, _localizer);

command.ReplyToCommand($"Player with steamid {steamid} is not online. Gag has been added offline.");
}

Expand Down Expand Up @@ -370,6 +372,8 @@ public void OnAddMuteCommand(CCSPlayerController? caller, CommandInfo command)
await MuteManager.AddMuteBySteamid(steamid, adminInfo, reason, time, 1);
});

Helper.SendDiscordPenaltyMessage(caller, steamid, reason, time, PenaltyType.Mute, _localizer);

command.ReplyToCommand($"Player with steamid {steamid} is not online. Mute has been added offline.");
}

Expand Down Expand Up @@ -589,6 +593,8 @@ public void OnAddSilenceCommand(CCSPlayerController? caller, CommandInfo command
await MuteManager.AddMuteBySteamid(steamid, adminInfo, reason, time, 2);
});

Helper.SendDiscordPenaltyMessage(caller, steamid, reason, time, PenaltyType.Silence, _localizer);

command.ReplyToCommand($"Player with steamid {steamid} is not online. Silence has been added offline.");
}

Expand Down
8 changes: 5 additions & 3 deletions CS2-SimpleAdmin/Database/Database.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,18 @@ public void DatabaseMigration()
migrator.ExecuteMigrations();
}

public bool CheckDatabaseConnection()
public bool CheckDatabaseConnection(out string? exception)
{
using var connection = GetConnection();

exception = null;

try
{
return connection.Ping();
}
catch
catch (Exception ex)
{
exception = ex.Message;
return false;
}
}
Expand Down
13 changes: 9 additions & 4 deletions CS2-SimpleAdmin/Events.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public HookResult OnClientDisconnect(EventPlayerDisconnect @event, GameEventInfo
GravityPlayers.Remove(player);

if (player.UserId.HasValue)
PlayersInfo.Remove(player.UserId.Value);
PlayersInfo.TryRemove(player.UserId.Value, out _);

var authorizedSteamId = player.AuthorizedSteamID;
if (authorizedSteamId == null || !PermissionManager.AdminCache.TryGetValue(authorizedSteamId,
Expand Down Expand Up @@ -132,7 +132,7 @@ public HookResult OnPlayerFullConnect(EventPlayerConnectFull @event, GameEventIn
public HookResult OnRoundStart(EventRoundStart @event, GameEventInfo info)
{
#if DEBUG
Logger.LogCritical("[OnRoundEnd]");
Logger.LogCritical("[OnRoundStart]");
#endif

GodPlayers.Clear();
Expand Down Expand Up @@ -209,7 +209,9 @@ private HookResult ComamndListenerHandler(CCSPlayerController? player, CommandIn
if (target == null || !target.IsValid || target.Connected != PlayerConnectedState.PlayerConnected)
return HookResult.Continue;

return !AdminManager.CanPlayerTarget(player, target) ? HookResult.Stop : HookResult.Continue;
Logger.LogInformation($"{player.PlayerName} {AdminManager.GetPlayerImmunity(player).ToString()} probuje wywalic {target.PlayerName} {AdminManager.GetPlayerImmunity(target).ToString()}");

return !player.CanTarget(target) ? HookResult.Stop : HookResult.Continue;
}
}

Expand Down Expand Up @@ -366,12 +368,15 @@ public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info)
{
var player = @event.Userid;

if (player?.UserId == null || player.IsBot || player.Connected != PlayerConnectedState.PlayerConnected)
if (player?.UserId == null || !player.IsValid || player.IsHLTV || player.Connected != PlayerConnectedState.PlayerConnected)
return HookResult.Continue;

SpeedPlayers.Remove(player.Slot);
GravityPlayers.Remove(player);

if (!PlayersInfo.ContainsKey(player.UserId.Value))
return HookResult.Continue;

PlayersInfo[player.UserId.Value].DiePosition = new DiePosition(
new Vector(
player.PlayerPawn.Value?.AbsOrigin?.X ?? 0,
Expand Down
96 changes: 96 additions & 0 deletions CS2-SimpleAdmin/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,102 @@ public static void SendDiscordPenaltyMessage(CCSPlayerController? caller, CCSPla
var hostname = ConVar.Find("hostname")?.StringValue ?? localizer["sa_unknown"];
var colorHex = penaltySetting.FirstOrDefault(s => s.Name.Equals("Color"))?.Value ?? "#FFFFFF";

if (string.IsNullOrEmpty(colorHex))
colorHex = "#FFFFFF";

var embed = new Embed
{
Color = DiscordManager.ColorFromHex(colorHex),
Title = penalty switch
{
PenaltyType.Ban => localizer["sa_discord_penalty_ban"],
PenaltyType.Mute => localizer["sa_discord_penalty_mute"],
PenaltyType.Gag => localizer["sa_discord_penalty_gag"],
PenaltyType.Silence => localizer["sa_discord_penalty_silence"],
PenaltyType.Warn => localizer["sa_discord_penalty_warn"],
_ => throw new ArgumentOutOfRangeException(nameof(penalty), penalty, null)
},
Description = $"{hostname}",
ThumbnailUrl = penaltySetting.FirstOrDefault(s => s.Name.Equals("ThumbnailUrl"))?.Value,
ImageUrl = penaltySetting.FirstOrDefault(s => s.Name.Equals("ImageUrl"))?.Value,
Footer = new Footer
{
Text = penaltySetting.FirstOrDefault(s => s.Name.Equals("Footer"))?.Value
},

Timestamp = Time.ActualDateTime().ToUniversalTime().ToString("o"),
};

for (var i = 0; i < fieldNames.Length; i++)
{
embed.AddField(fieldNames[i], fieldValues[i], inlineFlags[i]);
}

Task.Run(async () =>
{
try
{
await new DiscordManager(webhookUrl).SendEmbedAsync(embed);
}
catch (Exception ex)
{
// Log or handle the exception
CS2_SimpleAdmin._logger?.LogError("Unable to send discord webhook: {exception}", ex.Message);
}
});
}

public static void SendDiscordPenaltyMessage(CCSPlayerController? caller, string steamId, string reason, int duration, PenaltyType penalty, IStringLocalizer? localizer)
{
if (localizer == null) return;

var penaltySetting = penalty switch
{
PenaltyType.Ban => CS2_SimpleAdmin.Instance.Config.Discord.DiscordPenaltyBanSettings,
PenaltyType.Mute => CS2_SimpleAdmin.Instance.Config.Discord.DiscordPenaltyMuteSettings,
PenaltyType.Gag => CS2_SimpleAdmin.Instance.Config.Discord.DiscordPenaltyGagSettings,
PenaltyType.Silence => CS2_SimpleAdmin.Instance.Config.Discord.DiscordPenaltySilenceSettings,
PenaltyType.Warn => CS2_SimpleAdmin.Instance.Config.Discord.DiscordPenaltyWarnSettings,
_ => throw new ArgumentOutOfRangeException(nameof(penalty), penalty, null)
};

var webhookUrl = penaltySetting.FirstOrDefault(s => s.Name.Equals("Webhook"))?.Value;

if (string.IsNullOrEmpty(webhookUrl)) return;
const string defaultCommunityUrl = "<https://steamcommunity.com/profiles/0>";
var callerCommunityUrl = caller != null ? $"<{new SteamID(caller.SteamID).ToCommunityUrl()}>" : defaultCommunityUrl;
var targetCommunityUrl = $"<{new SteamID(ulong.Parse(steamId)).ToCommunityUrl()}>";

var callerName = caller?.PlayerName ?? CS2_SimpleAdmin._localizer?["sa_console"] ?? "Console";
var targetName = steamId;
var targetSteamId = steamId;

var futureTime = Time.ActualDateTime().AddMinutes(duration);
var futureUnixTimestamp = new DateTimeOffset(futureTime).ToUnixTimeSeconds();

string time;

if (penaltySetting.FirstOrDefault(s => s.Name.Equals("Time"))?.Value == "{relative}")
time = duration != 0 ? $"<t:{futureUnixTimestamp}:R>" : localizer["sa_permanent"];
else
time = duration != 0 ? ConvertMinutesToTime(duration) : localizer["sa_permanent"];

string[] fieldNames = [
localizer["sa_player"],
localizer["sa_steamid"],
localizer["sa_duration"],
localizer["sa_reason"],
localizer["sa_admin"]];
string[] fieldValues =
[
$"[{targetName}]({targetCommunityUrl})", $"||{targetSteamId}||", time, reason,
$"[{callerName}]({callerCommunityUrl})"
];

bool[] inlineFlags = [true, true, true, false, false];
var hostname = ConVar.Find("hostname")?.StringValue ?? localizer["sa_unknown"];
var colorHex = penaltySetting.FirstOrDefault(s => s.Name.Equals("Color"))?.Value ?? "#FFFFFF";

var embed = new Embed
{
Color = DiscordManager.ColorFromHex(colorHex),
Expand Down
11 changes: 5 additions & 6 deletions CS2-SimpleAdmin/Managers/PermissionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ ORDER BY sa_admins.player_steamid
}
catch (Exception ex)
{
CS2_SimpleAdmin._logger?.LogError(ex.ToString());
CS2_SimpleAdmin._logger?.LogError("Unable to load admins from database! {exception}", ex.Message);
return [];
}
}
Expand Down Expand Up @@ -224,7 +224,7 @@ FROM sa_groups_flags f
}
catch (Exception ex)
{
CS2_SimpleAdmin._logger?.LogError(ex.ToString());
CS2_SimpleAdmin._logger?.LogError("Unable to load groups from database! {exception}", ex.Message);
}

return [];
Expand Down Expand Up @@ -371,7 +371,6 @@ public async Task CreateAdminsJsonFile()
public async Task DeleteAdminBySteamId(string playerSteamId, bool globalDelete = false)
{
if (database == null) return;

if (string.IsNullOrEmpty(playerSteamId)) return;

//_adminCache.TryRemove(playerSteamId, out _);
Expand Down Expand Up @@ -453,7 +452,7 @@ public async Task AddAdminBySteamId(string playerSteamId, string playerName, Lis
});
}

await Server.NextFrameAsync(() =>
await Server.NextWorldUpdateAsync(() =>
{
CS2_SimpleAdmin.Instance.ReloadAdmins(null);
});
Expand Down Expand Up @@ -500,15 +499,15 @@ public async Task AddGroup(string groupName, List<string> flagsList, int immunit

await connection.ExecuteAsync(insertGroupServer, new { groupId, server_id = globalGroup ? null : CS2_SimpleAdmin.ServerId });

await Server.NextFrameAsync(() =>
await Server.NextWorldUpdateAsync(() =>
{
CS2_SimpleAdmin.Instance.ReloadAdmins(null);
});

}
catch (Exception ex)
{
CS2_SimpleAdmin._logger?.LogError(ex.ToString());
CS2_SimpleAdmin._logger?.LogError("Problem with loading admins: {exception}", ex.Message);
}
}

Expand Down
9 changes: 7 additions & 2 deletions CS2-SimpleAdmin/Managers/PlayerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ public void LoadPlayerData(CCSPlayerController player)

try
{
if (!CS2_SimpleAdmin.PlayersInfo.ContainsKey(userId))
{
Helper.KickPlayer(userId, NetworkDisconnectionReason.NETWORK_DISCONNECT_REJECT_INVALIDCONNECTION);
}

// Check if the player is banned
var isBanned = await CS2_SimpleAdmin.Instance.BanManager.IsPlayerBanned(CS2_SimpleAdmin.PlayersInfo[userId]);

Expand Down Expand Up @@ -194,7 +199,7 @@ await Server.NextFrameAsync(() =>
}
catch (Exception ex)
{
CS2_SimpleAdmin._logger?.LogError($"Error processing player connection: {ex}");
CS2_SimpleAdmin._logger?.LogError("Error processing player connection: {exception}", ex.Message);
}
});

Expand Down Expand Up @@ -263,7 +268,7 @@ public void CheckPlayersTimer()
}
catch (Exception ex)
{
CS2_SimpleAdmin._logger?.LogError($"Unexpected error: {ex.Message}");
CS2_SimpleAdmin._logger?.LogError("Unexpected error: {exception}", ex.Message);
}

CS2_SimpleAdmin.BannedPlayers.Clear();
Expand Down
Loading

0 comments on commit b2ebe13

Please sign in to comment.