fixes, hopefully
This commit is contained in:
parent
7495e34ade
commit
cbc24e7672
13 changed files with 449 additions and 78 deletions
|
|
@ -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<ServerInfoResponse>(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<AuthResponse>(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<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
||||
?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 ?? "";
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<T>(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<T>()
|
||||
{
|
||||
return JsonSerializer.Deserialize<T>(Payload);
|
||||
return JsonSerializer.Deserialize<T>(Payload, s_jsonOptions);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -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<NetworkEnvelope>(json);
|
||||
if (envelope == null) return;
|
||||
var envelope = JsonSerializer.Deserialize<NetworkEnvelope>(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<SendMessagePacket>();
|
||||
|
|
@ -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 <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" +
|
||||
" /users - List all registered users\n" +
|
||||
" /motd - Display message of the day";
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 = `
|
||||
<div class="channel-meta">
|
||||
<span class="channel-title">#${escapeHtml(ch.name)}</span>
|
||||
<span class="channel-desc">${escapeHtml(ch.topic || '')}</span>
|
||||
<span class="channel-title">#${escapeHtml(chName)}</span>
|
||||
<span class="channel-desc">${escapeHtml(chTopic)}</span>
|
||||
</div>
|
||||
${ch.id === state.activeChannelId ? '<span class="channel-badge">ACTIVE</span>' : ''}
|
||||
${isActive ? '<span class="channel-badge">ACTIVE</span>' : ''}
|
||||
`;
|
||||
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 = `
|
||||
<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>
|
||||
</div>
|
||||
`;
|
||||
|
|
@ -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>
|
||||
<a class="attachment-card" href="/api/files/${encodeURIComponent(msg.attachmentId)}?token=${encodeURIComponent(state.token)}" target="_blank" download>
|
||||
📎 ${escapeHtml(msg.attachmentName || 'file')} (${sizeStr})
|
||||
</a>
|
||||
<button type="button" class="attachment-card" data-file-id="${safeId}" data-file-name="${safeName}">
|
||||
📎 ${safeName} (${sizeStr})
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
div.innerHTML = `
|
||||
<div class="message-meta">
|
||||
<span class="message-author">@${escapeHtml(msg.senderUsername)}</span>
|
||||
<span class="role-badge role-${roleClass}">${escapeHtml(msg.senderRole || 'Member')}</span>
|
||||
<span class="message-author">@${escapeHtml(sender)}</span>
|
||||
<span class="role-badge role-${roleClass}">${escapeHtml(rawRole)}</span>
|
||||
<span class="message-time">${time}</span>
|
||||
</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.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 = `
|
||||
<div class="user-meta">
|
||||
<span class="user-dot ${u.isOnline ? 'online' : ''}"></span>
|
||||
<span style="font-weight:600;">@${escapeHtml(u.username)}</span>
|
||||
<span class="user-dot ${isOnline ? 'online' : ''}"></span>
|
||||
<span style="font-weight:600;">@${escapeHtml(username)}</span>
|
||||
</div>
|
||||
<span class="role-badge role-${roleClass}">${escapeHtml(u.role)}</span>
|
||||
<span class="role-badge role-${roleClass}">${escapeHtml(role)}</span>
|
||||
`;
|
||||
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 = `
|
||||
<div class="file-meta">
|
||||
<div style="font-weight:600;">📎 ${escapeHtml(f.originalFileName)}</div>
|
||||
<div style="font-size:0.8rem; color:var(--text-muted);">${sizeStr} • shared by @${escapeHtml(f.uploaderUsername)} on ${dateStr}</div>
|
||||
<div style="font-weight:600;">📎 ${escapeHtml(fileName)}</div>
|
||||
<div style="font-size:0.8rem; color:var(--text-muted);">${sizeStr} • shared by @${escapeHtml(uploader)} on ${dateStr}</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);
|
||||
});
|
||||
}
|
||||
|
|
@ -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();
|
||||
}
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -3,10 +3,36 @@
|
|||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<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>
|
||||
<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>
|
||||
<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 -->
|
||||
<div id="app" class="app-layout">
|
||||
|
||||
|
|
@ -41,7 +67,9 @@
|
|||
<div class="chat-header">
|
||||
<div class="channel-info">
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -163,7 +191,5 @@
|
|||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue