Skip to content

Commit

Permalink
Merge pull request #2 from oscar-wos/1.3
Browse files Browse the repository at this point in the history
1.3.0
  • Loading branch information
oscar-wos authored May 28, 2024
2 parents e9b6741 + ec440d7 commit b5be0ed
Show file tree
Hide file tree
Showing 17 changed files with 888 additions and 157 deletions.
2 changes: 1 addition & 1 deletion Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace Sessions;

public class CoreConfig : BasePluginConfig
public class SessionsConfig : BasePluginConfig
{
public override int Version { get; set; } = 1;

Expand Down
5 changes: 3 additions & 2 deletions Globals.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using SessionsLibrary;

namespace Sessions;

public partial class Sessions
{
public override string ModuleName => "Sessions";
public override string ModuleDescription => "Track player sessions";
public override string ModuleAuthor => "github.com/oscar-wos/Sessions";
public override string ModuleVersion => "1.2.8";
public override string ModuleVersion => "1.3.0";

public required IDatabase _database;
public readonly Ip _ip = new();
Expand Down
25 changes: 11 additions & 14 deletions IDatabase.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
using Microsoft.Extensions.Logging;
using SessionsLibrary;

namespace Sessions;

public interface IDatabase
{
string BuildConnectionString(CoreConfig config);
string BuildConnectionString(SessionsConfig config);
Task CreateTablesAsync();

Task<ServerSQL> GetServerAsync(string serverIp, ushort serverPort);
Task<MapSQL> GetMapAsync(string mapName);
Task<PlayerSQL> GetPlayerAsync(ulong steamId);
Task<SessionSQL> GetSessionAsync(int playerId, int serverId, int mapId, string ip);
Task<AliasSQL?> GetAliasAsync(int playerId);

void CreateTablesAsync();
void UpdateSessionsBulkAsync(int[] playerIds, long[] sessionIds);
void UpdateSeen(int playerId);
void UpdateSessions(List<int> playerIds, List<long> sessionIds);

void InsertAlias(long sessionId, int playerId, string alias);
void InsertMessage(long sessionId, int playerId, MessageType messageType, string message);
Expand All @@ -30,7 +31,7 @@ public class DatabaseFactory : IDatabaseFactory
private readonly IDatabase _database;
private readonly ILogger _logger;

public DatabaseFactory(CoreConfig config)
public DatabaseFactory(SessionsConfig config)
{
CheckConfig(config);

Expand All @@ -45,17 +46,13 @@ public DatabaseFactory(CoreConfig config)
};
}

public IDatabase Database => _database;

private static void CheckConfig(CoreConfig config)
private static void CheckConfig(SessionsConfig config)
{
if (string.IsNullOrWhiteSpace(config.DatabaseType) ||
string.IsNullOrWhiteSpace(config.DatabaseHost) ||
string.IsNullOrWhiteSpace(config.DatabaseUser) ||
string.IsNullOrWhiteSpace(config.DatabaseName) ||
config.DatabasePort == 0)
{
if (string.IsNullOrWhiteSpace(config.DatabaseType) || string.IsNullOrWhiteSpace(config.DatabaseHost)
|| string.IsNullOrWhiteSpace(config.DatabaseUser) || string.IsNullOrWhiteSpace(config.DatabaseName)
|| config.DatabasePort == 0)
throw new InvalidOperationException("Database is not set in the configuration file");
}
}

public IDatabase Database => _database;
}
32 changes: 0 additions & 32 deletions IDatabaseQueries.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,36 +62,4 @@ public IEnumerable<string> GetCreateQueries()
yield return CreateAliases;
yield return CreateMessages;
}
}

public class ServerSQL()
{
public short Id { get; set; }

public MapSQL? Map { get; set; }
}

public class MapSQL()
{
public short Id { get; set; }
}

public class PlayerSQL()
{
public int Id { get; set; }
public DateTime FirstSeen { get; set; }
public DateTime LastSeen { get; set; }

public SessionSQL? Session { get; set; }
}

public class SessionSQL()
{
public long Id { get; set; }
}

public class AliasSQL
{
public int Id { get; set; }
public required string Alias { get; set; }
}
69 changes: 35 additions & 34 deletions PostgreService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Dapper;
using Npgsql;
using Microsoft.Extensions.Logging;
using SessionsLibrary;

namespace Sessions;

Expand All @@ -12,12 +13,12 @@ public class PostgreService : IDatabase
private readonly string _connectionString;
private readonly NpgsqlConnection _connection;

public PostgreService(CoreConfig config, ILogger logger)
public PostgreService(SessionsConfig config, ILogger logger)
{
_logger = logger;
_queries = new PostgreServiceQueries();
_connectionString = BuildConnectionString(config);

try
{
_connection = new NpgsqlConnection(_connectionString);
Expand All @@ -30,7 +31,7 @@ public PostgreService(CoreConfig config, ILogger logger)
}
}

