fixes, hopefully

This commit is contained in:
tyuXX 2026-10-10 20:48:03 +00:00
parent 7495e34ade
commit cbc24e7672
13 changed files with 449 additions and 78 deletions

View file

@ -47,9 +47,22 @@ public class ChatClientConnection : IDisposable
var res = await _httpClient.GetAsync("/api/info"); var res = await _httpClient.GetAsync("/api/info");
if (res.IsSuccessStatusCode) 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 json = await res.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<ServerInfoResponse>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); return JsonSerializer.Deserialize<ServerInfoResponse>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
} }
else
{
_state.SetStatus($"Server returned HTTP {(int)res.StatusCode} ({res.ReasonPhrase}) on /api/info");
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -73,6 +86,15 @@ public class ChatClientConnection : IDisposable
{ {
var res = await _httpClient.PostAsync("/api/auth/register", content); var res = await _httpClient.PostAsync("/api/auth/register", content);
var resJson = await res.Content.ReadAsStringAsync(); 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<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) return JsonSerializer.Deserialize<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." }; ?? 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 res = await _httpClient.PostAsync("/api/auth/login", content);
var resJson = await res.Content.ReadAsStringAsync(); 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<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) return JsonSerializer.Deserialize<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." }; ?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." };
} }

View file

@ -194,8 +194,8 @@ public class Program
Console.WriteLine($"{Ansi.BrightGreen}Success! Welcome @{authResult.Username} [{authResult.Role}]{Ansi.Reset}"); Console.WriteLine($"{Ansi.BrightGreen}Success! Welcome @{authResult.Username} [{authResult.Role}]{Ansi.Reset}");
// Save server to history // Save server to history (with upgraded protocol if applicable)
historyManager.SaveServer(serverUrl, info.ServerName, authResult.Username); historyManager.SaveServer(state.ServerUrl, info.ServerName, authResult.Username);
state.Token = authResult.Token; state.Token = authResult.Token;
state.CurrentUserId = authResult.UserId ?? ""; state.CurrentUserId = authResult.UserId ?? "";

View file

@ -115,9 +115,20 @@ public class ServerHistoryManager
if (!input.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && if (!input.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
!input.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) !input.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{ {
// Default to http:// unless standard SSL port 443 // 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}"; 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; return input;
} }

View file

@ -35,6 +35,7 @@ public class ServerInfoResponse
public bool RequiresServerPassword { get; set; } public bool RequiresServerPassword { get; set; }
public string Motd { get; set; } = "Welcome to GsDChat!"; public string Motd { get; set; } = "Welcome to GsDChat!";
public long MaxFileSizeMb { get; set; } = 50; public long MaxFileSizeMb { get; set; } = 50;
public bool AllowMemberChannelCreation { get; set; } = true;
} }
public class UploadFileResponse public class UploadFileResponse

View file

@ -1,5 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization;
using GsDChat.Core.Models; using GsDChat.Core.Models;
namespace GsDChat.Core.Protocol; namespace GsDChat.Core.Protocol;
@ -28,7 +29,16 @@ public static class MessageTypes
public class NetworkEnvelope public class NetworkEnvelope
{ {
private static readonly JsonSerializerOptions s_jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
[JsonPropertyName("type")]
public string Type { get; set; } = string.Empty; public string Type { get; set; } = string.Empty;
[JsonPropertyName("payload")]
public string Payload { get; set; } = "{}"; public string Payload { get; set; } = "{}";
public static NetworkEnvelope Create<T>(string type, T payload) public static NetworkEnvelope Create<T>(string type, T payload)
@ -36,13 +46,13 @@ public class NetworkEnvelope
return new NetworkEnvelope return new NetworkEnvelope
{ {
Type = type, Type = type,
Payload = JsonSerializer.Serialize(payload) Payload = JsonSerializer.Serialize(payload, s_jsonOptions)
}; };
} }
public T? Unpack<T>() public T? Unpack<T>()
{ {
return JsonSerializer.Deserialize<T>(Payload); return JsonSerializer.Deserialize<T>(Payload, s_jsonOptions);
} }
} }

