Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Listeners.cs/Events.cs #6

Merged
merged 1 commit into from
Jun 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Sessions.API/Sessions.API.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ public class Server
{
public short Id { get; init; }
public Map? Map { get; set; }
public required string Ip { get; set; }
public required ushort Port { get; set; }
}

public class Map
Expand Down
59 changes: 37 additions & 22 deletions TestPlugin/TestPlugin.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Capabilities;
using CounterStrikeSharp.API.Modules.Commands;
using Microsoft.Extensions.Logging;
using Sessions.API;

Expand All @@ -15,28 +16,42 @@ public class TestPlugin : BasePlugin

public override void Load(bool isReload)
{
AddCommand("css_test", "test", (controller, _) =>
{
if (controller == null)
return;

var server = CapabilityServer.Get()!.Server;
var player = CapabilityPlayer.Get(controller)!.Player;
var session = CapabilityPlayer.Get(controller)!.Session;

Logger.LogInformation($"Server: {server!.Id} - Map: ${server!.Map!.Id} - Player: {player!.Id} - Session: {session!.Id}");
});

RegisterEventHandler<EventPlayerConnect>((@event, _) =>
{
if (@event.Userid == null)
return HookResult.Continue;

var controller = @event.Userid;
var player = CapabilityPlayer.Get(controller)!.Player;

Logger.LogInformation($"Player {player!.Id} connected");
var server = CapabilityServer.Get()!.Server;

if (server != null)
Logger.LogInformation($"Server: {server.Id} (${server.Ip}:${server.Port}) - Map: ${server.Map!.Id}");

AddCommand("css_test", "test", CommandTest);
RegisterEventHandler<EventPlayerConnect>(EventConnect, HookMode.Pre);
}

private void CommandTest(CCSPlayerController? controller, CommandInfo info)
{
if (controller == null)
return;

var server = CapabilityServer.Get()!.Server;
var player = CapabilityPlayer.Get(controller)!.Player;
var session = CapabilityPlayer.Get(controller)!.Session;

if (server == null || player == null || session == null)
return;

Logger.LogInformation($"Player: {player.Id} - Session: {session.Id} - Server: {server.Id}/{CounterStrikeSharp.API.Server.MapName}[{server.Map!.Id}] ({server.Ip}:{server.Port}");
}

private HookResult EventConnect(EventPlayerConnect @event, GameEventInfo info)
{
if (@event.Userid == null)
return HookResult.Continue;
}, HookMode.Pre);

var controller = @event.Userid;
var player = CapabilityPlayer.Get(controller)!.Player;

if (player == null)
return HookResult.Continue;

Logger.LogInformation($"Player {player.Id} connected");
return HookResult.Continue;
}
}
20 changes: 20 additions & 0 deletions src/Events.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;

namespace Sessions;

public partial class Sessions
{
private HookResult OnPlayerChat(EventPlayerChat @event, GameEventInfo info)
{
var player = Utilities.GetPlayerFromUserid(@event.Userid);

if (!IsValidPlayer(player) || !Players.TryGetValue(player!.Slot, out var value) || value.Session == null)
return HookResult.Continue;

var messageType = @event.Teamonly ? MessageType.TeamChat : MessageType.Chat;
Database.InsertMessage(value.Session.Id, value.Id, messageType, @event.Text);

return HookResult.Continue;
}
}
2 changes: 1 addition & 1 deletion src/IDatabase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace Sessions;

