Remove hardcodes and implement WebClient

This commit is contained in:
tyuXX 2026-10-10 17:53:31 +00:00
parent f25ba8adcd
commit c316ef0092
11 changed files with 2062 additions and 75 deletions

View file

@ -132,17 +132,33 @@ This deploys GsDChat in an isolated container with zero open host ports, securel
### 4. Run the Client TUI
Launch the client interactively:
```bash
dotnet run --project src/GsDChat.Client
```
When launched, GsDChat opens a user-friendly **Server Selection Menu**:
- Displays a quick-access list of your recently visited servers and remembered usernames (like Discord server list).
- Option `[N]` to connect to a new server URL or IP.
- Option `[D]` to delete an entry from history.
- Prompts for credentials (or uses saved username) and masked password.
Or connect directly with credentials:
Or connect directly via command-line arguments:
```bash
dotnet run --project src/GsDChat.Client -- --server http://localhost:5000 --username Alice --password MyPassword123!
dotnet run --project src/GsDChat.Client -- --server https://chat.example.com --username Alice --password MyPassword123!
```
---
## Zero-Install WebClient (Mobile & Desktop)
GsDChat includes a responsive, zero-install WebClient built with pure HTML5, CSS3, and JavaScript (served directly from the server's `wwwroot/`):
- **Access**: Open `http://<server-ip>:5000/` or your Cloudflare Tunnel URL in any browser.
- **Mobile Optimized**: Designed specifically for phones and touchscreens with responsive navigation tabs, bottom chat bar, and native file pickers.
- **Offline / Private LAN Ready**: 100% self-contained with zero external CDN dependencies.
- **Features**: Real-time WebSocket messaging, channel switching, online user presence, authenticated file uploads, and downloads. Session tokens are remembered in browser storage.
---
## Client TUI Navigation
| Key | Action |

View file

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using GsDChat.Client.Network;
@ -11,7 +12,7 @@ public class Program
{
public static async Task Main(string[] args)
{
string serverUrl = "http://localhost:5000";
string? serverUrl = null;
string? username = null;
string? password = null;
string? serverPassword = null;
@ -32,6 +33,81 @@ public class Program
Console.WriteLine(" GsDChat - Private Community TUI");
Console.WriteLine($"========================================{Ansi.Reset}");
var historyManager = new ServerHistoryManager();
string? rememberedUsername = null;
// If no server was specified via CLI, show interactive server selection menu
while (string.IsNullOrEmpty(serverUrl))
{
var servers = historyManager.LoadServers();
Console.WriteLine($"\n{Ansi.Bold}Choose a Server:{Ansi.Reset}");
if (servers.Count > 0)
{
for (int i = 0; i < servers.Count; i++)
{
var s = servers[i];
string userTag = !string.IsNullOrEmpty(s.LastUsername) ? $" (@{s.LastUsername})" : "";
Console.WriteLine($" {Ansi.BrightYellow}[{i + 1}]{Ansi.Reset} {Ansi.BrightWhite}{s.Name}{Ansi.Reset} {Ansi.Gray}({s.Url}){userTag}{Ansi.Reset}");
}
}
else
{
Console.WriteLine($" {Ansi.Gray}(No saved servers yet){Ansi.Reset}");
}
Console.WriteLine($" {Ansi.BrightCyan}[N]{Ansi.Reset} Connect to a New Server");
if (servers.Count > 0)
{
Console.WriteLine($" {Ansi.BrightRed}[D]{Ansi.Reset} Delete a server from history");
}
Console.WriteLine($" {Ansi.Gray}[Q]{Ansi.Reset} Quit");
Console.Write($"\nSelect option: ");
string? input = Console.ReadLine()?.Trim();
if (string.Equals(input, "Q", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Goodbye.");
return;
}
if (string.Equals(input, "D", StringComparison.OrdinalIgnoreCase) && servers.Count > 0)
{
Console.Write("Enter number to delete: ");
if (int.TryParse(Console.ReadLine(), out int delIdx) && delIdx >= 1 && delIdx <= servers.Count)
{
historyManager.RemoveServer(servers[delIdx - 1].Id);
Console.WriteLine($"{Ansi.Green}Removed server from history.{Ansi.Reset}");
}
continue;
}
if (string.Equals(input, "N", StringComparison.OrdinalIgnoreCase) || servers.Count == 0 && string.IsNullOrEmpty(input))
{
Console.Write("\nEnter Server URL or IP (e.g. chat.example.com, http://localhost:5000): ");
string? customUrl = Console.ReadLine()?.Trim();
if (!string.IsNullOrEmpty(customUrl))
{
serverUrl = ServerHistoryManager.NormalizeUrl(customUrl);
}
continue;
}
if (int.TryParse(input, out int sel) && sel >= 1 && sel <= servers.Count)
{
var chosen = servers[sel - 1];
serverUrl = chosen.Url;
rememberedUsername = chosen.LastUsername;
break;
}
Console.WriteLine($"{Ansi.BrightRed}Invalid choice. Please select again.{Ansi.Reset}");
}
// Connection attempt loop
while (true)
{
var state = new ClientState
{
ServerUrl = serverUrl
@ -39,17 +115,29 @@ public class Program
using var connection = new ChatClientConnection(state, allowInsecure);
Console.Write($"Connecting to server at {serverUrl}... ");
Console.Write($"\nConnecting to server at {Ansi.BrightCyan}{serverUrl}{Ansi.Reset}... ");
var info = await connection.GetServerInfoAsync();
if (info == null)
{
Console.WriteLine($"{Ansi.BrightRed}Failed to reach server!{Ansi.Reset}");
Console.WriteLine("Ensure the server is running and the URL is correct.");
Console.Write("Would you like to [R]etry, choose [A]nother server, or [Q]uit? ");
var failChoice = Console.ReadLine()?.Trim().ToUpperInvariant();
if (failChoice == "A")
{
serverUrl = null;
await Main(args); // Restart server selection
return;
}
if (failChoice == "Q")
{
return;
}
continue; // Retry
}
Console.WriteLine($"{Ansi.BrightGreen}Connected!{Ansi.Reset}");
Console.WriteLine($"Server: {info.ServerName} (v{info.Version})");
Console.WriteLine($"Server: {Ansi.Bold}{info.ServerName}{Ansi.Reset} (v{info.Version})");
if (!string.IsNullOrEmpty(info.Motd))
{
Console.WriteLine($"MOTD: {info.Motd}");
@ -70,8 +158,13 @@ public class Program
doRegister = true;
}
Console.Write("Username: ");
username = Console.ReadLine()?.Trim();
string userPrompt = !string.IsNullOrEmpty(rememberedUsername)
? $"Username [{rememberedUsername}]: "
: "Username: ";
Console.Write(userPrompt);
string? enteredUser = Console.ReadLine()?.Trim();
username = string.IsNullOrEmpty(enteredUser) ? rememberedUsername : enteredUser;
Console.Write("Password: ");
password = ReadMaskedPassword();
@ -80,7 +173,9 @@ public class Program
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
Console.WriteLine($"{Ansi.BrightRed}Username and password are required.{Ansi.Reset}");
return;
username = null;
password = null;
continue;
}
Console.WriteLine(doRegister ? "Registering account..." : "Logging in...");
@ -92,11 +187,16 @@ public class Program
if (!authResult.Success || string.IsNullOrEmpty(authResult.Token))
{
Console.WriteLine($"{Ansi.BrightRed}Authentication failed: {authResult.ErrorMessage}{Ansi.Reset}");
return;
username = null;
password = null;
continue;
}
Console.WriteLine($"{Ansi.BrightGreen}Success! Welcome @{authResult.Username} [{authResult.Role}]{Ansi.Reset}");
// Save server to history
historyManager.SaveServer(serverUrl, info.ServerName, authResult.Username);
state.Token = authResult.Token;
state.CurrentUserId = authResult.UserId ?? "";
state.CurrentUsername = authResult.Username ?? username;
@ -114,6 +214,8 @@ public class Program
var ui = new ConsoleUi(state, connection);
await ui.RunAsync(cts.Token);
break;
}
}
private static string ReadMaskedPassword()

View file

@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace GsDChat.Client.State;
public class ServerHistoryManager
{
private const int MaxServers = 10;
private readonly string _filePath;
public ServerHistoryManager(string? customPath = null)
{
if (!string.IsNullOrEmpty(customPath))
{
_filePath = customPath;
}
else
{
try
{
string homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
if (string.IsNullOrEmpty(homeDir)) homeDir = Directory.GetCurrentDirectory();
string gsdDir = Path.Combine(homeDir, ".gsdchat");
Directory.CreateDirectory(gsdDir);
_filePath = Path.Combine(gsdDir, "servers.json");
}
catch
{
_filePath = Path.Combine(Directory.GetCurrentDirectory(), "servers.json");
}
}
}
public List<ServerProfile> LoadServers()
{
if (!File.Exists(_filePath))
{
return new List<ServerProfile>();
}
try
{
string json = File.ReadAllText(_filePath);
var list = JsonSerializer.Deserialize<List<ServerProfile>>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return list?.OrderByDescending(s => s.LastConnected).Take(MaxServers).ToList() ?? new List<ServerProfile>();
}
catch
{
return new List<ServerProfile>();
}
}
public void SaveServer(string url, string name, string? username)
{
try
{
var servers = LoadServers();
string normalizedUrl = NormalizeUrl(url);
var existing = servers.FirstOrDefault(s => NormalizeUrl(s.Url).Equals(normalizedUrl, StringComparison.OrdinalIgnoreCase));
if (existing != null)
{
existing.Name = string.IsNullOrWhiteSpace(name) ? existing.Name : name;
existing.Url = normalizedUrl;
if (!string.IsNullOrWhiteSpace(username)) existing.LastUsername = username;
existing.LastConnected = DateTime.UtcNow;
}
else
{
servers.Insert(0, new ServerProfile
{
Name = string.IsNullOrWhiteSpace(name) ? normalizedUrl : name,
Url = normalizedUrl,
LastUsername = username,
LastConnected = DateTime.UtcNow
});
}
var trimmed = servers.OrderByDescending(s => s.LastConnected).Take(MaxServers).ToList();
string json = JsonSerializer.Serialize(trimmed, new JsonSerializerOptions { WriteIndented = true });
string? dir = Path.GetDirectoryName(_filePath);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(_filePath, json);
}
catch (Exception ex)
{
Console.WriteLine($"[Warning] Could not save server history: {ex.Message}");
}
}
public void RemoveServer(string idOrUrl)
{
try
{
var servers = LoadServers();
servers.RemoveAll(s => s.Id == idOrUrl || NormalizeUrl(s.Url).Equals(NormalizeUrl(idOrUrl), StringComparison.OrdinalIgnoreCase));
string json = JsonSerializer.Serialize(servers, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(_filePath, json);
}
catch { }
}
public static string NormalizeUrl(string input)
{
if (string.IsNullOrWhiteSpace(input)) return string.Empty;
input = input.Trim().TrimEnd('/');
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}";
}
return input;
}
}

View file

@ -0,0 +1,12 @@
using System;
namespace GsDChat.Client.State;
public class ServerProfile
{
public string Id { get; set; } = Guid.NewGuid().ToString("N");
public string Name { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
public string? LastUsername { get; set; }
public DateTime LastConnected { get; set; } = DateTime.UtcNow;
}

View file

@ -19,9 +19,12 @@
<None Update="serversettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="mods\**\*">
<None Update="mods/**/*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<Content Update="wwwroot/**/*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View file

@ -134,6 +134,10 @@ app.Lifetime.ApplicationStopping.Register(() =>
modLoader.ShutdownModsAsync().GetAwaiter().GetResult();
});
// Static Files (WebClient for Browser & Mobile access)
app.UseDefaultFiles();
app.UseStaticFiles();
// WebSockets Middleware
app.UseWebSockets(new WebSocketOptions
{

View file

@ -0,0 +1,674 @@
:root {
--bg-main: #090d16;
--bg-surface: #131b2e;
--bg-surface-hover: #1e293b;
--border-color: #27354f;
--text-main: #f8fafc;
--text-muted: #94a3b8;
--accent: #06b6d4;
--accent-hover: #0891b2;
--accent-rgb: 6, 182, 212;
--success: #10b981;
--danger: #ef4444;
--warning: #f59e0b;
--badge-owner: #fbbf24;
--badge-admin: #c084fc;
--badge-member: #38bdf8;
--font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
-webkit-tap-highlight-color: transparent;
}
html, body {
width: 100%;
height: 100%;
height: 100dvh;
background-color: var(--bg-main);
color: var(--text-main);
font-family: var(--font-family);
overflow: hidden;
}
/* Main Layout */
.app-layout {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
max-width: 1200px;
margin: 0 auto;
}
/* Header */
.app-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 16px;
background-color: var(--bg-surface);
border-bottom: 1px solid var(--border-color);
gap: 12px;
flex-shrink: 0;
}
.header-left {
display: flex;
align-items: center;
gap: 10px;
}
.status-indicator {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: var(--danger);
box-shadow: 0 0 6px rgba(239, 68, 68, 0.6);
transition: background-color 0.3s, box-shadow 0.3s;
}
.status-indicator.online {
background-color: var(--success);
box-shadow: 0 0 8px rgba(16, 185, 129, 0.8);
}
.server-title {
font-size: 1.1rem;
font-weight: 700;
color: var(--text-main);
white-space: nowrap;
}
.nav-tabs {
display: flex;
gap: 6px;
overflow-x: auto;
scrollbar-width: none;
}
.nav-tabs::-webkit-scrollbar {
display: none;
}
.nav-tab {
background: transparent;
border: 1px solid transparent;
color: var(--text-muted);
padding: 6px 12px;
border-radius: 6px;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
white-space: nowrap;
}
.nav-tab:hover {
color: var(--text-main);
background-color: var(--bg-surface-hover);
}
.nav-tab.active {
color: #fff;
background-color: rgba(var(--accent-rgb), 0.2);
border-color: var(--accent);
}
.header-right {
display: flex;
align-items: center;
gap: 10px;
}
.user-badge {
display: flex;
flex-direction: column;
align-items: flex-end;
line-height: 1.2;
}
.user-name {
font-weight: 600;
font-size: 0.9rem;
color: var(--accent);
}
.user-role {
font-size: 0.75rem;
color: var(--text-muted);
}
/* Main Content Area */
.app-main {
flex: 1;
overflow: hidden;
position: relative;
}
.tab-view {
display: none;
width: 100%;
height: 100%;
flex-direction: column;
}
.tab-view.active {
display: flex;
}
/* Chat View */
.chat-header {
padding: 10px 16px;
background-color: rgba(19, 27, 46, 0.7);
border-bottom: 1px solid var(--border-color);
}
.channel-info {
display: flex;
align-items: baseline;
gap: 6px;
}
.channel-hash {
color: var(--accent);
font-size: 1.2rem;
font-weight: 700;
}
.channel-name {
font-size: 1.05rem;
font-weight: 600;
}
.channel-topic {
font-size: 0.85rem;
color: var(--text-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 16px;
display: flex;
flex-direction: column;
gap: 10px;
}
.welcome-message {
text-align: center;
padding: 24px 16px;
color: var(--text-muted);
border: 1px dashed var(--border-color);
border-radius: 8px;
margin-bottom: 12px;
}
.welcome-message h3 {
color: var(--accent);
margin-bottom: 6px;
}
.message-item {
display: flex;
flex-direction: column;
background-color: rgba(19, 27, 46, 0.5);
padding: 8px 12px;
border-radius: 8px;
border: 1px solid rgba(39, 53, 79, 0.4);
animation: fadeIn 0.15s ease-in-out;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
.message-meta {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 4px;
}
.message-author {
font-weight: 600;
font-size: 0.9rem;
}
.role-badge {
font-size: 0.7rem;
padding: 2px 6px;
border-radius: 4px;
font-weight: 600;
text-transform: uppercase;
}
.role-owner {
background-color: rgba(251, 191, 36, 0.2);
color: var(--badge-owner);
}
.role-admin {
background-color: rgba(192, 132, 252, 0.2);
color: var(--badge-admin);
}
.role-member {
background-color: rgba(56, 189, 248, 0.2);
color: var(--badge-member);
}
.message-time {
font-size: 0.75rem;
color: var(--text-muted);
margin-left: auto;
}
.message-content {
font-size: 0.95rem;
line-height: 1.4;
word-break: break-word;
white-space: pre-wrap;
}
.attachment-card {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 6px;
padding: 6px 12px;
background-color: var(--bg-surface-hover);
border: 1px solid var(--border-color);
border-radius: 6px;
font-size: 0.85rem;
text-decoration: none;
color: var(--text-main);
cursor: pointer;
width: fit-content;
}
.attachment-card:hover {
border-color: var(--accent);
}
.system-notice {
padding: 6px 12px;
border-radius: 6px;
font-size: 0.85rem;
text-align: center;
background-color: rgba(39, 53, 79, 0.4);
color: var(--text-muted);
}
.chat-input-bar {
display: flex;
gap: 8px;
padding: 12px 16px;
background-color: var(--bg-surface);
border-top: 1px solid var(--border-color);
padding-bottom: calc(12px + env(safe-area-inset-bottom));
}
.chat-input-bar input[type="text"] {
flex: 1;
background-color: var(--bg-main);
border: 1px solid var(--border-color);
color: var(--text-main);
border-radius: 6px;
padding: 10px 14px;
font-size: 0.95rem;
outline: none;
transition: border-color 0.2s;
}
.chat-input-bar input[type="text"]:focus {
border-color: var(--accent);
}
.btn-icon {
display: flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
background-color: var(--bg-surface-hover);
border: 1px solid var(--border-color);
border-radius: 6px;
cursor: pointer;
font-size: 1.1rem;
}
/* General Views (Channels, Users, Files) */
.view-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px;
border-bottom: 1px solid var(--border-color);
}
.view-header h2 {
font-size: 1.2rem;
font-weight: 600;
}
.channel-list, .user-list, .files-list {
flex: 1;
overflow-y: auto;
padding: 16px;
display: flex;
flex-direction: column;
gap: 8px;
}
.channel-item, .user-item, .file-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
background-color: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 8px;
cursor: pointer;
transition: all 0.2s;
}
.channel-item:hover, .file-item:hover {
background-color: var(--bg-surface-hover);
border-color: var(--accent);
}
.channel-item.active {
border-color: var(--accent);
background-color: rgba(var(--accent-rgb), 0.1);
}
.channel-meta {
display: flex;
flex-direction: column;
gap: 2px;
}
.channel-title {
font-weight: 600;
font-size: 1rem;
}
.channel-desc {
font-size: 0.85rem;
color: var(--text-muted);
}
.channel-badge {
font-size: 0.75rem;
padding: 4px 8px;
border-radius: 4px;
background-color: rgba(16, 185, 129, 0.2);
color: var(--success);
font-weight: 600;
}
.user-item {
cursor: default;
}
.user-meta {
display: flex;
align-items: center;
gap: 10px;
}
.user-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: var(--text-muted);
}
.user-dot.online {
background-color: var(--success);
box-shadow: 0 0 6px rgba(16, 185, 129, 0.6);
}
.user-count-badge {
background-color: rgba(var(--accent-rgb), 0.15);
color: var(--accent);
padding: 4px 10px;
border-radius: 12px;
font-size: 0.85rem;
font-weight: 600;
}
.channel-create-card {
margin: 16px;
padding: 16px;
background-color: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 8px;
}
.channel-create-card h3 {
margin-bottom: 12px;
color: var(--accent);
}
/* Buttons */
.btn {
padding: 8px 16px;
border-radius: 6px;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
border: 1px solid transparent;
transition: all 0.2s;
text-decoration: none;
display: inline-flex;
align-items: center;
justify-content: center;
}
.btn-primary {
background-color: var(--accent);
color: #000;
}
.btn-primary:hover {
background-color: var(--accent-hover);
}
.btn-secondary {
background-color: var(--bg-surface-hover);
color: var(--text-main);
border-color: var(--border-color);
}
.btn-outline-danger {
background: transparent;
color: var(--danger);
border-color: var(--danger);
}
.btn-outline-danger:hover {
background-color: rgba(239, 68, 68, 0.1);
}
.btn-sm {
padding: 4px 10px;
font-size: 0.8rem;
}
.btn-block {
width: 100%;
}
/* Forms */
.form-group {
margin-bottom: 12px;
display: flex;
flex-direction: column;
gap: 6px;
}
.form-group label {
font-size: 0.85rem;
color: var(--text-muted);
}
.form-group input {
background-color: var(--bg-main);
border: 1px solid var(--border-color);
color: var(--text-main);
border-radius: 6px;
padding: 10px 12px;
font-size: 0.95rem;
outline: none;
}
.form-group input:focus {
border-color: var(--accent);
}
.form-actions {
display: flex;
gap: 10px;
margin-top: 16px;
}
/* Modal */
.modal-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
padding: 16px;
z-index: 1000;
}
.modal-card {
width: 100%;
max-width: 400px;
background-color: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 24px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
}
.modal-header {
text-align: center;
margin-bottom: 20px;
}
.modal-header h2 {
color: var(--accent);
font-size: 1.4rem;
margin-bottom: 4px;
}
.modal-motd {
font-size: 0.85rem;
color: var(--text-muted);
}
.auth-tabs {
display: flex;
border-bottom: 1px solid var(--border-color);
margin-bottom: 18px;
}
.auth-tab {
flex: 1;
padding: 8px;
background: transparent;
border: none;
border-bottom: 2px solid transparent;
color: var(--text-muted);
font-size: 0.95rem;
font-weight: 600;
cursor: pointer;
}
.auth-tab.active {
color: var(--accent);
border-bottom-color: var(--accent);
}
.auth-error {
color: var(--danger);
font-size: 0.85rem;
margin-bottom: 12px;
text-align: center;
min-height: 18px;
}
/* Toasts */
.toast-container {
position: fixed;
bottom: 70px;
left: 50%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
gap: 8px;
z-index: 2000;
pointer-events: none;
}
.toast {
background-color: var(--bg-surface-hover);
border: 1px solid var(--border-color);
color: var(--text-main);
padding: 8px 16px;
border-radius: 6px;
font-size: 0.9rem;
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
animation: toastIn 0.2s ease-out;
}
@keyframes toastIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
/* Mobile Media Queries */
@media (max-width: 600px) {
.app-header {
flex-wrap: wrap;
padding: 8px 12px;
}
.nav-tabs {
order: 3;
width: 100%;
margin-top: 6px;
justify-content: space-around;
}
.nav-tab {
flex: 1;
text-align: center;
padding: 6px 4px;
font-size: 0.82rem;
}
.server-title {
font-size: 1rem;
}
.user-badge {
display: none;
}
}

View file

@ -0,0 +1,676 @@
(() => {
// Application State
const state = {
token: localStorage.getItem('gsdchat_token') || null,
user: JSON.parse(localStorage.getItem('gsdchat_user') || 'null'),
serverInfo: null,
activeChannelId: null,
channels: [],
messages: {}, // channelId -> array
users: [],
files: [],
socket: null,
isRegister: false,
reconnectTimer: null
};
// DOM Elements
const el = {
serverTitle: document.getElementById('serverTitle'),
connIndicator: document.getElementById('connIndicator'),
navTabs: document.querySelectorAll('.nav-tab'),
tabViews: document.querySelectorAll('.tab-view'),
currentUsername: document.getElementById('currentUsername'),
currentUserRole: document.getElementById('currentUserRole'),
logoutBtn: document.getElementById('logoutBtn'),
userBadge: document.getElementById('userBadge'),
// Chat View
activeChannelName: document.getElementById('activeChannelName'),
activeChannelTopic: document.getElementById('activeChannelTopic'),
chatMessages: document.getElementById('chatMessages'),
messageInput: document.getElementById('messageInput'),
sendBtn: document.getElementById('sendBtn'),
fileInput: document.getElementById('fileInput'),
welcomeMotd: document.getElementById('welcomeMotd'),
// Channels View
channelList: document.getElementById('channelList'),
openCreateChannelBtn: document.getElementById('openCreateChannelBtn'),
createChannelCard: document.getElementById('createChannelCard'),
newChannelName: document.getElementById('newChannelName'),
newChannelTopic: document.getElementById('newChannelTopic'),
submitCreateChannelBtn: document.getElementById('submitCreateChannelBtn'),
cancelCreateChannelBtn: document.getElementById('cancelCreateChannelBtn'),
// Users View
userList: document.getElementById('userList'),
userCountBadge: document.getElementById('userCountBadge'),
// Files View
filesList: document.getElementById('filesList'),
filesViewUploadInput: document.getElementById('filesViewUploadInput'),
// Auth Modal
authModal: document.getElementById('authModal'),
modalServerName: document.getElementById('modalServerName'),
modalMotd: document.getElementById('modalMotd'),
tabLogin: document.getElementById('tabLogin'),
tabRegister: document.getElementById('tabRegister'),
authForm: document.getElementById('authForm'),
groupServerPassword: document.getElementById('groupServerPassword'),
groupInviteToken: document.getElementById('groupInviteToken'),
authServerPassword: document.getElementById('authServerPassword'),
authUsername: document.getElementById('authUsername'),
authPassword: document.getElementById('authPassword'),
authInviteToken: document.getElementById('authInviteToken'),
authSubmitBtn: document.getElementById('authSubmitBtn'),
authError: document.getElementById('authError'),
toastContainer: document.getElementById('toastContainer')
};
// ==========================================
// Initialization
// ==========================================
async function init() {
setupEventListeners();
await fetchServerInfo();
if (state.token && state.user) {
updateUserUI();
hideAuthModal();
connectWebSocket();
} else {
showAuthModal();
}
}
// ==========================================
// REST API Calls
// ==========================================
async function fetchServerInfo() {
try {
const res = await fetch('/api/info');
if (res.ok) {
state.serverInfo = await res.json();
el.serverTitle.textContent = state.serverInfo.serverName || 'GsDChat';
el.modalServerName.textContent = state.serverInfo.serverName || 'GsDChat';
if (state.serverInfo.motd) {
el.modalMotd.textContent = state.serverInfo.motd;
el.welcomeMotd.textContent = state.serverInfo.motd;
}
if (state.serverInfo.requiresServerPassword) {
el.groupServerPassword.style.display = 'flex';
}
if (state.serverInfo.registrationMode === 'InviteOnly') {
el.groupInviteToken.style.display = 'flex';
}
}
} catch (err) {
showToast('Could not reach server info endpoint');
}
}
async function handleAuthSubmit() {
el.authError.textContent = '';
const username = el.authUsername.value.trim();
const password = el.authPassword.value;
const serverPassword = el.authServerPassword.value;
const inviteToken = el.authInviteToken.value.trim();
if (!username || !password) {
el.authError.textContent = 'Please enter username and password.';
return;
}
const endpoint = state.isRegister ? '/api/auth/register' : '/api/auth/login';
const body = {
username,
password,
serverPassword: serverPassword || null,
inviteToken: inviteToken || null
};
try {
el.authSubmitBtn.disabled = true;
el.authSubmitBtn.textContent = 'Authenticating...';
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const data = await res.json();
if (!res.ok || !data.success) {
el.authError.textContent = data.errorMessage || 'Authentication failed.';
return;
}
// Success
state.token = data.token;
state.user = {
id: data.userId,
username: data.username,
role: data.role
};
localStorage.setItem('gsdchat_token', state.token);
localStorage.setItem('gsdchat_user', JSON.stringify(state.user));
updateUserUI();
hideAuthModal();
connectWebSocket();
} catch (err) {
el.authError.textContent = 'Connection error. Please try again.';
} finally {
el.authSubmitBtn.disabled = false;
el.authSubmitBtn.textContent = state.isRegister ? 'Register' : 'Login';
}
}
// ==========================================
// WebSocket Communication
// ==========================================
function connectWebSocket() {
if (state.socket) {
state.socket.close();
}
const wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${wsProto}//${window.location.host}/ws?token=${encodeURIComponent(state.token)}`;
try {
state.socket = new WebSocket(wsUrl);
state.socket.onopen = () => {
el.connIndicator.classList.add('online');
el.connIndicator.title = 'Connected';
showToast('Connected to chat server');
};
state.socket.onclose = () => {
el.connIndicator.classList.remove('online');
el.connIndicator.title = 'Disconnected';
// Auto-reconnect after 3 seconds if logged in
if (state.token) {
clearTimeout(state.reconnectTimer);
state.reconnectTimer = setTimeout(connectWebSocket, 3000);
}
};
state.socket.onerror = () => {
el.connIndicator.classList.remove('online');
};
state.socket.onmessage = (event) => {
try {
const envelope = JSON.parse(event.data);
handleNetworkEnvelope(envelope);
} catch (err) {
console.error('Failed to parse WebSocket message', err);
}
};
} catch (err) {
console.error('WebSocket connection error', err);
}
}
function sendEnvelope(type, payload) {
if (!state.socket || state.socket.readyState !== WebSocket.OPEN) {
showToast('Not connected to server');
return;
}
const envelope = {
type: type,
payload: JSON.stringify(payload)
};
state.socket.send(JSON.stringify(envelope));
}
function handleNetworkEnvelope(envelope) {
const payload = JSON.parse(envelope.payload || '{}');
switch (envelope.type) {
case 'CHANNEL_LIST_SYNC':
state.channels = payload.channels || [];
if (payload.activeChannelId) {
state.activeChannelId = payload.activeChannelId;
}
renderChannels();
updateActiveChannelHeader();
break;
case 'HISTORY_SYNC':
if (payload.channelId) {
state.messages[payload.channelId] = payload.messages || [];
if (state.activeChannelId === payload.channelId) {
renderMessages();
}
}
break;
case 'MESSAGE_BROADCAST':
if (payload.message) {
const chId = payload.message.channelId;
if (!state.messages[chId]) state.messages[chId] = [];
state.messages[chId].push(payload.message);
if (state.activeChannelId === chId) {
appendMessage(payload.message);
}
}
break;
case 'USER_LIST_SYNC':
state.users = payload.users || [];
renderUsers();
break;
case 'FILE_LIST_SYNC':
state.files = payload.files || [];
renderFiles();
break;
case 'SYSTEM_NOTICE':
if (payload.text) {
showToast(payload.text);
if (state.activeChannelId) {
appendSystemNotice(payload.text);
}
}
break;
case 'COMMAND_RESULT':
if (payload.output) {
appendSystemNotice(payload.output);
}
break;
case 'ERROR':
if (payload.message) {
showToast(`Error: ${payload.message}`);
}
break;
}
}
// ==========================================
// UI Renderers
// ==========================================
function switchTab(tabName) {
el.navTabs.forEach(tab => {
tab.classList.toggle('active', tab.dataset.tab === tabName);
});
el.tabViews.forEach(view => {
view.classList.toggle('active', view.id === `view-${tabName}`);
});
}
function updateActiveChannelHeader() {
const active = state.channels.find(c => 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)`;
}
}
function renderChannels() {
el.channelList.innerHTML = '';
state.channels.forEach(ch => {
const item = document.createElement('div');
item.className = 'channel-item' + (ch.id === state.activeChannelId ? ' active' : '');
item.innerHTML = `
<div class="channel-meta">
<span class="channel-title">#${escapeHtml(ch.name)}</span>
<span class="channel-desc">${escapeHtml(ch.topic || '')}</span>
</div>
${ch.id === state.activeChannelId ? '<span class="channel-badge">ACTIVE</span>' : ''}
`;
item.addEventListener('click', () => {
joinChannel(ch.id);
switchTab('chat');
});
el.channelList.appendChild(item);
});
// Show create button for Admin or Owner
const isPrivileged = state.user && (state.user.role === 'Owner' || state.user.role === 'Admin');
el.openCreateChannelBtn.style.display = isPrivileged ? 'inline-flex' : 'none';
}
function joinChannel(channelId) {
state.activeChannelId = channelId;
sendEnvelope('JOIN_CHANNEL', { channelId });
renderChannels();
updateActiveChannelHeader();
renderMessages();
}
function renderMessages() {
el.chatMessages.innerHTML = '';
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>
<p>No messages yet. Say hello!</p>
</div>
`;
return;
}
msgs.forEach(appendMessage);
}
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 div = document.createElement('div');
div.className = 'message-item';
let contentHtml = escapeHtml(msg.content);
if (msg.attachmentId) {
const sizeStr = formatBytes(msg.attachmentSizeBytes || 0);
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>
</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-time">${time}</span>
</div>
<div class="message-content">${contentHtml}</div>
`;
el.chatMessages.appendChild(div);
el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
}
function appendSystemNotice(text) {
const div = document.createElement('div');
div.className = 'system-notice';
div.textContent = text;
el.chatMessages.appendChild(div);
el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
}
function renderUsers() {
el.userList.innerHTML = '';
const onlineCount = state.users.filter(u => 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();
item.innerHTML = `
<div class="user-meta">
<span class="user-dot ${u.isOnline ? 'online' : ''}"></span>
<span style="font-weight:600;">@${escapeHtml(u.username)}</span>
</div>
<span class="role-badge role-${roleClass}">${escapeHtml(u.role)}</span>
`;
el.userList.appendChild(item);
});
}
function renderFiles() {
el.filesList.innerHTML = '';
if (state.files.length === 0) {
el.filesList.innerHTML = '<div style="color:var(--text-muted); text-align:center; padding:20px;">No shared files yet.</div>';
return;
}
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();
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>
<a class="btn btn-primary btn-sm" href="/api/files/${encodeURIComponent(f.id)}?token=${encodeURIComponent(state.token)}" download>Download</a>
`;
el.filesList.appendChild(item);
});
}
function updateUserUI() {
if (state.user) {
el.currentUsername.textContent = `@${state.user.username}`;
el.currentUserRole.textContent = `[${state.user.role}]`;
el.userBadge.style.display = 'flex';
el.logoutBtn.style.display = 'inline-flex';
} else {
el.userBadge.style.display = 'none';
el.logoutBtn.style.display = 'none';
}
}
function showAuthModal() {
el.authModal.style.display = 'flex';
}
function hideAuthModal() {
el.authModal.style.display = 'none';
}
function showToast(message) {
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = message;
el.toastContainer.appendChild(toast);
setTimeout(() => toast.remove(), 3500);
}
// ==========================================
// Actions
// ==========================================
function sendMessage() {
const text = el.messageInput.value.trim();
if (!text) return;
el.messageInput.value = '';
if (text.startsWith('/')) {
handleSlashCommand(text);
return;
}
if (!state.activeChannelId) {
showToast('Select a channel first');
return;
}
sendEnvelope('SEND_MESSAGE', {
channelId: state.activeChannelId,
content: text
});
}
function handleSlashCommand(input) {
const parts = input.split(' ');
const cmd = parts[0].substring(1).toLowerCase();
const args = parts.slice(1).join(' ').trim();
if (cmd === 'join') {
const ch = state.channels.find(c => c.name.toLowerCase() === args.replace('#', '').toLowerCase());
if (ch) joinChannel(ch.id);
else showToast(`Channel ${args} not found`);
return;
}
if (cmd === 'create') {
const cParts = args.split(' ');
createChannel(cParts[0], cParts.slice(1).join(' '));
return;
}
sendEnvelope('EXECUTE_COMMAND', {
command: cmd,
args: args,
channelId: state.activeChannelId || ''
});
}
function createChannel(name, topic) {
if (!name) {
showToast('Channel name required');
return;
}
sendEnvelope('CREATE_CHANNEL', { name, topic: topic || '' });
el.createChannelCard.style.display = 'none';
el.newChannelName.value = '';
el.newChannelTopic.value = '';
}
async function uploadFile(file) {
if (!file) return;
if (!state.activeChannelId) {
showToast('Please join a channel to share files');
return;
}
const formData = new FormData();
formData.append('file', file);
formData.append('channelId', state.activeChannelId);
showToast(`Uploading ${file.name}...`);
try {
const res = await fetch('/api/files/upload', {
method: 'POST',
headers: {
'Authorization': `Bearer ${state.token}`
},
body: formData
});
const data = await res.json();
if (res.ok && data.success) {
showToast(`Uploaded ${file.name} successfully!`);
} else {
showToast(`Upload failed: ${data.errorMessage || 'Server error'}`);
}
} catch (err) {
showToast(`Upload failed: ${err.message}`);
}
}
function logout() {
state.token = null;
state.user = null;
localStorage.removeItem('gsdchat_token');
localStorage.removeItem('gsdchat_user');
if (state.socket) state.socket.close();
updateUserUI();
showAuthModal();
}
// ==========================================
// Event Listeners
// ==========================================
function setupEventListeners() {
// Navigation Tabs
el.navTabs.forEach(tab => {
tab.addEventListener('click', () => switchTab(tab.dataset.tab));
});
// Auth Tabs
el.tabLogin.addEventListener('click', () => {
state.isRegister = false;
el.tabLogin.classList.add('active');
el.tabRegister.classList.remove('active');
el.authSubmitBtn.textContent = 'Login';
el.authError.textContent = '';
});
el.tabRegister.addEventListener('click', () => {
state.isRegister = true;
el.tabRegister.classList.add('active');
el.tabLogin.classList.remove('active');
el.authSubmitBtn.textContent = 'Register';
el.authError.textContent = '';
});
el.authForm.addEventListener('submit', (e) => {
e.preventDefault();
handleAuthSubmit();
});
// Chat Input
el.sendBtn.addEventListener('click', sendMessage);
el.messageInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
sendMessage();
}
});
// File Uploads
el.fileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
uploadFile(e.target.files[0]);
e.target.value = '';
}
});
el.filesViewUploadInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
uploadFile(e.target.files[0]);
e.target.value = '';
}
});
// Channels Create Form
el.openCreateChannelBtn.addEventListener('click', () => {
el.createChannelCard.style.display = 'block';
el.newChannelName.focus();
});
el.cancelCreateChannelBtn.addEventListener('click', () => {
el.createChannelCard.style.display = 'none';
});
el.submitCreateChannelBtn.addEventListener('click', () => {
createChannel(el.newChannelName.value.trim(), el.newChannelTopic.value.trim());
});
// Logout
el.logoutBtn.addEventListener('click', logout);
}
// ==========================================
// Helper Functions
// ==========================================
function escapeHtml(str) {
if (!str) return '';
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
function formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Start app
window.addEventListener('DOMContentLoaded', init);
})();

