From cbc24e7672b177477d0f105510e2f7a3cc1c64c9 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 10 Oct 2026 20:48:03 +0000 Subject: [PATCH] fixes, hopefully --- .../Network/ChatClientConnection.cs | 31 ++ src/GsDChat.Client/Program.cs | 4 +- .../State/ServerHistoryManager.cs | 15 +- src/GsDChat.Core/Protocol/HttpModels.cs | 1 + src/GsDChat.Core/Protocol/NetworkMessages.cs | 14 +- .../Configuration/ServerOptions.cs | 1 + src/GsDChat.Server/Program.cs | 6 +- .../WebSockets/ChatWebSocketManager.cs | 20 +- src/GsDChat.Server/wwwroot/app.css | 84 +++++- src/GsDChat.Server/wwwroot/app.js | 275 ++++++++++++++---- src/GsDChat.Server/wwwroot/index.html | 34 ++- tests/GsDChat.Tests/NetworkProtocolTests.cs | 41 +++ tests/GsDChat.Tests/ServerHistoryTests.cs | 1 + 13 files changed, 449 insertions(+), 78 deletions(-) diff --git a/src/GsDChat.Client/Network/ChatClientConnection.cs b/src/GsDChat.Client/Network/ChatClientConnection.cs index a7274fb..a01fcc9 100644 --- a/src/GsDChat.Client/Network/ChatClientConnection.cs +++ b/src/GsDChat.Client/Network/ChatClientConnection.cs @@ -47,9 +47,22 @@ public class ChatClientConnection : IDisposable 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) { @@ -73,6 +86,15 @@ public class ChatClientConnection : IDisposable { 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." }; } @@ -97,6 +119,15 @@ public class ChatClientConnection : IDisposable { 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." }; } diff --git a/src/GsDChat.Client/Program.cs b/src/GsDChat.Client/Program.cs index d3556d2..e3e467e 100644 --- a/src/GsDChat.Client/Program.cs +++ b/src/GsDChat.Client/Program.cs @@ -194,8 +194,8 @@ public class Program Console.WriteLine($"{Ansi.BrightGreen}Success! Welcome @{authResult.Username} [{authResult.Role}]{Ansi.Reset}"); - // Save server to history - historyManager.SaveServer(serverUrl, info.ServerName, authResult.Username); + // Save server to history (with upgraded protocol if applicable) + historyManager.SaveServer(state.ServerUrl, info.ServerName, authResult.Username); state.Token = authResult.Token; state.CurrentUserId = authResult.UserId ?? ""; diff --git a/src/GsDChat.Client/State/ServerHistoryManager.cs b/src/GsDChat.Client/State/ServerHistoryManager.cs index 7429c2f..de16548 100644 --- a/src/GsDChat.Client/State/ServerHistoryManager.cs +++ b/src/GsDChat.Client/State/ServerHistoryManager.cs @@ -115,8 +115,19 @@ public class ServerHistoryManager if (!input.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !input.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { - // Default to http:// unless standard SSL port 443 - input = input.EndsWith(":443") ? $"https://{input}" : $"http://{input}"; + // If local loopback or private LAN IP without explicit https, default to http:// + if (input.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) || + input.StartsWith("127.0.0.1", StringComparison.OrdinalIgnoreCase) || + input.StartsWith("192.168.", StringComparison.OrdinalIgnoreCase) || + input.StartsWith("10.", StringComparison.OrdinalIgnoreCase)) + { + input = input.EndsWith(":443") ? $"https://{input}" : $"http://{input}"; + } + else + { + // Default to https:// for all public domain names and remote hosts unless explicit port 80 + input = input.EndsWith(":80") ? $"http://{input}" : $"https://{input}"; + } } return input; diff --git a/src/GsDChat.Core/Protocol/HttpModels.cs b/src/GsDChat.Core/Protocol/HttpModels.cs index 8570447..4eb8d28 100644 --- a/src/GsDChat.Core/Protocol/HttpModels.cs +++ b/src/GsDChat.Core/Protocol/HttpModels.cs @@ -35,6 +35,7 @@ public class ServerInfoResponse public bool RequiresServerPassword { get; set; } public string Motd { get; set; } = "Welcome to GsDChat!"; public long MaxFileSizeMb { get; set; } = 50; + public bool AllowMemberChannelCreation { get; set; } = true; } public class UploadFileResponse diff --git a/src/GsDChat.Core/Protocol/NetworkMessages.cs b/src/GsDChat.Core/Protocol/NetworkMessages.cs index fd07498..d939660 100644 --- a/src/GsDChat.Core/Protocol/NetworkMessages.cs +++ b/src/GsDChat.Core/Protocol/NetworkMessages.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Text.Json; +using System.Text.Json.Serialization; using GsDChat.Core.Models; namespace GsDChat.Core.Protocol; @@ -28,7 +29,16 @@ public static class MessageTypes public class NetworkEnvelope { + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + [JsonPropertyName("type")] public string Type { get; set; } = string.Empty; + + [JsonPropertyName("payload")] public string Payload { get; set; } = "{}"; public static NetworkEnvelope Create(string type, T payload) @@ -36,13 +46,13 @@ public class NetworkEnvelope return new NetworkEnvelope { Type = type, - Payload = JsonSerializer.Serialize(payload) + Payload = JsonSerializer.Serialize(payload, s_jsonOptions) }; } public T? Unpack() { - return JsonSerializer.Deserialize(Payload); + return JsonSerializer.Deserialize(Payload, s_jsonOptions); } } diff --git a/src/GsDChat.Server/Configuration/ServerOptions.cs b/src/GsDChat.Server/Configuration/ServerOptions.cs index 6dc0c27..8bb2f7f 100644 --- a/src/GsDChat.Server/Configuration/ServerOptions.cs +++ b/src/GsDChat.Server/Configuration/ServerOptions.cs @@ -13,4 +13,5 @@ public class ServerOptions public long MaxFileSizeMb { get; set; } = 50; public string ServerName { get; set; } = "GsDChat Community Server"; public string Motd { get; set; } = "Welcome to GsDChat! Enjoy private, modular messaging."; + public bool AllowMemberChannelCreation { get; set; } = true; } diff --git a/src/GsDChat.Server/Program.cs b/src/GsDChat.Server/Program.cs index 71c57be..710a08f 100644 --- a/src/GsDChat.Server/Program.cs +++ b/src/GsDChat.Server/Program.cs @@ -69,6 +69,9 @@ if (!string.IsNullOrEmpty(envCertPath)) serverOptions.CertificatePath = envCertP string? envCertPass = Environment.GetEnvironmentVariable("GSDCHAT_CERT_PASSWORD"); if (!string.IsNullOrEmpty(envCertPass)) serverOptions.CertificatePassword = envCertPass; +string? envAllowMemberChannels = Environment.GetEnvironmentVariable("GSDCHAT_ALLOW_MEMBER_CHANNELS"); +if (!string.IsNullOrEmpty(envAllowMemberChannels) && bool.TryParse(envAllowMemberChannels, out bool eamc)) serverOptions.AllowMemberChannelCreation = eamc; + // Allow CLI overrides e.g. --port 5000 --tls false for (int i = 0; i < args.Length; i++) { @@ -172,7 +175,8 @@ app.MapGet("/api/info", (ServerOptions opt) => RegistrationMode = opt.RegistrationMode, RequiresServerPassword = !string.IsNullOrWhiteSpace(opt.ServerWidePassword), Motd = opt.Motd, - MaxFileSizeMb = opt.MaxFileSizeMb + MaxFileSizeMb = opt.MaxFileSizeMb, + AllowMemberChannelCreation = opt.AllowMemberChannelCreation }); }); diff --git a/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs b/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs index fc21cb8..a524725 100644 --- a/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs +++ b/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs @@ -138,14 +138,21 @@ public class ChatWebSocketManager } } + private static readonly JsonSerializerOptions s_envelopeJsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private async Task ProcessClientMessageAsync(ConnectedClient client, string json, CancellationToken ct) { try { - var envelope = JsonSerializer.Deserialize(json); - if (envelope == null) return; + var envelope = JsonSerializer.Deserialize(json, s_envelopeJsonOptions); + if (envelope == null || string.IsNullOrWhiteSpace(envelope.Type)) return; - switch (envelope.Type) + string msgType = envelope.Type.Trim().ToUpperInvariant(); + + switch (msgType) { case MessageTypes.SendMessage: var sendMsg = envelope.Unpack(); @@ -271,7 +278,7 @@ public class ChatWebSocketManager private async Task HandleCreateChannelAsync(ConnectedClient client, CreateChannelPacket packet, CancellationToken ct) { - if (client.User.Role != UserRoles.Owner && client.User.Role != UserRoles.Admin) + if (!_options.AllowMemberChannelCreation && client.User.Role != UserRoles.Owner && client.User.Role != UserRoles.Admin) { await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Only Admins can create channels." }, ct); return; @@ -326,7 +333,7 @@ public class ChatWebSocketManager private async Task HandleCommandAsync(ConnectedClient client, ExecuteCommandPacket packet, CancellationToken ct) { - string cmd = packet.Command.TrimStart('/').ToLowerInvariant(); + string cmd = (packet.Command ?? string.Empty).TrimStart('/').ToLowerInvariant(); // Check mod command interceptor first if (CommandInterceptor != null) @@ -343,10 +350,11 @@ public class ChatWebSocketManager switch (cmd) { case "help": + string createDesc = _options.AllowMemberChannelCreation ? "Create a new channel" : "Create a new channel (Admin)"; string helpText = "Available commands:\n" + " /help - Show this help\n" + " /join - Switch active channel\n" + - " /create [topic]- Create a new channel (Admin)\n" + + $" /create [topic]- {createDesc}\n" + " /delete - Delete a channel (Admin)\n" + " /users - List all registered users\n" + " /motd - Display message of the day"; diff --git a/src/GsDChat.Server/wwwroot/app.css b/src/GsDChat.Server/wwwroot/app.css index e31b8b0..916510c 100644 --- a/src/GsDChat.Server/wwwroot/app.css +++ b/src/GsDChat.Server/wwwroot/app.css @@ -170,8 +170,10 @@ html, body { .channel-info { display: flex; - align-items: baseline; + align-items: center; gap: 6px; + flex: 1; + min-width: 0; } .channel-hash { @@ -185,6 +187,29 @@ html, body { font-weight: 600; } +.channel-dropdown { + background-color: rgba(19, 27, 46, 0.8); + color: var(--text-main); + border: 1px solid var(--border-color); + font-size: 1rem; + font-weight: 600; + font-family: inherit; + cursor: pointer; + padding: 4px 8px; + border-radius: 6px; + outline: none; + transition: border-color 0.15s; +} + +.channel-dropdown:hover, .channel-dropdown:focus { + border-color: var(--accent); +} + +.channel-dropdown option { + background-color: var(--bg-surface); + color: var(--text-main); +} + .channel-topic { font-size: 0.85rem; color: var(--text-muted); @@ -300,12 +325,16 @@ html, body { } .system-notice { - padding: 6px 12px; + padding: 8px 14px; border-radius: 6px; font-size: 0.85rem; - text-align: center; - background-color: rgba(39, 53, 79, 0.4); - color: var(--text-muted); + text-align: left; + white-space: pre-wrap; + font-family: var(--font-mono); + background-color: rgba(39, 53, 79, 0.45); + color: #cbd5e1; + border-left: 3px solid var(--accent); + line-height: 1.45; } .chat-input-bar { @@ -672,3 +701,48 @@ html, body { display: none; } } + +/* Drag & Drop Overlay */ +.drop-overlay { + position: fixed; + inset: 0; + background-color: rgba(9, 13, 22, 0.85); + backdrop-filter: blur(4px); + -webkit-backdrop-filter: blur(4px); + display: flex; + align-items: center; + justify-content: center; + z-index: 10000; + opacity: 0; + pointer-events: none; + transition: opacity 0.2s ease-in-out; +} + +.drop-overlay.visible { + opacity: 1; + pointer-events: auto; +} + +.drop-message { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + padding: 36px 48px; + border: 2px dashed var(--accent); + border-radius: 12px; + background-color: var(--bg-surface); + color: var(--text-main); + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5); + pointer-events: none; +} + +.drop-icon { + font-size: 2.8rem; +} + +.drop-text { + font-size: 1.1rem; + font-weight: 600; + color: var(--accent); +} diff --git a/src/GsDChat.Server/wwwroot/app.js b/src/GsDChat.Server/wwwroot/app.js index 7ab6566..6729de0 100644 --- a/src/GsDChat.Server/wwwroot/app.js +++ b/src/GsDChat.Server/wwwroot/app.js @@ -26,7 +26,7 @@ userBadge: document.getElementById('userBadge'), // Chat View - activeChannelName: document.getElementById('activeChannelName'), + channelSelectDropdown: document.getElementById('channelSelectDropdown'), activeChannelTopic: document.getElementById('activeChannelTopic'), chatMessages: document.getElementById('chatMessages'), messageInput: document.getElementById('messageInput'), @@ -66,7 +66,8 @@ authInviteToken: document.getElementById('authInviteToken'), authSubmitBtn: document.getElementById('authSubmitBtn'), authError: document.getElementById('authError'), - toastContainer: document.getElementById('toastContainer') + toastContainer: document.getElementById('toastContainer'), + dropOverlay: document.getElementById('dropOverlay') }; // ========================================== @@ -229,66 +230,84 @@ } function handleNetworkEnvelope(envelope) { - const payload = JSON.parse(envelope.payload || '{}'); + const type = (envelope.type || envelope.Type || '').toUpperCase(); + const payloadRaw = envelope.payload ?? envelope.Payload ?? '{}'; + let payload = {}; + try { + payload = typeof payloadRaw === 'string' ? JSON.parse(payloadRaw) : payloadRaw; + } catch (e) { + console.error('Failed to parse envelope payload', e); + return; + } - switch (envelope.type) { + switch (type) { case 'CHANNEL_LIST_SYNC': - state.channels = payload.channels || []; - if (payload.activeChannelId) { - state.activeChannelId = payload.activeChannelId; + state.channels = payload.channels || payload.Channels || []; + const activeCh = payload.activeChannelId || payload.ActiveChannelId; + if (activeCh) { + state.activeChannelId = activeCh; + } else if (!state.activeChannelId && state.channels.length > 0) { + const first = state.channels[0]; + state.activeChannelId = first.id || first.Id; } renderChannels(); updateActiveChannelHeader(); break; case 'HISTORY_SYNC': - if (payload.channelId) { - state.messages[payload.channelId] = payload.messages || []; - if (state.activeChannelId === payload.channelId) { + const histChId = payload.channelId || payload.ChannelId; + if (histChId) { + state.messages[histChId] = payload.messages || payload.Messages || []; + if (state.activeChannelId === histChId) { renderMessages(); } } break; case 'MESSAGE_BROADCAST': - if (payload.message) { - const chId = payload.message.channelId; + const msg = payload.message || payload.Message; + if (msg) { + const chId = msg.channelId || msg.ChannelId; if (!state.messages[chId]) state.messages[chId] = []; - state.messages[chId].push(payload.message); + state.messages[chId].push(msg); if (state.activeChannelId === chId) { - appendMessage(payload.message); + appendMessage(msg); } } break; case 'USER_LIST_SYNC': - state.users = payload.users || []; + state.users = payload.users || payload.Users || []; renderUsers(); break; case 'FILE_LIST_SYNC': - state.files = payload.files || []; + state.files = payload.files || payload.Files || []; renderFiles(); break; case 'SYSTEM_NOTICE': - if (payload.text) { - showToast(payload.text); + const noticeText = payload.text || payload.Text; + if (noticeText) { + showToast(noticeText); if (state.activeChannelId) { - appendSystemNotice(payload.text); + appendSystemNotice(noticeText); } } break; case 'COMMAND_RESULT': - if (payload.output) { - appendSystemNotice(payload.output); + const cmdOut = payload.output || payload.Output; + if (cmdOut) { + appendSystemNotice(cmdOut); } break; case 'ERROR': - if (payload.message) { - showToast(`Error: ${payload.message}`); + const errMsg = payload.message || payload.Message; + if (errMsg) { + showToast(`Error: ${errMsg}`); + appendSystemNotice(`[Error] ${errMsg}`); } break; } @@ -307,36 +326,61 @@ } function updateActiveChannelHeader() { - const active = state.channels.find(c => c.id === state.activeChannelId); + const active = state.channels.find(c => (c.id || c.Id) === state.activeChannelId); if (active) { - el.activeChannelName.textContent = active.name; - el.activeChannelTopic.textContent = active.topic ? ` - ${active.topic}` : ''; - el.messageInput.placeholder = `Message #${active.name}... (or /help)`; + const chId = active.id || active.Id; + const chName = active.name || active.Name || 'general'; + const chTopic = active.topic || active.Topic || ''; + if (el.channelSelectDropdown) { + el.channelSelectDropdown.value = chId; + } + el.activeChannelTopic.textContent = chTopic ? ` - ${chTopic}` : ''; + el.messageInput.placeholder = `Message #${chName}... (or /help)`; } } function renderChannels() { el.channelList.innerHTML = ''; + if (el.channelSelectDropdown) { + el.channelSelectDropdown.innerHTML = ''; + } + state.channels.forEach(ch => { + const chId = ch.id || ch.Id; + const chName = ch.name || ch.Name; + const chTopic = ch.topic || ch.Topic || ''; + const isActive = chId === state.activeChannelId; + + // Channels View list item const item = document.createElement('div'); - item.className = 'channel-item' + (ch.id === state.activeChannelId ? ' active' : ''); + item.className = 'channel-item' + (isActive ? ' active' : ''); item.innerHTML = `
- #${escapeHtml(ch.name)} - ${escapeHtml(ch.topic || '')} + #${escapeHtml(chName)} + ${escapeHtml(chTopic)}
- ${ch.id === state.activeChannelId ? 'ACTIVE' : ''} + ${isActive ? 'ACTIVE' : ''} `; item.addEventListener('click', () => { - joinChannel(ch.id); + joinChannel(chId); switchTab('chat'); }); el.channelList.appendChild(item); + + // In-chat dropdown option + if (el.channelSelectDropdown) { + const opt = document.createElement('option'); + opt.value = chId; + opt.textContent = `#${chName}`; + opt.selected = isActive; + el.channelSelectDropdown.appendChild(opt); + } }); - // Show create button for Admin or Owner + // Show create button for Admin, Owner, or if allowed for members const isPrivileged = state.user && (state.user.role === 'Owner' || state.user.role === 'Admin'); - el.openCreateChannelBtn.style.display = isPrivileged ? 'inline-flex' : 'none'; + const allowMemberChannels = state.serverInfo && state.serverInfo.allowMemberChannelCreation; + el.openCreateChannelBtn.style.display = (isPrivileged || allowMemberChannels) ? 'inline-flex' : 'none'; } function joinChannel(channelId) { @@ -349,11 +393,13 @@ function renderMessages() { el.chatMessages.innerHTML = ''; + const active = state.channels.find(c => (c.id || c.Id) === state.activeChannelId); + const activeName = active ? (active.name || active.Name) : 'general'; const msgs = state.messages[state.activeChannelId] || []; if (msgs.length === 0) { el.chatMessages.innerHTML = `
-

