Commands + Server first development release ready (USER: TEST, PASS: 1234) (Serveradress: 185.113.120.99, PORT: 3767)

This commit is contained in:
Tim G. | SnapixLP
2025-06-05 22:58:56 +02:00
parent 838b31cb1f
commit 38a9a72740
15 changed files with 148 additions and 138 deletions

View File

@@ -43,6 +43,7 @@ public class BackendServer : DX86.TcpServer
JsonMessage? jsonMessage;
if (message.StartsWith("{") && message.EndsWith("}"))
{
this.SendMessageAsync(client, "Command received\n");
try
{
jsonMessage = JsonSerializer.Deserialize<JsonMessage>(message);

View File

@@ -1,6 +0,0 @@
namespace Server.Commands;
public class ClockCommand
{
}

View File

@@ -1,6 +1,7 @@
using System.Net.Sockets;
using System.Text.Json;
using DX86;
using Server.Commands;
using Library;
namespace Server;
@@ -26,21 +27,24 @@ public class CommandLibrary
#region Client Commands
[Command("login")]
public static string LoginCommand(string[] args, TcpClient? client, TcpServer? socket)
[Command("login")]
public static string LoginCommand(string[] args, TcpClient? client, TcpServer? socket)
{
if (args.Length < 2)
throw new CommandException("Missing arguments: usage is login <username> <password>");
string username = args[0];
string password = args[1];
if (socket?.LoggedInClients.ContainsKey(client) == true)
throw new CommandException("User already logged in.");
if (username == "test" && password == "1234")
if (username == "TEST" && password == "1234")
{
if (client != null)
{
socket?.LoggedInClients.Add(client, username);
return "Login successful";
return "success";
}
throw new CommandException("No client connection detected.");
@@ -55,10 +59,26 @@ public class CommandLibrary
if (client != null && socket?.LoggedInClients.ContainsKey(client) == true)
{
socket.LoggedInClients.Remove(client);
return "Logout successful";
return "success";
}
throw new CommandException("No client provided or not logged in");
}
[Command("getSelfUser")]
public static string GetSelfUserCommand(TcpClient? client, TcpServer? socket)
{
if (client == null || socket == null)
throw new CommandException("No client connection detected.");
if (socket.LoggedInClients.TryGetValue(client, out var username))
{
Employee returnEmployee = new Employee(username);
string jsonEmployee = JsonSerializer.Serialize(returnEmployee);
return jsonEmployee;
}
throw new CommandException("User not logged in.");
}
#endregion

View File

@@ -2,7 +2,6 @@
using System.Reflection;
using System.Text.Json;
using DX86;
using Server.Commands;
namespace Server;
@@ -29,8 +28,15 @@ public class CommandManager
Program.messageSender.Log($"[COMMANDMANAGER] Registered command: {attr.Name}");
}
}
public void ExecuteCommand(string executor, TcpClient? client = null, TcpServer? clientSocket = null, string cid = "", params string[] args)
public void ExecuteCommand(string executor,
TcpClient? client = null,
TcpServer? clientSocket = null,
string cid = "",
params string[] args)
{
// — ensure args is never null —
args ??= Array.Empty<string>();
if (_commands.TryGetValue(executor.ToLower(), out var method))
{
try
@@ -50,43 +56,55 @@ public class CommandManager
arguments[i] = clientSocket;
else
{
Program.messageSender.Warn($"[COMMANDMANAGER] Unknown parameter type '{param.ParameterType.Name}' in command '{executor}'. Defaulting to null.");
Program.messageSender.Warn(
$"[COMMANDMANAGER] Unknown parameter type '{param.ParameterType.Name}' in '{executor}'. Defaulting that argument to null."
);
arguments[i] = null;
}
}
Program.messageSender.Debug($"[COMMANDMANAGER] Executing command '{executor}'...");
string result = method.Invoke(null, arguments)?.ToString() ?? "";
Program.messageSender.Debug($"[COMMANDMANAGER] Executing command '{executor}'");
var rawResult = method.Invoke(null, arguments); // invoke the static command method
string result = rawResult?.ToString() ?? "";
var returnMessage = new JsonMessage
// **Log the returned string before sending**
Program.messageSender.Debug($"[COMMANDMANAGER] Command '{executor}' returned: \"{result}\"");
var returnMessage = new Library.Server.JsonResponse
{
cid = cid,
cmd = result
Id = cid,
Response = result
};
var sendClientMessage = JsonSerializer.Serialize(returnMessage);
clientSocket?.SendMessageAsync(client, sendClientMessage + "\n");
Program.messageSender.Debug($"[COMMANDMANAGER] Response sent to client.");
}
// If your command threw a CommandException, catch it here:
catch (TargetInvocationException ex) when (ex.InnerException is CommandException cmdEx)
{
Program.messageSender.Warn($"[COMMANDMANAGER] Command '{executor}' failed: {cmdEx.Message}");
var returnMessage = new JsonMessage
var returnMessage = new Library.Server.JsonResponse
{
cid = cid,
cmd = $"Error: {cmdEx.Message}"
Id = cid,
Response = $"Error: {cmdEx.Message}"
};
var sendClientMessage = JsonSerializer.Serialize(returnMessage);
clientSocket?.SendMessageAsync(client, sendClientMessage + "\n");
}
// Any other exception inside the invoked method
catch (TargetInvocationException ex)
{
var actualError = ex.InnerException?.Message ?? ex.Message;
Program.messageSender.Error($"[COMMANDMANAGER] Unexpected error in command '{executor}': {actualError}");
Program.messageSender.Debug($"[COMMANDMANAGER] Stack Trace: {ex.InnerException?.StackTrace ?? ex.StackTrace}");
Program.messageSender.Error(
$"[COMMANDMANAGER] Unexpected error in command '{executor}': {actualError}"
);
Program.messageSender.Debug(
$"[COMMANDMANAGER] Stack Trace: {ex.InnerException?.StackTrace ?? ex.StackTrace}"
);
}
// Anything else thrown before or during Invoke()
catch (Exception ex)
{
Program.messageSender.Error($"[COMMANDMANAGER] Failed to invoke command '{executor}': {ex.Message}");

View File

@@ -1,6 +0,0 @@
namespace Server.Commands;
public class GetCommand
{
}

View File

@@ -1,26 +0,0 @@
using System.Net.Sockets;
using DX86;
namespace Server.Commands;
public class HelpCommand : ICommand
{
public string Executor { get; }
public HelpCommand()
{
Executor = "help";
}
public string Exec(string[] args, TcpClient? client = null, TcpServer? clientSocket = null)
{
return
"Available commands:\n" +
"1. help - Show this help message\n" +
"2. exit - Exit the server\n" +
"3. user - User management\n" +
"4. settings - Server settings\n" +
"5. start - Start the server\n" +
"6. stop - Stop the server\n"
;
}
}

View File

@@ -1,10 +0,0 @@
using System.Net.Sockets;
using DX86;
namespace Server.Commands;
public interface ICommand
{
string Executor { get; }
public string Exec(string[] args, TcpClient? client, TcpServer? clientSocket);
}

View File

@@ -1,34 +0,0 @@
using System.Net.Sockets;
using DX86;
using MySqlX.XDevAPI;
namespace Server.Commands;
public class LoginCommand : ICommand
{
public string Executor { get; }
public LoginCommand()
{
Executor = "login";
}
public string Exec(string[] args, TcpClient? client, TcpServer? clientSocket)
{
if (args[0] == "test" && args[1] == "test")
{
if (client != null)
{
//clientSocket?.SendMessageAsync(client, "Login successful");
clientSocket?.LoggedInClients.Add(client, "test");
return "Login successful";
}
}
else
{
if (client != null) return "Invalid credentials";
}
return "No client provided or invalid credentials";
}
}

View File

@@ -1,30 +0,0 @@
using System.Net.Sockets;
using DX86;
namespace Server.Commands;
public class LogoutCommand : ICommand
{
public string Executor { get; }
public LogoutCommand()
{
Executor = "logout";
}
public string Exec(string[] args, TcpClient? client = null, TcpServer? clientSocket = null)
{
if (clientSocket == null && client == null)
return "Please provide a valid client or clientSocket.";
if (client != null && clientSocket != null && clientSocket.LoggedInClients.ContainsKey(client))
{
clientSocket.LoggedInClients.Remove(client);
//clientSocket.SendMessageAsync(client, "Success");
return "Logout successful.";
}
else
{
//clientSocket?.SendMessageAsync(client, "Logout failed. You are not logged in.");
return "Logout failed. You are not logged in.";
}
}
}