using System.Text; namespace Firefly { public partial class Firefly { #region Server Operations /// /// Handles the AUTH command which authenticates a client. /// /// The password to authenticate with /// The client ID /// OK on success, error if authentication fails static byte[] HandleAuthCommand(string password, string clientId) { if (string.IsNullOrEmpty(serverPassword)) { Console.WriteLine("AUTH command received but server has no password set"); return Encoding.UTF8.GetBytes("-ERR this server does not require authentication\r\n"); } if (serverPassword == password) { Console.WriteLine($"Client {clientId} successfully authenticated"); authenticatedClients[clientId] = true; return Encoding.UTF8.GetBytes("+OK\r\n"); } Console.WriteLine($"Client {clientId} failed authentication attempt with password: {password}"); return Encoding.UTF8.GetBytes("-ERR invalid password\r\n"); } /// /// Checks if a client is authenticated. /// /// The client ID /// True if the client is authenticated, false otherwise static bool IsAuthenticated(string clientId) { // If no password is set, all clients are authenticated by default if (string.IsNullOrEmpty(serverPassword)) { return true; } return authenticatedClients.TryGetValue(clientId, out bool authenticated) && authenticated; } /// /// Handles the SAVE command which triggers a manual backup of the data. /// static byte[] HandleSaveCommand() { try { BackupData(); return Encoding.UTF8.GetBytes("+OK\r\n"); } catch (Exception ex) { return Encoding.UTF8.GetBytes($"-ERR save failed: {ex.Message}\r\n"); } } /// /// Handles the BGSAVE command which triggers an asynchronous backup of the data. /// static byte[] HandleBgSaveCommand() { // Start backup in a separate task Task.Run(() => BackupData()); return Encoding.UTF8.GetBytes("+Background saving started\r\n"); } /// /// Handles server shutdown operations /// static async Task ShutdownServer() { if (backupsEnabled) { Console.WriteLine("Performing final backup before shutdown..."); await Task.Run(() => BackupData()); } // Clean up any remaining client connections foreach (var clientId in authenticatedClients.Keys.ToList()) { authenticatedClients.Remove(clientId); } Console.WriteLine("Server shutdown complete."); } #endregion } }