using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Net.WebSockets; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using GsDChat.Client.State; using GsDChat.Core.Models; using GsDChat.Core.Protocol; using GsDChat.Core.Security; namespace GsDChat.Client.Network; public class ChatClientConnection : IDisposable { private readonly ClientState _state; private readonly bool _allowInsecure; private readonly HttpClient _httpClient; private ClientWebSocket? _webSocket; private CancellationTokenSource? _cts; private readonly SemaphoreSlim _sendLock = new(1, 1); public ChatClientConnection(ClientState state, bool allowInsecure = false) { _state = state; _allowInsecure = allowInsecure; var handler = new HttpClientHandler(); if (allowInsecure) { handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; } _httpClient = new HttpClient(handler) { BaseAddress = new Uri(state.ServerUrl) }; } private async Task FetchCsrfTokenAsync() { try { var res = await _httpClient.GetAsync("/api/csrf-token"); if (res.IsSuccessStatusCode) { var json = await res.Content.ReadAsStringAsync(); var tokenData = JsonSerializer.Deserialize>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (tokenData != null && tokenData.TryGetValue("token", out var token)) { return token; } } } catch (Exception ex) { _state.SetStatus($"Failed to fetch CSRF token: {ex.Message}"); } // Fallback to empty string if CSRF token fetch fails return string.Empty; } public async Task GetServerInfoAsync() { try { var request = new HttpRequestMessage(HttpMethod.Get, "/api/info"); if (!string.IsNullOrWhiteSpace(_state.Token)) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _state.Token); } var res = await _httpClient.SendAsync(request); if (res.IsSuccessStatusCode) { // Auto-upgrade ServerUrl if redirected to HTTPS if (res.RequestMessage?.RequestUri != null && res.RequestMessage.RequestUri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) && _state.ServerUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { _state.ServerUrl = res.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority); _httpClient.BaseAddress = new Uri(_state.ServerUrl); } var json = await res.Content.ReadAsStringAsync(); var info = JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (info != null) { _state.AllowDmE2ee = info.AllowDmE2ee; _state.MaxGroupChatUsers = info.MaxGroupChatUsers; } return info; } else if (res.StatusCode == System.Net.HttpStatusCode.Unauthorized) { // Server requires auth for info endpoint, return null and continue return null; } else { _state.SetStatus($"Server returned HTTP {(int)res.StatusCode} ({res.ReasonPhrase}) on /api/info"); } } catch (Exception ex) { _state.SetStatus($"Failed to reach server: {ex.Message}"); } return null; } public async Task RegisterAsync(string username, string password, string? serverPassword = null, string? inviteToken = null) { var req = new RegisterRequest { Username = username, Password = password, ServerPassword = serverPassword, InviteToken = inviteToken }; var json = JsonSerializer.Serialize(req); var content = new StringContent(json, Encoding.UTF8, "application/json"); try { // Fetch CSRF token from server string csrfToken = await FetchCsrfTokenAsync(); var request = new HttpRequestMessage(HttpMethod.Post, "/api/auth/register") { Content = content }; // Add CSRF token request.Headers.Add("X-CSRF-Token", csrfToken); var res = await _httpClient.SendAsync(request); var resJson = await res.Content.ReadAsStringAsync(); if (string.IsNullOrWhiteSpace(resJson)) { return new AuthResponse { Success = false, ErrorMessage = $"Server returned HTTP {(int)res.StatusCode} ({res.ReasonPhrase}) with empty response." }; } var authRes = JsonSerializer.Deserialize(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." }; if (authRes.Success) { _state.Token = authRes.Token ?? _state.Token; _state.CurrentUserId = authRes.UserId ?? _state.CurrentUserId; _state.CurrentUsername = authRes.Username ?? username; _state.CurrentUserRole = authRes.Role ?? _state.CurrentUserRole; _state.ServerPublicKeyBase64 = authRes.PublicKey; _state.ServerEncryptedPrivateKey = authRes.EncryptedPrivateKey; _state.AccountE2eeEnabled = authRes.E2eeEnabled; _state.TryRestoreCachedE2eeKey(); } return authRes; } catch (Exception ex) { return new AuthResponse { Success = false, ErrorMessage = ex.Message }; } } public async Task LoginAsync(string username, string password, string? serverPassword = null) { var req = new LoginRequest { Username = username, Password = password, ServerPassword = serverPassword }; var json = JsonSerializer.Serialize(req); var content = new StringContent(json, Encoding.UTF8, "application/json"); try { // Fetch CSRF token from server string csrfToken = await FetchCsrfTokenAsync(); var request = new HttpRequestMessage(HttpMethod.Post, "/api/auth/login") { Content = content }; // Add CSRF token request.Headers.Add("X-CSRF-Token", csrfToken); var res = await _httpClient.SendAsync(request); var resJson = await res.Content.ReadAsStringAsync(); if (string.IsNullOrWhiteSpace(resJson)) { return new AuthResponse { Success = false, ErrorMessage = $"Server returned HTTP {(int)res.StatusCode} ({res.ReasonPhrase}) with empty response." }; } var authRes = JsonSerializer.Deserialize(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." }; if (authRes.Success) { _state.Token = authRes.Token ?? _state.Token; _state.CurrentUserId = authRes.UserId ?? _state.CurrentUserId; _state.CurrentUsername = authRes.Username ?? username; _state.CurrentUserRole = authRes.Role ?? _state.CurrentUserRole; _state.ServerPublicKeyBase64 = authRes.PublicKey; _state.ServerEncryptedPrivateKey = authRes.EncryptedPrivateKey; _state.AccountE2eeEnabled = authRes.E2eeEnabled; _state.TryRestoreCachedE2eeKey(); } return authRes; } catch (Exception ex) { return new AuthResponse { Success = false, ErrorMessage = ex.Message }; } } public async Task StartWebSocketAsync() { _state.TryRestoreCachedE2eeKey(); _cts = new CancellationTokenSource(); _webSocket = new ClientWebSocket(); if (_allowInsecure) { _webSocket.Options.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; } var baseUri = new Uri(_state.ServerUrl); string wsScheme = baseUri.Scheme == "https" ? "wss" : "ws"; var wsUri = new Uri($"{wsScheme}://{baseUri.Authority}/ws?token={_state.Token}"); await _webSocket.ConnectAsync(wsUri, _cts.Token); _state.IsConnected = true; _state.SetStatus("Connected to chat server!"); _ = Task.Run(() => ReceiveLoopAsync(_cts.Token)); if (_state.HasUnlockedE2eeKey && string.IsNullOrWhiteSpace(_state.ServerPublicKeyBase64)) { await PublishPublicKeyAsync(_state.PublicKeyBase64); } } public async Task<(bool Success, string Message)> UnlockOrInitializeE2eeWithPinAsync(string pin, bool resetKeys = false) { if (string.IsNullOrWhiteSpace(pin)) { return (false, "E2EE Passphrase/PIN cannot be empty."); } if (!resetKeys && !string.IsNullOrWhiteSpace(_state.ServerEncryptedPrivateKey)) { string? unwrapped = E2eeCrypto.UnwrapPrivateKey(_state.ServerEncryptedPrivateKey, pin, _state.CurrentUsername); if (string.IsNullOrWhiteSpace(unwrapped)) { return (false, "Incorrect E2EE PIN. Try again, or use '/e2ee reset ' to reset your E2EE keys."); } string pub = !string.IsNullOrWhiteSpace(_state.ServerPublicKeyBase64) ? _state.ServerPublicKeyBase64! : E2eeCrypto.ExtractPublicKeyFromPrivateKey(unwrapped); _state.PrivateKeyBase64 = unwrapped; _state.PublicKeyBase64 = pub; _state.ServerPublicKeyBase64 = pub; _state.IsPromptingE2eePin = false; _state.E2eePinInputBuffer = string.Empty; _state.SaveCachedE2eeKeys(); ReDecryptLoadedMessages(); return (true, "E2EE key vault unlocked! Past encrypted DMs decrypted."); } else { var (pub, priv) = E2eeCrypto.GenerateKeyPair(); string wrapped = E2eeCrypto.WrapPrivateKey(priv, pin, _state.CurrentUsername); _state.PublicKeyBase64 = pub; _state.PrivateKeyBase64 = priv; _state.ServerPublicKeyBase64 = pub; _state.ServerEncryptedPrivateKey = wrapped; _state.IsPromptingE2eePin = false; _state.E2eePinInputBuffer = string.Empty; _state.SaveCachedE2eeKeys(); await PublishPublicKeyAsync(pub, wrapped, resetKeys); ReDecryptLoadedMessages(); return (true, resetKeys ? "E2EE keypair & PIN reset! New messages will use your new key." : "E2EE PIN created and key vault initialized!"); } } public void LockE2eeKeys() { _state.ClearCachedE2eeKeys(); _state.SetStatus("E2EE key vault locked on this device."); } public void ReDecryptLoadedMessages() { foreach (var msg in _state.GetAllLoadedMessages()) { if (E2eeCrypto.IsEncryptedPayload(msg.Content)) { DecryptMessageIfNeeded(msg); } } foreach (var item in _state.GetInboxItems()) { if (E2eeCrypto.IsEncryptedPayload(item.ContentPreview)) { DecryptInboxItemIfNeeded(item); } } _state.NeedsRedraw = true; } private async Task ReceiveLoopAsync(CancellationToken ct) { var buffer = new byte[8192]; var accumulator = new List(); try { while (_webSocket != null && _webSocket.State == WebSocketState.Open && !ct.IsCancellationRequested) { var result = await _webSocket.ReceiveAsync(new ArraySegment(buffer), ct); if (result.MessageType == WebSocketMessageType.Close) { break; } if (result.MessageType == WebSocketMessageType.Text) { accumulator.AddRange(buffer.AsSpan(0, result.Count).ToArray()); if (result.EndOfMessage) { string json = Encoding.UTF8.GetString(accumulator.ToArray()); accumulator.Clear(); ProcessIncomingEnvelope(json); } } } } catch (OperationCanceledException) { } catch (Exception ex) { _state.SetStatus($"Connection lost: {ex.Message}"); } finally { _state.IsConnected = false; _state.SetStatus("Disconnected from server."); } } private void ProcessIncomingEnvelope(string json) { try { var envelope = JsonSerializer.Deserialize(json); if (envelope == null) return; switch (envelope.Type) { case MessageTypes.AuthResult: var authRes = envelope.Unpack(); if (authRes != null && authRes.Success) { if (!string.IsNullOrWhiteSpace(authRes.UserId)) _state.CurrentUserId = authRes.UserId; if (!string.IsNullOrWhiteSpace(authRes.Username)) _state.CurrentUsername = authRes.Username; if (!string.IsNullOrWhiteSpace(authRes.PublicKey)) _state.ServerPublicKeyBase64 = authRes.PublicKey; if (!string.IsNullOrWhiteSpace(authRes.EncryptedPrivateKey)) _state.ServerEncryptedPrivateKey = authRes.EncryptedPrivateKey; _state.AccountE2eeEnabled = authRes.E2eeEnabled; if (!_state.HasUnlockedE2eeKey) { _state.TryRestoreCachedE2eeKey(); } _state.CheckLazyDmE2eePrompt(); } break; case MessageTypes.UiSync: var ui = envelope.Unpack(); if (ui != null) { _state.UiSync = ui; _state.ServerName = ui.ServerName; _state.Motd = ui.Motd; _state.AllowDmE2ee = ui.AllowDmE2ee; _state.MaxGroupChatUsers = ui.MaxGroupChatUsers; _state.CheckLazyDmE2eePrompt(); _state.NeedsRedraw = true; } break; case MessageTypes.ChannelListSync: var chSync = envelope.Unpack(); if (chSync != null) { _state.UpdateChannels(chSync.Channels, chSync.ActiveChannelId, chSync.DirectMessages, chSync.GroupChats); ReDecryptLoadedMessages(); } break; case MessageTypes.HistorySync: var histSync = envelope.Unpack(); if (histSync != null) { foreach (var msg in histSync.Messages) { DecryptMessageIfNeeded(msg); } if (histSync.Prepend) { _state.PrependHistory(histSync.ChannelId, histSync.Messages, histSync.HasMore); } else { _state.SetHistory(histSync.ChannelId, histSync.Messages, histSync.HasMore); } } break; case MessageTypes.MessageBroadcast: var msgBc = envelope.Unpack(); if (msgBc != null) { DecryptMessageIfNeeded(msgBc.Message); _state.AddChatMessage(msgBc.Message); } break; case MessageTypes.UserListSync: var uSync = envelope.Unpack(); if (uSync != null) { _state.UpdateUsers(uSync.Users); ReDecryptLoadedMessages(); } break; case MessageTypes.FileListSync: var fSync = envelope.Unpack(); if (fSync != null) { _state.UpdateFiles(fSync.Files); } break; case MessageTypes.InboxSync: var inSync = envelope.Unpack(); if (inSync != null) { foreach (var item in inSync.Items) { DecryptInboxItemIfNeeded(item); } _state.SetInboxSync(inSync.Items, inSync.UnreadCount, inSync.Preferences); } break; case MessageTypes.InboxNewItem: var inNew = envelope.Unpack(); if (inNew != null && inNew.Item != null) { DecryptInboxItemIfNeeded(inNew.Item); _state.AddOrUpdateInboxItem(inNew.Item, inNew.UnreadCount); _state.SetStatus($"[Inbox] New {inNew.Item.Category} from @{inNew.Item.SenderUsername} (Press F5)", 4); } break; case MessageTypes.SystemNotice: var notice = envelope.Unpack(); if (notice != null) { _state.AddNotice(notice.Text); _state.SetStatus(notice.Text, 4); } break; case MessageTypes.CommandResult: var cmdRes = envelope.Unpack(); if (cmdRes != null) { _state.AddNotice(cmdRes.Output); _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)) { _state.AddSystemMessageToChat(cmdRes.Output, cmdRes.ChannelId); } } break; case MessageTypes.Error: var err = envelope.Unpack(); if (err != null) { _state.SetStatus($"[Error] {err.Message}", 5); } break; } } catch (Exception ex) { _state.SetStatus($"Error parsing packet: {ex.Message}"); } } private void DecryptMessageIfNeeded(ChatMessage msg) { if (!msg.IsEncrypted && !E2eeCrypto.IsEncryptedPayload(msg.Content)) { return; } msg.IsEncrypted = true; if (!E2eeCrypto.IsEncryptedPayload(msg.Content) || string.IsNullOrWhiteSpace(_state.PrivateKeyBase64)) { return; } string? peerPubKey = null; bool sentByMe = string.Equals(msg.SenderId, _state.CurrentUserId, StringComparison.OrdinalIgnoreCase) || string.Equals(msg.SenderUsername, _state.CurrentUsername, StringComparison.OrdinalIgnoreCase); if (sentByMe) { // For messages I sent, use RecipientPublicKey first so even if the peer later resets their key, my sent history still decrypts! if (!string.IsNullOrWhiteSpace(msg.RecipientPublicKey)) { peerPubKey = msg.RecipientPublicKey; } } else { // For messages received from peer, use SenderPublicKey first if (!string.IsNullOrWhiteSpace(msg.SenderPublicKey)) { peerPubKey = msg.SenderPublicKey; } } // Fallback to current DM channel participant public key if (string.IsNullOrWhiteSpace(peerPubKey)) { var conv = _state.GetConversationById(msg.ChannelId); if (conv != null) { peerPubKey = _state.GetPeerPublicKeyForDm(conv); } } if (string.IsNullOrWhiteSpace(peerPubKey)) { peerPubKey = !string.IsNullOrWhiteSpace(msg.RecipientPublicKey) ? msg.RecipientPublicKey : msg.SenderPublicKey; } if (!string.IsNullOrWhiteSpace(peerPubKey)) { string decrypted = E2eeCrypto.DecryptMessage(msg.Content, _state.PrivateKeyBase64, peerPubKey); // Only replace raw E2EE:v1: payload if decryption succeeded if (!decrypted.StartsWith("[Encrypted Message")) { msg.Content = decrypted; } } } private void DecryptInboxItemIfNeeded(InboxItem item) { if (!item.IsEncrypted && !E2eeCrypto.IsEncryptedPayload(item.ContentPreview)) { return; } item.IsEncrypted = true; if (!E2eeCrypto.IsEncryptedPayload(item.ContentPreview) || string.IsNullOrWhiteSpace(_state.PrivateKeyBase64)) { return; } string? peerPubKey = !string.IsNullOrWhiteSpace(item.SenderPublicKey) ? item.SenderPublicKey : item.RecipientPublicKey; if (string.IsNullOrWhiteSpace(peerPubKey)) { var conv = _state.GetConversationById(item.ChannelId); if (conv != null) { peerPubKey = _state.GetPeerPublicKeyForDm(conv); } } if (!string.IsNullOrWhiteSpace(peerPubKey)) { string decrypted = E2eeCrypto.DecryptMessage(item.ContentPreview, _state.PrivateKeyBase64, peerPubKey); if (!decrypted.StartsWith("[Encrypted Message")) { item.ContentPreview = decrypted; } } } public async Task SendEnvelopeAsync(NetworkEnvelope envelope) { if (_webSocket == null || _webSocket.State != WebSocketState.Open) return; string json = JsonSerializer.Serialize(envelope); byte[] bytes = Encoding.UTF8.GetBytes(json); await _sendLock.WaitAsync(); try { if (_webSocket.State == WebSocketState.Open) { await _webSocket.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, true, CancellationToken.None); } } finally { _sendLock.Release(); } } public Task SendChatMessageAsync(string channelId, string content, bool? forceEncrypt = null) { var conv = _state.GetConversationById(channelId); bool isDm = conv != null && conv.Type == ChannelTypes.DirectMessage; bool e2eeActiveForDm = isDm && conv!.IsE2ee && _state.AllowDmE2ee && _state.AccountE2eeEnabled; bool shouldEncrypt = forceEncrypt ?? e2eeActiveForDm; string payloadContent = content; bool isEncrypted = false; string? recipientPubKey = null; if (shouldEncrypt) { if (!_state.HasUnlockedE2eeKey) { if (forceEncrypt == true) { var (tempPub, tempPriv) = E2eeCrypto.GenerateKeyPair(); payloadContent = E2eeCrypto.EncryptMessage(content, tempPriv, tempPub); isEncrypted = true; } else { _state.SetStatus("Warning: Your E2EE key is not unlocked — sending as plaintext. Use '/e2ee pin ' to unlock.", 5); } } else { recipientPubKey = conv != null ? _state.GetPeerPublicKeyForDm(conv) : _state.PublicKeyBase64; if (string.IsNullOrWhiteSpace(recipientPubKey) && forceEncrypt == true) { recipientPubKey = _state.PublicKeyBase64; } if (!string.IsNullOrWhiteSpace(recipientPubKey)) { payloadContent = E2eeCrypto.EncryptMessage(content, _state.PrivateKeyBase64, recipientPubKey); isEncrypted = true; } else { _state.SetStatus("Warning: Recipient has not initialized E2EE yet — message sent as plaintext.", 5); } } } var envelope = NetworkEnvelope.Create(MessageTypes.SendMessage, new SendMessagePacket { ChannelId = channelId, Content = payloadContent, IsEncrypted = isEncrypted, SenderPublicKey = isEncrypted ? _state.PublicKeyBase64 : null, RecipientPublicKey = isEncrypted ? recipientPubKey : null }); return SendEnvelopeAsync(envelope); } public Task FetchOlderHistoryAsync(string channelId, int limit = 50) { if (string.IsNullOrWhiteSpace(channelId)) return Task.CompletedTask; if (_state.LoadingHistoryChannels.Contains(channelId)) return Task.CompletedTask; int currentCount = 0; if (_state.ChannelMessages.TryGetValue(channelId, out var list)) { currentCount = list.Count; } _state.LoadingHistoryChannels.Add(channelId); var envelope = NetworkEnvelope.Create(MessageTypes.FetchHistory, new FetchHistoryPacket { ChannelId = channelId, Offset = currentCount, Limit = limit }); return SendEnvelopeAsync(envelope); } public Task ToggleE2eeAsync(string scope, bool enabled, string? channelId = null) { var envelope = NetworkEnvelope.Create(MessageTypes.ToggleE2ee, new ToggleE2eePacket { Scope = scope, ChannelId = channelId ?? _state.ActiveChannelId, Enabled = enabled }); return SendEnvelopeAsync(envelope); } public Task JoinChannelAsync(string channelId) { _state.MarkChannelInboxItemsReadLocally(channelId); var envelope = NetworkEnvelope.Create(MessageTypes.JoinChannel, new JoinChannelPacket { ChannelId = channelId }); return SendEnvelopeAsync(envelope); } public Task CreateChannelAsync(string name, string topic) { var envelope = NetworkEnvelope.Create(MessageTypes.CreateChannel, new CreateChannelPacket { Name = name, Topic = topic }); return SendEnvelopeAsync(envelope); } public Task DeleteChannelAsync(string channelId) { var envelope = NetworkEnvelope.Create(MessageTypes.DeleteChannel, new DeleteChannelPacket { ChannelId = channelId }); return SendEnvelopeAsync(envelope); } public Task StartDmAsync(string targetUsername, string? targetUserId = null) { var envelope = NetworkEnvelope.Create(MessageTypes.StartDm, new StartDmPacket { TargetUsername = targetUsername, TargetUserId = targetUserId ?? string.Empty }); return SendEnvelopeAsync(envelope); } public Task CreateGroupChatAsync(string name, IEnumerable? memberUsernames = null, string topic = "", int? maxUsers = null) { var envelope = NetworkEnvelope.Create(MessageTypes.CreateGroup, new CreateGroupPacket { Name = name, Topic = topic, MemberUsernames = memberUsernames?.ToList() ?? new List(), MaxUsers = maxUsers }); return SendEnvelopeAsync(envelope); } public Task InviteToGroupAsync(string channelId, string targetUsername) { var envelope = NetworkEnvelope.Create(MessageTypes.InviteToGroup, new InviteToGroupPacket { ChannelId = channelId, TargetUsername = targetUsername }); return SendEnvelopeAsync(envelope); } public Task LeaveGroupAsync(string channelId) { var envelope = NetworkEnvelope.Create(MessageTypes.LeaveGroup, new LeaveGroupPacket { ChannelId = channelId }); return SendEnvelopeAsync(envelope); } public Task PublishPublicKeyAsync(string publicKey, string? encryptedPrivateKey = null, bool resetKeys = false) { var envelope = NetworkEnvelope.Create(MessageTypes.PublishPublicKey, new PublishPublicKeyPacket { PublicKey = publicKey, EncryptedPrivateKey = encryptedPrivateKey, ResetKeys = resetKeys }); return SendEnvelopeAsync(envelope); } public Task ExecuteCommandAsync(string command, string args, string channelId) { var envelope = NetworkEnvelope.Create(MessageTypes.ExecuteCommand, new ExecuteCommandPacket { Command = command, Args = args, ChannelId = channelId }); return SendEnvelopeAsync(envelope); } public Task RequestInboxSyncAsync() { var envelope = NetworkEnvelope.Create(MessageTypes.InboxSync, new { }); return SendEnvelopeAsync(envelope); } public Task SendInboxActionAsync(string action, string? itemId = null, string? channelId = null) { var envelope = NetworkEnvelope.Create(MessageTypes.InboxAction, new InboxActionPacket { Action = action, ItemId = itemId, ChannelId = channelId }); return SendEnvelopeAsync(envelope); } public Task UpdateInboxPreferencesAsync(UpdateInboxPreferencesPacket packet) { var envelope = NetworkEnvelope.Create(MessageTypes.UpdateInboxPreferences, packet); return SendEnvelopeAsync(envelope); } public Task ToggleFollowChannelAsync(string channelId, bool? follow = null) { var envelope = NetworkEnvelope.Create(MessageTypes.ToggleFollowChannel, new ToggleFollowChannelPacket { ChannelId = channelId, Follow = follow }); return SendEnvelopeAsync(envelope); } public async Task UploadFileAsync(string localFilePath, string channelId) { if (!File.Exists(localFilePath)) { _state.SetStatus($"File does not exist: {localFilePath}", 4); return false; } try { using var fileStream = File.OpenRead(localFilePath); using var content = new MultipartFormDataContent(); var fileContent = new StreamContent(fileStream); fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); content.Add(fileContent, "file", Path.GetFileName(localFilePath)); content.Add(new StringContent(channelId), "channelId"); using var req = new HttpRequestMessage(HttpMethod.Post, "/api/files/upload") { Content = content }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _state.Token); var res = await _httpClient.SendAsync(req); if (res.IsSuccessStatusCode) { _state.SetStatus($"Uploaded {Path.GetFileName(localFilePath)} successfully!", 4); return true; } else { string errText = await res.Content.ReadAsStringAsync(); _state.SetStatus($"Upload failed: {res.StatusCode} - {errText}", 5); return false; } } catch (Exception ex) { _state.SetStatus($"Upload error: {ex.Message}", 5); return false; } } public async Task DownloadFileAsync(string fileId, string targetDirectory) { Directory.CreateDirectory(targetDirectory); try { using var req = new HttpRequestMessage(HttpMethod.Get, $"/api/files/{fileId}"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _state.Token); var res = await _httpClient.SendAsync(req, HttpCompletionOption.ResponseHeadersRead); if (!res.IsSuccessStatusCode) { _state.SetStatus($"Download failed: {res.StatusCode}", 4); return false; } string fileName = res.Content.Headers.ContentDisposition?.FileName?.Trim('\"') ?? $"{fileId}.bin"; string targetPath = Path.Combine(targetDirectory, fileName); using var srcStream = await res.Content.ReadAsStreamAsync(); using var fileStream = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None, 81920, useAsync: true); await srcStream.CopyToAsync(fileStream); _state.SetStatus($"Downloaded to {targetPath}", 5); return true; } catch (Exception ex) { _state.SetStatus($"Download error: {ex.Message}", 5); return false; } } public void Dispose() { _cts?.Cancel(); _webSocket?.Dispose(); _httpClient.Dispose(); } }