481 lines
19 KiB
C#
481 lines
19 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using GsDChat.Client.Network;
|
|
using GsDChat.Client.Rendering;
|
|
using GsDChat.Client.State;
|
|
using GsDChat.Core.Models;
|
|
|
|
namespace GsDChat.Client.Screens;
|
|
|
|
public class ChatScreen : IScreen
|
|
{
|
|
private readonly ClientState _state;
|
|
private readonly ChatClientConnection _connection;
|
|
|
|
public string ScreenId => "F1_Chat";
|
|
public string Title => "Chat";
|
|
public string ShortcutKey => "F1";
|
|
|
|
public ChatScreen(ClientState state, ChatClientConnection connection)
|
|
{
|
|
_state = state;
|
|
_connection = connection;
|
|
}
|
|
|
|
public void Render(int width, int height, StringBuilder sb)
|
|
{
|
|
var ch = _state.ActiveChannel;
|
|
string chName;
|
|
string topic = "";
|
|
|
|
if (ch == null)
|
|
{
|
|
chName = "(no channel)";
|
|
}
|
|
else if (ch.Type == ChannelTypes.DirectMessage)
|
|
{
|
|
string e2eeTag;
|
|
if (!_state.AllowDmE2ee)
|
|
{
|
|
e2eeTag = $"{Ansi.BrightYellow}[Plaintext / Server E2EE Off]{Ansi.Reset}";
|
|
}
|
|
else if (!_state.AccountE2eeEnabled || !ch.IsE2ee)
|
|
{
|
|
e2eeTag = $"{Ansi.BrightYellow}[⚠ Plaintext / E2EE Disabled]{Ansi.Reset}";
|
|
}
|
|
else if (!_state.HasUnlockedE2eeKey)
|
|
{
|
|
e2eeTag = $"{Ansi.BrightYellow}[🔑 E2EE Vault Locked — Enter PIN]{Ansi.Reset}";
|
|
}
|
|
else if (string.IsNullOrWhiteSpace(_state.GetPeerPublicKeyForDm(ch)))
|
|
{
|
|
e2eeTag = $"{Ansi.BrightYellow}[⚠ Plaintext — Peer E2EE Not Set Up]{Ansi.Reset}";
|
|
}
|
|
else
|
|
{
|
|
e2eeTag = $"{Ansi.BrightGreen}[🔒 Full E2EE]{Ansi.Reset}";
|
|
}
|
|
chName = $"DM @{ch.Name.TrimStart('@')}";
|
|
topic = $" {e2eeTag}";
|
|
}
|
|
else if (ch.Type == ChannelTypes.Group)
|
|
{
|
|
int maxU = ch.MaxUsers > 0 ? ch.MaxUsers : _state.MaxGroupChatUsers;
|
|
string membersList = ch.MemberUsernames.Count > 0 ? string.Join(", @", ch.MemberUsernames) : "";
|
|
chName = $"[Group] {ch.Name} ({ch.MemberIds.Count}/{maxU})";
|
|
topic = !string.IsNullOrEmpty(ch.Topic)
|
|
? $" - {ch.Topic}"
|
|
: (!string.IsNullOrEmpty(membersList) ? $" - @{membersList}" : "");
|
|
}
|
|
else
|
|
{
|
|
chName = $"#{ch.Name}";
|
|
topic = !string.IsNullOrEmpty(ch.Topic) ? $" - {ch.Topic}" : "";
|
|
}
|
|
|
|
// Header line
|
|
int onlineCount = _state.Users.Count(u => u.IsOnline);
|
|
string onlineTag = $" {Ansi.Gray}({Ansi.BrightGreen}● {onlineCount} online{Ansi.Gray}){Ansi.Reset}";
|
|
string header = $" {Ansi.Bold}{Ansi.Cyan}{chName}{Ansi.Reset}{Ansi.Gray}{topic}{Ansi.Reset}{onlineTag}";
|
|
sb.AppendLine(PadOrTruncate(header, width));
|
|
sb.AppendLine(new string('─', Math.Max(0, width - 1)));
|
|
|
|
// Messages area: height minus (Header: 2, Footer/Input: 3, Tab bar & status: 3) = height - 8
|
|
int msgAreaHeight = Math.Max(3, height - 8);
|
|
|
|
List<ChatMessage> messages = _state.GetMessagesForChannel(_state.ActiveChannelId);
|
|
|
|
bool hasMore = !string.IsNullOrEmpty(_state.ActiveChannelId) &&
|
|
_state.ChannelHasMoreHistory.TryGetValue(_state.ActiveChannelId, out bool hm) && hm;
|
|
|
|
// Viewport calculation with scroll offset
|
|
int totalMessages = messages.Count;
|
|
int maxScroll = Math.Max(0, totalMessages - msgAreaHeight);
|
|
int scroll = Math.Clamp(_state.ChatScrollOffset, 0, maxScroll);
|
|
int startIndex = Math.Max(0, totalMessages - msgAreaHeight - scroll);
|
|
int countToTake = Math.Min(msgAreaHeight, totalMessages - startIndex);
|
|
|
|
var visible = messages.Skip(startIndex).Take(countToTake).ToList();
|
|
|
|
int emptyLines = msgAreaHeight - visible.Count;
|
|
if (startIndex == 0 && hasMore && emptyLines > 0)
|
|
{
|
|
sb.AppendLine($" {Ansi.Gray}[↑ Press PageUp or /history to load older messages from server ↑]{Ansi.Reset}");
|
|
emptyLines--;
|
|
}
|
|
|
|
// Print blank lines if fewer messages than viewport height
|
|
for (int i = 0; i < emptyLines; i++)
|
|
{
|
|
sb.AppendLine();
|
|
}
|
|
|
|
foreach (var msg in visible)
|
|
{
|
|
string time = msg.CreatedAt.ToLocalTime().ToString("HH:mm:ss");
|
|
string roleColor = msg.SenderRole switch
|
|
{
|
|
"Owner" => Ansi.BrightYellow,
|
|
"Admin" => Ansi.BrightMagenta,
|
|
"System" => Ansi.BrightGreen,
|
|
_ => Ansi.BrightCyan
|
|
};
|
|
|
|
string lockBadge = msg.IsEncrypted ? $"{Ansi.BrightGreen}🔒 {Ansi.Reset}" : "";
|
|
string displayContent = msg.Content;
|
|
if (displayContent.StartsWith("E2EE:v1:", StringComparison.Ordinal))
|
|
{
|
|
displayContent = !_state.HasUnlockedE2eeKey
|
|
? $"{Ansi.BrightYellow}[🔒 Encrypted Message — Enter E2EE PIN or '/e2ee pin <pin>' to unlock]{Ansi.Reset}"
|
|
: $"{Ansi.BrightYellow}[🔒 Encrypted with previous E2EE key]{Ansi.Reset}";
|
|
}
|
|
|
|
string line;
|
|
if (msg.SenderRole == "System")
|
|
{
|
|
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} {Ansi.BrightGreen}*** {msg.Content}{Ansi.Reset}";
|
|
}
|
|
else if (!string.IsNullOrEmpty(msg.AttachmentId))
|
|
{
|
|
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} {lockBadge}<{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {Ansi.BrightYellow}📎 [{msg.AttachmentName} - {FileStorageServiceFormat(msg.AttachmentSizeBytes ?? 0)}]{Ansi.Reset}";
|
|
}
|
|
else
|
|
{
|
|
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} {lockBadge}<{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {displayContent}";
|
|
}
|
|
|
|
sb.AppendLine(PadOrTruncate(line, width));
|
|
}
|
|
|
|
// Divider
|
|
sb.AppendLine(new string('─', Math.Max(0, width - 1)));
|
|
|
|
// Input Line or Lazy E2EE PIN Prompt
|
|
if (_state.IsPromptingE2eePin)
|
|
{
|
|
string pinPromptLabel = _state.HasServerKeyVault
|
|
? $"{Ansi.BrightYellow}[🔑 Unlock E2EE Key Vault] Enter E2EE PIN (Esc=Plaintext): {Ansi.Reset}"
|
|
: $"{Ansi.BrightGreen}[🔑 Setup E2EE Key Vault] Create E2EE PIN (Esc=Plaintext): {Ansi.Reset}";
|
|
string maskedPin = new string('*', _state.E2eePinInputBuffer.Length) + "█";
|
|
sb.AppendLine($" {pinPromptLabel}{maskedPin}");
|
|
}
|
|
else
|
|
{
|
|
string prompt = $" {Ansi.Cyan}[{chName}] > {Ansi.Reset}";
|
|
string inputDisplay = _state.InputBuffer + "█";
|
|
sb.AppendLine(prompt + inputDisplay);
|
|
}
|
|
}
|
|
|
|
public async Task HandleKeyAsync(ConsoleKeyInfo key)
|
|
{
|
|
if (_state.IsPromptingE2eePin)
|
|
{
|
|
if (key.Key == ConsoleKey.Enter)
|
|
{
|
|
string pin = _state.E2eePinInputBuffer.Trim();
|
|
_state.E2eePinInputBuffer = string.Empty;
|
|
if (string.IsNullOrEmpty(pin))
|
|
{
|
|
_state.SetStatus("PIN cannot be empty (Press Esc to skip and use plaintext).");
|
|
return;
|
|
}
|
|
|
|
var (ok, msg) = await _connection.UnlockOrInitializeE2eeWithPinAsync(pin, resetKeys: false);
|
|
_state.SetStatus(msg, 5);
|
|
if (ok)
|
|
{
|
|
_state.IsPromptingE2eePin = false;
|
|
}
|
|
_state.NeedsRedraw = true;
|
|
}
|
|
else if (key.Key == ConsoleKey.Escape)
|
|
{
|
|
_state.IsPromptingE2eePin = false;
|
|
_state.E2eePinInputBuffer = string.Empty;
|
|
_state.SetStatus("E2EE PIN prompt skipped. Use '/e2ee pin <pin>' anytime to unlock.");
|
|
_state.NeedsRedraw = true;
|
|
}
|
|
else if (key.Key == ConsoleKey.Backspace)
|
|
{
|
|
if (_state.E2eePinInputBuffer.Length > 0)
|
|
{
|
|
_state.E2eePinInputBuffer = _state.E2eePinInputBuffer[..^1];
|
|
_state.NeedsRedraw = true;
|
|
}
|
|
}
|
|
else if (!char.IsControl(key.KeyChar))
|
|
{
|
|
_state.E2eePinInputBuffer += key.KeyChar;
|
|
_state.NeedsRedraw = true;
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (key.Key == ConsoleKey.Enter)
|
|
{
|
|
string text = _state.InputBuffer.Trim();
|
|
_state.InputBuffer = string.Empty;
|
|
|
|
if (string.IsNullOrEmpty(text)) return;
|
|
|
|
if (text.StartsWith("/"))
|
|
{
|
|
await HandleSlashCommandAsync(text);
|
|
}
|
|
else
|
|
{
|
|
if (!string.IsNullOrEmpty(_state.ActiveChannelId))
|
|
{
|
|
await _connection.SendChatMessageAsync(_state.ActiveChannelId, text);
|
|
}
|
|
else
|
|
{
|
|
_state.SetStatus("Please join a channel first (Press F2).");
|
|
}
|
|
}
|
|
_state.ChatScrollOffset = 0;
|
|
_state.NeedsRedraw = true;
|
|
}
|
|
else if (key.Key == ConsoleKey.Backspace)
|
|
{
|
|
if (_state.InputBuffer.Length > 0)
|
|
{
|
|
_state.InputBuffer = _state.InputBuffer[..^1];
|
|
_state.NeedsRedraw = true;
|
|
}
|
|
}
|
|
else if (key.Key == ConsoleKey.PageUp)
|
|
{
|
|
_state.ChatScrollOffset += 5;
|
|
if (!string.IsNullOrEmpty(_state.ActiveChannelId) &&
|
|
_state.ChannelHasMoreHistory.TryGetValue(_state.ActiveChannelId, out bool hasMore) &&
|
|
hasMore)
|
|
{
|
|
await _connection.FetchOlderHistoryAsync(_state.ActiveChannelId, 50);
|
|
_state.SetStatus("Loading older messages from server...", 2);
|
|
}
|
|
_state.NeedsRedraw = true;
|
|
}
|
|
else if (key.Key == ConsoleKey.PageDown)
|
|
{
|
|
_state.ChatScrollOffset = Math.Max(0, _state.ChatScrollOffset - 5);
|
|
_state.NeedsRedraw = true;
|
|
}
|
|
else if (key.Key == ConsoleKey.Escape)
|
|
{
|
|
_state.InputBuffer = string.Empty;
|
|
_state.NeedsRedraw = true;
|
|
}
|
|
else if (!char.IsControl(key.KeyChar))
|
|
{
|
|
_state.InputBuffer += key.KeyChar;
|
|
_state.NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
private async Task HandleSlashCommandAsync(string input)
|
|
{
|
|
string[] parts = input.Split(' ', 2);
|
|
string cmd = parts[0].TrimStart('/').ToLowerInvariant();
|
|
string args = parts.Length > 1 ? parts[1].Trim() : string.Empty;
|
|
|
|
switch (cmd)
|
|
{
|
|
case "join":
|
|
if (string.IsNullOrEmpty(args))
|
|
{
|
|
_state.SetStatus("Usage: /join <channel_or_group_or_dm>");
|
|
return;
|
|
}
|
|
string cleanTarget = args.TrimStart('#', '@');
|
|
var target = _state.Channels.FirstOrDefault(c => c.Name.Equals(cleanTarget, StringComparison.OrdinalIgnoreCase))
|
|
?? _state.GroupChats.FirstOrDefault(g => g.Name.Equals(cleanTarget, StringComparison.OrdinalIgnoreCase))
|
|
?? _state.DirectMessages.FirstOrDefault(d => d.Name.TrimStart('@').Equals(cleanTarget, StringComparison.OrdinalIgnoreCase));
|
|
if (target != null)
|
|
{
|
|
await _connection.JoinChannelAsync(target.Id);
|
|
_state.SetStatus($"Switched to {target.Name}");
|
|
}
|
|
else
|
|
{
|
|
_state.SetStatus($"Conversation '{args}' not found.");
|
|
}
|
|
break;
|
|
|
|
case "create":
|
|
if (string.IsNullOrEmpty(args))
|
|
{
|
|
_state.SetStatus("Usage: /create <channel_name> [topic]");
|
|
return;
|
|
}
|
|
var createParts = args.Split(' ', 2);
|
|
string newName = createParts[0];
|
|
string newTopic = createParts.Length > 1 ? createParts[1] : string.Empty;
|
|
await _connection.CreateChannelAsync(newName, newTopic);
|
|
break;
|
|
|
|
case "dm":
|
|
if (string.IsNullOrEmpty(args))
|
|
{
|
|
_state.SetStatus("Usage: /dm <username> [message]");
|
|
return;
|
|
}
|
|
var dmParts = args.Split(' ', 2);
|
|
string dmUser = dmParts[0].TrimStart('@');
|
|
await _connection.StartDmAsync(dmUser);
|
|
_state.SetStatus($"Opening DM with @{dmUser}...");
|
|
if (dmParts.Length > 1 && !string.IsNullOrWhiteSpace(dmParts[1]))
|
|
{
|
|
await Task.Delay(100);
|
|
var dmConv = _state.DirectMessages.FirstOrDefault(d => d.Name.TrimStart('@').Equals(dmUser, StringComparison.OrdinalIgnoreCase));
|
|
if (dmConv != null)
|
|
{
|
|
await _connection.SendChatMessageAsync(dmConv.Id, dmParts[1]);
|
|
}
|
|
}
|
|
break;
|
|
|
|
case "e2ee":
|
|
var e2eeTokens = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
|
|
if (e2eeTokens.Length == 0)
|
|
{
|
|
_state.IsPromptingE2eePin = true;
|
|
_state.NeedsRedraw = true;
|
|
return;
|
|
}
|
|
string e2eeSub = e2eeTokens[0].ToLowerInvariant();
|
|
string e2eeArg = e2eeTokens.Length > 1 ? e2eeTokens[1].Trim() : string.Empty;
|
|
if ((e2eeSub == "pin" || e2eeSub == "unlock") && !string.IsNullOrEmpty(e2eeArg))
|
|
{
|
|
var (ok, msg) = await _connection.UnlockOrInitializeE2eeWithPinAsync(e2eeArg, resetKeys: false);
|
|
_state.SetStatus(msg, 5);
|
|
}
|
|
else if (e2eeSub == "reset" && !string.IsNullOrEmpty(e2eeArg))
|
|
{
|
|
var (ok, msg) = await _connection.UnlockOrInitializeE2eeWithPinAsync(e2eeArg, resetKeys: true);
|
|
_state.SetStatus(msg, 5);
|
|
}
|
|
else if (e2eeSub == "lock")
|
|
{
|
|
_connection.LockE2eeKeys();
|
|
}
|
|
else if ((e2eeSub == "dm" || e2eeSub == "account") && !string.IsNullOrEmpty(e2eeArg))
|
|
{
|
|
bool enable = e2eeArg.Equals("on", StringComparison.OrdinalIgnoreCase) ||
|
|
e2eeArg.Equals("true", StringComparison.OrdinalIgnoreCase) ||
|
|
e2eeArg.Equals("1", StringComparison.OrdinalIgnoreCase);
|
|
await _connection.ToggleE2eeAsync(e2eeSub, enable, _state.ActiveChannelId);
|
|
}
|
|
else
|
|
{
|
|
_state.SetStatus("Usage: /e2ee pin <pin> | /e2ee reset <new_pin> | /e2ee lock | /e2ee dm <on|off> | /e2ee account <on|off>", 6);
|
|
}
|
|
break;
|
|
|
|
case "history":
|
|
case "more":
|
|
if (!string.IsNullOrEmpty(_state.ActiveChannelId))
|
|
{
|
|
await _connection.FetchOlderHistoryAsync(_state.ActiveChannelId, 50);
|
|
_state.SetStatus("Fetching older history from server...", 3);
|
|
}
|
|
break;
|
|
|
|
case "group":
|
|
case "gcreate":
|
|
string gArgs = cmd == "gcreate" ? $"create {args}" : args;
|
|
var gTokens = gArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
|
if (gTokens.Length == 0)
|
|
{
|
|
_state.SetStatus("Usage: /group create <name> [user1,user2] | /group invite <user> | /group leave");
|
|
return;
|
|
}
|
|
string sub = gTokens[0].ToLowerInvariant();
|
|
if (sub == "create" && gTokens.Length >= 2)
|
|
{
|
|
string gName = gTokens[1];
|
|
var members = gTokens.Skip(2).ToList();
|
|
await _connection.CreateGroupChatAsync(gName, members);
|
|
_state.SetStatus($"Creating group '{gName}'...");
|
|
}
|
|
else if (sub == "invite" && gTokens.Length >= 2)
|
|
{
|
|
await _connection.InviteToGroupAsync(_state.ActiveChannelId, gTokens[1]);
|
|
}
|
|
else if (sub == "leave")
|
|
{
|
|
await _connection.LeaveGroupAsync(_state.ActiveChannelId);
|
|
}
|
|
else
|
|
{
|
|
_state.SetStatus("Usage: /group create <name> [user1,user2] | /group invite <user> | /group leave");
|
|
}
|
|
break;
|
|
|
|
case "invite":
|
|
if (string.IsNullOrEmpty(args))
|
|
{
|
|
_state.SetStatus("Usage: /invite <username>");
|
|
return;
|
|
}
|
|
await _connection.InviteToGroupAsync(_state.ActiveChannelId, args);
|
|
break;
|
|
|
|
case "leave":
|
|
await _connection.LeaveGroupAsync(_state.ActiveChannelId);
|
|
break;
|
|
|
|
case "upload":
|
|
if (string.IsNullOrEmpty(args))
|
|
{
|
|
_state.SetStatus("Usage: /upload <local_file_path>");
|
|
return;
|
|
}
|
|
if (string.IsNullOrEmpty(_state.ActiveChannelId))
|
|
{
|
|
_state.SetStatus("Select an active channel first.");
|
|
return;
|
|
}
|
|
_state.SetStatus($"Uploading {args}...");
|
|
await _connection.UploadFileAsync(args, _state.ActiveChannelId);
|
|
break;
|
|
|
|
case "download":
|
|
if (string.IsNullOrEmpty(args))
|
|
{
|
|
_state.SetStatus("Usage: /download <file_id>");
|
|
return;
|
|
}
|
|
_state.SetStatus($"Downloading file {args}...");
|
|
await _connection.DownloadFileAsync(args, "downloads");
|
|
break;
|
|
|
|
default:
|
|
await _connection.ExecuteCommandAsync(cmd, args, _state.ActiveChannelId);
|
|
break;
|
|
}
|
|
}
|
|
|
|
private static string FileStorageServiceFormat(long bytes)
|
|
{
|
|
string[] suffixes = { "B", "KB", "MB", "GB" };
|
|
int order = 0;
|
|
double size = bytes;
|
|
while (size >= 1024 && order < suffixes.Length - 1)
|
|
{
|
|
order++;
|
|
size /= 1024;
|
|
}
|
|
return $"{size:0.##} {suffixes[order]}";
|
|
}
|
|
|
|
private static string PadOrTruncate(string str, int width)
|
|
{
|
|
if (width <= 0) return string.Empty;
|
|
return str;
|
|
}
|
|
}
|