using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using GsDChat.Client.Network; using GsDChat.Client.Rendering; using GsDChat.Client.State; namespace GsDChat.Client; public class Program { public static async Task Main(string[] args) { try { Console.OutputEncoding = System.Text.Encoding.UTF8; Console.InputEncoding = System.Text.Encoding.UTF8; } catch { } string? serverUrl = null; string? username = null; string? password = null; string? serverPassword = null; bool doRegister = false; bool allowInsecure = false; for (int i = 0; i < args.Length; i++) { if (args[i] == "--server" && i + 1 < args.Length) serverUrl = args[i + 1]; if (args[i] == "--username" && i + 1 < args.Length) username = args[i + 1]; if (args[i] == "--password" && i + 1 < args.Length) password = args[i + 1]; if (args[i] == "--server-password" && i + 1 < args.Length) serverPassword = args[i + 1]; if (args[i] == "--register") doRegister = true; if (args[i] == "--insecure") allowInsecure = true; } Console.WriteLine($"{Ansi.Bold}{Ansi.Cyan}========================================"); Console.WriteLine(" GsDChat - Private Community TUI"); Console.WriteLine($"========================================{Ansi.Reset}"); var historyManager = new ServerHistoryManager(); UserProfile? selectedProfile = null; // If no server was specified via CLI, show interactive server selection menu while (string.IsNullOrEmpty(serverUrl)) { var servers = historyManager.LoadServers(); Console.WriteLine($"\n{Ansi.Bold}Choose a Server:{Ansi.Reset}"); if (servers.Count > 0) { for (int i = 0; i < servers.Count; i++) { var s = servers[i]; string profileCount = s.UserProfiles.Count > 0 ? $" ({s.UserProfiles.Count} profile{(s.UserProfiles.Count > 1 ? "s" : "")})" : ""; Console.WriteLine($" {Ansi.BrightYellow}[{i + 1}]{Ansi.Reset} {Ansi.BrightWhite}{s.Name}{Ansi.Reset} {Ansi.Gray}({s.Url}){profileCount}{Ansi.Reset}"); } } else { Console.WriteLine($" {Ansi.Gray}(No saved servers yet){Ansi.Reset}"); } Console.WriteLine($" {Ansi.BrightCyan}[N]{Ansi.Reset} Connect to a New Server"); if (servers.Count > 0) { Console.WriteLine($" {Ansi.BrightRed}[D]{Ansi.Reset} Delete a server from history"); } Console.WriteLine($" {Ansi.Gray}[Q]{Ansi.Reset} Quit"); Console.Write($"\nSelect option: "); char input = ReadKeyChar(); if (char.ToUpper(input) == 'Q') { Console.WriteLine("Goodbye."); return; } if (char.ToUpper(input) == 'D' && servers.Count > 0) { selectedProfile = null; Console.Write("Enter number to delete: "); char delChar = ReadKeyChar(); if (delChar >= '1' && delChar <= '9') { int delIdx = delChar - '0'; if (delIdx >= 1 && delIdx <= servers.Count) { historyManager.RemoveServer(servers[delIdx - 1].Id); Console.WriteLine($"{Ansi.Green}Removed server from history.{Ansi.Reset}"); } else { Console.WriteLine($"{Ansi.BrightRed}Invalid number.{Ansi.Reset}"); } } else { Console.WriteLine($"{Ansi.BrightRed}Invalid input.{Ansi.Reset}"); } continue; } if (char.ToUpper(input) == 'N' || (servers.Count == 0 && input == '\r')) { selectedProfile = null; Console.Write("\nEnter Server URL or IP (e.g. chat.example.com, http://localhost:5000): "); string? customUrl = Console.ReadLine()?.Trim(); if (!string.IsNullOrEmpty(customUrl)) { serverUrl = ServerHistoryManager.NormalizeUrl(customUrl); } continue; } if (input >= '1' && input <= '9') { int sel = input - '0'; if (sel >= 1 && sel <= servers.Count) { var chosen = servers[sel - 1]; serverUrl = chosen.Url; selectedProfile = null; // Show profile selection if profiles exist if (chosen.UserProfiles.Count > 0) { selectedProfile = SelectProfile(chosen); if (selectedProfile == null) { // User cancelled profile selection, reset serverUrl and let them choose again serverUrl = null; continue; } // If user chose "use different username", clear selectedProfile if (string.IsNullOrEmpty(selectedProfile.Username)) { selectedProfile = null; } } break; } } Console.WriteLine($"{Ansi.BrightRed}Invalid choice. Please select again.{Ansi.Reset}"); } // Connection attempt loop while (true) { var state = new ClientState { ServerUrl = serverUrl }; using var connection = new ChatClientConnection(state, allowInsecure); Console.Write($"\nConnecting to server at {Ansi.BrightCyan}{serverUrl}{Ansi.Reset}... "); var info = await connection.GetServerInfoAsync(); if (info == null) { Console.WriteLine($"{Ansi.BrightRed}Failed to reach server!{Ansi.Reset}"); Console.Write("Would you like to [R]etry, choose [A]nother server, or [Q]uit? "); char failChoice = ReadKeyChar(); if (char.ToUpper(failChoice) == 'A') { serverUrl = null; selectedProfile = null; await Main(args); // Restart server selection return; } if (char.ToUpper(failChoice) == 'Q') { return; } selectedProfile = null; continue; // Retry } Console.WriteLine($"{Ansi.BrightGreen}Connected!{Ansi.Reset}"); Console.WriteLine($"Server: {Ansi.Bold}{info.ServerName}{Ansi.Reset} (v{info.Version})"); if (!string.IsNullOrEmpty(info.Motd)) { Console.WriteLine($"MOTD: {info.Motd}"); } if (info.RequiresServerPassword && string.IsNullOrEmpty(serverPassword)) { Console.Write("Enter Server Password: "); serverPassword = ReadMaskedPassword(); } if (string.IsNullOrEmpty(username)) { // If a profile is selected with a username, skip login/register choice and use the profile if (selectedProfile != null && !string.IsNullOrEmpty(selectedProfile.Username)) { username = selectedProfile.Username; // If profile has saved password, use it without prompting if (!string.IsNullOrEmpty(selectedProfile.SavedPassword)) { password = selectedProfile.SavedPassword; Console.WriteLine($"\nUsing saved profile: {Ansi.BrightCyan}{username}{Ansi.Reset}"); Console.WriteLine("Password: (saved)"); } else { Console.WriteLine($"\nUsing saved profile: {Ansi.BrightCyan}{username}{Ansi.Reset}"); Console.Write("Password: "); password = ReadMaskedPassword(); } } else { // No profile selected or user chose different username - skip login/register since we have a server Console.Write("\nUsername: "); username = Console.ReadLine()?.Trim(); Console.Write("Password: "); password = ReadMaskedPassword(); } } if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) { Console.WriteLine($"{Ansi.BrightRed}Username and password are required.{Ansi.Reset}"); username = null; password = null; selectedProfile = null; continue; } Console.WriteLine(doRegister ? "Registering account..." : "Logging in..."); var authResult = doRegister ? await connection.RegisterAsync(username, password, serverPassword) : await connection.LoginAsync(username, password, serverPassword); if (!authResult.Success || string.IsNullOrEmpty(authResult.Token)) { Console.WriteLine($"{Ansi.BrightRed}Authentication failed: {authResult.ErrorMessage}{Ansi.Reset}"); username = null; password = null; selectedProfile = null; continue; } Console.WriteLine($"{Ansi.BrightGreen}Success! Welcome @{authResult.Username} [{authResult.Role}]{Ansi.Reset}"); // Handle profile saving if (!string.IsNullOrEmpty(authResult.Username)) { if (selectedProfile == null || selectedProfile.Username != authResult.Username) { // Ask if user wants to save this profile Console.Write($"\nSave this profile for {Ansi.BrightCyan}{info.ServerName}{Ansi.Reset}? [Y/n]: "); char saveChoice = ReadKeyChar(); if (char.ToUpper(saveChoice) != 'N') { // Ask if user wants to save password Console.Write($"Save password for {Ansi.BrightCyan}{authResult.Username}{Ansi.Reset}? [y/N]: "); char savePasswordChoice = ReadKeyChar(); bool savePassword = char.ToUpper(savePasswordChoice) == 'Y'; historyManager.SaveProfile(state.ServerUrl, authResult.Username, password, savePassword); Console.WriteLine(savePassword ? $"{Ansi.Green}Profile and password saved.{Ansi.Reset}" : $"{Ansi.Green}Profile saved (password not saved).{Ansi.Reset}"); } } else { // Update last used time for existing profile historyManager.SaveProfile(state.ServerUrl, authResult.Username, null, false); } } state.Token = authResult.Token; state.CurrentUserId = authResult.UserId ?? ""; state.CurrentUsername = authResult.Username ?? username; state.CurrentUserRole = authResult.Role ?? "Member"; await connection.StartWebSocketAsync(); // Launch TUI using var cts = new CancellationTokenSource(); Console.CancelKeyPress += (s, e) => { e.Cancel = true; cts.Cancel(); }; var ui = new ConsoleUi(state, connection); await ui.RunAsync(cts.Token); break; } } private static string ReadMaskedPassword() { string pwd = ""; while (true) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter) { Console.WriteLine(); break; } if (key.Key == ConsoleKey.Backspace) { if (pwd.Length > 0) { pwd = pwd[..^1]; Console.Write("\b \b"); } } else if (!char.IsControl(key.KeyChar)) { pwd += key.KeyChar; Console.Write("*"); } } return pwd; } private static char ReadKeyChar() { while (true) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter) { Console.WriteLine(); return '\r'; } if (!char.IsControl(key.KeyChar)) { Console.Write(key.KeyChar); Console.WriteLine(); return key.KeyChar; } } } private static UserProfile? SelectProfile(ServerProfile server) { Console.WriteLine($"\n{Ansi.Bold}Select Profile for {server.Name}:{Ansi.Reset}"); for (int i = 0; i < server.UserProfiles.Count; i++) { var p = server.UserProfiles[i]; string hasPassword = !string.IsNullOrEmpty(p.SavedPassword) ? $"{Ansi.Green}[+password]{Ansi.Reset}" : $"{Ansi.Gray}[no password]{Ansi.Reset}"; Console.WriteLine($" {Ansi.BrightYellow}[{i + 1}]{Ansi.Reset} {Ansi.BrightWhite}{p.Username}{Ansi.Reset} {hasPassword}"); } Console.WriteLine($" {Ansi.BrightCyan}[N]{Ansi.Reset} Use a different username"); Console.WriteLine($" {Ansi.Gray}[Esc]{Ansi.Reset} Go back"); Console.Write($"\nSelect option: "); while (true) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Escape) { Console.WriteLine(); return null; } if (char.ToUpper(key.KeyChar) == 'N') { Console.WriteLine(); // Return a special marker to indicate "use different username" return new UserProfile { Username = "" }; } if (key.KeyChar >= '1' && key.KeyChar <= '9') { int sel = key.KeyChar - '0'; if (sel >= 1 && sel <= server.UserProfiles.Count) { Console.WriteLine(); return server.UserProfiles[sel - 1]; } } } } }