View file

@ -0,0 +1,169 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>GsDChat - Web Client</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<!-- App Container -->
<div id="app" class="app-layout">
<!-- Header / Navigation Bar -->
<header class="app-header">
<div class="header-left">
<span class="status-indicator" id="connIndicator" title="Connection Status"></span>
<h1 class="server-title" id="serverTitle">GsDChat</h1>
</div>
<nav class="nav-tabs" id="navTabs">
<button class="nav-tab active" data-tab="chat">💬 Chat</button>
<button class="nav-tab" data-tab="channels">📁 Channels</button>
<button class="nav-tab" data-tab="users">👥 Users</button>
<button class="nav-tab" data-tab="files">📎 Files</button>
</nav>
<div class="header-right">
<div class="user-badge" id="userBadge">
<span class="user-name" id="currentUsername"></span>
<span class="user-role" id="currentUserRole"></span>
</div>
<button class="btn btn-outline-danger btn-sm" id="logoutBtn" title="Logout">Disconnect</button>
</div>
</header>
<!-- Main Views Container -->
<main class="app-main">
<!-- View 1: Chat View -->
<section id="view-chat" class="tab-view active">
<div class="chat-header">
<div class="channel-info">
<span class="channel-hash">#</span>
<span class="channel-name" id="activeChannelName">general</span>
<span class="channel-topic" id="activeChannelTopic"></span>
</div>
</div>
<div class="chat-messages" id="chatMessages">
<div class="welcome-message">
<h3 id="welcomeMotd">Welcome to GsDChat!</h3>
<p>Select a channel or start chatting below.</p>
</div>
</div>
<div class="chat-input-bar">
<label class="btn-icon upload-btn" title="Upload File">
📎
<input type="file" id="fileInput" style="display:none;">
</label>
<input type="text" id="messageInput" placeholder="Message #general... (or /help)" autocomplete="off">
<button class="btn btn-primary send-btn" id="sendBtn">Send</button>
</div>
</section>
<!-- View 2: Channels View -->
<section id="view-channels" class="tab-view">
<div class="view-header">
<h2>Server Channels</h2>
<button class="btn btn-primary" id="openCreateChannelBtn" style="display:none;">+ Create Channel</button>
</div>
<div class="channel-list" id="channelList">
<!-- Populated by JS -->
</div>
<!-- Channel Creation Form -->
<div class="card channel-create-card" id="createChannelCard" style="display:none;">
<h3>Create New Channel</h3>
<div class="form-group">
<label for="newChannelName">Channel Name</label>
<input type="text" id="newChannelName" placeholder="e.g. gaming, music">
</div>
<div class="form-group">
<label for="newChannelTopic">Topic (Optional)</label>
<input type="text" id="newChannelTopic" placeholder="Channel description...">
</div>
<div class="form-actions">
<button class="btn btn-primary" id="submitCreateChannelBtn">Create</button>
<button class="btn btn-secondary" id="cancelCreateChannelBtn">Cancel</button>
</div>
</div>
</section>
<!-- View 3: Users View -->
<section id="view-users" class="tab-view">
<div class="view-header">
<h2>Community Members</h2>
<span class="user-count-badge" id="userCountBadge">0 Online</span>
</div>
<div class="user-list" id="userList">
<!-- Populated by JS -->
</div>
</section>
<!-- View 4: Files View -->
<section id="view-files" class="tab-view">
<div class="view-header">
<h2>Shared Files</h2>
<label class="btn btn-primary">
+ Upload File
<input type="file" id="filesViewUploadInput" style="display:none;">
</label>
</div>
<div class="files-list" id="filesList">
<!-- Populated by JS -->
</div>
</section>
</main>
<!-- Toast Notification Overlay -->
<div id="toastContainer" class="toast-container"></div>
<!-- Auth Modal (Login / Register) -->
<div id="authModal" class="modal-backdrop">
<div class="modal-card">
<div class="modal-header">
<h2 id="modalServerName">GsDChat Community</h2>
<p class="modal-motd" id="modalMotd">Secure & Private Messaging</p>
</div>
<div class="auth-tabs">
<button class="auth-tab active" id="tabLogin">Login</button>
<button class="auth-tab" id="tabRegister">Register</button>
</div>
<form id="authForm" class="auth-form" onsubmit="return false;">
<div class="form-group" id="groupServerPassword" style="display:none;">
<label for="authServerPassword">Server Password</label>
<input type="password" id="authServerPassword" placeholder="Required for this server">
</div>
<div class="form-group">
<label for="authUsername">Username</label>
<input type="text" id="authUsername" placeholder="Enter username" required autocomplete="username">
</div>
<div class="form-group">
<label for="authPassword">Password</label>
<input type="password" id="authPassword" placeholder="Enter password" required autocomplete="current-password">
</div>
<div class="form-group" id="groupInviteToken" style="display:none;">
<label for="authInviteToken">Invite Token (Optional)</label>
<input type="text" id="authInviteToken" placeholder="Required if invite-only">
</div>
<div class="auth-error" id="authError"></div>
<button type="submit" class="btn btn-primary btn-block" id="authSubmitBtn">Login</button>
</form>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>

