Merge branch 'master' into add_dms_and_groups

# Conflicts:
#	src/GsDChat.Client/Network/ChatClientConnection.cs
#	src/GsDChat.Client/Screens/ChatScreen.cs
#	src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs
This commit is contained in:
tyuXX 2026-10-17 13:18:01 +00:00
commit dae028f686
8 changed files with 309 additions and 41 deletions

8
GsDChat.code-workspace Normal file
View file

@ -0,0 +1,8 @@
{
"folders": [
{
"path": "."
}
],
"settings": {}
}

View file

@ -418,6 +418,7 @@ public class ChatClientConnection : IDisposable
{ {
_state.AddNotice(cmdRes.Output); _state.AddNotice(cmdRes.Output);
_state.SetStatus(cmdRes.Success ? "Command executed." : "Command error.", 4); _state.SetStatus(cmdRes.Success ? "Command executed." : "Command error.", 4);
// Also add to chat as a system message for visibility
if (!string.IsNullOrEmpty(cmdRes.Output) && !string.IsNullOrEmpty(cmdRes.ChannelId)) if (!string.IsNullOrEmpty(cmdRes.Output) && !string.IsNullOrEmpty(cmdRes.ChannelId))
{ {
_state.AddSystemMessageToChat(cmdRes.Output, cmdRes.ChannelId); _state.AddSystemMessageToChat(cmdRes.Output, cmdRes.ChannelId);

View file

@ -41,7 +41,7 @@ public class Program
Console.WriteLine($"========================================{Ansi.Reset}"); Console.WriteLine($"========================================{Ansi.Reset}");
var historyManager = new ServerHistoryManager(); var historyManager = new ServerHistoryManager();
string? rememberedUsername = null; UserProfile? selectedProfile = null;
// If no server was specified via CLI, show interactive server selection menu // If no server was specified via CLI, show interactive server selection menu
while (string.IsNullOrEmpty(serverUrl)) while (string.IsNullOrEmpty(serverUrl))
@ -54,8 +54,8 @@ public class Program
for (int i = 0; i < servers.Count; i++) for (int i = 0; i < servers.Count; i++)
{ {
var s = servers[i]; var s = servers[i];
string userTag = !string.IsNullOrEmpty(s.LastUsername) ? $" (@{s.LastUsername})" : ""; 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}){userTag}{Ansi.Reset}"); Console.WriteLine($" {Ansi.BrightYellow}[{i + 1}]{Ansi.Reset} {Ansi.BrightWhite}{s.Name}{Ansi.Reset} {Ansi.Gray}({s.Url}){profileCount}{Ansi.Reset}");
} }
} }
else else
@ -71,27 +71,42 @@ public class Program
Console.WriteLine($" {Ansi.Gray}[Q]{Ansi.Reset} Quit"); Console.WriteLine($" {Ansi.Gray}[Q]{Ansi.Reset} Quit");
Console.Write($"\nSelect option: "); Console.Write($"\nSelect option: ");
string? input = Console.ReadLine()?.Trim(); char input = ReadKeyChar();
if (string.Equals(input, "Q", StringComparison.OrdinalIgnoreCase)) if (char.ToUpper(input) == 'Q')
{ {
Console.WriteLine("Goodbye."); Console.WriteLine("Goodbye.");
return; return;
} }
if (string.Equals(input, "D", StringComparison.OrdinalIgnoreCase) && servers.Count > 0) if (char.ToUpper(input) == 'D' && servers.Count > 0)
{ {
selectedProfile = null;
Console.Write("Enter number to delete: "); Console.Write("Enter number to delete: ");
if (int.TryParse(Console.ReadLine(), out int delIdx) && delIdx >= 1 && delIdx <= servers.Count) char delChar = ReadKeyChar();
if (delChar >= '1' && delChar <= '9')
{
int delIdx = delChar - '0';
if (delIdx >= 1 && delIdx <= servers.Count)
{ {
historyManager.RemoveServer(servers[delIdx - 1].Id); historyManager.RemoveServer(servers[delIdx - 1].Id);
Console.WriteLine($"{Ansi.Green}Removed server from history.{Ansi.Reset}"); 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; continue;
} }
if (string.Equals(input, "N", StringComparison.OrdinalIgnoreCase) || servers.Count == 0 && string.IsNullOrEmpty(input)) 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): "); Console.Write("\nEnter Server URL or IP (e.g. chat.example.com, http://localhost:5000): ");
string? customUrl = Console.ReadLine()?.Trim(); string? customUrl = Console.ReadLine()?.Trim();
if (!string.IsNullOrEmpty(customUrl)) if (!string.IsNullOrEmpty(customUrl))
@ -101,13 +116,35 @@ public class Program
continue; continue;
} }
if (int.TryParse(input, out int sel) && sel >= 1 && sel <= servers.Count) if (input >= '1' && input <= '9')
{
int sel = input - '0';
if (sel >= 1 && sel <= servers.Count)
{ {
var chosen = servers[sel - 1]; var chosen = servers[sel - 1];
serverUrl = chosen.Url; serverUrl = chosen.Url;
rememberedUsername = chosen.LastUsername; 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; break;
} }
}
Console.WriteLine($"{Ansi.BrightRed}Invalid choice. Please select again.{Ansi.Reset}"); Console.WriteLine($"{Ansi.BrightRed}Invalid choice. Please select again.{Ansi.Reset}");
} }
@ -129,17 +166,19 @@ public class Program
{ {
Console.WriteLine($"{Ansi.BrightRed}Failed to reach server!{Ansi.Reset}"); 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? "); Console.Write("Would you like to [R]etry, choose [A]nother server, or [Q]uit? ");
var failChoice = Console.ReadLine()?.Trim().ToUpperInvariant(); char failChoice = ReadKeyChar();
if (failChoice == "A") if (char.ToUpper(failChoice) == 'A')
{ {
serverUrl = null; serverUrl = null;
selectedProfile = null;
await Main(args); // Restart server selection await Main(args); // Restart server selection
return; return;
} }
if (failChoice == "Q") if (char.ToUpper(failChoice) == 'Q')
{ {
return; return;
} }
selectedProfile = null;
continue; // Retry continue; // Retry
} }
@ -158,30 +197,42 @@ public class Program
if (string.IsNullOrEmpty(username)) if (string.IsNullOrEmpty(username))
{ {
Console.Write("\nChoose action: [L]ogin or [R]egister: "); // If a profile is selected with a username, skip login/register choice and use the profile
var choice = Console.ReadLine()?.Trim().ToUpperInvariant(); if (selectedProfile != null && !string.IsNullOrEmpty(selectedProfile.Username))
if (choice == "R" || choice == "REGISTER")
{ {
doRegister = true; 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
string userPrompt = !string.IsNullOrEmpty(rememberedUsername) {
? $"Username [{rememberedUsername}]: " Console.WriteLine($"\nUsing saved profile: {Ansi.BrightCyan}{username}{Ansi.Reset}");
: "Username: "; Console.Write("Password: ");
password = ReadMaskedPassword();
Console.Write(userPrompt); }
string? enteredUser = Console.ReadLine()?.Trim(); }
username = string.IsNullOrEmpty(enteredUser) ? rememberedUsername : enteredUser; 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: "); Console.Write("Password: ");
password = ReadMaskedPassword(); password = ReadMaskedPassword();
} }
}
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{ {
Console.WriteLine($"{Ansi.BrightRed}Username and password are required.{Ansi.Reset}"); Console.WriteLine($"{Ansi.BrightRed}Username and password are required.{Ansi.Reset}");
username = null; username = null;
password = null; password = null;
selectedProfile = null;
continue; continue;
} }
@ -196,13 +247,38 @@ public class Program
Console.WriteLine($"{Ansi.BrightRed}Authentication failed: {authResult.ErrorMessage}{Ansi.Reset}"); Console.WriteLine($"{Ansi.BrightRed}Authentication failed: {authResult.ErrorMessage}{Ansi.Reset}");
username = null; username = null;
password = null; password = null;
selectedProfile = null;
continue; continue;
} }
Console.WriteLine($"{Ansi.BrightGreen}Success! Welcome @{authResult.Username} [{authResult.Role}]{Ansi.Reset}"); Console.WriteLine($"{Ansi.BrightGreen}Success! Welcome @{authResult.Username} [{authResult.Role}]{Ansi.Reset}");
// Save server to history (with upgraded protocol if applicable) // Handle profile saving
historyManager.SaveServer(state.ServerUrl, info.ServerName, authResult.Username); 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.Token = authResult.Token;
state.CurrentUserId = authResult.UserId ?? ""; state.CurrentUserId = authResult.UserId ?? "";
@ -252,4 +328,68 @@ public class Program
} }
return pwd; 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];
}
}
}
}
} }