View file

@ -13,4 +13,5 @@ public class ServerOptions
public long MaxFileSizeMb { get; set; } = 50; public long MaxFileSizeMb { get; set; } = 50;
public string ServerName { get; set; } = "GsDChat Community Server"; public string ServerName { get; set; } = "GsDChat Community Server";
public string Motd { get; set; } = "Welcome to GsDChat! Enjoy private, modular messaging."; public string Motd { get; set; } = "Welcome to GsDChat! Enjoy private, modular messaging.";
public bool AllowMemberChannelCreation { get; set; } = true;
} }

View file

@ -69,6 +69,9 @@ if (!string.IsNullOrEmpty(envCertPath)) serverOptions.CertificatePath = envCertP
string? envCertPass = Environment.GetEnvironmentVariable("GSDCHAT_CERT_PASSWORD"); string? envCertPass = Environment.GetEnvironmentVariable("GSDCHAT_CERT_PASSWORD");
if (!string.IsNullOrEmpty(envCertPass)) serverOptions.CertificatePassword = envCertPass; 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 // Allow CLI overrides e.g. --port 5000 --tls false
for (int i = 0; i < args.Length; i++) for (int i = 0; i < args.Length; i++)
{ {
@ -172,7 +175,8 @@ app.MapGet("/api/info", (ServerOptions opt) =>
RegistrationMode = opt.RegistrationMode, RegistrationMode = opt.RegistrationMode,
RequiresServerPassword = !string.IsNullOrWhiteSpace(opt.ServerWidePassword), RequiresServerPassword = !string.IsNullOrWhiteSpace(opt.ServerWidePassword),
Motd = opt.Motd, Motd = opt.Motd,
MaxFileSizeMb = opt.MaxFileSizeMb MaxFileSizeMb = opt.MaxFileSizeMb,
AllowMemberChannelCreation = opt.AllowMemberChannelCreation
}); });
}); });

View file