View file

@ -0,0 +1,77 @@
using System;
using System.IO;
using GsDChat.Client.State;
using Xunit;
namespace GsDChat.Tests;
public class ServerHistoryTests : IDisposable
{
private readonly string _testFile;
public ServerHistoryTests()
{
_testFile = Path.Combine(Path.GetTempPath(), "gsdchat_servers_" + Guid.NewGuid().ToString("N") + ".json");
}
public void Dispose()
{
try
{
if (File.Exists(_testFile))
{
File.Delete(_testFile);
}
}
catch { }
}
[Theory]
[InlineData("localhost:5000", "http://localhost:5000")]
[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("192.168.1.100:8080", "http://192.168.1.100:8080")]
public void NormalizeUrl_ShouldFormatProperly(string input, string expected)
{
string result = ServerHistoryManager.NormalizeUrl(input);
Assert.Equal(expected, result);
}
[Fact]
public void SaveServer_ShouldPersistAndOrderDescending()
{
var manager = new ServerHistoryManager(_testFile);
manager.SaveServer("http://server1.local:5000", "Server 1", "User1");
manager.SaveServer("http://server2.local:5000", "Server 2", "User2");
var list = manager.LoadServers();
Assert.Equal(2, list.Count);
Assert.Equal("http://server2.local:5000", list[0].Url);
Assert.Equal("http://server1.local:5000", list[1].Url);
// Updating server1 should bump it to the top
manager.SaveServer("http://server1.local:5000", "Server 1 Updated", "User1New");
var updatedList = manager.LoadServers();
Assert.Equal(2, updatedList.Count);
Assert.Equal("http://server1.local:5000", updatedList[0].Url);
Assert.Equal("Server 1 Updated", updatedList[0].Name);
Assert.Equal("User1New", updatedList[0].LastUsername);
}
[Fact]
public void RemoveServer_ShouldDeleteEntry()
{
var manager = new ServerHistoryManager(_testFile);
manager.SaveServer("http://server1.local:5000", "Server 1", "User1");
manager.SaveServer("http://server2.local:5000", "Server 2", "User2");
manager.RemoveServer("http://server1.local:5000");
var list = manager.LoadServers();
Assert.Single(list);
Assert.Equal("http://server2.local:5000", list[0].Url);
}
}