View file

@ -68,18 +68,26 @@ public class ServerHistoryManager
{ {
existing.Name = string.IsNullOrWhiteSpace(name) ? existing.Name : name; existing.Name = string.IsNullOrWhiteSpace(name) ? existing.Name : name;
existing.Url = normalizedUrl; existing.Url = normalizedUrl;
if (!string.IsNullOrWhiteSpace(username)) existing.LastUsername = username;
existing.LastConnected = DateTime.UtcNow; existing.LastConnected = DateTime.UtcNow;
// Add or update the user profile without saving password
AddOrUpdateProfile(existing, username, null);
} }
else else
{ {
servers.Insert(0, new ServerProfile var newServer = new ServerProfile
{ {
Name = string.IsNullOrWhiteSpace(name) ? normalizedUrl : name, Name = string.IsNullOrWhiteSpace(name) ? normalizedUrl : name,
Url = normalizedUrl, Url = normalizedUrl,
LastUsername = username,
LastConnected = DateTime.UtcNow LastConnected = DateTime.UtcNow
}); };
if (!string.IsNullOrWhiteSpace(username))
{
AddOrUpdateProfile(newServer, username, null);
}
servers.Insert(0, newServer);
} }
var trimmed = servers.OrderByDescending(s => s.LastConnected).Take(MaxServers).ToList(); var trimmed = servers.OrderByDescending(s => s.LastConnected).Take(MaxServers).ToList();
@ -95,6 +103,106 @@ public class ServerHistoryManager
} }
} }
public void SaveProfile(string url, string username, string? password, bool savePassword)
{
try
{
var servers = LoadServers();
string normalizedUrl = NormalizeUrl(url);
var existing = servers.FirstOrDefault(s => NormalizeUrl(s.Url).Equals(normalizedUrl, StringComparison.OrdinalIgnoreCase));
if (existing == null)
{
existing = new ServerProfile
{
Name = normalizedUrl,
Url = normalizedUrl,
LastConnected = DateTime.UtcNow
};
servers.Insert(0, existing);
}
existing.LastConnected = DateTime.UtcNow;
AddOrUpdateProfile(existing, username, savePassword ? password : null);
var trimmed = servers.OrderByDescending(s => s.LastConnected).Take(MaxServers).ToList();
string json = JsonSerializer.Serialize(trimmed, new JsonSerializerOptions { WriteIndented = true });
string? dir = Path.GetDirectoryName(_filePath);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(_filePath, json);
}
catch (Exception ex)
{
Console.WriteLine($"[Warning] Could not save profile: {ex.Message}");
}
}
private void AddOrUpdateProfile(ServerProfile server, string? username, string? password)
{
if (string.IsNullOrWhiteSpace(username)) return;
var existingProfile = server.UserProfiles.FirstOrDefault(p =>
p.Username.Equals(username, StringComparison.OrdinalIgnoreCase));
if (existingProfile != null)
{
existingProfile.LastUsed = DateTime.UtcNow;
// Only update password if a new one is provided
if (password != null)
{
existingProfile.SavedPassword = password;
}
}
else
{
server.UserProfiles.Add(new UserProfile
{
Username = username,
SavedPassword = password,
LastUsed = DateTime.UtcNow
});
}
}
public UserProfile? GetProfile(string url, string username)
{
var servers = LoadServers();
string normalizedUrl = NormalizeUrl(url);
var server = servers.FirstOrDefault(s => NormalizeUrl(s.Url).Equals(normalizedUrl, StringComparison.OrdinalIgnoreCase));
if (server == null) return null;
return server.UserProfiles.FirstOrDefault(p =>
p.Username.Equals(username, StringComparison.OrdinalIgnoreCase));
}
public void RemoveProfile(string url, string username)
{
try
{
var servers = LoadServers();
string normalizedUrl = NormalizeUrl(url);
var server = servers.FirstOrDefault(s => NormalizeUrl(s.Url).Equals(normalizedUrl, StringComparison.OrdinalIgnoreCase));
if (server != null)
{
server.UserProfiles.RemoveAll(p =>
p.Username.Equals(username, StringComparison.OrdinalIgnoreCase));
// If no profiles left, remove the server entirely
if (server.UserProfiles.Count == 0)
{
servers.Remove(server);
}
string json = JsonSerializer.Serialize(servers, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(_filePath, json);
}
}
catch { }
}
public void RemoveServer(string idOrUrl) public void RemoveServer(string idOrUrl)
{ {
try try

View file

@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Generic;
namespace GsDChat.Client.State; namespace GsDChat.Client.State;
@ -7,6 +8,13 @@ public class ServerProfile
public string Id { get; set; } = Guid.NewGuid().ToString("N"); public string Id { get; set; } = Guid.NewGuid().ToString("N");
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty; public string Url { get; set; } = string.Empty;
public string? LastUsername { get; set; } public List<UserProfile> UserProfiles { get; set; } = new();
public DateTime LastConnected { get; set; } = DateTime.UtcNow; public DateTime LastConnected { get; set; } = DateTime.UtcNow;
} }
public class UserProfile
{
public string Username { get; set; } = string.Empty;
public string? SavedPassword { get; set; }
public DateTime LastUsed { get; set; } = DateTime.UtcNow;
}

View file

@ -82,7 +82,8 @@ public class ModLoaderService
return new Core.Protocol.CommandResultPacket return new Core.Protocol.CommandResultPacket
{ {
Success = res.Success, Success = res.Success,
Output = res.Output Output = res.Output,
ChannelId = client.ActiveChannelId
}; };
} }
return null; return null;

2
start-tunnel.sh Normal file
View file

@ -0,0 +1,2 @@
docker compose -f docker-compose.tunnel.yml down
docker compose -f docker-compose.tunnel.yml up -d --build

View file

@ -58,7 +58,7 @@ public class ServerHistoryTests : IDisposable
Assert.Equal(2, updatedList.Count); Assert.Equal(2, updatedList.Count);
Assert.Equal("http://server1.local:5000", updatedList[0].Url); Assert.Equal("http://server1.local:5000", updatedList[0].Url);
Assert.Equal("Server 1 Updated", updatedList[0].Name); Assert.Equal("Server 1 Updated", updatedList[0].Name);
Assert.Equal("User1New", updatedList[0].LastUsername); Assert.Contains(updatedList[0].UserProfiles, p => p.Username == "User1New");
} }
[Fact] [Fact]