Skip to content

Commit

Permalink
Add SQL Gang Manager
Browse files Browse the repository at this point in the history
  • Loading branch information
MSWS committed Sep 3, 2024
1 parent 11ffe34 commit def99cb
Show file tree
Hide file tree
Showing 46 changed files with 353 additions and 278 deletions.
5 changes: 2 additions & 3 deletions Commands/CommandCollection.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using GangsAPI.Extensions;
using GangsAPI.Services;
using GangsAPI.Extensions;
using GangsAPI.Services.Commands;
using Microsoft.Extensions.DependencyInjection;

namespace Commands;

Expand Down
1 change: 0 additions & 1 deletion Commands/CommandManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using CounterStrikeSharp.API.Core;
using GangsAPI;
using GangsAPI.Data;
using GangsAPI.Data.Command;
using GangsAPI.Services;
using GangsAPI.Services.Commands;
using Mock;
Expand Down
6 changes: 3 additions & 3 deletions Commands/Commands.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1"/>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\GangsAPI\GangsAPI.csproj" />
<ProjectReference Include="..\GangsImpl\Mock\Mock.csproj" />
<ProjectReference Include="..\GangsAPI\GangsAPI.csproj"/>
<ProjectReference Include="..\GangsImpl\Mock\Mock.csproj"/>
</ItemGroup>

</Project>
10 changes: 4 additions & 6 deletions Commands/GangCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,10 @@
using GangsAPI.Data.Command;
using GangsAPI.Services;
using GangsAPI.Services.Commands;
using Mock;

namespace Commands;