public interface IDatabase
{
Task CreateTablesAsync();
Task StartAsync();
Task<Server> GetServerAsync(string serverIp, ushort serverPort);
Task<Map> GetMapAsync(string mapName);
Task<Player> GetPlayerAsync(ulong steamId);
Expand Down
2 changes: 1 addition & 1 deletion src/Ip.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class Ip
private CNetworkSystemUpdatePublicIp? _networkSystemUpdatePublicIp;
private readonly nint _networkSystem = NativeAPI.GetValveInterface(0, "NetworkSystemVersion001");

public string GetPublicIp()
public string? GetPublicIp()
{
unsafe
{
Expand Down
32 changes: 32 additions & 0 deletions src/Listeners.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API;

namespace Sessions;

public partial class Sessions
{
private void OnMapStart(string mapName)
{
Server!.Map = Database.GetMapAsync(mapName).GetAwaiter().GetResult();
}

private void OnClientAuthorized(int playerSlot, CounterStrikeSharp.API.Modules.Entities.SteamID steamId)
{
var player = Utilities.GetPlayerFromSlot(playerSlot);

if (!IsValidPlayer(player))
return;

OnPlayerConnect(playerSlot, steamId.SteamId64, NativeAPI.GetPlayerIpAddress(playerSlot).Split(":")[0]).GetAwaiter().GetResult();
CheckAlias(playerSlot, player!.PlayerName).GetAwaiter().GetResult();
}

private void OnClientDisconnect(int playerSlot)
{
if (!Players.TryGetValue(playerSlot, out var value))
return;

Database.UpdateSeen(value.Id);
Players.Remove(playerSlot);
}
}
2 changes: 1 addition & 1 deletion src/PostgresService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ private static string BuildConnectionString(SessionsConfig config)
return builder.ConnectionString;
}

public async Task CreateTablesAsync()
public async Task StartAsync()
{
try
{
Expand Down
55 changes: 11 additions & 44 deletions src/Sessions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Timers;
using Microsoft.Extensions.Logging;

namespace Sessions;

Expand All @@ -15,52 +14,20 @@ public void OnConfigParsed(SessionsConfig config)

public override void Load(bool isReload)
{
RegisterCapabilities();

var ip = _ip.GetPublicIp();
var ip = _ip.GetPublicIp()!;
var port = (ushort)ConVar.Find("hostport")!.GetPrimitiveValue<int>();
Logger.LogInformation($"Ip: {ip}:{port}");

Database.CreateTablesAsync().GetAwaiter().GetResult();
Database.StartAsync().GetAwaiter().GetResult();
Server = Database.GetServerAsync(ip, port).GetAwaiter().GetResult();
AddTimer(1.0f, Timer_Repeat, TimerFlags.REPEAT);
Server.Ip = ip;
Server.Port = port;

RegisterListener<Listeners.OnMapStart>(mapName =>
Server.Map = Database.GetMapAsync(mapName).GetAwaiter().GetResult()
);

RegisterListener<Listeners.OnClientAuthorized>((playerSlot, steamId) =>
{
var player = Utilities.GetPlayerFromSlot(playerSlot);

if (!IsValidPlayer(player))
return;

OnPlayerConnect(playerSlot, steamId.SteamId64, NativeAPI.GetPlayerIpAddress(playerSlot).Split(":")[0]).GetAwaiter().GetResult();
CheckAlias(playerSlot, player!.PlayerName).GetAwaiter().GetResult();
});

RegisterListener<Listeners.OnClientDisconnect>(playerSlot =>
{
if (!Players.TryGetValue(playerSlot, out var value))
return;

Database.UpdateSeen(value.Id);
Players.Remove(playerSlot);
});

RegisterEventHandler<EventPlayerChat>((@event, _) =>
{
var player = Utilities.GetPlayerFromUserid(@event.Userid);

if (!IsValidPlayer(player) || !Players.TryGetValue(player!.Slot, out var value) || value.Session == null)
return HookResult.Continue;

var messageType = @event.Teamonly ? MessageType.TeamChat : MessageType.Chat;
Database.InsertMessage(value.Session.Id, value.Id, messageType, @event.Text);

return HookResult.Continue;
});
RegisterCapabilities();
RegisterListener<Listeners.OnMapStart>(OnMapStart);
RegisterListener<Listeners.OnClientAuthorized>(OnClientAuthorized);
RegisterListener<Listeners.OnClientDisconnect>(OnClientDisconnect);
RegisterEventHandler<EventPlayerChat>(OnPlayerChat);
AddTimer(1.0f, Timer_Repeat, TimerFlags.REPEAT);

if (!isReload)
return;
Expand All @@ -69,7 +36,7 @@ public override void Load(bool isReload)

foreach (var player in Utilities.GetPlayers().Where(IsValidPlayer))
{
OnPlayerConnect(player.Slot, player.SteamID, NativeAPI.GetPlayerIpAddress(player.Slot).Split(":")[0]).GetAwaiter().GetResult();
OnPlayerConnect(player.Slot, player.AuthorizedSteamID!.SteamId64, NativeAPI.GetPlayerIpAddress(player.Slot).Split(":")[0]).GetAwaiter().GetResult();
CheckAlias(player.Slot, player.PlayerName).GetAwaiter().GetResult();
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/SqlService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ private static string BuildConnectionString(SessionsConfig config)
return builder.ConnectionString;
}

public async Task CreateTablesAsync()
public async Task StartAsync()
{
try
{
Expand Down Expand Up @@ -73,7 +73,7 @@ public async Task<Server> GetServerAsync(string serverIp, ushort serverPort)
return result;

var insert = await _connection.ExecuteScalarAsync(_queries.InsertServer, new { ServerIp = serverIp, ServerPort = serverPort });
return new Server { Id = Convert.ToInt16(insert) };
return new Server { Id = Convert.ToInt16(insert), Ip = serverIp, Port = serverPort };
}
catch (MySqlException ex)
{
Expand Down
Loading