public string BuildConnectionString(CoreConfig config)
public string BuildConnectionString(SessionsConfig config)
{
NpgsqlConnectionStringBuilder builder = new()
{
Expand All @@ -45,6 +46,24 @@ public string BuildConnectionString(CoreConfig config)
return builder.ConnectionString;
}

public async Task CreateTablesAsync()
{
try
{
await using NpgsqlTransaction tx = await _connection.BeginTransactionAsync();

foreach (string query in _queries.GetCreateQueries())
await _connection.ExecuteAsync(query, transaction: tx);

await tx.CommitAsync();
}
catch (NpgsqlException ex)
{
_logger.LogError(ex, "Failed to create tables");
throw;
}
}

public async Task<ServerSQL> GetServerAsync(string serverIp, ushort serverPort)
{
short serverPortSigned = (short)(serverPort - 0x8000);
Expand Down Expand Up @@ -127,25 +146,20 @@ public async Task<SessionSQL> GetSessionAsync(int playerId, int serverId, int ma
}
}

public async void CreateTablesAsync()
public async void UpdateSeen(int playerId)
{
try
{
await using NpgsqlTransaction tx = await _connection.BeginTransactionAsync();

foreach (string query in _queries.GetCreateQueries())
await _connection.ExecuteAsync(query, transaction: tx);

await tx.CommitAsync();
await _connection.ExecuteAsync(_queries.UpdateSeen, new { PlayerId = playerId });
}
catch (NpgsqlException ex)
{
_logger.LogError(ex, "Failed to create tables");
_logger.LogError(ex, "Error while updating seen");
throw;
}
}

public async void UpdateSessionsBulkAsync(int[] playerIds, long[] sessionIds)
public async void UpdateSessions(List<int> playerIds, List<long> sessionIds)
{
await using NpgsqlTransaction tx = await _connection.BeginTransactionAsync();

Expand All @@ -156,7 +170,7 @@ public async void UpdateSessionsBulkAsync(int[] playerIds, long[] sessionIds)

foreach (long sessionId in sessionIds)
await _connection.ExecuteAsync(_queries.UpdateSession, new { SessionId = sessionId }, transaction: tx);

await tx.CommitAsync();
}
catch (NpgsqlException ex)
Expand All @@ -167,20 +181,7 @@ public async void UpdateSessionsBulkAsync(int[] playerIds, long[] sessionIds)
}
}

public void UpdateSeen(int playerId)
{
try
{
_connection.ExecuteAsync(_queries.UpdateSeen, new { PlayerId = playerId });
}
catch (NpgsqlException ex)
{
_logger.LogError(ex, "Error while updating seen");
throw;
}
}

public void InsertAlias(long sessionId, int playerId, string alias)
public async void InsertAlias(long sessionId, int playerId, string alias)
{
try
{
Expand All @@ -189,8 +190,8 @@ public void InsertAlias(long sessionId, int playerId, string alias)
command.Parameters.AddWithValue("@SessionId", sessionId);
command.Parameters.AddWithValue("@PlayerId", playerId);
command.Parameters.AddWithValue("@Alias", alias);
command.ExecuteNonQuery();

await command.ExecuteNonQueryAsync();
}
catch (NpgsqlException ex)
{
Expand All @@ -199,7 +200,7 @@ public void InsertAlias(long sessionId, int playerId, string alias)
}
}

public void InsertMessage(long sessionId, int playerId, MessageType messageType, string message)
public async void InsertMessage(long sessionId, int playerId, MessageType messageType, string message)
{
try
{
Expand All @@ -209,8 +210,8 @@ public void InsertMessage(long sessionId, int playerId, MessageType messageType,
command.Parameters.AddWithValue("@PlayerId", playerId);
command.Parameters.AddWithValue("@MessageType", (int)messageType);
command.Parameters.AddWithValue("@Message", message);
command.ExecuteNonQuery();

await command.ExecuteNonQueryAsync();
}
catch (NpgsqlException ex)
{
Expand Down Expand Up @@ -276,9 +277,9 @@ message VARCHAR(512)
public override string SelectPlayer => "SELECT id, first_seen, last_seen FROM players WHERE steam_id = @SteamId";
public override string InsertPlayer => "INSERT INTO players (steam_id) VALUES (@SteamId) RETURNING id, first_seen, last_seen";

public override string InsertSession => "INSERT INTO sessions (player_id, server_id, map_id, ip) VALUES (@PlayerId, @ServerId, @MapId, CAST(@Ip as INET)) RETURNING id";
public override string UpdateSession => "UPDATE sessions SET end_time = NOW() WHERE id = @SessionId";
public override string UpdateSeen => "UPDATE players SET last_seen = NOW() WHERE id = @PlayerId";
public override string UpdateSession => "UPDATE sessions SET end_time = NOW() WHERE id = @SessionId";
public override string InsertSession => "INSERT INTO sessions (player_id, server_id, map_id, ip) VALUES (@PlayerId, @ServerId, @MapId, CAST(@Ip as INET)) RETURNING id";

public override string SelectAlias => "SELECT id, alias FROM aliases WHERE player_id = @PlayerId ORDER BY id DESC LIMIT 1";
public override string InsertAlias => "INSERT INTO aliases (session_id, player_id, alias) VALUES (@SessionId, @PlayerId, @Alias)";
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Supports postgre + mysql
Supports postgresql + mysql
`counterstrikesharp/configs/plugins/Sessions/Sessions.json`
```
{
Expand Down
Loading

0 comments on commit b5be0ed

Please sign in to comment.