using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Net.WebSockets; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using GsDChat.Client.State; using GsDChat.Core.Protocol; 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) }; } public async Task GetServerInfoAsync() { try { var res = await _httpClient.GetAsync("/api/info"); 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(); return JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } 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) { var req = new RegisterRequest { Username = username, Password = password, ServerPassword = serverPassword }; var json = JsonSerializer.Serialize(req); var content = new StringContent(json, Encoding.UTF8, "application/json"); try { var res = await _httpClient.PostAsync("/api/auth/register", content); 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." }; } return JsonSerializer.Deserialize(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." }; } 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 { var res = await _httpClient.PostAsync("/api/auth/login", content); 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." }; } return JsonSerializer.Deserialize(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." }; } catch (Exception ex) { return new AuthResponse { Success = false, ErrorMessage = ex.Message }; } } public async Task StartWebSocketAsync() { _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)); } private async Task ReceiveLoopAsync(CancellationToken ct) { var buffer = new byte[8192]; var accumulator = new System.Collections.Generic.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.UiSync: var ui = envelope.Unpack(); if (ui != null) { _state.UiSync = ui; _state.ServerName = ui.ServerName; _state.Motd = ui.Motd; _state.NeedsRedraw = true; } break; case MessageTypes.ChannelListSync: var chSync = envelope.Unpack(); if (chSync != null) { _state.UpdateChannels(chSync.Channels, chSync.ActiveChannelId); } break; case MessageTypes.HistorySync: var histSync = envelope.Unpack(); if (histSync != null) { _state.SetHistory(histSync.ChannelId, histSync.Messages); } break; case MessageTypes.MessageBroadcast: var msgBc = envelope.Unpack(); if (msgBc != null) { _state.AddChatMessage(msgBc.Message); } break; case MessageTypes.UserListSync: var uSync = envelope.Unpack(); if (uSync != null) { _state.UpdateUsers(uSync.Users); } break; case MessageTypes.FileListSync: var fSync = envelope.Unpack(); if (fSync != null) { _state.UpdateFiles(fSync.Files); } 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); } 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}"); } } 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) { var envelope = NetworkEnvelope.Create(MessageTypes.SendMessage, new SendMessagePacket { ChannelId = channelId, Content = content }); return SendEnvelopeAsync(envelope); } public Task JoinChannelAsync(string 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 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 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(); } }