Welcome to #${escapeHtml(el.activeChannelName.textContent)}

+

Welcome to #${escapeHtml(activeName)}

No messages yet. Say hello!

`; @@ -362,37 +408,85 @@ msgs.forEach(appendMessage); } + async function downloadFile(fileId, fileName) { + if (!state.token) { + showToast('Please login to download files'); + return; + } + showToast(`Downloading ${fileName}...`); + try { + const res = await fetch(`/api/files/${encodeURIComponent(fileId)}`, { + headers: { + 'Authorization': `Bearer ${state.token}` + } + }); + if (!res.ok) { + showToast(`Failed to download ${fileName} (HTTP ${res.status})`); + return; + } + const blob = await res.blob(); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = fileName; + document.body.appendChild(a); + a.click(); + setTimeout(() => { + document.body.removeChild(a); + URL.revokeObjectURL(url); + }, 200); + } catch (err) { + showToast(`Download error: ${err.message}`); + } + } + function appendMessage(msg) { const welcome = el.chatMessages.querySelector('.welcome-message'); if (welcome) welcome.remove(); - const time = new Date(msg.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); - const roleClass = (msg.senderRole || 'member').toLowerCase(); + const createdAt = msg.createdAt || msg.CreatedAt; + const time = createdAt ? new Date(createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''; + const rawRole = msg.senderRole || msg.SenderRole || 'member'; + const roleClass = rawRole.toLowerCase(); + const sender = msg.senderUsername || msg.SenderUsername || 'User'; + const rawContent = msg.content || msg.Content || ''; + const attId = msg.attachmentId || msg.AttachmentId; + const attName = msg.attachmentName || msg.AttachmentName; + const attBytes = msg.attachmentSizeBytes ?? msg.AttachmentSizeBytes ?? 0; const div = document.createElement('div'); div.className = 'message-item'; - let contentHtml = escapeHtml(msg.content); - if (msg.attachmentId) { - const sizeStr = formatBytes(msg.attachmentSizeBytes || 0); + let contentHtml = escapeHtml(rawContent); + if (attId) { + const sizeStr = formatBytes(attBytes); + const safeId = escapeHtml(attId); + const safeName = escapeHtml(attName || 'file'); contentHtml += ` `; } div.innerHTML = `
- @${escapeHtml(msg.senderUsername)} - ${escapeHtml(msg.senderRole || 'Member')} + @${escapeHtml(sender)} + ${escapeHtml(rawRole)} ${time}
${contentHtml}
`; + div.querySelectorAll('.attachment-card').forEach(btn => { + btn.addEventListener('click', (e) => { + e.preventDefault(); + downloadFile(btn.dataset.fileId, btn.dataset.fileName); + }); + }); + el.chatMessages.appendChild(div); el.chatMessages.scrollTop = el.chatMessages.scrollHeight; } @@ -407,19 +501,22 @@ function renderUsers() { el.userList.innerHTML = ''; - const onlineCount = state.users.filter(u => u.isOnline).length; + const onlineCount = state.users.filter(u => u.isOnline ?? u.IsOnline).length; el.userCountBadge.textContent = `${onlineCount} Online / ${state.users.length} Total`; state.users.forEach(u => { const item = document.createElement('div'); item.className = 'user-item'; - const roleClass = (u.role || 'member').toLowerCase(); + const username = u.username || u.Username || 'User'; + const role = u.role || u.Role || 'Member'; + const roleClass = role.toLowerCase(); + const isOnline = u.isOnline ?? u.IsOnline ?? false; item.innerHTML = `
- - @${escapeHtml(u.username)} + + @${escapeHtml(username)}
- ${escapeHtml(u.role)} + ${escapeHtml(role)} `; el.userList.appendChild(item); }); @@ -435,16 +532,28 @@ state.files.forEach(f => { const item = document.createElement('div'); item.className = 'file-item'; - const sizeStr = formatBytes(f.fileSizeBytes || 0); - const dateStr = new Date(f.createdAt).toLocaleDateString(); + const fileId = f.id || f.Id; + const fileName = f.originalFileName || f.OriginalFileName || 'file'; + const fileBytes = f.fileSizeBytes ?? f.FileSizeBytes ?? 0; + const uploader = f.uploaderUsername || f.UploaderUsername || 'User'; + const createdAt = f.createdAt || f.CreatedAt; + const sizeStr = formatBytes(fileBytes); + const dateStr = createdAt ? new Date(createdAt).toLocaleDateString() : ''; item.innerHTML = `
-
📎 ${escapeHtml(f.originalFileName)}
-
${sizeStr} • shared by @${escapeHtml(f.uploaderUsername)} on ${dateStr}
+
📎 ${escapeHtml(fileName)}
+
${sizeStr} • shared by @${escapeHtml(uploader)} on ${dateStr}
- Download + `; + const dlBtn = item.querySelector('.btn-download'); + if (dlBtn) { + dlBtn.addEventListener('click', (e) => { + e.preventDefault(); + downloadFile(dlBtn.dataset.fileId, dlBtn.dataset.fileName); + }); + } el.filesList.appendChild(item); }); } @@ -649,6 +758,56 @@ createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim()); }); + // In-chat Channel Selector Dropdown + if (el.channelSelectDropdown) { + el.channelSelectDropdown.addEventListener('change', (e) => { + if (e.target.value) { + joinChannel(e.target.value); + } + }); + } + + // Global Drag & Drop handling (Prevents Firefox "Security Error: Content may not load or link to file:///") + let dragCounter = 0; + + window.addEventListener('dragenter', (e) => { + e.preventDefault(); + dragCounter++; + if (el.dropOverlay) { + el.dropOverlay.classList.add('visible'); + } + }, false); + + window.addEventListener('dragover', (e) => { + e.preventDefault(); + if (e.dataTransfer) { + e.dataTransfer.dropEffect = 'copy'; + } + }, false); + + window.addEventListener('dragleave', (e) => { + e.preventDefault(); + dragCounter--; + if (dragCounter <= 0) { + dragCounter = 0; + if (el.dropOverlay) { + el.dropOverlay.classList.remove('visible'); + } + } + }, false); + + window.addEventListener('drop', (e) => { + e.preventDefault(); + dragCounter = 0; + if (el.dropOverlay) { + el.dropOverlay.classList.remove('visible'); + } + + if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length > 0) { + uploadFile(e.dataTransfer.files[0]); + } + }, false); + // Logout el.logoutBtn.addEventListener('click', logout); } @@ -672,5 +831,9 @@ } // Start app - window.addEventListener('DOMContentLoaded', init); + if (document.readyState === 'loading') { + window.addEventListener('DOMContentLoaded', init); + } else { + init(); + } })(); diff --git a/src/GsDChat.Server/wwwroot/index.html b/src/GsDChat.Server/wwwroot/index.html index c56ce2f..e44dec2 100644 --- a/src/GsDChat.Server/wwwroot/index.html +++ b/src/GsDChat.Server/wwwroot/index.html @@ -3,10 +3,36 @@ + + GsDChat - Web Client - + + + + + + + +
+
+ 📎 + Drop file here to upload to channel +
+
+
@@ -41,7 +67,9 @@
# - general +
@@ -163,7 +191,5 @@
- - diff --git a/tests/GsDChat.Tests/NetworkProtocolTests.cs b/tests/GsDChat.Tests/NetworkProtocolTests.cs index 6d41d19..3255da0 100644 --- a/tests/GsDChat.Tests/NetworkProtocolTests.cs +++ b/tests/GsDChat.Tests/NetworkProtocolTests.cs @@ -39,4 +39,45 @@ public class NetworkProtocolTests Assert.Contains(sync.Screens, s => s.ScreenId == "F3_Users"); Assert.Contains(sync.Screens, s => s.ScreenId == "F4_Files"); } + + [Fact] + public void NetworkEnvelope_ShouldUnpackCamelCasePayloadFromWebClient() + { + // Simulated browser payload + string envelopeJson = "{\"type\":\"EXECUTE_COMMAND\",\"payload\":\"{\\\"command\\\":\\\"help\\\",\\\"args\\\":\\\"\\\",\\\"channelId\\\":\\\"ch_1\\\"}\"}"; + + var envelope = System.Text.Json.JsonSerializer.Deserialize(envelopeJson, new System.Text.Json.JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }); + + Assert.NotNull(envelope); + Assert.Equal("EXECUTE_COMMAND", envelope.Type); + + var packet = envelope.Unpack(); + Assert.NotNull(packet); + Assert.Equal("help", packet.Command); + Assert.Equal("", packet.Args); + Assert.Equal("ch_1", packet.ChannelId); + } + + [Fact] + public void NetworkEnvelope_ShouldUnpackCreateChannelFromWebClient() + { + // Simulated browser channel creation + string envelopeJson = "{\"type\":\"CREATE_CHANNEL\",\"payload\":\"{\\\"name\\\":\\\"gaming\\\",\\\"topic\\\":\\\"General Gaming Room\\\"}\"}"; + + var envelope = System.Text.Json.JsonSerializer.Deserialize(envelopeJson, new System.Text.Json.JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }); + + Assert.NotNull(envelope); + Assert.Equal("CREATE_CHANNEL", envelope.Type); + + var packet = envelope.Unpack(); + Assert.NotNull(packet); + Assert.Equal("gaming", packet.Name); + Assert.Equal("General Gaming Room", packet.Topic); + } } diff --git a/tests/GsDChat.Tests/ServerHistoryTests.cs b/tests/GsDChat.Tests/ServerHistoryTests.cs index f2453aa..555a458 100644 --- a/tests/GsDChat.Tests/ServerHistoryTests.cs +++ b/tests/GsDChat.Tests/ServerHistoryTests.cs @@ -31,6 +31,7 @@ public class ServerHistoryTests : IDisposable [InlineData("http://localhost:5000/", "http://localhost:5000")] [InlineData("https://chat.example.com", "https://chat.example.com")] [InlineData("chat.example.com:443", "https://chat.example.com:443")] + [InlineData("chat.gsdistance.org", "https://chat.gsdistance.org")] [InlineData("192.168.1.100:8080", "http://192.168.1.100:8080")] public void NormalizeUrl_ShouldFormatProperly(string input, string expected) {