public class GangCommand(IGangManager gangMgr) : ICommand {
public string Name => "css_gang";
public string? Description => "Master command for gangs";

private readonly Dictionary<string, ICommand> sub = new() {
// ["delete"] = new DeleteGangCommand(),
// ["invite"] = new InviteGangCommand(),
Expand All @@ -23,6 +19,9 @@ public class GangCommand(IGangManager gangMgr) : ICommand {
["create"] = new CreateCommand(gangMgr), ["help"] = new HelpCommand()
};

public string Name => "css_gang";
public string? Description => "Master command for gangs";

public async Task<CommandResult> Execute(PlayerWrapper? executor,
CommandInfoWrapper info) {
if (info.ArgCount == 0)
Expand All @@ -35,11 +34,10 @@ public async Task<CommandResult> Execute(PlayerWrapper? executor,

if (info.ArgCount == 1) return CommandResult.INVALID_ARGS;

if (!sub.TryGetValue(info[1], out var command)) {
if (!sub.TryGetValue(info[1], out var command))
// print usage
// info.ReplySync("Usage: /css_gang [create|help]");
return CommandResult.UNKNOWN_COMMAND;
}

var newInfo = new CommandInfoWrapper(info, 1);
return await command.Execute(executor, newInfo);
Expand Down
6 changes: 2 additions & 4 deletions Commands/gang/CreateCommand.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
using CounterStrikeSharp.API;
using GangsAPI.Data;
using GangsAPI.Data;
using GangsAPI.Data.Command;
using GangsAPI.Services;
using GangsAPI.Services.Commands;
using Microsoft.VisualBasic;

namespace Commands.gang;

Expand All @@ -15,7 +13,7 @@ public class CreateCommand(IGangManager gang) : ICommand {

public async Task<CommandResult> Execute(PlayerWrapper? executor,
CommandInfoWrapper info) {
if (executor == null) { return CommandResult.PLAYER_ONLY; }
if (executor == null) return CommandResult.PLAYER_ONLY;

if (info.ArgCount < 2) {
info.ReplySync("Please provide a name for the gang");
Expand Down
3 changes: 1 addition & 2 deletions Commands/gang/HelpCommand.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using CounterStrikeSharp.API.Core.Commands;
using GangsAPI.Data;
using GangsAPI.Data;
using GangsAPI.Data.Command;
using GangsAPI.Services.Commands;

Expand Down
2 changes: 1 addition & 1 deletion Gangs.sln
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GangsImpl", "GangsImpl", "{
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQL", "GangsImpl\SQL\SQL.csproj", "{1899055E-62B8-4907-85A2-DFE22531729E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GenericDB", "GangsImpl\GenericDB\GenericDB.csproj", "{74B15261-4B12-4EF6-859A-E46B315E7DD3}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AbstractDB", "GangsImpl\AbstractDB\AbstractDB.csproj", "{74B15261-4B12-4EF6-859A-E46B315E7DD3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQLite", "GangsImpl\SQLite\SQLite.csproj", "{5186EA9C-D2A4-4D70-8F52-0D6C7B6A61B6}"
EndProject
Expand Down
1 change: 0 additions & 1 deletion Gangs/CS2Gangs.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Collections.Immutable;
using CounterStrikeSharp.API.Core;
using GangsAPI;
using GangsAPI.Services.Commands;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

Expand Down
6 changes: 4 additions & 2 deletions Gangs/GangServiceCollection.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
using Commands;
using CounterStrikeSharp.API.Core;
using GangsAPI;
using GangsAPI.Extensions;
using GangsAPI.Services;
using Microsoft.Extensions.DependencyInjection;
using Mock;
using SQLImpl;

namespace GangsImpl;

public class GangServiceCollection : IPluginServiceCollection<CS2Gangs> {
public void ConfigureServices(IServiceCollection serviceCollection) {
serviceCollection.AddPluginBehavior<IGangManager, MockGangManager>();
// serviceCollection.AddPluginBehavior<IGangManager, SQLStatManager>();
serviceCollection.AddPluginBehavior<IGangManager, SQLGangManager>();
serviceCollection.AddPluginBehavior<IPlayerManager, MockPlayerManager>();
serviceCollection.AddPluginBehavior<IStatManager, MockStatManager>();
serviceCollection.AddPluginBehavior<IStatManager, SQLStatManager>();
serviceCollection
.AddPluginBehavior<IGangStatManager, MockInstanceStatManager>();
serviceCollection
Expand Down
9 changes: 5 additions & 4 deletions Gangs/Gangs.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<ItemGroup>
<ProjectReference Include="..\Commands\Commands.csproj"/>
<ProjectReference Include="..\GangsAPI\GangsAPI.csproj"/>
<ProjectReference Include="..\GangsImpl\SQL\SQL.csproj"/>
</ItemGroup>

<ItemGroup>
Expand All @@ -18,16 +19,16 @@
</ItemGroup>

<ItemGroup>
<Compile Remove="build\**" />
<Compile Remove="build\**"/>
</ItemGroup>

<ItemGroup>
<EmbeddedResource Remove="build\**" />
<EmbeddedResource Remove="build\**"/>
</ItemGroup>

<ItemGroup>
<None Remove="build\**" />
<None Remove="Gangs.zip" />
<None Remove="build\**"/>
<None Remove="Gangs.zip"/>
</ItemGroup>

<PropertyGroup>
Expand Down
8 changes: 3 additions & 5 deletions GangsAPI/Data/Command/CommandInfoWrapper.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Commands;

namespace GangsAPI.Data.Command;

public class CommandInfoWrapper(PlayerWrapper? executor, int offset = 0,
params string[] args) {
public readonly PlayerWrapper? CallingPlayer = executor;

public readonly CommandCallingContext CallingContext =
CommandCallingContext.Console;

public readonly PlayerWrapper? CallingPlayer = executor;

public CommandInfoWrapper(CommandInfo info, int offset = 0) : this(
info.CallingPlayer == null ? null : new PlayerWrapper(info.CallingPlayer),
offset, info.ArgString.Split(" ")) {
Expand Down
20 changes: 10 additions & 10 deletions GangsAPI/Data/Command/CommandResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,37 @@

public enum CommandResult {
/// <summary>
/// The command completed successfully
/// The command completed successfully
/// </summary>
SUCCESS,

/// <summary>
/// The command encountered an error or other
/// scenario that prevented success
/// The command encountered an error or other
/// scenario that prevented success
/// </summary>
FAILURE,

/// <summary>
/// The command was improperly formatted
/// The command was improperly formatted
/// </summary>
UNKNOWN_COMMAND,

/// <summary>
/// The command has improper arguments, or
/// no sufficient arguments
/// The command has improper arguments, or
/// no sufficient arguments
/// </summary>
INVALID_ARGS,

/// <summary>
/// The executor of the command did not have
/// the required permissions
/// The executor of the command did not have
/// the required permissions
/// </summary>
NO_PERMISSION,


/// <summary>
/// This command can only be executed by a player
/// (i.e. not from the console)
/// This command can only be executed by a player
/// (i.e. not from the console)
/// </summary>
PLAYER_ONLY
}
10 changes: 5 additions & 5 deletions GangsAPI/Data/PlayerWrapper.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Admin;

namespace GangsAPI.Data;

public class PlayerWrapper {
private readonly List<string> chatOutput = [], consoleOutput = [];
public readonly string? Name;
public readonly CCSPlayerController? Player;
public readonly ulong Steam;
public AdminData? Data;
private readonly List<string> chatOutput = [], consoleOutput = [];
public IReadOnlyList<string> ChatOutput => chatOutput;
public IReadOnlyList<string> ConsoleOutput => consoleOutput;

public PlayerWrapper(CCSPlayerController player) {
Player = player;
Expand All @@ -30,6 +27,9 @@ public PlayerWrapper(ulong steam, string? name) {
Data = new AdminData { Identity = Steam.ToString() };
}

public IReadOnlyList<string> ChatOutput => chatOutput;
public IReadOnlyList<string> ConsoleOutput => consoleOutput;

public bool IsValid => Player == null || Player.IsValid;

private static char USER_CHAR => PermissionCharacters.UserPermissionChar;
Expand Down
4 changes: 1 addition & 3 deletions GangsAPI/Data/Stat/IPerk.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
namespace GangsAPI.Data.Stat;

public interface IPerk : IStat, IPluginBehavior {

}
public interface IPerk : IStat, IPluginBehavior { }
2 changes: 1 addition & 1 deletion GangsAPI/Services/Commands/ICommandManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public interface ICommandManager : IPluginBehavior {
bool RegisterCommand(ICommand command);

/// <summary>
/// Unregisters a command from the manager.
/// Unregisters a command from the manager.
/// </summary>
/// <param name="command">True if the command was successfully unregistered.</param>
bool UnregisterCommand(ICommand command);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>GenericDB</RootNamespace>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\GangsAPI\GangsAPI.csproj"/>
<ProjectReference Include="..\Mock\Mock.csproj"/>
</ItemGroup>

<ItemGroup>
Expand Down
79 changes: 79 additions & 0 deletions GangsImpl/AbstractDB/AbstractDBGangManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using System.Data.Common;
using CounterStrikeSharp.API.Core;
using Dapper;
using GangsAPI.Data.Gang;
using Mock;
using Xunit;

namespace GenericDB;

public abstract class AbstractDBGangManager(string connectionString,
string table = "gang_gangs", bool testing = false) : MockGangManager {
private DbConnection connection = null!;
private DbTransaction? transaction;
public override void ClearCache() { cachedGangs.Clear(); }

public override void Start(BasePlugin? plugin, bool hotReload) {
Assert.NotNull(table);
connection = CreateDbConnection(connectionString);

connection.Open();

if (testing) transaction = connection.BeginTransaction();

try {
var command = connection.CreateCommand();

command.Transaction = transaction;
command.CommandText = testing ?
$"CREATE TEMPORARY TABLE IF NOT EXISTS {table} (GangId INT NOT NULL AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(255) NOT NULL)" :
$"CREATE TABLE IF NOT EXISTS {table} (GangId INT NOT NULL PRIMARY KEY, Name VARCHAR(255) NOT NULL)";

command.ExecuteNonQuery();
} catch (Exception e) {
transaction?.Rollback();
throw new InvalidOperationException("Failed initializing the database",
e);
}
}

abstract protected DbConnection CreateDbConnection(string connectionString);

public override async Task Load() {
var query = $"SELECT * FROM {table}";
var gangs = await connection.QueryAsync<DBGang>(query);
foreach (var gang in gangs) cachedGangs.Add(gang);
}

public override async Task<bool> UpdateGang(IGang gang) {
await base.UpdateGang(gang);
var query = $"UPDATE {table} SET Name = @Name WHERE GangId = @GangId";
return await connection.ExecuteAsync(query, new { gang.Name, gang.GangId },
transaction) > 0;
}

public override async Task<bool> DeleteGang(int id) {
await base.DeleteGang(id);
var query = $"DELETE FROM {table} WHERE GangId = @id";
return await connection.ExecuteAsync(query, new { id }, transaction) > 0;
}

public override async Task<IGang?> CreateGang(string name, ulong owner) {
Assert.NotNull(table);
if (cachedGangs.Any(g => g.Name == name)) return null;
var query = $"INSERT INTO {table} (Name) VALUES (@name)";
var result =
await connection.ExecuteAsync(query, new { name }, transaction);
if (result == 0) return null;
var id = await connection.ExecuteScalarAsync<int>("SELECT LAST_INSERT_ID()",
transaction: transaction);
var gang = new DBGang(id, name, owner);
cachedGangs.Add(gang);
return gang.Clone() as IGang;
}

public override void Dispose() {
transaction?.Dispose();
connection.Dispose();
}
}
Loading

0 comments on commit def99cb

Please sign in to comment.