@ -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) private async Task ProcessClientMessageAsync(ConnectedClient client, string json, CancellationToken ct)
{ {
try try
{ {
var envelope = JsonSerializer.Deserialize<NetworkEnvelope>(json); var envelope = JsonSerializer.Deserialize<NetworkEnvelope>(json, s_envelopeJsonOptions);
if (envelope == null) return; if (envelope == null || string.IsNullOrWhiteSpace(envelope.Type)) return;
switch (envelope.Type) string msgType = envelope.Type.Trim().ToUpperInvariant();
switch (msgType)
{ {
case MessageTypes.SendMessage: case MessageTypes.SendMessage:
var sendMsg = envelope.Unpack<SendMessagePacket>(); var sendMsg = envelope.Unpack<SendMessagePacket>();
@ -271,7 +278,7 @@ public class ChatWebSocketManager
private async Task HandleCreateChannelAsync(ConnectedClient client, CreateChannelPacket packet, CancellationToken ct) 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); await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Only Admins can create channels." }, ct);
return; return;
@ -326,7 +333,7 @@ public class ChatWebSocketManager
private async Task HandleCommandAsync(ConnectedClient client, ExecuteCommandPacket packet, CancellationToken ct) 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 // Check mod command interceptor first
if (CommandInterceptor != null) if (CommandInterceptor != null)
@ -343,10 +350,11 @@ public class ChatWebSocketManager
switch (cmd) switch (cmd)
{ {
case "help": case "help":
string createDesc = _options.AllowMemberChannelCreation ? "Create a new channel" : "Create a new channel (Admin)";
string helpText = "Available commands:\n" + string helpText = "Available commands:\n" +
" /help - Show this help\n" + " /help - Show this help\n" +
" /join <channel> - Switch active channel\n" + " /join <channel> - Switch active channel\n" +
" /create <name> [topic]- Create a new channel (Admin)\n" + $" /create <name> [topic]- {createDesc}\n" +
" /delete <name> - Delete a channel (Admin)\n" + " /delete <name> - Delete a channel (Admin)\n" +
" /users - List all registered users\n" + " /users - List all registered users\n" +
" /motd - Display message of the day"; " /motd - Display message of the day";

View file

@ -170,8 +170,10 @@ html, body {
.channel-info { .channel-info {
display: flex; display: flex;
align-items: baseline; align-items: center;
gap: 6px; gap: 6px;
flex: 1;
min-width: 0;
} }
.channel-hash { .channel-hash {
@ -185,6 +187,29 @@ html, body {
font-weight: 600; 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 { .channel-topic {
font-size: 0.85rem; font-size: 0.85rem;
color: var(--text-muted); color: var(--text-muted);
@ -300,12 +325,16 @@ html, body {
} }
.system-notice { .system-notice {
padding: 6px 12px; padding: 8px 14px;
border-radius: 6px; border-radius: 6px;
font-size: 0.85rem; font-size: 0.85rem;
text-align: center; text-align: left;
background-color: rgba(39, 53, 79, 0.4); white-space: pre-wrap;
color: var(--text-muted); 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 { .chat-input-bar {
@ -672,3 +701,48 @@ html, body {
display: none; 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);
}

View file

@ -26,7 +26,7 @@
userBadge: document.getElementById('userBadge'), userBadge: document.getElementById('userBadge'),
// Chat View // Chat View
activeChannelName: document.getElementById('activeChannelName'), channelSelectDropdown: document.getElementById('channelSelectDropdown'),
activeChannelTopic: document.getElementById('activeChannelTopic'), activeChannelTopic: document.getElementById('activeChannelTopic'),
chatMessages: document.getElementById('chatMessages'), chatMessages: document.getElementById('chatMessages'),
messageInput: document.getElementById('messageInput'), messageInput: document.getElementById('messageInput'),
@ -66,7 +66,8 @@
authInviteToken: document.getElementById('authInviteToken'), authInviteToken: document.getElementById('authInviteToken'),
authSubmitBtn: document.getElementById('authSubmitBtn'), authSubmitBtn: document.getElementById('authSubmitBtn'),
authError: document.getElementById('authError'), authError: document.getElementById('authError'),
toastContainer: document.getElementById('toastContainer') toastContainer: document.getElementById('toastContainer'),
dropOverlay: document.getElementById('dropOverlay')
}; };
// ========================================== // ==========================================
@ -229,66 +230,84 @@
} }
function handleNetworkEnvelope(envelope) { 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': case 'CHANNEL_LIST_SYNC':
state.channels = payload.channels || []; state.channels = payload.channels || payload.Channels || [];
if (payload.activeChannelId) { const activeCh = payload.activeChannelId || payload.ActiveChannelId;
state.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(); renderChannels();
updateActiveChannelHeader(); updateActiveChannelHeader();
break; break;
case 'HISTORY_SYNC': case 'HISTORY_SYNC':
if (payload.channelId) { const histChId = payload.channelId || payload.ChannelId;
state.messages[payload.channelId] = payload.messages || []; if (histChId) {
if (state.activeChannelId === payload.channelId) { state.messages[histChId] = payload.messages || payload.Messages || [];
if (state.activeChannelId === histChId) {
renderMessages(); renderMessages();
} }
} }
break; break;
case 'MESSAGE_BROADCAST': case 'MESSAGE_BROADCAST':
if (payload.message) { const msg = payload.message || payload.Message;
const chId = payload.message.channelId; if (msg) {
const chId = msg.channelId || msg.ChannelId;
if (!state.messages[chId]) state.messages[chId] = []; if (!state.messages[chId]) state.messages[chId] = [];
state.messages[chId].push(payload.message); state.messages[chId].push(msg);
if (state.activeChannelId === chId) { if (state.activeChannelId === chId) {
appendMessage(payload.message); appendMessage(msg);
} }
} }
break; break;
case 'USER_LIST_SYNC': case 'USER_LIST_SYNC':
state.users = payload.users || []; state.users = payload.users || payload.Users || [];
renderUsers(); renderUsers();
break; break;
case 'FILE_LIST_SYNC': case 'FILE_LIST_SYNC':
state.files = payload.files || []; state.files = payload.files || payload.Files || [];
renderFiles(); renderFiles();
break; break;
case 'SYSTEM_NOTICE': case 'SYSTEM_NOTICE':
if (payload.text) { const noticeText = payload.text || payload.Text;
showToast(payload.text); if (noticeText) {
showToast(noticeText);
if (state.activeChannelId) { if (state.activeChannelId) {
appendSystemNotice(payload.text); appendSystemNotice(noticeText);
} }
} }
break; break;
case 'COMMAND_RESULT': case 'COMMAND_RESULT':
if (payload.output) { const cmdOut = payload.output || payload.Output;
appendSystemNotice(payload.output); if (cmdOut) {
appendSystemNotice(cmdOut);
} }
break; break;
case 'ERROR': case 'ERROR':
if (payload.message) { const errMsg = payload.message || payload.Message;
showToast(`Error: ${payload.message}`); if (errMsg) {
showToast(`Error: ${errMsg}`);
appendSystemNotice(`[Error] ${errMsg}`);
} }
break; break;
} }
@ -307,36 +326,61 @@
} }
function updateActiveChannelHeader() { 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) { if (active) {
el.activeChannelName.textContent = active.name; const chId = active.id || active.Id;
el.activeChannelTopic.textContent = active.topic ? ` - ${active.topic}` : ''; const chName = active.name || active.Name || 'general';
el.messageInput.placeholder = `Message #${active.name}... (or /help)`; 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() { function renderChannels() {
el.channelList.innerHTML = ''; el.channelList.innerHTML = '';
if (el.channelSelectDropdown) {
el.channelSelectDropdown.innerHTML = '';
}
state.channels.forEach(ch => { 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'); const item = document.createElement('div');
item.className = 'channel-item' + (ch.id === state.activeChannelId ? ' active' : ''); item.className = 'channel-item' + (isActive ? ' active' : '');
item.innerHTML = ` item.innerHTML = `
<div class="channel-meta"> <div class="channel-meta">
<span class="channel-title">#${escapeHtml(ch.name)}</span> <span class="channel-title">#${escapeHtml(chName)}</span>
<span class="channel-desc">${escapeHtml(ch.topic || '')}</span> <span class="channel-desc">${escapeHtml(chTopic)}</span>
</div> </div>
${ch.id === state.activeChannelId ? '<span class="channel-badge">ACTIVE</span>' : ''} ${isActive ? '<span class="channel-badge">ACTIVE</span>' : ''}
`; `;
item.addEventListener('click', () => { item.addEventListener('click', () => {
joinChannel(ch.id); joinChannel(chId);
switchTab('chat'); switchTab('chat');
}); });
el.channelList.appendChild(item); 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'); 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) { function joinChannel(channelId) {
@ -349,11 +393,13 @@
function renderMessages() { function renderMessages() {
el.chatMessages.innerHTML = ''; 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] || []; const msgs = state.messages[state.activeChannelId] || [];
if (msgs.length === 0) { if (msgs.length === 0) {
el.chatMessages.innerHTML = ` el.chatMessages.innerHTML = `
<div class="welcome-message"> <div class="welcome-message">
<h3>Welcome to #${escapeHtml(el.activeChannelName.textContent)}</h3> <h3>Welcome to #${escapeHtml(activeName)}</h3>
<p>No messages yet. Say hello!</p> <p>No messages yet. Say hello!</p>
</div> </div>
`; `;
@ -362,37 +408,85 @@
msgs.forEach(appendMessage); 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) { function appendMessage(msg) {
const welcome = el.chatMessages.querySelector('.welcome-message'); const welcome = el.chatMessages.querySelector('.welcome-message');
if (welcome) welcome.remove(); if (welcome) welcome.remove();
const time = new Date(msg.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); const createdAt = msg.createdAt || msg.CreatedAt;
const roleClass = (msg.senderRole || 'member').toLowerCase(); 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'); const div = document.createElement('div');
div.className = 'message-item'; div.className = 'message-item';
let contentHtml = escapeHtml(msg.content); let contentHtml = escapeHtml(rawContent);
if (msg.attachmentId) { if (attId) {
const sizeStr = formatBytes(msg.attachmentSizeBytes || 0); const sizeStr = formatBytes(attBytes);
const safeId = escapeHtml(attId);
const safeName = escapeHtml(attName || 'file');
contentHtml += ` contentHtml += `
<div> <div>
<a class="attachment-card" href="/api/files/${encodeURIComponent(msg.attachmentId)}?token=${encodeURIComponent(state.token)}" target="_blank" download> <button type="button" class="attachment-card" data-file-id="${safeId}" data-file-name="${safeName}">
📎 ${escapeHtml(msg.attachmentName || 'file')} (${sizeStr}) 📎 ${safeName} (${sizeStr})
</a> </button>
</div> </div>
`; `;
} }
div.innerHTML = ` div.innerHTML = `
<div class="message-meta"> <div class="message-meta">
<span class="message-author">@${escapeHtml(msg.senderUsername)}</span> <span class="message-author">@${escapeHtml(sender)}</span>
<span class="role-badge role-${roleClass}">${escapeHtml(msg.senderRole || 'Member')}</span> <span class="role-badge role-${roleClass}">${escapeHtml(rawRole)}</span>
<span class="message-time">${time}</span> <span class="message-time">${time}</span>
</div> </div>
<div class="message-content">${contentHtml}</div> <div class="message-content">${contentHtml}</div>
`; `;
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.appendChild(div);
el.chatMessages.scrollTop = el.chatMessages.scrollHeight; el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
} }
@ -407,19 +501,22 @@
function renderUsers() { function renderUsers() {
el.userList.innerHTML = ''; 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`; el.userCountBadge.textContent = `${onlineCount} Online / ${state.users.length} Total`;
state.users.forEach(u => { state.users.forEach(u => {
const item = document.createElement('div'); const item = document.createElement('div');
item.className = 'user-item'; 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 = ` item.innerHTML = `
<div class="user-meta"> <div class="user-meta">
<span class="user-dot ${u.isOnline ? 'online' : ''}"></span> <span class="user-dot ${isOnline ? 'online' : ''}"></span>
<span style="font-weight:600;">@${escapeHtml(u.username)}</span> <span style="font-weight:600;">@${escapeHtml(username)}</span>
</div> </div>
<span class="role-badge role-${roleClass}">${escapeHtml(u.role)}</span> <span class="role-badge role-${roleClass}">${escapeHtml(role)}</span>
`; `;
el.userList.appendChild(item); el.userList.appendChild(item);
}); });
@ -435,16 +532,28 @@
state.files.forEach(f => { state.files.forEach(f => {
const item = document.createElement('div'); const item = document.createElement('div');
item.className = 'file-item'; item.className = 'file-item';
const sizeStr = formatBytes(f.fileSizeBytes || 0); const fileId = f.id || f.Id;
const dateStr = new Date(f.createdAt).toLocaleDateString(); 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 = ` item.innerHTML = `
<div class="file-meta"> <div class="file-meta">
<div style="font-weight:600;">📎 ${escapeHtml(f.originalFileName)}</div> <div style="font-weight:600;">📎 ${escapeHtml(fileName)}</div>
<div style="font-size:0.8rem; color:var(--text-muted);">${sizeStr} • shared by @${escapeHtml(f.uploaderUsername)} on ${dateStr}</div> <div style="font-size:0.8rem; color:var(--text-muted);">${sizeStr} • shared by @${escapeHtml(uploader)} on ${dateStr}</div>
</div> </div>
<a class="btn btn-primary btn-sm" href="/api/files/${encodeURIComponent(f.id)}?token=${encodeURIComponent(state.token)}" download>Download</a> <button type="button" class="btn btn-primary btn-sm btn-download" data-file-id="${escapeHtml(fileId)}" data-file-name="${escapeHtml(fileName)}">Download</button>
`; `;
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); el.filesList.appendChild(item);
}); });
} }
@ -649,6 +758,56 @@
createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim()); 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 // Logout
el.logoutBtn.addEventListener('click', logout); el.logoutBtn.addEventListener('click', logout);
} }
@ -672,5 +831,9 @@
} }
// Start app // Start app
if (document.readyState === 'loading') {
window.addEventListener('DOMContentLoaded', init); window.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})(); })();

View file

@ -3,10 +3,36 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="theme-color" content="#090d16">
<meta name="color-scheme" content="dark">
<title>GsDChat - Web Client</title> <title>GsDChat - Web Client</title>
<link rel="stylesheet" href="app.css"> <!-- Preload stylesheet to prevent flash of unstyled content and forced layout reflow -->
<link rel="preload" href="/app.css" as="style">
<link rel="stylesheet" href="/app.css">
<!-- Critical baseline styles before external stylesheet parse -->
<style>
html, body {
background-color: #090d16;
color: #f8fafc;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
height: 100dvh;
overflow: hidden;
}
</style>
<script defer src="/app.js"></script>
</head> </head>
<body> <body>
<!-- Drag & Drop Overlay -->
<div id="dropOverlay" class="drop-overlay">
<div class="drop-message">
<span class="drop-icon">📎</span>
<span class="drop-text">Drop file here to upload to channel</span>
</div>
</div>
<!-- App Container --> <!-- App Container -->
<div id="app" class="app-layout"> <div id="app" class="app-layout">
@ -41,7 +67,9 @@
<div class="chat-header"> <div class="chat-header">
<div class="channel-info"> <div class="channel-info">
<span class="channel-hash">#</span> <span class="channel-hash">#</span>
<span class="channel-name" id="activeChannelName">general</span> <select class="channel-dropdown" id="channelSelectDropdown" title="Switch Channel">
<option value="">general</option>
</select>
<span class="channel-topic" id="activeChannelTopic"></span> <span class="channel-topic" id="activeChannelTopic"></span>
</div> </div>
</div> </div>
@ -163,7 +191,5 @@
</div> </div>
</div> </div>
<script src="app.js"></script>
</body> </body>
</html> </html>

View file

@ -39,4 +39,45 @@ public class NetworkProtocolTests
Assert.Contains(sync.Screens, s => s.ScreenId == "F3_Users"); Assert.Contains(sync.Screens, s => s.ScreenId == "F3_Users");
Assert.Contains(sync.Screens, s => s.ScreenId == "F4_Files"); 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<NetworkEnvelope>(envelopeJson, new System.Text.Json.JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
Assert.NotNull(envelope);
Assert.Equal("EXECUTE_COMMAND", envelope.Type);
var packet = envelope.Unpack<ExecuteCommandPacket>();
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<NetworkEnvelope>(envelopeJson, new System.Text.Json.JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
Assert.NotNull(envelope);
Assert.Equal("CREATE_CHANNEL", envelope.Type);
var packet = envelope.Unpack<CreateChannelPacket>();
Assert.NotNull(packet);
Assert.Equal("gaming", packet.Name);
Assert.Equal("General Gaming Room", packet.Topic);
}
} }

View file

@ -31,6 +31,7 @@ public class ServerHistoryTests : IDisposable
[InlineData("http://localhost:5000/", "http://localhost:5000")] [InlineData("http://localhost:5000/", "http://localhost:5000")]
[InlineData("https://chat.example.com", "https://chat.example.com")] [InlineData("https://chat.example.com", "https://chat.example.com")]
[InlineData("chat.example.com:443", "https://chat.example.com:443")] [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")] [InlineData("192.168.1.100:8080", "http://192.168.1.100:8080")]
public void NormalizeUrl_ShouldFormatProperly(string input, string expected) public void NormalizeUrl_ShouldFormatProperly(string input, string expected)
{ {