531 lines
17 KiB
C#
531 lines
17 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text.Json;
|
|
using GsDChat.Core.Models;
|
|
using GsDChat.Core.Protocol;
|
|
|
|
namespace GsDChat.Client.State;
|
|
|
|
public class ClientState
|
|
{
|
|
private readonly object _lock = new();
|
|
private readonly string? _customKeyCachePath;
|
|
|
|
public string ServerUrl { get; set; } = "http://localhost:5000";
|
|
public string Token { get; set; } = string.Empty;
|
|
public string CurrentUserId { get; set; } = string.Empty;
|
|
public string CurrentUsername { get; set; } = string.Empty;
|
|
public string CurrentUserRole { get; set; } = UserRoles.Member;
|
|
|
|
public string PublicKeyBase64 { get; set; } = string.Empty;
|
|
public string PrivateKeyBase64 { get; set; } = string.Empty;
|
|
public string? ServerPublicKeyBase64 { get; set; }
|
|
public string? ServerEncryptedPrivateKey { get; set; }
|
|
public bool AccountE2eeEnabled { get; set; } = true;
|
|
|
|
public bool IsPromptingE2eePin { get; set; } = false;
|
|
public string E2eePinInputBuffer { get; set; } = string.Empty;
|
|
|
|
public string ServerName { get; set; } = "GsDChat Server";
|
|
public string Motd { get; set; } = string.Empty;
|
|
public bool AllowDmE2ee { get; set; } = true;
|
|
public int MaxGroupChatUsers { get; set; } = 10;
|
|
public ServerUiSync UiSync { get; set; } = ServerUiSync.CreateDefault();
|
|
|
|
public string ActiveScreenId { get; set; } = "F1_Chat";
|
|
public string ActiveChannelId { get; set; } = string.Empty;
|
|
|
|
public List<Channel> Channels { get; } = new();
|
|
public List<Channel> DirectMessages { get; } = new();
|
|
public List<Channel> GroupChats { get; } = new();
|
|
public Dictionary<string, List<ChatMessage>> ChannelMessages { get; } = new();
|
|
public Dictionary<string, bool> ChannelHasMoreHistory { get; } = new(StringComparer.OrdinalIgnoreCase);
|
|
public HashSet<string> LoadingHistoryChannels { get; } = new(StringComparer.OrdinalIgnoreCase);
|
|
public List<UserSummary> Users { get; } = new();
|
|
public List<FileSummary> Files { get; } = new();
|
|
public List<InboxItem> InboxItems { get; } = new();
|
|
public int UnreadInboxCount { get; set; } = 0;
|
|
public InboxPreferences InboxPreferences { get; set; } = new();
|
|
public List<string> SystemNotices { get; } = new();
|
|
|
|
public int ChatScrollOffset { get; set; } = 0;
|
|
public string InputBuffer { get; set; } = string.Empty;
|
|
public bool NeedsRedraw { get; set; } = true;
|
|
public bool IsConnected { get; set; } = false;
|
|
public string StatusMessage { get; set; } = string.Empty;
|
|
public DateTime StatusMessageUntil { get; set; } = DateTime.MinValue;
|
|
|
|
public ClientState(string? customKeyCachePath = null)
|
|
{
|
|
_customKeyCachePath = customKeyCachePath;
|
|
}
|
|
|
|
public bool HasUnlockedE2eeKey => !string.IsNullOrWhiteSpace(PrivateKeyBase64) && !string.IsNullOrWhiteSpace(PublicKeyBase64);
|
|
public bool HasServerKeyVault => !string.IsNullOrWhiteSpace(ServerEncryptedPrivateKey) || !string.IsNullOrWhiteSpace(ServerPublicKeyBase64);
|
|
|
|
public Channel? ActiveChannel
|
|
{
|
|
get
|
|
{
|
|
lock (_lock)
|
|
{
|
|
return GetConversationByIdInternal(ActiveChannelId);
|
|
}
|
|
}
|
|
}
|
|
|
|
public Channel? GetConversationById(string channelId)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
return GetConversationByIdInternal(channelId);
|
|
}
|
|
}
|
|
|
|
private Channel? GetConversationByIdInternal(string channelId)
|
|
{
|
|
if (string.IsNullOrEmpty(channelId)) return null;
|
|
return Channels.FirstOrDefault(c => c.Id == channelId)
|
|
?? GroupChats.FirstOrDefault(g => g.Id == channelId)
|
|
?? DirectMessages.FirstOrDefault(d => d.Id == channelId);
|
|
}
|
|
|
|
public string? GetPeerPublicKeyForDm(Channel dm)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
// Find the other participant in the DM
|
|
var peerId = dm.MemberIds.FirstOrDefault(id => !string.Equals(id, CurrentUserId, StringComparison.OrdinalIgnoreCase));
|
|
if (!string.IsNullOrEmpty(peerId))
|
|
{
|
|
if (dm.MemberPublicKeys.TryGetValue(peerId, out var key) && !string.IsNullOrWhiteSpace(key))
|
|
{
|
|
return key;
|
|
}
|
|
var user = Users.FirstOrDefault(u => string.Equals(u.Id, peerId, StringComparison.OrdinalIgnoreCase));
|
|
if (!string.IsNullOrWhiteSpace(user?.PublicKey))
|
|
{
|
|
return user.PublicKey;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
var peerName = dm.MemberUsernames.FirstOrDefault(n => !string.Equals(n, CurrentUsername, StringComparison.OrdinalIgnoreCase)) ?? dm.Name;
|
|
if (!string.IsNullOrEmpty(peerName))
|
|
{
|
|
string clean = peerName.TrimStart('@');
|
|
if (!string.Equals(clean, CurrentUsername, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
if (dm.MemberPublicKeys.TryGetValue(clean, out var key) && !string.IsNullOrWhiteSpace(key))
|
|
{
|
|
return key;
|
|
}
|
|
var user = Users.FirstOrDefault(u => string.Equals(u.Username, clean, StringComparison.OrdinalIgnoreCase));
|
|
if (!string.IsNullOrWhiteSpace(user?.PublicKey))
|
|
{
|
|
return user.PublicKey;
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// Self-DM fallback only when messaging oneself
|
|
if (dm.MemberIds.Count == 1 && string.Equals(dm.MemberIds[0], CurrentUserId, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return string.IsNullOrWhiteSpace(PublicKeyBase64) ? null : PublicKeyBase64;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public void CheckLazyDmE2eePrompt()
|
|
{
|
|
lock (_lock)
|
|
{
|
|
var active = GetConversationByIdInternal(ActiveChannelId);
|
|
if (active != null &&
|
|
active.Type == ChannelTypes.DirectMessage &&
|
|
AllowDmE2ee &&
|
|
AccountE2eeEnabled &&
|
|
active.IsE2ee &&
|
|
!HasUnlockedE2eeKey)
|
|
{
|
|
IsPromptingE2eePin = true;
|
|
NeedsRedraw = true;
|
|
}
|
|
else
|
|
{
|
|
IsPromptingE2eePin = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
private string GetKeyCacheFilePath()
|
|
{
|
|
if (!string.IsNullOrEmpty(_customKeyCachePath)) return _customKeyCachePath;
|
|
try
|
|
{
|
|
string homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
|
if (string.IsNullOrEmpty(homeDir)) homeDir = Directory.GetCurrentDirectory();
|
|
string gsdDir = Path.Combine(homeDir, ".gsdchat");
|
|
Directory.CreateDirectory(gsdDir);
|
|
return Path.Combine(gsdDir, "e2ee_keys.json");
|
|
}
|
|
catch
|
|
{
|
|
return Path.Combine(Directory.GetCurrentDirectory(), "e2ee_keys.json");
|
|
}
|
|
}
|
|
|
|
private string GetCacheEntryKey()
|
|
{
|
|
string normUrl = ServerHistoryManager.NormalizeUrl(ServerUrl).ToLowerInvariant();
|
|
string userKey = !string.IsNullOrWhiteSpace(CurrentUserId) ? CurrentUserId.ToLowerInvariant() : CurrentUsername.ToLowerInvariant();
|
|
return $"{normUrl}|{userKey}";
|
|
}
|
|
|
|
public bool TryRestoreCachedE2eeKey()
|
|
{
|
|
try
|
|
{
|
|
string path = GetKeyCacheFilePath();
|
|
if (!File.Exists(path)) return false;
|
|
|
|
string json = File.ReadAllText(path);
|
|
var dict = JsonSerializer.Deserialize<Dictionary<string, CachedKeyPair>>(json);
|
|
if (dict == null) return false;
|
|
|
|
if (dict.TryGetValue(GetCacheEntryKey(), out var cached) &&
|
|
!string.IsNullOrWhiteSpace(cached.PublicKey) &&
|
|
!string.IsNullOrWhiteSpace(cached.PrivateKey))
|
|
{
|
|
// Verify cached key matches server public key if server already has one
|
|
if (!string.IsNullOrWhiteSpace(ServerPublicKeyBase64) &&
|
|
!string.Equals(ServerPublicKeyBase64, cached.PublicKey, StringComparison.Ordinal))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
PublicKeyBase64 = cached.PublicKey;
|
|
PrivateKeyBase64 = cached.PrivateKey;
|
|
return true;
|
|
}
|
|
}
|
|
catch { }
|
|
return false;
|
|
}
|
|
|
|
public void SaveCachedE2eeKeys()
|
|
{
|
|
if (string.IsNullOrWhiteSpace(PublicKeyBase64) || string.IsNullOrWhiteSpace(PrivateKeyBase64)) return;
|
|
try
|
|
{
|
|
string path = GetKeyCacheFilePath();
|
|
Dictionary<string, CachedKeyPair> dict = new();
|
|
if (File.Exists(path))
|
|
{
|
|
try
|
|
{
|
|
dict = JsonSerializer.Deserialize<Dictionary<string, CachedKeyPair>>(File.ReadAllText(path)) ?? new();
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
dict[GetCacheEntryKey()] = new CachedKeyPair
|
|
{
|
|
PublicKey = PublicKeyBase64,
|
|
PrivateKey = PrivateKeyBase64
|
|
};
|
|
|
|
File.WriteAllText(path, JsonSerializer.Serialize(dict, new JsonSerializerOptions { WriteIndented = true }));
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
public void ClearCachedE2eeKeys()
|
|
{
|
|
PublicKeyBase64 = string.Empty;
|
|
PrivateKeyBase64 = string.Empty;
|
|
try
|
|
{
|
|
string path = GetKeyCacheFilePath();
|
|
if (!File.Exists(path)) return;
|
|
var dict = JsonSerializer.Deserialize<Dictionary<string, CachedKeyPair>>(File.ReadAllText(path));
|
|
if (dict != null && dict.Remove(GetCacheEntryKey()))
|
|
{
|
|
File.WriteAllText(path, JsonSerializer.Serialize(dict, new JsonSerializerOptions { WriteIndented = true }));
|
|
}
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
private class CachedKeyPair
|
|
{
|
|
public string PublicKey { get; set; } = string.Empty;
|
|
public string PrivateKey { get; set; } = string.Empty;
|
|
}
|
|
|
|
public void SetStatus(string message, int durationSeconds = 5)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
StatusMessage = message;
|
|
StatusMessageUntil = DateTime.UtcNow.AddSeconds(durationSeconds);
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public void AddNotice(string text)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
SystemNotices.Add($"[{DateTime.Now:HH:mm:ss}] {text}");
|
|
if (SystemNotices.Count > 100) SystemNotices.RemoveAt(0);
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public void AddSystemMessageToChat(string text, string channelId)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
if (!ChannelMessages.TryGetValue(channelId, out var list))
|
|
{
|
|
list = new List<ChatMessage>();
|
|
ChannelMessages[channelId] = list;
|
|
}
|
|
list.Add(new ChatMessage
|
|
{
|
|
Id = Guid.NewGuid().ToString(),
|
|
ChannelId = channelId,
|
|
SenderUsername = "System",
|
|
SenderRole = "System",
|
|
Content = text,
|
|
CreatedAt = DateTime.UtcNow
|
|
});
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public void AddChatMessage(ChatMessage message)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
if (!ChannelMessages.TryGetValue(message.ChannelId, out var list))
|
|
{
|
|
list = new List<ChatMessage>();
|
|
ChannelMessages[message.ChannelId] = list;
|
|
}
|
|
if (!list.Any(m => m.Id == message.Id))
|
|
{
|
|
list.Add(message);
|
|
}
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public List<ChatMessage> GetMessagesForChannel(string channelId)
|
|
{
|
|
if (string.IsNullOrEmpty(channelId)) return new List<ChatMessage>();
|
|
lock (_lock)
|
|
{
|
|
if (ChannelMessages.TryGetValue(channelId, out var list))
|
|
{
|
|
return new List<ChatMessage>(list);
|
|
}
|
|
return new List<ChatMessage>();
|
|
}
|
|
}
|
|
|
|
public List<ChatMessage> GetAllLoadedMessages()
|
|
{
|
|
lock (_lock)
|
|
{
|
|
var all = new List<ChatMessage>();
|
|
foreach (var kvp in ChannelMessages)
|
|
{
|
|
all.AddRange(kvp.Value);
|
|
}
|
|
return all;
|
|
}
|
|
}
|
|
|
|
public void SetHistory(string channelId, List<ChatMessage> messages, bool hasMore = false)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
ChannelMessages[channelId] = messages;
|
|
ChannelHasMoreHistory[channelId] = hasMore;
|
|
LoadingHistoryChannels.Remove(channelId);
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public void PrependHistory(string channelId, List<ChatMessage> olderMessages, bool hasMore)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
if (!ChannelMessages.TryGetValue(channelId, out var existing))
|
|
{
|
|
existing = new List<ChatMessage>();
|
|
ChannelMessages[channelId] = existing;
|
|
}
|
|
|
|
var existingIds = new HashSet<string>(existing.Select(m => m.Id), StringComparer.OrdinalIgnoreCase);
|
|
var uniqueOlder = olderMessages.Where(m => !existingIds.Contains(m.Id)).ToList();
|
|
if (uniqueOlder.Count > 0)
|
|
{
|
|
existing.InsertRange(0, uniqueOlder);
|
|
}
|
|
|
|
ChannelHasMoreHistory[channelId] = hasMore;
|
|
LoadingHistoryChannels.Remove(channelId);
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public void UpdateChannels(List<Channel> channels, string activeId, List<Channel>? directMessages = null, List<Channel>? groupChats = null)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
Channels.Clear();
|
|
Channels.AddRange(channels);
|
|
|
|
if (directMessages != null)
|
|
{
|
|
DirectMessages.Clear();
|
|
DirectMessages.AddRange(directMessages);
|
|
}
|
|
|
|
if (groupChats != null)
|
|
{
|
|
GroupChats.Clear();
|
|
GroupChats.AddRange(groupChats);
|
|
}
|
|
|
|
if (!string.IsNullOrEmpty(activeId))
|
|
{
|
|
ActiveChannelId = activeId;
|
|
}
|
|
NeedsRedraw = true;
|
|
}
|
|
CheckLazyDmE2eePrompt();
|
|
}
|
|
|
|
public void UpdateUsers(List<UserSummary> users)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
Users.Clear();
|
|
Users.AddRange(users);
|
|
var me = users.FirstOrDefault(u => string.Equals(u.Id, CurrentUserId, StringComparison.OrdinalIgnoreCase));
|
|
if (me != null)
|
|
{
|
|
AccountE2eeEnabled = me.E2eeEnabled;
|
|
if (!string.IsNullOrWhiteSpace(me.PublicKey))
|
|
{
|
|
ServerPublicKeyBase64 = me.PublicKey;
|
|
}
|
|
}
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public void UpdateFiles(List<FileSummary> files)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
Files.Clear();
|
|
Files.AddRange(files);
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public void RemoveFile(string fileId)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
Files.RemoveAll(f => f.Id == fileId);
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public void SetInboxSync(List<InboxItem> items, int unreadCount, InboxPreferences? preferences = null)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
InboxItems.Clear();
|
|
InboxItems.AddRange(items);
|
|
UnreadInboxCount = unreadCount;
|
|
if (preferences != null)
|
|
{
|
|
InboxPreferences = preferences;
|
|
}
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public void AddOrUpdateInboxItem(InboxItem item, int unreadCount)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
int idx = InboxItems.FindIndex(x => string.Equals(x.Id, item.Id, StringComparison.OrdinalIgnoreCase));
|
|
if (idx >= 0)
|
|
{
|
|
InboxItems[idx] = item;
|
|
}
|
|
else
|
|
{
|
|
InboxItems.Insert(0, item);
|
|
}
|
|
UnreadInboxCount = unreadCount;
|
|
NeedsRedraw = true;
|
|
}
|
|
}
|
|
|
|
public int MarkChannelInboxItemsReadLocally(string channelId)
|
|
{
|
|
if (string.IsNullOrEmpty(channelId)) return 0;
|
|
lock (_lock)
|
|
{
|
|
int changed = 0;
|
|
foreach (var item in InboxItems)
|
|
{
|
|
if (string.Equals(item.ChannelId, channelId, StringComparison.OrdinalIgnoreCase) && !item.IsRead)
|
|
{
|
|
item.IsRead = true;
|
|
changed++;
|
|
}
|
|
}
|
|
if (changed > 0)
|
|
{
|
|
UnreadInboxCount = Math.Max(0, UnreadInboxCount - changed);
|
|
NeedsRedraw = true;
|
|
}
|
|
return changed;
|
|
}
|
|
}
|
|
|
|
public List<InboxItem> GetInboxItems()
|
|
{
|
|
lock (_lock)
|
|
{
|
|
return new List<InboxItem>(InboxItems);
|
|
}
|
|
}
|
|
|
|
public bool IsConversationFollowed(Channel ch)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
if (ch.Type == ChannelTypes.Channel)
|
|
{
|
|
return InboxPreferences.FollowedChannelIds.Contains(ch.Id, StringComparer.OrdinalIgnoreCase);
|
|
}
|
|
return !InboxPreferences.MutedChannelIds.Contains(ch.Id, StringComparer.OrdinalIgnoreCase);
|
|
}
|
|
}
|
|
}
|