View file

@ -0,0 +1,130 @@
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using GsDChat.Server.Configuration;
using GsDChat.Server.Data;
using GsDChat.Server.Services;
using GsDChat.Server.WebSockets;
using Xunit;
namespace GsDChat.Tests;
public class WebClientStaticTests : IAsyncLifetime
{
private readonly string _testDir;
private WebApplication? _app;
private int _port;
private string _serverUrl = string.Empty;
private HttpClient? _httpClient;
public WebClientStaticTests()
{
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_webclient_" + Guid.NewGuid().ToString("N"));
}
public async Task InitializeAsync()
{
using var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
listener.Start();
_port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
_serverUrl = $"http://127.0.0.1:{_port}";
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
ContentRootPath = Path.Combine(AppContext.BaseDirectory),
WebRootPath = Path.Combine(AppContext.BaseDirectory, "wwwroot")
});
builder.WebHost.UseUrls(_serverUrl);
builder.Logging.ClearProviders();
var serverOptions = new ServerOptions
{
Host = "127.0.0.1",
Port = _port,
UseTls = false,
DataDirectory = _testDir,
ServerName = "WebClient Test Server"
};
builder.Services.AddSingleton(serverOptions);
builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory));
builder.Services.AddSingleton<IAuthService, AuthService>();
builder.Services.AddSingleton<FileStorageService>();
builder.Services.AddSingleton<ChatWebSocketManager>();
_app = builder.Build();
_app.UseDefaultFiles();
_app.UseStaticFiles();
await _app.StartAsync();
_httpClient = new HttpClient { BaseAddress = new Uri(_serverUrl) };
}
public async Task DisposeAsync()
{
_httpClient?.Dispose();
if (_app != null)
{
await _app.StopAsync();
await _app.DisposeAsync();
}
try
{
if (Directory.Exists(_testDir))
{
Directory.Delete(_testDir, true);
}
}
catch { }
}
[Fact]
public async Task GetRoot_ShouldServeIndexHtml()
{
Assert.NotNull(_httpClient);
var response = await _httpClient.GetAsync("/");
Assert.True(response.IsSuccessStatusCode);
string html = await response.Content.ReadAsStringAsync();
Assert.Contains("GsDChat - Web Client", html);
Assert.Contains("id=\"app\"", html);
Assert.Contains("id=\"authModal\"", html);
}
[Fact]
public async Task GetAppCss_ShouldServeStylesheet()
{
Assert.NotNull(_httpClient);
var response = await _httpClient.GetAsync("/app.css");
Assert.True(response.IsSuccessStatusCode);
string css = await response.Content.ReadAsStringAsync();
Assert.Contains("--bg-main", css);
Assert.Contains(".app-layout", css);
}
[Fact]
public async Task GetAppJs_ShouldServeJavaScript()
{
Assert.NotNull(_httpClient);
var response = await _httpClient.GetAsync("/app.js");
Assert.True(response.IsSuccessStatusCode);
string js = await response.Content.ReadAsStringAsync();
Assert.Contains("connectWebSocket", js);
Assert.Contains("handleNetworkEnvelope", js);
}
}