init
This commit is contained in:
commit
f25ba8adcd
64 changed files with 5959 additions and 0 deletions
53
Dockerfile
Normal file
53
Dockerfile
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
# ========================================================
|
||||||
|
# Build Stage
|
||||||
|
# ========================================================
|
||||||
|
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||||
|
WORKDIR /src
|
||||||
|
|
||||||
|
# Copy solution and project files for layer caching
|
||||||
|
COPY GsDChat.slnx ./
|
||||||
|
COPY src/GsDChat.Core/GsDChat.Core.csproj src/GsDChat.Core/
|
||||||
|
COPY src/GsDChat.Modding/GsDChat.Modding.csproj src/GsDChat.Modding/
|
||||||
|
COPY src/GsDChat.Server/GsDChat.Server.csproj src/GsDChat.Server/
|
||||||
|
COPY src/GsDChat.Mods.SampleBot/GsDChat.Mods.SampleBot.csproj src/GsDChat.Mods.SampleBot/
|
||||||
|
|
||||||
|
# Restore dependencies
|
||||||
|
RUN dotnet restore src/GsDChat.Server/GsDChat.Server.csproj
|
||||||
|
RUN dotnet restore src/GsDChat.Mods.SampleBot/GsDChat.Mods.SampleBot.csproj
|
||||||
|
|
||||||
|
# Copy source tree
|
||||||
|
COPY src/ ./src/
|
||||||
|
|
||||||
|
# Publish GsDChat Server
|
||||||
|
RUN dotnet publish src/GsDChat.Server/GsDChat.Server.csproj -c Release -o /app/publish /p:UseAppHost=false
|
||||||
|
|
||||||
|
# Publish SampleBot reference mod
|
||||||
|
RUN dotnet publish src/GsDChat.Mods.SampleBot/GsDChat.Mods.SampleBot.csproj -c Release -o /app/mod_publish /p:UseAppHost=false
|
||||||
|
|
||||||
|
# Place default mod in published mods directory
|
||||||
|
RUN mkdir -p /app/publish/mods && cp /app/mod_publish/GsDChat.Mods.SampleBot.dll /app/publish/mods/
|
||||||
|
|
||||||
|
# ========================================================
|
||||||
|
# Runtime Stage
|
||||||
|
# ========================================================
|
||||||
|
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy published application
|
||||||
|
COPY --from=build /app/publish .
|
||||||
|
|
||||||
|
# Create persistence directories for database, files, and mods
|
||||||
|
RUN mkdir -p /app/data /app/mods
|
||||||
|
|
||||||
|
# Configure default container environment
|
||||||
|
ENV ASPNETCORE_URLS=http://+:5000
|
||||||
|
ENV GSDCHAT_HOST=0.0.0.0
|
||||||
|
ENV GSDCHAT_PORT=5000
|
||||||
|
ENV GSDCHAT_DATA_DIR=/app/data
|
||||||
|
ENV GSDCHAT_MODS_DIR=/app/mods
|
||||||
|
|
||||||
|
EXPOSE 5000
|
||||||
|
|
||||||
|
VOLUME ["/app/data", "/app/mods"]
|
||||||
|
|
||||||
|
ENTRYPOINT ["dotnet", "GsDChat.Server.dll"]
|
||||||
12
GsDChat.slnx
Normal file
12
GsDChat.slnx
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
<Solution>
|
||||||
|
<Folder Name="/src/">
|
||||||
|
<Project Path="src/GsDChat.Client/GsDChat.Client.csproj" />
|
||||||
|
<Project Path="src/GsDChat.Core/GsDChat.Core.csproj" />
|
||||||
|
<Project Path="src/GsDChat.Modding/GsDChat.Modding.csproj" />
|
||||||
|
<Project Path="src/GsDChat.Mods.SampleBot/GsDChat.Mods.SampleBot.csproj" />
|
||||||
|
<Project Path="src/GsDChat.Server/GsDChat.Server.csproj" />
|
||||||
|
</Folder>
|
||||||
|
<Folder Name="/tests/">
|
||||||
|
<Project Path="tests/GsDChat.Tests/GsDChat.Tests.csproj" />
|
||||||
|
</Folder>
|
||||||
|
</Solution>
|
||||||
217
README.md
Normal file
217
README.md
Normal file
|
|
@ -0,0 +1,217 @@
|
||||||
|
# GsDChat
|
||||||
|
|
||||||
|
A lightweight, secure, and private community chat platform built in pure C# (.NET 10) without external non-.NET libraries.
|
||||||
|
|
||||||
|
GsDChat provides a single-server architecture with SQLite persistence, dynamic DLL modding via `AssemblyLoadContext`, HTTPS/WSS and tunnel-ready HTTP/WS support, authenticated file transfers, and a server-driven screen-swapping Terminal User Interface (TUI).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Key Features
|
||||||
|
|
||||||
|
- **Pure .NET Architecture**: Strict adherence to the standard .NET runtime and first-party `Microsoft.Data.Sqlite`. Zero native/unmanaged C/C++ third-party dependencies.
|
||||||
|
- **Flexible Network & Tunnel Support**: Configurable direct HTTPS/WSS (with custom PFX/PEM certificates or self-signed certs) or plain HTTP/WS for running inside Docker containers behind **Cloudflare Tunnels (`cloudflared`)**, Tailscale, or reverse proxies.
|
||||||
|
- **Screen-Swapping TUI Client**: Built with ANSI escape codes and `System.Console` (zero third-party UI dependencies). Fast screen-swapping using function keys:
|
||||||
|
- **F1**: Active Channel Chat (scrollable history, timestamps, role badges, file card indicators, bottom input box).
|
||||||
|
- **F2**: Channel Browser (channel list, topics, active indicator, join and create channels).
|
||||||
|
- **F3**: User Directory (member list, role tags, real-time online `●` / offline `○` presence).
|
||||||
|
- **F4**: Shared Files Browser (table of uploaded files, download to `./downloads/`, upload from local path).
|
||||||
|
- **F5+**: Mod-defined custom screens rendered dynamically from server layout schemas.
|
||||||
|
- **Dynamic Modding System**: Place mod `.dll` files in `./mods/` to dynamically extend the server using `AssemblyLoadContext`:
|
||||||
|
- Intercept and transform chat messages (e.g. shorthand emoji formatting `:shrug:`, word filters).
|
||||||
|
- Register custom slash commands (e.g. `/roll 2d6`, `/announce`).
|
||||||
|
- Subscribe to server lifecycle and entity events (`UserConnected`, `ChannelCreated`, `FileUploaded`).
|
||||||
|
- Inject custom TUI screens or customize server MOTD.
|
||||||
|
- **Security & Authentication**:
|
||||||
|
- PBKDF2 with SHA-512 (100,000 iterations) and 256-bit cryptographically secure salt.
|
||||||
|
- Constant-time verification preventing timing attacks.
|
||||||
|
- 256-bit secure session tokens.
|
||||||
|
- Optional server-wide password gate.
|
||||||
|
- Role-based permissions (`Owner`, `Admin`, `Member`). First registered user automatically becomes the Server Owner.
|
||||||
|
- **Direct File Transfers**: Authenticated multipart HTTPS uploads (`POST /api/files/upload`) and streaming downloads (`GET /api/files/{id}`) with SHA-256 integrity verification.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
GsDChat/
|
||||||
|
├── GsDChat.slnx
|
||||||
|
├── src/
|
||||||
|
│ ├── GsDChat.Core/ # Shared models, crypto, and network/UI protocols
|
||||||
|
│ ├── GsDChat.Modding/ # Mod SDK: IMod, pipelines, command registry, event bus
|
||||||
|
│ ├── GsDChat.Server/ # ASP.NET Core Kestrel, SQLite DB, WebSockets, File REST
|
||||||
|
│ ├── GsDChat.Client/ # Pure C# screen-swapping TUI client
|
||||||
|
│ └── GsDChat.Mods.SampleBot/ # Reference mod: /roll, /announce, emoji transformer, F5 screen
|
||||||
|
└── tests/
|
||||||
|
└── GsDChat.Tests/ # Comprehensive xUnit test suite (Unit, Integration, E2E)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### 1. Build Solution
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet build GsDChat.slnx
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Run All Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet test GsDChat.slnx
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Run the Server
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet run --project src/GsDChat.Server
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, the server runs on `http://0.0.0.0:5000` with SQLite database in `./data/chat.db` and loads any mod DLLs in `./mods/`.
|
||||||
|
|
||||||
|
#### Server Configuration (`serversettings.json` / CLI flags)
|
||||||
|
|
||||||
|
You can edit `src/GsDChat.Server/serversettings.json` or pass command-line arguments:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"Host": "0.0.0.0",
|
||||||
|
"Port": 5000,
|
||||||
|
"UseTls": false,
|
||||||
|
"CertificatePath": "",
|
||||||
|
"CertificatePassword": "",
|
||||||
|
"ServerWidePassword": "",
|
||||||
|
"RegistrationMode": "Open",
|
||||||
|
"DataDirectory": "data",
|
||||||
|
"MaxFileSizeMb": 50,
|
||||||
|
"ServerName": "GsDChat Community Server",
|
||||||
|
"Motd": "Welcome to GsDChat! Enjoy private and modular messaging."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
CLI Overrides:
|
||||||
|
```bash
|
||||||
|
dotnet run --project src/GsDChat.Server -- --port 8080 --server-password "MySecretCommunityPassword"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Docker & Cloudflare Tunnel Deployment
|
||||||
|
|
||||||
|
### Option A: Standard Docker Compose
|
||||||
|
|
||||||
|
1. Copy `.env.example` to `.env` (already done by default) and customize variables:
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
2. Start the container:
|
||||||
|
```bash
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
Data (database + files) is persisted in `./data/` and mods in `./mods/`.
|
||||||
|
|
||||||
|
### Option B: Built-in Cloudflare Tunnel (`cloudflared`)
|
||||||
|
|
||||||
|
This deploys GsDChat in an isolated container with zero open host ports, securely accessible globally via Cloudflare Tunnel.
|
||||||
|
|
||||||
|
1. Create a tunnel in **Cloudflare Zero Trust** (`Networks -> Tunnels -> Add a Tunnel`).
|
||||||
|
2. Copy the tunnel token into `.env`:
|
||||||
|
```bash
|
||||||
|
CLOUDFLARE_TUNNEL_TOKEN=eyJh...
|
||||||
|
```
|
||||||
|
3. In Cloudflare Zero Trust, configure the Public Hostname:
|
||||||
|
- **Service**: `HTTP`
|
||||||
|
- **URL**: `gsdchat:5000`
|
||||||
|
4. Start both GsDChat and the cloudflared tunnel:
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.tunnel.yml up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4. Run the Client TUI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet run --project src/GsDChat.Client
|
||||||
|
```
|
||||||
|
|
||||||
|
Or connect directly with credentials:
|
||||||
|
```bash
|
||||||
|
dotnet run --project src/GsDChat.Client -- --server http://localhost:5000 --username Alice --password MyPassword123!
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Client TUI Navigation
|
||||||
|
|
||||||
|
| Key | Action |
|
||||||
|
|---|---|
|
||||||
|
| **F1** | Switch to **Chat** view |
|
||||||
|
| **F2** | Switch to **Channels** view |
|
||||||
|
| **F3** | Switch to **Users** directory view |
|
||||||
|
| **F4** | Switch to **Files** transfer view |
|
||||||
|
| **F5** | Switch to **Server Status** (SampleBot mod view) |
|
||||||
|
| **Enter** (on F1) | Send message or run slash command |
|
||||||
|
| **PageUp / PageDown** | Scroll message viewport up and down |
|
||||||
|
| **Ctrl + C** | Exit client |
|
||||||
|
|
||||||
|
### Built-in & Mod Slash Commands
|
||||||
|
|
||||||
|
Type these directly in the chat input on **F1**:
|
||||||
|
- `/help` — List available commands.
|
||||||
|
- `/join <channel>` — Switch to a channel (e.g. `/join general`).
|
||||||
|
- `/create <name> [topic]` — Create a new channel (Admin/Owner).
|
||||||
|
- `/upload <local_path>` — Upload a file to the active channel.
|
||||||
|
- `/download <file_id>` — Download a shared file to `./downloads/`.
|
||||||
|
- `/roll [NdM]` *(SampleBot)* — Roll dice (e.g. `/roll 2d6`, `/roll 1d20`).
|
||||||
|
- `/announce <text>` *(SampleBot)* — Post an official broadcast announcement (Admin/Owner).
|
||||||
|
- Text emoji shortcuts: `:shrug:` converts to `¯\_(ツ)_/¯`, `:tableflip:` converts to `(╯°□°)╯︵ ┻━┻`, `:heart:` to `❤️`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Modding Guide
|
||||||
|
|
||||||
|
To create a custom mod:
|
||||||
|
1. Create a class library targeting `net10.0`.
|
||||||
|
2. Reference `GsDChat.Modding.csproj`.
|
||||||
|
3. Implement `IMod`:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
using GsDChat.Modding;
|
||||||
|
|
||||||
|
public class MyCustomMod : IMod
|
||||||
|
{
|
||||||
|
public string Id => "com.example.mycustommod";
|
||||||
|
public string Name => "My Custom Mod";
|
||||||
|
public string Version => "1.0.0";
|
||||||
|
public string Description => "Example custom mod for GsDChat";
|
||||||
|
|
||||||
|
public Task InitializeAsync(IModContext context)
|
||||||
|
{
|
||||||
|
// Register a custom slash command
|
||||||
|
context.Commands.RegisterCommand("ping", "Responds with pong", async cmdCtx =>
|
||||||
|
{
|
||||||
|
return CommandResult.Ok("🏓 Pong from custom mod!");
|
||||||
|
});
|
||||||
|
|
||||||
|
// Intercept messages
|
||||||
|
context.Pipeline.Use(async (msgCtx, next) =>
|
||||||
|
{
|
||||||
|
// Inspect or modify msgCtx.Message.Content
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task ShutdownAsync() => Task.CompletedTask;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Drop the built `.dll` into the server's `./mods/` directory and restart the server.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## License
|
||||||
|
MIT License.
|
||||||
57
docker-compose.tunnel.yml
Normal file
57
docker-compose.tunnel.yml
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
# ========================================================
|
||||||
|
# GsDChat Deployment with Cloudflare Tunnel (cloudflared)
|
||||||
|
# ========================================================
|
||||||
|
# Usage:
|
||||||
|
# 1. Fill in CLOUDFLARE_TUNNEL_TOKEN in your .env file.
|
||||||
|
# 2. In your Cloudflare Zero Trust dashboard (Networks -> Tunnels):
|
||||||
|
# Route your public hostname (e.g. chat.yourdomain.com) to:
|
||||||
|
# Type: HTTP
|
||||||
|
# URL: gsdchat:5000
|
||||||
|
# 3. Deploy:
|
||||||
|
# docker compose -f docker-compose.tunnel.yml up -d --build
|
||||||
|
# ========================================================
|
||||||
|
|
||||||
|
services:
|
||||||
|
gsdchat:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: gsdchat-server
|
||||||
|
restart: unless-stopped
|
||||||
|
# The server runs in an internal, closed-off docker network.
|
||||||
|
# No ports need to be publicly exposed on the host machine.
|
||||||
|
# (Optional: uncomment the line below to allow local access on the host)
|
||||||
|
# ports:
|
||||||
|
# - "127.0.0.1:5000:5000"
|
||||||
|
environment:
|
||||||
|
- GSDCHAT_PORT=5000
|
||||||
|
- GSDCHAT_HOST=0.0.0.0
|
||||||
|
- GSDCHAT_SERVER_NAME=${SERVER_NAME:-GsDChat Community Server}
|
||||||
|
- GSDCHAT_MOTD=${SERVER_MOTD:-Welcome to GsDChat! Enjoy private and modular messaging.}
|
||||||
|
- GSDCHAT_SERVER_PASSWORD=${SERVER_PASSWORD:-}
|
||||||
|
- GSDCHAT_REGISTRATION_MODE=${REGISTRATION_MODE:-Open}
|
||||||
|
- GSDCHAT_MAX_FILE_SIZE_MB=${MAX_FILE_SIZE_MB:-50}
|
||||||
|
- GSDCHAT_USE_TLS=false
|
||||||
|
- GSDCHAT_DATA_DIR=/app/data
|
||||||
|
- GSDCHAT_MODS_DIR=/app/mods
|
||||||
|
volumes:
|
||||||
|
- ./data:/app/data
|
||||||
|
- ./mods:/app/mods
|
||||||
|
networks:
|
||||||
|
- gsdchat-net
|
||||||
|
|
||||||
|
cloudflared:
|
||||||
|
image: cloudflare/cloudflared:latest
|
||||||
|
container_name: gsdchat-tunnel
|
||||||
|
restart: unless-stopped
|
||||||
|
command: tunnel --no-autoupdate run
|
||||||
|
environment:
|
||||||
|
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN}
|
||||||
|
depends_on:
|
||||||
|
- gsdchat
|
||||||
|
networks:
|
||||||
|
- gsdchat-net
|
||||||
|
|
||||||
|
networks:
|
||||||
|
gsdchat-net:
|
||||||
|
driver: bridge
|
||||||
23
docker-compose.yml
Normal file
23
docker-compose.yml
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
services:
|
||||||
|
gsdchat:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: gsdchat-server
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "${PORT:-5000}:5000"
|
||||||
|
environment:
|
||||||
|
- GSDCHAT_PORT=5000
|
||||||
|
- GSDCHAT_HOST=0.0.0.0
|
||||||
|
- GSDCHAT_SERVER_NAME=${SERVER_NAME:-GsDChat Community Server}
|
||||||
|
- GSDCHAT_MOTD=${SERVER_MOTD:-Welcome to GsDChat! Enjoy private and modular messaging.}
|
||||||
|
- GSDCHAT_SERVER_PASSWORD=${SERVER_PASSWORD:-}
|
||||||
|
- GSDCHAT_REGISTRATION_MODE=${REGISTRATION_MODE:-Open}
|
||||||
|
- GSDCHAT_MAX_FILE_SIZE_MB=${MAX_FILE_SIZE_MB:-50}
|
||||||
|
- GSDCHAT_USE_TLS=false
|
||||||
|
- GSDCHAT_DATA_DIR=/app/data
|
||||||
|
- GSDCHAT_MODS_DIR=/app/mods
|
||||||
|
volumes:
|
||||||
|
- ./data:/app/data
|
||||||
|
- ./mods:/app/mods
|
||||||
14
src/GsDChat.Client/GsDChat.Client.csproj
Normal file
14
src/GsDChat.Client/GsDChat.Client.csproj
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\GsDChat.Core\GsDChat.Core.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
404
src/GsDChat.Client/Network/ChatClientConnection.cs
Normal file
404
src/GsDChat.Client/Network/ChatClientConnection.cs
Normal file
|
|
@ -0,0 +1,404 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Security;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Client.State;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
namespace GsDChat.Client.Network;
|
||||||
|
|
||||||
|
public class ChatClientConnection : IDisposable
|
||||||
|
{
|
||||||
|
private readonly ClientState _state;
|
||||||
|
private readonly bool _allowInsecure;
|
||||||
|
private readonly HttpClient _httpClient;
|
||||||
|
private ClientWebSocket? _webSocket;
|
||||||
|
private CancellationTokenSource? _cts;
|
||||||
|
private readonly SemaphoreSlim _sendLock = new(1, 1);
|
||||||
|
|
||||||
|
public ChatClientConnection(ClientState state, bool allowInsecure = false)
|
||||||
|
{
|
||||||
|
_state = state;
|
||||||
|
_allowInsecure = allowInsecure;
|
||||||
|
|
||||||
|
var handler = new HttpClientHandler();
|
||||||
|
if (allowInsecure)
|
||||||
|
{
|
||||||
|
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
|
||||||
|
}
|
||||||
|
|
||||||
|
_httpClient = new HttpClient(handler)
|
||||||
|
{
|
||||||
|
BaseAddress = new Uri(state.ServerUrl)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ServerInfoResponse?> GetServerInfoAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var res = await _httpClient.GetAsync("/api/info");
|
||||||
|
if (res.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var json = await res.Content.ReadAsStringAsync();
|
||||||
|
return JsonSerializer.Deserialize<ServerInfoResponse>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Failed to reach server: {ex.Message}");
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AuthResponse> RegisterAsync(string username, string password, string? serverPassword = null)
|
||||||
|
{
|
||||||
|
var req = new RegisterRequest
|
||||||
|
{
|
||||||
|
Username = username,
|
||||||
|
Password = password,
|
||||||
|
ServerPassword = serverPassword
|
||||||
|
};
|
||||||
|
var json = JsonSerializer.Serialize(req);
|
||||||
|
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var res = await _httpClient.PostAsync("/api/auth/register", content);
|
||||||
|
var resJson = await res.Content.ReadAsStringAsync();
|
||||||
|
return JsonSerializer.Deserialize<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
||||||
|
?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." };
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return new AuthResponse { Success = false, ErrorMessage = ex.Message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AuthResponse> LoginAsync(string username, string password, string? serverPassword = null)
|
||||||
|
{
|
||||||
|
var req = new LoginRequest
|
||||||
|
{
|
||||||
|
Username = username,
|
||||||
|
Password = password,
|
||||||
|
ServerPassword = serverPassword
|
||||||
|
};
|
||||||
|
var json = JsonSerializer.Serialize(req);
|
||||||
|
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var res = await _httpClient.PostAsync("/api/auth/login", content);
|
||||||
|
var resJson = await res.Content.ReadAsStringAsync();
|
||||||
|
return JsonSerializer.Deserialize<AuthResponse>(resJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
|
||||||
|
?? new AuthResponse { Success = false, ErrorMessage = "Invalid response from server." };
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return new AuthResponse { Success = false, ErrorMessage = ex.Message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task StartWebSocketAsync()
|
||||||
|
{
|
||||||
|
_cts = new CancellationTokenSource();
|
||||||
|
_webSocket = new ClientWebSocket();
|
||||||
|
|
||||||
|
if (_allowInsecure)
|
||||||
|
{
|
||||||
|
_webSocket.Options.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
|
||||||
|
}
|
||||||
|
|
||||||
|
var baseUri = new Uri(_state.ServerUrl);
|
||||||
|
string wsScheme = baseUri.Scheme == "https" ? "wss" : "ws";
|
||||||
|
var wsUri = new Uri($"{wsScheme}://{baseUri.Authority}/ws?token={_state.Token}");
|
||||||
|
|
||||||
|
await _webSocket.ConnectAsync(wsUri, _cts.Token);
|
||||||
|
_state.IsConnected = true;
|
||||||
|
_state.SetStatus("Connected to chat server!");
|
||||||
|
|
||||||
|
_ = Task.Run(() => ReceiveLoopAsync(_cts.Token));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ReceiveLoopAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
var buffer = new byte[8192];
|
||||||
|
var accumulator = new System.Collections.Generic.List<byte>();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (_webSocket != null && _webSocket.State == WebSocketState.Open && !ct.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), ct);
|
||||||
|
if (result.MessageType == WebSocketMessageType.Close)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.MessageType == WebSocketMessageType.Text)
|
||||||
|
{
|
||||||
|
accumulator.AddRange(buffer.AsSpan(0, result.Count).ToArray());
|
||||||
|
if (result.EndOfMessage)
|
||||||
|
{
|
||||||
|
string json = Encoding.UTF8.GetString(accumulator.ToArray());
|
||||||
|
accumulator.Clear();
|
||||||
|
ProcessIncomingEnvelope(json);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Connection lost: {ex.Message}");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_state.IsConnected = false;
|
||||||
|
_state.SetStatus("Disconnected from server.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ProcessIncomingEnvelope(string json)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var envelope = JsonSerializer.Deserialize<NetworkEnvelope>(json);
|
||||||
|
if (envelope == null) return;
|
||||||
|
|
||||||
|
switch (envelope.Type)
|
||||||
|
{
|
||||||
|
case MessageTypes.UiSync:
|
||||||
|
var ui = envelope.Unpack<ServerUiSync>();
|
||||||
|
if (ui != null)
|
||||||
|
{
|
||||||
|
_state.UiSync = ui;
|
||||||
|
_state.ServerName = ui.ServerName;
|
||||||
|
_state.Motd = ui.Motd;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.ChannelListSync:
|
||||||
|
var chSync = envelope.Unpack<ChannelListSyncPacket>();
|
||||||
|
if (chSync != null)
|
||||||
|
{
|
||||||
|
_state.UpdateChannels(chSync.Channels, chSync.ActiveChannelId);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.HistorySync:
|
||||||
|
var histSync = envelope.Unpack<HistorySyncPacket>();
|
||||||
|
if (histSync != null)
|
||||||
|
{
|
||||||
|
_state.SetHistory(histSync.ChannelId, histSync.Messages);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.MessageBroadcast:
|
||||||
|
var msgBc = envelope.Unpack<MessageBroadcastPacket>();
|
||||||
|
if (msgBc != null)
|
||||||
|
{
|
||||||
|
_state.AddChatMessage(msgBc.Message);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.UserListSync:
|
||||||
|
var uSync = envelope.Unpack<UserListSyncPacket>();
|
||||||
|
if (uSync != null)
|
||||||
|
{
|
||||||
|
_state.UpdateUsers(uSync.Users);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.FileListSync:
|
||||||
|
var fSync = envelope.Unpack<FileListSyncPacket>();
|
||||||
|
if (fSync != null)
|
||||||
|
{
|
||||||
|
_state.UpdateFiles(fSync.Files);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.SystemNotice:
|
||||||
|
var notice = envelope.Unpack<SystemNoticePacket>();
|
||||||
|
if (notice != null)
|
||||||
|
{
|
||||||
|
_state.AddNotice(notice.Text);
|
||||||
|
_state.SetStatus(notice.Text, 4);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.CommandResult:
|
||||||
|
var cmdRes = envelope.Unpack<CommandResultPacket>();
|
||||||
|
if (cmdRes != null)
|
||||||
|
{
|
||||||
|
_state.AddNotice(cmdRes.Output);
|
||||||
|
_state.SetStatus(cmdRes.Success ? "Command executed." : "Command error.", 4);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.Error:
|
||||||
|
var err = envelope.Unpack<ErrorPacket>();
|
||||||
|
if (err != null)
|
||||||
|
{
|
||||||
|
_state.SetStatus($"[Error] {err.Message}", 5);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Error parsing packet: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SendEnvelopeAsync(NetworkEnvelope envelope)
|
||||||
|
{
|
||||||
|
if (_webSocket == null || _webSocket.State != WebSocketState.Open) return;
|
||||||
|
|
||||||
|
string json = JsonSerializer.Serialize(envelope);
|
||||||
|
byte[] bytes = Encoding.UTF8.GetBytes(json);
|
||||||
|
|
||||||
|
await _sendLock.WaitAsync();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_webSocket.State == WebSocketState.Open)
|
||||||
|
{
|
||||||
|
await _webSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_sendLock.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task SendChatMessageAsync(string channelId, string content)
|
||||||
|
{
|
||||||
|
var envelope = NetworkEnvelope.Create(MessageTypes.SendMessage, new SendMessagePacket
|
||||||
|
{
|
||||||
|
ChannelId = channelId,
|
||||||
|
Content = content
|
||||||
|
});
|
||||||
|
return SendEnvelopeAsync(envelope);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task JoinChannelAsync(string channelId)
|
||||||
|
{
|
||||||
|
var envelope = NetworkEnvelope.Create(MessageTypes.JoinChannel, new JoinChannelPacket { ChannelId = channelId });
|
||||||
|
return SendEnvelopeAsync(envelope);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task CreateChannelAsync(string name, string topic)
|
||||||
|
{
|
||||||
|
var envelope = NetworkEnvelope.Create(MessageTypes.CreateChannel, new CreateChannelPacket { Name = name, Topic = topic });
|
||||||
|
return SendEnvelopeAsync(envelope);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task DeleteChannelAsync(string channelId)
|
||||||
|
{
|
||||||
|
var envelope = NetworkEnvelope.Create(MessageTypes.DeleteChannel, new DeleteChannelPacket { ChannelId = channelId });
|
||||||
|
return SendEnvelopeAsync(envelope);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task ExecuteCommandAsync(string command, string args, string channelId)
|
||||||
|
{
|
||||||
|
var envelope = NetworkEnvelope.Create(MessageTypes.ExecuteCommand, new ExecuteCommandPacket
|
||||||
|
{
|
||||||
|
Command = command,
|
||||||
|
Args = args,
|
||||||
|
ChannelId = channelId
|
||||||
|
});
|
||||||
|
return SendEnvelopeAsync(envelope);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> UploadFileAsync(string localFilePath, string channelId)
|
||||||
|
{
|
||||||
|
if (!File.Exists(localFilePath))
|
||||||
|
{
|
||||||
|
_state.SetStatus($"File does not exist: {localFilePath}", 4);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var fileStream = File.OpenRead(localFilePath);
|
||||||
|
using var content = new MultipartFormDataContent();
|
||||||
|
var fileContent = new StreamContent(fileStream);
|
||||||
|
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||||
|
|
||||||
|
content.Add(fileContent, "file", Path.GetFileName(localFilePath));
|
||||||
|
content.Add(new StringContent(channelId), "channelId");
|
||||||
|
|
||||||
|
using var req = new HttpRequestMessage(HttpMethod.Post, "/api/files/upload")
|
||||||
|
{
|
||||||
|
Content = content
|
||||||
|
};
|
||||||
|
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _state.Token);
|
||||||
|
|
||||||
|
var res = await _httpClient.SendAsync(req);
|
||||||
|
if (res.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Uploaded {Path.GetFileName(localFilePath)} successfully!", 4);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
string errText = await res.Content.ReadAsStringAsync();
|
||||||
|
_state.SetStatus($"Upload failed: {res.StatusCode} - {errText}", 5);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Upload error: {ex.Message}", 5);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DownloadFileAsync(string fileId, string targetDirectory)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(targetDirectory);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var req = new HttpRequestMessage(HttpMethod.Get, $"/api/files/{fileId}");
|
||||||
|
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _state.Token);
|
||||||
|
|
||||||
|
var res = await _httpClient.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
|
||||||
|
if (!res.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Download failed: {res.StatusCode}", 4);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
string fileName = res.Content.Headers.ContentDisposition?.FileName?.Trim('\"') ?? $"{fileId}.bin";
|
||||||
|
string targetPath = Path.Combine(targetDirectory, fileName);
|
||||||
|
|
||||||
|
using var srcStream = await res.Content.ReadAsStreamAsync();
|
||||||
|
using var fileStream = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None, 81920, useAsync: true);
|
||||||
|
await srcStream.CopyToAsync(fileStream);
|
||||||
|
|
||||||
|
_state.SetStatus($"Downloaded to {targetPath}", 5);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Download error: {ex.Message}", 5);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_cts?.Cancel();
|
||||||
|
_webSocket?.Dispose();
|
||||||
|
_httpClient.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
146
src/GsDChat.Client/Program.cs
Normal file
146
src/GsDChat.Client/Program.cs
Normal file
|
|
@ -0,0 +1,146 @@
|
||||||
|
using System;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Client.Network;
|
||||||
|
using GsDChat.Client.Rendering;
|
||||||
|
using GsDChat.Client.State;
|
||||||
|
|
||||||
|
namespace GsDChat.Client;
|
||||||
|
|
||||||
|
public class Program
|
||||||
|
{
|
||||||
|
public static async Task Main(string[] args)
|
||||||
|
{
|
||||||
|
string serverUrl = "http://localhost:5000";
|
||||||
|
string? username = null;
|
||||||
|
string? password = null;
|
||||||
|
string? serverPassword = null;
|
||||||
|
bool doRegister = false;
|
||||||
|
bool allowInsecure = false;
|
||||||
|
|
||||||
|
for (int i = 0; i < args.Length; i++)
|
||||||
|
{
|
||||||
|
if (args[i] == "--server" && i + 1 < args.Length) serverUrl = args[i + 1];
|
||||||
|
if (args[i] == "--username" && i + 1 < args.Length) username = args[i + 1];
|
||||||
|
if (args[i] == "--password" && i + 1 < args.Length) password = args[i + 1];
|
||||||
|
if (args[i] == "--server-password" && i + 1 < args.Length) serverPassword = args[i + 1];
|
||||||
|
if (args[i] == "--register") doRegister = true;
|
||||||
|
if (args[i] == "--insecure") allowInsecure = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine($"{Ansi.Bold}{Ansi.Cyan}========================================");
|
||||||
|
Console.WriteLine(" GsDChat - Private Community TUI");
|
||||||
|
Console.WriteLine($"========================================{Ansi.Reset}");
|
||||||
|
|
||||||
|
var state = new ClientState
|
||||||
|
{
|
||||||
|
ServerUrl = serverUrl
|
||||||
|
};
|
||||||
|
|
||||||
|
using var connection = new ChatClientConnection(state, allowInsecure);
|
||||||
|
|
||||||
|
Console.Write($"Connecting to server at {serverUrl}... ");
|
||||||
|
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.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine($"{Ansi.BrightGreen}Connected!{Ansi.Reset}");
|
||||||
|
Console.WriteLine($"Server: {info.ServerName} (v{info.Version})");
|
||||||
|
if (!string.IsNullOrEmpty(info.Motd))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"MOTD: {info.Motd}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (info.RequiresServerPassword && string.IsNullOrEmpty(serverPassword))
|
||||||
|
{
|
||||||
|
Console.Write("Enter Server Password: ");
|
||||||
|
serverPassword = ReadMaskedPassword();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(username))
|
||||||
|
{
|
||||||
|
Console.Write("\nChoose action: [L]ogin or [R]egister: ");
|
||||||
|
var choice = Console.ReadLine()?.Trim().ToUpperInvariant();
|
||||||
|
if (choice == "R" || choice == "REGISTER")
|
||||||
|
{
|
||||||
|
doRegister = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.Write("Username: ");
|
||||||
|
username = Console.ReadLine()?.Trim();
|
||||||
|
|
||||||
|
Console.Write("Password: ");
|
||||||
|
password = ReadMaskedPassword();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"{Ansi.BrightRed}Username and password are required.{Ansi.Reset}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine(doRegister ? "Registering account..." : "Logging in...");
|
||||||
|
|
||||||
|
var authResult = doRegister
|
||||||
|
? await connection.RegisterAsync(username, password, serverPassword)
|
||||||
|
: await connection.LoginAsync(username, password, serverPassword);
|
||||||
|
|
||||||
|
if (!authResult.Success || string.IsNullOrEmpty(authResult.Token))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"{Ansi.BrightRed}Authentication failed: {authResult.ErrorMessage}{Ansi.Reset}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine($"{Ansi.BrightGreen}Success! Welcome @{authResult.Username} [{authResult.Role}]{Ansi.Reset}");
|
||||||
|
|
||||||
|
state.Token = authResult.Token;
|
||||||
|
state.CurrentUserId = authResult.UserId ?? "";
|
||||||
|
state.CurrentUsername = authResult.Username ?? username;
|
||||||
|
state.CurrentUserRole = authResult.Role ?? "Member";
|
||||||
|
|
||||||
|
await connection.StartWebSocketAsync();
|
||||||
|
|
||||||
|
// Launch TUI
|
||||||
|
using var cts = new CancellationTokenSource();
|
||||||
|
Console.CancelKeyPress += (s, e) =>
|
||||||
|
{
|
||||||
|
e.Cancel = true;
|
||||||
|
cts.Cancel();
|
||||||
|
};
|
||||||
|
|
||||||
|
var ui = new ConsoleUi(state, connection);
|
||||||
|
await ui.RunAsync(cts.Token);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ReadMaskedPassword()
|
||||||
|
{
|
||||||
|
string pwd = "";
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var key = Console.ReadKey(true);
|
||||||
|
if (key.Key == ConsoleKey.Enter)
|
||||||
|
{
|
||||||
|
Console.WriteLine();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (key.Key == ConsoleKey.Backspace)
|
||||||
|
{
|
||||||
|
if (pwd.Length > 0)
|
||||||
|
{
|
||||||
|
pwd = pwd[..^1];
|
||||||
|
Console.Write("\b \b");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (!char.IsControl(key.KeyChar))
|
||||||
|
{
|
||||||
|
pwd += key.KeyChar;
|
||||||
|
Console.Write("*");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pwd;
|
||||||
|
}
|
||||||
|
}
|
||||||
74
src/GsDChat.Client/Rendering/Ansi.cs
Normal file
74
src/GsDChat.Client/Rendering/Ansi.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GsDChat.Client.Rendering;
|
||||||
|
|
||||||
|
public static class Ansi
|
||||||
|
{
|
||||||
|
public const string Reset = "\x1b[0m";
|
||||||
|
public const string Bold = "\x1b[1m";
|
||||||
|
public const string Dim = "\x1b[2m";
|
||||||
|
public const string Italic = "\x1b[3m";
|
||||||
|
public const string Underline = "\x1b[4m";
|
||||||
|
public const string Inverse = "\x1b[7m";
|
||||||
|
|
||||||
|
// Standard foreground colors
|
||||||
|
public const string Black = "\x1b[30m";
|
||||||
|
public const string Red = "\x1b[31m";
|
||||||
|
public const string Green = "\x1b[32m";
|
||||||
|
public const string Yellow = "\x1b[33m";
|
||||||
|
public const string Blue = "\x1b[34m";
|
||||||
|
public const string Magenta = "\x1b[35m";
|
||||||
|
public const string Cyan = "\x1b[36m";
|
||||||
|
public const string White = "\x1b[37m";
|
||||||
|
|
||||||
|
// Bright foreground colors
|
||||||
|
public const string Gray = "\x1b[90m";
|
||||||
|
public const string BrightRed = "\x1b[91m";
|
||||||
|
public const string BrightGreen = "\x1b[92m";
|
||||||
|
public const string BrightYellow = "\x1b[93m";
|
||||||
|
public const string BrightBlue = "\x1b[94m";
|
||||||
|
public const string BrightMagenta = "\x1b[95m";
|
||||||
|
public const string BrightCyan = "\x1b[96m";
|
||||||
|
public const string BrightWhite = "\x1b[97m";
|
||||||
|
|
||||||
|
// Background colors
|
||||||
|
public const string BgBlack = "\x1b[40m";
|
||||||
|
public const string BgRed = "\x1b[41m";
|
||||||
|
public const string BgGreen = "\x1b[42m";
|
||||||
|
public const string BgYellow = "\x1b[43m";
|
||||||
|
public const string BgBlue = "\x1b[44m";
|
||||||
|
public const string BgMagenta = "\x1b[45m";
|
||||||
|
public const string BgCyan = "\x1b[46m";
|
||||||
|
public const string BgWhite = "\x1b[47m";
|
||||||
|
public const string BgDarkGray = "\x1b[100m";
|
||||||
|
|
||||||
|
// Screen and Cursor commands
|
||||||
|
public const string ClearScreen = "\x1b[2J";
|
||||||
|
public const string ClearLine = "\x1b[2K";
|
||||||
|
public const string CursorHome = "\x1b[H";
|
||||||
|
public const string HideCursor = "\x1b[?25l";
|
||||||
|
public const string ShowCursor = "\x1b[?25h";
|
||||||
|
public const string EnableAltBuffer = "\x1b[?1049h";
|
||||||
|
public const string DisableAltBuffer = "\x1b[?1049l";
|
||||||
|
|
||||||
|
public static string MoveTo(int row, int col) => $"\x1b[{row};{col}H";
|
||||||
|
|
||||||
|
public static string ColorFromName(string colorName)
|
||||||
|
{
|
||||||
|
return colorName.ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
"black" => Black,
|
||||||
|
"red" => BrightRed,
|
||||||
|
"green" => BrightGreen,
|
||||||
|
"yellow" => BrightYellow,
|
||||||
|
"blue" => BrightBlue,
|
||||||
|
"magenta" => BrightMagenta,
|
||||||
|
"cyan" => BrightCyan,
|
||||||
|
"white" => BrightWhite,
|
||||||
|
"darkcyan" => Cyan,
|
||||||
|
"darkgray" => Gray,
|
||||||
|
"gray" => Gray,
|
||||||
|
_ => BrightCyan
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
217
src/GsDChat.Client/Rendering/ConsoleUi.cs
Normal file
217
src/GsDChat.Client/Rendering/ConsoleUi.cs
Normal file
|
|
@ -0,0 +1,217 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Client.Network;
|
||||||
|
using GsDChat.Client.Screens;
|
||||||
|
using GsDChat.Client.State;
|
||||||
|
|
||||||
|
namespace GsDChat.Client.Rendering;
|
||||||
|
|
||||||
|
public class ConsoleUi
|
||||||
|
{
|
||||||
|
private readonly ClientState _state;
|
||||||
|
private readonly ChatClientConnection _connection;
|
||||||
|
private readonly Dictionary<string, IScreen> _screens = new();
|
||||||
|
private bool _running = true;
|
||||||
|
|
||||||
|
public ConsoleUi(ClientState state, ChatClientConnection connection)
|
||||||
|
{
|
||||||
|
_state = state;
|
||||||
|
_connection = connection;
|
||||||
|
|
||||||
|
// Register default screens
|
||||||
|
RegisterScreen(new ChatScreen(state, connection));
|
||||||
|
RegisterScreen(new ChannelsScreen(state, connection));
|
||||||
|
RegisterScreen(new UsersScreen(state));
|
||||||
|
RegisterScreen(new FilesScreen(state, connection));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RegisterScreen(IScreen screen)
|
||||||
|
{
|
||||||
|
_screens[screen.ScreenId] = screen;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task RunAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
bool isTerminal = !Console.IsInputRedirected && !Console.IsOutputRedirected;
|
||||||
|
|
||||||
|
if (isTerminal)
|
||||||
|
{
|
||||||
|
Console.Write(Ansi.EnableAltBuffer);
|
||||||
|
Console.Write(Ansi.HideCursor);
|
||||||
|
Console.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (_running && !cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
// Dynamic server screens update check
|
||||||
|
UpdateDynamicScreens();
|
||||||
|
|
||||||
|
if (_state.NeedsRedraw || DateTime.UtcNow < _state.StatusMessageUntil)
|
||||||
|
{
|
||||||
|
Draw();
|
||||||
|
_state.NeedsRedraw = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Console.KeyAvailable)
|
||||||
|
{
|
||||||
|
var key = Console.ReadKey(intercept: true);
|
||||||
|
|
||||||
|
if (key.Key == ConsoleKey.C && (key.Modifiers & ConsoleModifiers.Control) != 0)
|
||||||
|
{
|
||||||
|
_running = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check Screen Swapping Function Keys
|
||||||
|
if (key.Key == ConsoleKey.F1)
|
||||||
|
{
|
||||||
|
_state.ActiveScreenId = "F1_Chat";
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.F2)
|
||||||
|
{
|
||||||
|
_state.ActiveScreenId = "F2_Channels";
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.F3)
|
||||||
|
{
|
||||||
|
_state.ActiveScreenId = "F3_Users";
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.F4)
|
||||||
|
{
|
||||||
|
_state.ActiveScreenId = "F4_Files";
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.F5 && _screens.ContainsKey("F5_Custom"))
|
||||||
|
{
|
||||||
|
_state.ActiveScreenId = "F5_Custom";
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var activeScreen = GetActiveScreen();
|
||||||
|
if (activeScreen != null)
|
||||||
|
{
|
||||||
|
await activeScreen.HandleKeyAsync(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await Task.Delay(30, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (isTerminal)
|
||||||
|
{
|
||||||
|
Console.Write(Ansi.ShowCursor);
|
||||||
|
Console.Write(Ansi.DisableAltBuffer);
|
||||||
|
Console.WriteLine("Exited GsDChat.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateDynamicScreens()
|
||||||
|
{
|
||||||
|
if (_state.UiSync.Screens != null)
|
||||||
|
{
|
||||||
|
foreach (var screenDef in _state.UiSync.Screens)
|
||||||
|
{
|
||||||
|
if (!_screens.ContainsKey(screenDef.ScreenId))
|
||||||
|
{
|
||||||
|
_screens[screenDef.ScreenId] = new DynamicModScreen(_state, screenDef);
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private IScreen? GetActiveScreen()
|
||||||
|
{
|
||||||
|
if (_screens.TryGetValue(_state.ActiveScreenId, out var screen))
|
||||||
|
{
|
||||||
|
return screen;
|
||||||
|
}
|
||||||
|
return _screens.Values.FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Draw()
|
||||||
|
{
|
||||||
|
int width = Console.WindowWidth > 10 ? Console.WindowWidth : 80;
|
||||||
|
int height = Console.WindowHeight > 10 ? Console.WindowHeight : 24;
|
||||||
|
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.Append(Ansi.CursorHome);
|
||||||
|
|
||||||
|
// 1. Top Bar: Server Title & Screen Tabs
|
||||||
|
RenderTopTabBar(sb, width);
|
||||||
|
|
||||||
|
// 2. Active Screen Content
|
||||||
|
var activeScreen = GetActiveScreen();
|
||||||
|
if (activeScreen != null)
|
||||||
|
{
|
||||||
|
activeScreen.Render(width, height, sb);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Bottom Status Bar
|
||||||
|
RenderBottomStatusBar(sb, width);
|
||||||
|
|
||||||
|
Console.Write(sb.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RenderTopTabBar(StringBuilder sb, int width)
|
||||||
|
{
|
||||||
|
string serverName = string.IsNullOrEmpty(_state.ServerName) ? "GsDChat" : _state.ServerName;
|
||||||
|
sb.Append($" {Ansi.Bold}{Ansi.BrightWhite}{serverName}{Ansi.Reset} │ ");
|
||||||
|
|
||||||
|
foreach (var screen in _screens.Values)
|
||||||
|
{
|
||||||
|
bool isActive = screen.ScreenId == _state.ActiveScreenId;
|
||||||
|
if (isActive)
|
||||||
|
{
|
||||||
|
sb.Append($"{Ansi.Inverse}{Ansi.Bold}[ {screen.ShortcutKey}: {screen.Title} ]{Ansi.Reset} ");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sb.Append($"{Ansi.Gray}[ {screen.ShortcutKey}: {screen.Title} ]{Ansi.Reset} ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine(new string('═', Math.Max(0, width)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RenderBottomStatusBar(StringBuilder sb, int width)
|
||||||
|
{
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
|
||||||
|
string connStatus = _state.IsConnected
|
||||||
|
? $"{Ansi.BrightGreen}● Online{Ansi.Reset}"
|
||||||
|
: $"{Ansi.BrightRed}○ Offline{Ansi.Reset}";
|
||||||
|
|
||||||
|
string userBadge = string.IsNullOrEmpty(_state.CurrentUsername)
|
||||||
|
? ""
|
||||||
|
: $"{Ansi.BrightCyan}@{_state.CurrentUsername}{Ansi.Reset} {Ansi.Gray}[{_state.CurrentUserRole}]{Ansi.Reset} │ ";
|
||||||
|
|
||||||
|
string status;
|
||||||
|
if (DateTime.UtcNow < _state.StatusMessageUntil && !string.IsNullOrEmpty(_state.StatusMessage))
|
||||||
|
{
|
||||||
|
status = $"{Ansi.BrightYellow}▶ {_state.StatusMessage}{Ansi.Reset}";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
status = $"{connStatus} │ {userBadge}{Ansi.Gray}F1-F4: Tabs │ /help: Commands │ Ctrl+C: Quit{Ansi.Reset}";
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.AppendLine($" {status}");
|
||||||
|
}
|
||||||
|
}
|
||||||
161
src/GsDChat.Client/Screens/ChannelsScreen.cs
Normal file
161
src/GsDChat.Client/Screens/ChannelsScreen.cs
Normal file
|
|
@ -0,0 +1,161 @@
|
||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Client.Network;
|
||||||
|
using GsDChat.Client.Rendering;
|
||||||
|
using GsDChat.Client.State;
|
||||||
|
|
||||||
|
namespace GsDChat.Client.Screens;
|
||||||
|
|
||||||
|
public class ChannelsScreen : IScreen
|
||||||
|
{
|
||||||
|
private readonly ClientState _state;
|
||||||
|
private readonly ChatClientConnection _connection;
|
||||||
|
private int _selectedIndex = 0;
|
||||||
|
private bool _isCreating = false;
|
||||||
|
private string _createBuffer = string.Empty;
|
||||||
|
|
||||||
|
public string ScreenId => "F2_Channels";
|
||||||
|
public string Title => "Channels";
|
||||||
|
public string ShortcutKey => "F2";
|
||||||
|
|
||||||
|
public ChannelsScreen(ClientState state, ChatClientConnection connection)
|
||||||
|
{
|
||||||
|
_state = state;
|
||||||
|
_connection = connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Render(int width, int height, StringBuilder sb)
|
||||||
|
{
|
||||||
|
sb.AppendLine($" {Ansi.Bold}{Ansi.Yellow}Channel Browser{Ansi.Reset} {Ansi.Gray}(Press ENTER to join, 'C' to create, 'D' to delete){Ansi.Reset}");
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
|
||||||
|
if (_state.Channels.Count == 0)
|
||||||
|
{
|
||||||
|
sb.AppendLine(" No channels available.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_selectedIndex >= _state.Channels.Count) _selectedIndex = _state.Channels.Count - 1;
|
||||||
|
if (_selectedIndex < 0) _selectedIndex = 0;
|
||||||
|
|
||||||
|
for (int i = 0; i < _state.Channels.Count; i++)
|
||||||
|
{
|
||||||
|
var ch = _state.Channels[i];
|
||||||
|
bool isSelected = i == _selectedIndex;
|
||||||
|
bool isActive = ch.Id == _state.ActiveChannelId;
|
||||||
|
|
||||||
|
string prefix = isSelected ? $"{Ansi.BrightYellow}► " : " ";
|
||||||
|
string activeTag = isActive ? $" {Ansi.BrightGreen}[ACTIVE]{Ansi.Reset}" : "";
|
||||||
|
string name = $"{Ansi.Bold}#{ch.Name}{Ansi.Reset}";
|
||||||
|
string topic = string.IsNullOrEmpty(ch.Topic) ? "" : $" {Ansi.Gray}- {ch.Topic}{Ansi.Reset}";
|
||||||
|
|
||||||
|
if (isSelected)
|
||||||
|
{
|
||||||
|
sb.AppendLine($"{prefix}{Ansi.Inverse}#{ch.Name}{Ansi.Reset}{activeTag}{topic}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sb.AppendLine($"{prefix}{name}{activeTag}{topic}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
|
||||||
|
if (_isCreating)
|
||||||
|
{
|
||||||
|
sb.AppendLine($" {Ansi.BrightYellow}Create Channel > Name [Topic]:{Ansi.Reset} {_createBuffer}█");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sb.AppendLine($" {Ansi.Gray}[↑/↓] Navigate [Enter] Join Channel [C] Create Channel [D] Delete Channel{Ansi.Reset}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task HandleKeyAsync(ConsoleKeyInfo key)
|
||||||
|
{
|
||||||
|
if (_isCreating)
|
||||||
|
{
|
||||||
|
if (key.Key == ConsoleKey.Enter)
|
||||||
|
{
|
||||||
|
string input = _createBuffer.Trim();
|
||||||
|
_isCreating = false;
|
||||||
|
_createBuffer = string.Empty;
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(input))
|
||||||
|
{
|
||||||
|
var parts = input.Split(' ', 2);
|
||||||
|
string name = parts[0];
|
||||||
|
string topic = parts.Length > 1 ? parts[1] : string.Empty;
|
||||||
|
await _connection.CreateChannelAsync(name, topic);
|
||||||
|
}
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.Escape)
|
||||||
|
{
|
||||||
|
_isCreating = false;
|
||||||
|
_createBuffer = string.Empty;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.Backspace)
|
||||||
|
{
|
||||||
|
if (_createBuffer.Length > 0)
|
||||||
|
{
|
||||||
|
_createBuffer = _createBuffer[..^1];
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (!char.IsControl(key.KeyChar))
|
||||||
|
{
|
||||||
|
_createBuffer += key.KeyChar;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key.Key == ConsoleKey.UpArrow)
|
||||||
|
{
|
||||||
|
_selectedIndex = Math.Max(0, _selectedIndex - 1);
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.DownArrow)
|
||||||
|
{
|
||||||
|
_selectedIndex = Math.Min(_state.Channels.Count - 1, _selectedIndex + 1);
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.Enter)
|
||||||
|
{
|
||||||
|
if (_selectedIndex >= 0 && _selectedIndex < _state.Channels.Count)
|
||||||
|
{
|
||||||
|
var selected = _state.Channels[_selectedIndex];
|
||||||
|
await _connection.JoinChannelAsync(selected.Id);
|
||||||
|
_state.ActiveScreenId = "F1_Chat";
|
||||||
|
_state.SetStatus($"Switched to #{selected.Name}");
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.C)
|
||||||
|
{
|
||||||
|
_isCreating = true;
|
||||||
|
_createBuffer = string.Empty;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.D)
|
||||||
|
{
|
||||||
|
if (_selectedIndex >= 0 && _selectedIndex < _state.Channels.Count)
|
||||||
|
{
|
||||||
|
var selected = _state.Channels[_selectedIndex];
|
||||||
|
if (selected.Name == "general")
|
||||||
|
{
|
||||||
|
_state.SetStatus("Cannot delete the general channel.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await _connection.DeleteChannelAsync(selected.Id);
|
||||||
|
_state.SetStatus($"Deleting #{selected.Name}...");
|
||||||
|
}
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
240
src/GsDChat.Client/Screens/ChatScreen.cs
Normal file
240
src/GsDChat.Client/Screens/ChatScreen.cs
Normal file
|
|
@ -0,0 +1,240 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Client.Network;
|
||||||
|
using GsDChat.Client.Rendering;
|
||||||
|
using GsDChat.Client.State;
|
||||||
|
|
||||||
|
namespace GsDChat.Client.Screens;
|
||||||
|
|
||||||
|
public class ChatScreen : IScreen
|
||||||
|
{
|
||||||
|
private readonly ClientState _state;
|
||||||
|
private readonly ChatClientConnection _connection;
|
||||||
|
|
||||||
|
public string ScreenId => "F1_Chat";
|
||||||
|
public string Title => "Chat";
|
||||||
|
public string ShortcutKey => "F1";
|
||||||
|
|
||||||
|
public ChatScreen(ClientState state, ChatClientConnection connection)
|
||||||
|
{
|
||||||
|
_state = state;
|
||||||
|
_connection = connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Render(int width, int height, StringBuilder sb)
|
||||||
|
{
|
||||||
|
var ch = _state.ActiveChannel;
|
||||||
|
string chName = ch != null ? $"#{ch.Name}" : "(no channel)";
|
||||||
|
string topic = ch != null && !string.IsNullOrEmpty(ch.Topic) ? $" - {ch.Topic}" : "";
|
||||||
|
|
||||||
|
// Header line
|
||||||
|
string header = $" {Ansi.Bold}{Ansi.Cyan}{chName}{Ansi.Reset}{Ansi.Gray}{topic}{Ansi.Reset}";
|
||||||
|
sb.AppendLine(PadOrTruncate(header, width));
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
|
||||||
|
// Messages area: height minus (Header: 2, Footer/Input: 3, Tab bar & status: 3) = height - 8
|
||||||
|
int msgAreaHeight = Math.Max(3, height - 8);
|
||||||
|
|
||||||
|
List<Core.Models.ChatMessage> messages = new();
|
||||||
|
if (!string.IsNullOrEmpty(_state.ActiveChannelId) &&
|
||||||
|
_state.ChannelMessages.TryGetValue(_state.ActiveChannelId, out var msgs))
|
||||||
|
{
|
||||||
|
messages = msgs;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Viewport calculation with scroll offset
|
||||||
|
int totalMessages = messages.Count;
|
||||||
|
int maxScroll = Math.Max(0, totalMessages - msgAreaHeight);
|
||||||
|
int scroll = Math.Clamp(_state.ChatScrollOffset, 0, maxScroll);
|
||||||
|
int startIndex = Math.Max(0, totalMessages - msgAreaHeight - scroll);
|
||||||
|
int countToTake = Math.Min(msgAreaHeight, totalMessages - startIndex);
|
||||||
|
|
||||||
|
var visible = messages.Skip(startIndex).Take(countToTake).ToList();
|
||||||
|
|
||||||
|
// Print blank lines if fewer messages than viewport height
|
||||||
|
int emptyLines = msgAreaHeight - visible.Count;
|
||||||
|
for (int i = 0; i < emptyLines; i++)
|
||||||
|
{
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var msg in visible)
|
||||||
|
{
|
||||||
|
string time = msg.CreatedAt.ToLocalTime().ToString("HH:mm:ss");
|
||||||
|
string roleColor = msg.SenderRole switch
|
||||||
|
{
|
||||||
|
"Owner" => Ansi.BrightYellow,
|
||||||
|
"Admin" => Ansi.BrightMagenta,
|
||||||
|
_ => Ansi.BrightCyan
|
||||||
|
};
|
||||||
|
|
||||||
|
string line;
|
||||||
|
if (!string.IsNullOrEmpty(msg.AttachmentId))
|
||||||
|
{
|
||||||
|
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} <{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {Ansi.BrightYellow}📎 [{msg.AttachmentName} - {FileStorageServiceFormat(msg.AttachmentSizeBytes ?? 0)}]{Ansi.Reset}";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
line = $" {Ansi.Gray}[{time}]{Ansi.Reset} <{roleColor}@{msg.SenderUsername}{Ansi.Reset}> {msg.Content}";
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.AppendLine(PadOrTruncate(line, width));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Divider
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
|
||||||
|
// Input Line
|
||||||
|
string prompt = $" {Ansi.Cyan}[{chName}] > {Ansi.Reset}";
|
||||||
|
string inputDisplay = _state.InputBuffer + "█";
|
||||||
|
sb.AppendLine(prompt + inputDisplay);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task HandleKeyAsync(ConsoleKeyInfo key)
|
||||||
|
{
|
||||||
|
if (key.Key == ConsoleKey.Enter)
|
||||||
|
{
|
||||||
|
string text = _state.InputBuffer.Trim();
|
||||||
|
_state.InputBuffer = string.Empty;
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(text)) return;
|
||||||
|
|
||||||
|
if (text.StartsWith("/"))
|
||||||
|
{
|
||||||
|
await HandleSlashCommandAsync(text);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrEmpty(_state.ActiveChannelId))
|
||||||
|
{
|
||||||
|
await _connection.SendChatMessageAsync(_state.ActiveChannelId, text);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_state.SetStatus("Please join a channel first (Press F2).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_state.ChatScrollOffset = 0;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.Backspace)
|
||||||
|
{
|
||||||
|
if (_state.InputBuffer.Length > 0)
|
||||||
|
{
|
||||||
|
_state.InputBuffer = _state.InputBuffer[..^1];
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.PageUp)
|
||||||
|
{
|
||||||
|
_state.ChatScrollOffset += 5;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.PageDown)
|
||||||
|
{
|
||||||
|
_state.ChatScrollOffset = Math.Max(0, _state.ChatScrollOffset - 5);
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.Escape)
|
||||||
|
{
|
||||||
|
_state.InputBuffer = string.Empty;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (!char.IsControl(key.KeyChar))
|
||||||
|
{
|
||||||
|
_state.InputBuffer += key.KeyChar;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleSlashCommandAsync(string input)
|
||||||
|
{
|
||||||
|
string[] parts = input.Split(' ', 2);
|
||||||
|
string cmd = parts[0].TrimStart('/').ToLowerInvariant();
|
||||||
|
string args = parts.Length > 1 ? parts[1].Trim() : string.Empty;
|
||||||
|
|
||||||
|
switch (cmd)
|
||||||
|
{
|
||||||
|
case "join":
|
||||||
|
if (string.IsNullOrEmpty(args))
|
||||||
|
{
|
||||||
|
_state.SetStatus("Usage: /join <channel_name>");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var target = _state.Channels.FirstOrDefault(c => c.Name.Equals(args.TrimStart('#'), StringComparison.OrdinalIgnoreCase));
|
||||||
|
if (target != null)
|
||||||
|
{
|
||||||
|
await _connection.JoinChannelAsync(target.Id);
|
||||||
|
_state.SetStatus($"Joined #{target.Name}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Channel #{args} not found.");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "create":
|
||||||
|
if (string.IsNullOrEmpty(args))
|
||||||
|
{
|
||||||
|
_state.SetStatus("Usage: /create <channel_name> [topic]");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var createParts = args.Split(' ', 2);
|
||||||
|
string newName = createParts[0];
|
||||||
|
string newTopic = createParts.Length > 1 ? createParts[1] : string.Empty;
|
||||||
|
await _connection.CreateChannelAsync(newName, newTopic);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "upload":
|
||||||
|
if (string.IsNullOrEmpty(args))
|
||||||
|
{
|
||||||
|
_state.SetStatus("Usage: /upload <local_file_path>");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (string.IsNullOrEmpty(_state.ActiveChannelId))
|
||||||
|
{
|
||||||
|
_state.SetStatus("Select an active channel first.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_state.SetStatus($"Uploading {args}...");
|
||||||
|
await _connection.UploadFileAsync(args, _state.ActiveChannelId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "download":
|
||||||
|
if (string.IsNullOrEmpty(args))
|
||||||
|
{
|
||||||
|
_state.SetStatus("Usage: /download <file_id>");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_state.SetStatus($"Downloading file {args}...");
|
||||||
|
await _connection.DownloadFileAsync(args, "downloads");
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
await _connection.ExecuteCommandAsync(cmd, args, _state.ActiveChannelId);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FileStorageServiceFormat(long bytes)
|
||||||
|
{
|
||||||
|
string[] suffixes = { "B", "KB", "MB", "GB" };
|
||||||
|
int order = 0;
|
||||||
|
double size = bytes;
|
||||||
|
while (size >= 1024 && order < suffixes.Length - 1)
|
||||||
|
{
|
||||||
|
order++;
|
||||||
|
size /= 1024;
|
||||||
|
}
|
||||||
|
return $"{size:0.##} {suffixes[order]}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string PadOrTruncate(string str, int width)
|
||||||
|
{
|
||||||
|
if (width <= 0) return string.Empty;
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
}
|
||||||
60
src/GsDChat.Client/Screens/DynamicModScreen.cs
Normal file
60
src/GsDChat.Client/Screens/DynamicModScreen.cs
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Client.Rendering;
|
||||||
|
using GsDChat.Client.State;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
namespace GsDChat.Client.Screens;
|
||||||
|
|
||||||
|
public class DynamicModScreen : IScreen
|
||||||
|
{
|
||||||
|
private readonly ClientState _state;
|
||||||
|
private readonly ScreenDefinition _definition;
|
||||||
|
|
||||||
|
public string ScreenId => _definition.ScreenId;
|
||||||
|
public string Title => _definition.Title;
|
||||||
|
public string ShortcutKey => _definition.ShortcutKey;
|
||||||
|
|
||||||
|
public DynamicModScreen(ClientState state, ScreenDefinition definition)
|
||||||
|
{
|
||||||
|
_state = state;
|
||||||
|
_definition = definition;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Render(int width, int height, StringBuilder sb)
|
||||||
|
{
|
||||||
|
sb.AppendLine($" {Ansi.Bold}{Ansi.Magenta}{_definition.Title}{Ansi.Reset} {Ansi.Gray}({_definition.Description}){Ansi.Reset}");
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
|
||||||
|
foreach (var panel in _definition.Panels)
|
||||||
|
{
|
||||||
|
if (panel.ShowBorder)
|
||||||
|
{
|
||||||
|
sb.AppendLine($" ┌─ {Ansi.Cyan}{panel.BorderTitle ?? panel.Name}{Ansi.Reset} " + new string('─', Math.Max(0, width - (panel.BorderTitle ?? panel.Name).Length - 6)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(panel.ContentTemplate))
|
||||||
|
{
|
||||||
|
sb.AppendLine($" │ {panel.ContentTemplate}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sb.AppendLine($" │ [Panel: {panel.Name} - Pos: {panel.Position}]");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (panel.ShowBorder)
|
||||||
|
{
|
||||||
|
sb.AppendLine(" └" + new string('─', Math.Max(0, width - 3)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
sb.AppendLine($" {Ansi.Gray}Dynamic screen rendered from server layout schema.{Ansi.Reset}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task HandleKeyAsync(ConsoleKeyInfo key)
|
||||||
|
{
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
162
src/GsDChat.Client/Screens/FilesScreen.cs
Normal file
162
src/GsDChat.Client/Screens/FilesScreen.cs
Normal file
|
|
@ -0,0 +1,162 @@
|
||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Client.Network;
|
||||||
|
using GsDChat.Client.Rendering;
|
||||||
|
using GsDChat.Client.State;
|
||||||
|
|
||||||
|
namespace GsDChat.Client.Screens;
|
||||||
|
|
||||||
|
public class FilesScreen : IScreen
|
||||||
|
{
|
||||||
|
private readonly ClientState _state;
|
||||||
|
private readonly ChatClientConnection _connection;
|
||||||
|
private int _selectedIndex = 0;
|
||||||
|
private bool _isUploading = false;
|
||||||
|
private string _uploadPathBuffer = string.Empty;
|
||||||
|
|
||||||
|
public string ScreenId => "F4_Files";
|
||||||
|
public string Title => "Files";
|
||||||
|
public string ShortcutKey => "F4";
|
||||||
|
|
||||||
|
public FilesScreen(ClientState state, ChatClientConnection connection)
|
||||||
|
{
|
||||||
|
_state = state;
|
||||||
|
_connection = connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Render(int width, int height, StringBuilder sb)
|
||||||
|
{
|
||||||
|
sb.AppendLine($" {Ansi.Bold}{Ansi.Cyan}Shared Files Browser{Ansi.Reset} {Ansi.Gray}(Press 'D' to download, 'U' to upload){Ansi.Reset}");
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
|
||||||
|
if (_state.Files.Count == 0)
|
||||||
|
{
|
||||||
|
sb.AppendLine(" No shared files yet. Press 'U' to upload a file.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (_selectedIndex >= _state.Files.Count) _selectedIndex = _state.Files.Count - 1;
|
||||||
|
if (_selectedIndex < 0) _selectedIndex = 0;
|
||||||
|
|
||||||
|
for (int i = 0; i < _state.Files.Count; i++)
|
||||||
|
{
|
||||||
|
var f = _state.Files[i];
|
||||||
|
bool isSelected = i == _selectedIndex;
|
||||||
|
|
||||||
|
string prefix = isSelected ? $"{Ansi.BrightYellow}► " : " ";
|
||||||
|
string sizeStr = FormatBytes(f.FileSizeBytes);
|
||||||
|
string dateStr = f.CreatedAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm");
|
||||||
|
|
||||||
|
string fileText = $"{f.OriginalFileName} ({sizeStr}) by @{f.UploaderUsername} [{dateStr}]";
|
||||||
|
|
||||||
|
if (isSelected)
|
||||||
|
{
|
||||||
|
sb.AppendLine($"{prefix}{Ansi.Inverse}📎 {fileText}{Ansi.Reset}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sb.AppendLine($"{prefix}📎 {fileText}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
|
||||||
|
if (_isUploading)
|
||||||
|
{
|
||||||
|
sb.AppendLine($" {Ansi.BrightYellow}Upload File > Enter local file path:{Ansi.Reset} {_uploadPathBuffer}█");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sb.AppendLine($" {Ansi.Gray}[↑/↓] Navigate [D] Download Selected [U] Upload Local File{Ansi.Reset}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task HandleKeyAsync(ConsoleKeyInfo key)
|
||||||
|
{
|
||||||
|
if (_isUploading)
|
||||||
|
{
|
||||||
|
if (key.Key == ConsoleKey.Enter)
|
||||||
|
{
|
||||||
|
string path = _uploadPathBuffer.Trim();
|
||||||
|
_isUploading = false;
|
||||||
|
_uploadPathBuffer = string.Empty;
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(path))
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(_state.ActiveChannelId))
|
||||||
|
{
|
||||||
|
_state.SetStatus("Please join a channel first.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Uploading {path}...");
|
||||||
|
await _connection.UploadFileAsync(path, _state.ActiveChannelId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.Escape)
|
||||||
|
{
|
||||||
|
_isUploading = false;
|
||||||
|
_uploadPathBuffer = string.Empty;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.Backspace)
|
||||||
|
{
|
||||||
|
if (_uploadPathBuffer.Length > 0)
|
||||||
|
{
|
||||||
|
_uploadPathBuffer = _uploadPathBuffer[..^1];
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (!char.IsControl(key.KeyChar))
|
||||||
|
{
|
||||||
|
_uploadPathBuffer += key.KeyChar;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key.Key == ConsoleKey.UpArrow)
|
||||||
|
{
|
||||||
|
_selectedIndex = Math.Max(0, _selectedIndex - 1);
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.DownArrow)
|
||||||
|
{
|
||||||
|
_selectedIndex = Math.Min(_state.Files.Count - 1, _selectedIndex + 1);
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.D)
|
||||||
|
{
|
||||||
|
if (_selectedIndex >= 0 && _selectedIndex < _state.Files.Count)
|
||||||
|
{
|
||||||
|
var selected = _state.Files[_selectedIndex];
|
||||||
|
_state.SetStatus($"Downloading {selected.OriginalFileName}...");
|
||||||
|
await _connection.DownloadFileAsync(selected.Id, "downloads");
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.U)
|
||||||
|
{
|
||||||
|
_isUploading = true;
|
||||||
|
_uploadPathBuffer = string.Empty;
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FormatBytes(long bytes)
|
||||||
|
{
|
||||||
|
string[] suffixes = { "B", "KB", "MB", "GB" };
|
||||||
|
int order = 0;
|
||||||
|
double size = bytes;
|
||||||
|
while (size >= 1024 && order < suffixes.Length - 1)
|
||||||
|
{
|
||||||
|
order++;
|
||||||
|
size /= 1024;
|
||||||
|
}
|
||||||
|
return $"{size:0.##} {suffixes[order]}";
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/GsDChat.Client/Screens/IScreen.cs
Normal file
14
src/GsDChat.Client/Screens/IScreen.cs
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace GsDChat.Client.Screens;
|
||||||
|
|
||||||
|
public interface IScreen
|
||||||
|
{
|
||||||
|
string ScreenId { get; }
|
||||||
|
string Title { get; }
|
||||||
|
string ShortcutKey { get; }
|
||||||
|
void Render(int width, int height, StringBuilder sb);
|
||||||
|
Task HandleKeyAsync(ConsoleKeyInfo key);
|
||||||
|
}
|
||||||
77
src/GsDChat.Client/Screens/UsersScreen.cs
Normal file
77
src/GsDChat.Client/Screens/UsersScreen.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Client.Rendering;
|
||||||
|
using GsDChat.Client.State;
|
||||||
|
|
||||||
|
namespace GsDChat.Client.Screens;
|
||||||
|
|
||||||
|
public class UsersScreen : IScreen
|
||||||
|
{
|
||||||
|
private readonly ClientState _state;
|
||||||
|
private int _selectedIndex = 0;
|
||||||
|
|
||||||
|
public string ScreenId => "F3_Users";
|
||||||
|
public string Title => "Users";
|
||||||
|
public string ShortcutKey => "F3";
|
||||||
|
|
||||||
|
public UsersScreen(ClientState state)
|
||||||
|
{
|
||||||
|
_state = state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Render(int width, int height, StringBuilder sb)
|
||||||
|
{
|
||||||
|
int onlineCount = _state.Users.Count(u => u.IsOnline);
|
||||||
|
sb.AppendLine($" {Ansi.Bold}{Ansi.Cyan}Community Directory{Ansi.Reset} {Ansi.Gray}({onlineCount} Online / {_state.Users.Count} Total){Ansi.Reset}");
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
|
||||||
|
if (_state.Users.Count == 0)
|
||||||
|
{
|
||||||
|
sb.AppendLine(" No users found.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_selectedIndex >= _state.Users.Count) _selectedIndex = _state.Users.Count - 1;
|
||||||
|
if (_selectedIndex < 0) _selectedIndex = 0;
|
||||||
|
|
||||||
|
for (int i = 0; i < _state.Users.Count; i++)
|
||||||
|
{
|
||||||
|
var u = _state.Users[i];
|
||||||
|
bool isSelected = i == _selectedIndex;
|
||||||
|
|
||||||
|
string statusDot = u.IsOnline ? $"{Ansi.BrightGreen}●{Ansi.Reset}" : $"{Ansi.Gray}○{Ansi.Reset}";
|
||||||
|
string roleBadge = u.Role switch
|
||||||
|
{
|
||||||
|
"Owner" => $"{Ansi.BrightYellow}[Owner]{Ansi.Reset}",
|
||||||
|
"Admin" => $"{Ansi.BrightMagenta}[Admin]{Ansi.Reset}",
|
||||||
|
_ => $"{Ansi.Gray}[Member]{Ansi.Reset}"
|
||||||
|
};
|
||||||
|
|
||||||
|
string prefix = isSelected ? $"{Ansi.BrightCyan}► " : " ";
|
||||||
|
string userDisplay = isSelected
|
||||||
|
? $"{Ansi.Inverse}@{u.Username}{Ansi.Reset}"
|
||||||
|
: $"@{u.Username}";
|
||||||
|
|
||||||
|
sb.AppendLine($"{prefix}{statusDot} {userDisplay} {roleBadge}");
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.AppendLine(new string('─', Math.Max(0, width)));
|
||||||
|
sb.AppendLine($" {Ansi.Gray}[↑/↓] Scroll Directory{Ansi.Reset}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task HandleKeyAsync(ConsoleKeyInfo key)
|
||||||
|
{
|
||||||
|
if (key.Key == ConsoleKey.UpArrow)
|
||||||
|
{
|
||||||
|
_selectedIndex = Math.Max(0, _selectedIndex - 1);
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.DownArrow)
|
||||||
|
{
|
||||||
|
_selectedIndex = Math.Min(_state.Users.Count - 1, _selectedIndex + 1);
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
126
src/GsDChat.Client/State/ClientState.cs
Normal file
126
src/GsDChat.Client/State/ClientState.cs
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
namespace GsDChat.Client.State;
|
||||||
|
|
||||||
|
public class ClientState
|
||||||
|
{
|
||||||
|
private readonly object _lock = new();
|
||||||
|
|
||||||
|
public string ServerUrl { get; set; } = "http://localhost:5000";
|
||||||
|
public string Token { get; set; } = string.Empty;
|
||||||
|
public string CurrentUserId { get; set; } = string.Empty;
|
||||||
|
public string CurrentUsername { get; set; } = string.Empty;
|
||||||
|
public string CurrentUserRole { get; set; } = UserRoles.Member;
|
||||||
|
|
||||||
|
public string ServerName { get; set; } = "GsDChat Server";
|
||||||
|
public string Motd { get; set; } = string.Empty;
|
||||||
|
public ServerUiSync UiSync { get; set; } = ServerUiSync.CreateDefault();
|
||||||
|
|
||||||
|
public string ActiveScreenId { get; set; } = "F1_Chat";
|
||||||
|
public string ActiveChannelId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public List<Channel> Channels { get; } = new();
|
||||||
|
public Dictionary<string, List<ChatMessage>> ChannelMessages { get; } = new();
|
||||||
|
public List<UserSummary> Users { get; } = new();
|
||||||
|
public List<FileSummary> Files { get; } = new();
|
||||||
|
public List<string> SystemNotices { get; } = new();
|
||||||
|
|
||||||
|
public int ChatScrollOffset { get; set; } = 0;
|
||||||
|
public string InputBuffer { get; set; } = string.Empty;
|
||||||
|
public bool NeedsRedraw { get; set; } = true;
|
||||||
|
public bool IsConnected { get; set; } = false;
|
||||||
|
public string StatusMessage { get; set; } = string.Empty;
|
||||||
|
public DateTime StatusMessageUntil { get; set; } = DateTime.MinValue;
|
||||||
|
|
||||||
|
public Channel? ActiveChannel
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return Channels.FirstOrDefault(c => c.Id == ActiveChannelId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetStatus(string message, int durationSeconds = 5)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
StatusMessage = message;
|
||||||
|
StatusMessageUntil = DateTime.UtcNow.AddSeconds(durationSeconds);
|
||||||
|
NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddNotice(string text)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
SystemNotices.Add($"[{DateTime.Now:HH:mm:ss}] {text}");
|
||||||
|
if (SystemNotices.Count > 100) SystemNotices.RemoveAt(0);
|
||||||
|
NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddChatMessage(ChatMessage message)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (!ChannelMessages.TryGetValue(message.ChannelId, out var list))
|
||||||
|
{
|
||||||
|
list = new List<ChatMessage>();
|
||||||
|
ChannelMessages[message.ChannelId] = list;
|
||||||
|
}
|
||||||
|
list.Add(message);
|
||||||
|
NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetHistory(string channelId, List<ChatMessage> messages)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
ChannelMessages[channelId] = messages;
|
||||||
|
NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void UpdateChannels(List<Channel> channels, string activeId)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
Channels.Clear();
|
||||||
|
Channels.AddRange(channels);
|
||||||
|
if (!string.IsNullOrEmpty(activeId))
|
||||||
|
{
|
||||||
|
ActiveChannelId = activeId;
|
||||||
|
}
|
||||||
|
NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void UpdateUsers(List<UserSummary> users)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
Users.Clear();
|
||||||
|
Users.AddRange(users);
|
||||||
|
NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void UpdateFiles(List<FileSummary> files)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
Files.Clear();
|
||||||
|
Files.AddRange(files);
|
||||||
|
NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
9
src/GsDChat.Core/GsDChat.Core.csproj
Normal file
9
src/GsDChat.Core/GsDChat.Core.csproj
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
13
src/GsDChat.Core/Models/Channel.cs
Normal file
13
src/GsDChat.Core/Models/Channel.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Models;
|
||||||
|
|
||||||
|
public class Channel
|
||||||
|
{
|
||||||
|
public string Id { get; set; } = Guid.NewGuid().ToString("N");
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string Topic { get; set; } = string.Empty;
|
||||||
|
public bool IsPrivate { get; set; } = false;
|
||||||
|
public string AllowedRoles { get; set; } = string.Empty; // Comma-separated or empty for public
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
}
|
||||||
17
src/GsDChat.Core/Models/ChatMessage.cs
Normal file
17
src/GsDChat.Core/Models/ChatMessage.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Models;
|
||||||
|
|
||||||
|
public class ChatMessage
|
||||||
|
{
|
||||||
|
public string Id { get; set; } = Guid.NewGuid().ToString("N");
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string SenderId { get; set; } = string.Empty;
|
||||||
|
public string SenderUsername { get; set; } = string.Empty;
|
||||||
|
public string SenderRole { get; set; } = UserRoles.Member;
|
||||||
|
public string Content { get; set; } = string.Empty;
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
public string? AttachmentId { get; set; }
|
||||||
|
public string? AttachmentName { get; set; }
|
||||||
|
public long? AttachmentSizeBytes { get; set; }
|
||||||
|
}
|
||||||
17
src/GsDChat.Core/Models/FileRecord.cs
Normal file
17
src/GsDChat.Core/Models/FileRecord.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Models;
|
||||||
|
|
||||||
|
public class FileRecord
|
||||||
|
{
|
||||||
|
public string Id { get; set; } = Guid.NewGuid().ToString("N");
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string UploaderId { get; set; } = string.Empty;
|
||||||
|
public string UploaderUsername { get; set; } = string.Empty;
|
||||||
|
public string OriginalFileName { get; set; } = string.Empty;
|
||||||
|
public string ContentType { get; set; } = "application/octet-stream";
|
||||||
|
public long FileSizeBytes { get; set; }
|
||||||
|
public string StoragePath { get; set; } = string.Empty;
|
||||||
|
public string Sha256Checksum { get; set; } = string.Empty;
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
}
|
||||||
13
src/GsDChat.Core/Models/Session.cs
Normal file
13
src/GsDChat.Core/Models/Session.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Models;
|
||||||
|
|
||||||
|
public class Session
|
||||||
|
{
|
||||||
|
public string Token { get; set; } = string.Empty;
|
||||||
|
public string UserId { get; set; } = string.Empty;
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
public DateTime ExpiresAt { get; set; } = DateTime.UtcNow.AddDays(30);
|
||||||
|
|
||||||
|
public bool IsExpired => DateTime.UtcNow > ExpiresAt;
|
||||||
|
}
|
||||||
21
src/GsDChat.Core/Models/User.cs
Normal file
21
src/GsDChat.Core/Models/User.cs
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Models;
|
||||||
|
|
||||||
|
public static class UserRoles
|
||||||
|
{
|
||||||
|
public const string Owner = "Owner";
|
||||||
|
public const string Admin = "Admin";
|
||||||
|
public const string Member = "Member";
|
||||||
|
}
|
||||||
|
|
||||||
|
public class User
|
||||||
|
{
|
||||||
|
public string Id { get; set; } = Guid.NewGuid().ToString("N");
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public string PasswordHash { get; set; } = string.Empty;
|
||||||
|
public string PasswordSalt { get; set; } = string.Empty;
|
||||||
|
public string Role { get; set; } = UserRoles.Member;
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
public bool IsBanned { get; set; } = false;
|
||||||
|
}
|
||||||
48
src/GsDChat.Core/Protocol/HttpModels.cs
Normal file
48
src/GsDChat.Core/Protocol/HttpModels.cs
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
public class RegisterRequest
|
||||||
|
{
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public string Password { get; set; } = string.Empty;
|
||||||
|
public string? ServerPassword { get; set; }
|
||||||
|
public string? InviteToken { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class LoginRequest
|
||||||
|
{
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public string Password { get; set; } = string.Empty;
|
||||||
|
public string? ServerPassword { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AuthResponse
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string? Token { get; set; }
|
||||||
|
public string? UserId { get; set; }
|
||||||
|
public string? Username { get; set; }
|
||||||
|
public string? Role { get; set; }
|
||||||
|
public string? ErrorMessage { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ServerInfoResponse
|
||||||
|
{
|
||||||
|
public string ServerName { get; set; } = "GsDChat Server";
|
||||||
|
public string Version { get; set; } = "1.0.0";
|
||||||
|
public string RegistrationMode { get; set; } = "Open"; // Open or InviteOnly
|
||||||
|
public bool RequiresServerPassword { get; set; }
|
||||||
|
public string Motd { get; set; } = "Welcome to GsDChat!";
|
||||||
|
public long MaxFileSizeMb { get; set; } = 50;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UploadFileResponse
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string? FileId { get; set; }
|
||||||
|
public string? FileName { get; set; }
|
||||||
|
public long FileSizeBytes { get; set; }
|
||||||
|
public string? ChannelId { get; set; }
|
||||||
|
public string? ErrorMessage { get; set; }
|
||||||
|
}
|
||||||
157
src/GsDChat.Core/Protocol/NetworkMessages.cs
Normal file
157
src/GsDChat.Core/Protocol/NetworkMessages.cs
Normal file
|
|
@ -0,0 +1,157 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text.Json;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
public static class MessageTypes
|
||||||
|
{
|
||||||
|
public const string Auth = "AUTH";
|
||||||
|
public const string AuthResult = "AUTH_RESULT";
|
||||||
|
public const string UiSync = "UI_SYNC";
|
||||||
|
public const string SendMessage = "SEND_MESSAGE";
|
||||||
|
public const string MessageBroadcast = "MESSAGE_BROADCAST";
|
||||||
|
public const string HistorySync = "HISTORY_SYNC";
|
||||||
|
public const string JoinChannel = "JOIN_CHANNEL";
|
||||||
|
public const string ChannelListSync = "CHANNEL_LIST_SYNC";
|
||||||
|
public const string CreateChannel = "CREATE_CHANNEL";
|
||||||
|
public const string DeleteChannel = "DELETE_CHANNEL";
|
||||||
|
public const string UserListSync = "USER_LIST_SYNC";
|
||||||
|
public const string FileListSync = "FILE_LIST_SYNC";
|
||||||
|
public const string SystemNotice = "SYSTEM_NOTICE";
|
||||||
|
public const string Error = "ERROR";
|
||||||
|
public const string ExecuteCommand = "EXECUTE_COMMAND";
|
||||||
|
public const string CommandResult = "COMMAND_RESULT";
|
||||||
|
public const string Ping = "PING";
|
||||||
|
public const string Pong = "PONG";
|
||||||
|
}
|
||||||
|
|
||||||
|
public class NetworkEnvelope
|
||||||
|
{
|
||||||
|
public string Type { get; set; } = string.Empty;
|
||||||
|
public string Payload { get; set; } = "{}";
|
||||||
|
|
||||||
|
public static NetworkEnvelope Create<T>(string type, T payload)
|
||||||
|
{
|
||||||
|
return new NetworkEnvelope
|
||||||
|
{
|
||||||
|
Type = type,
|
||||||
|
Payload = JsonSerializer.Serialize(payload)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public T? Unpack<T>()
|
||||||
|
{
|
||||||
|
return JsonSerializer.Deserialize<T>(Payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AuthPacket
|
||||||
|
{
|
||||||
|
public string Token { get; set; } = string.Empty;
|
||||||
|
public string? ServerPassword { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AuthResultPacket
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string UserId { get; set; } = string.Empty;
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public string Role { get; set; } = UserRoles.Member;
|
||||||
|
public string? ErrorMessage { get; set; }
|
||||||
|
public ServerUiSync? UiSync { get; set; }
|
||||||
|
public string? ActiveChannelId { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class SendMessagePacket
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string Content { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class MessageBroadcastPacket
|
||||||
|
{
|
||||||
|
public ChatMessage Message { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class HistorySyncPacket
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public List<ChatMessage> Messages { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class JoinChannelPacket
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ChannelListSyncPacket
|
||||||
|
{
|
||||||
|
public List<Channel> Channels { get; set; } = new();
|
||||||
|
public string ActiveChannelId { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class CreateChannelPacket
|
||||||
|
{
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string Topic { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class DeleteChannelPacket
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UserSummary
|
||||||
|
{
|
||||||
|
public string Id { get; set; } = string.Empty;
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public string Role { get; set; } = UserRoles.Member;
|
||||||
|
public bool IsOnline { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UserListSyncPacket
|
||||||
|
{
|
||||||
|
public List<UserSummary> Users { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class FileSummary
|
||||||
|
{
|
||||||
|
public string Id { get; set; } = string.Empty;
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string OriginalFileName { get; set; } = string.Empty;
|
||||||
|
public string ContentType { get; set; } = string.Empty;
|
||||||
|
public long FileSizeBytes { get; set; }
|
||||||
|
public string UploaderUsername { get; set; } = string.Empty;
|
||||||
|
public System.DateTime CreatedAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class FileListSyncPacket
|
||||||
|
{
|
||||||
|
public List<FileSummary> Files { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class SystemNoticePacket
|
||||||
|
{
|
||||||
|
public string Text { get; set; } = string.Empty;
|
||||||
|
public string Level { get; set; } = "Info"; // Info, Warning, Success
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ErrorPacket
|
||||||
|
{
|
||||||
|
public string Message { get; set; } = string.Empty;
|
||||||
|
public string? Code { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ExecuteCommandPacket
|
||||||
|
{
|
||||||
|
public string Command { get; set; } = string.Empty;
|
||||||
|
public string Args { get; set; } = string.Empty;
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class CommandResultPacket
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string Output { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
108
src/GsDChat.Core/Protocol/UiProtocol.cs
Normal file
108
src/GsDChat.Core/Protocol/UiProtocol.cs
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
public class PanelDefinition
|
||||||
|
{
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string Position { get; set; } = "Center"; // Top, Center, Bottom, Left, Right
|
||||||
|
public int? Height { get; set; }
|
||||||
|
public int? Width { get; set; }
|
||||||
|
public bool ShowBorder { get; set; } = true;
|
||||||
|
public string? BorderTitle { get; set; }
|
||||||
|
public string? ContentTemplate { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ScreenDefinition
|
||||||
|
{
|
||||||
|
public string ScreenId { get; set; } = string.Empty;
|
||||||
|
public string Title { get; set; } = string.Empty;
|
||||||
|
public string ShortcutKey { get; set; } = string.Empty; // e.g. F1, F2, F3, F4, F5
|
||||||
|
public string Description { get; set; } = string.Empty;
|
||||||
|
public List<PanelDefinition> Panels { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ThemeDefinition
|
||||||
|
{
|
||||||
|
public string PrimaryColor { get; set; } = "Cyan";
|
||||||
|
public string SecondaryColor { get; set; } = "DarkCyan";
|
||||||
|
public string BorderColor { get; set; } = "DarkGray";
|
||||||
|
public string HighlightColor { get; set; } = "Yellow";
|
||||||
|
public string ErrorColor { get; set; } = "Red";
|
||||||
|
public string SuccessColor { get; set; } = "Green";
|
||||||
|
public string TextMutedColor { get; set; } = "Gray";
|
||||||
|
public string SystemNoticeColor { get; set; } = "Magenta";
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ServerUiSync
|
||||||
|
{
|
||||||
|
public string ServerName { get; set; } = "GsDChat Server";
|
||||||
|
public string Motd { get; set; } = "Welcome to GsDChat!";
|
||||||
|
public ThemeDefinition Theme { get; set; } = new();
|
||||||
|
public List<ScreenDefinition> Screens { get; set; } = new();
|
||||||
|
|
||||||
|
public static ServerUiSync CreateDefault(string serverName = "GsDChat Server", string motd = "Welcome to GsDChat!")
|
||||||
|
{
|
||||||
|
return new ServerUiSync
|
||||||
|
{
|
||||||
|
ServerName = serverName,
|
||||||
|
Motd = motd,
|
||||||
|
Theme = new ThemeDefinition(),
|
||||||
|
Screens = new List<ScreenDefinition>
|
||||||
|
{
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
ScreenId = "F1_Chat",
|
||||||
|
Title = "Chat",
|
||||||
|
ShortcutKey = "F1",
|
||||||
|
Description = "Active Channel Chat View",
|
||||||
|
Panels = new List<PanelDefinition>
|
||||||
|
{
|
||||||
|
new() { Name = "Header", Position = "Top", Height = 3, ShowBorder = true, BorderTitle = "Channel Info" },
|
||||||
|
new() { Name = "Messages", Position = "Center", ShowBorder = true, BorderTitle = "Messages" },
|
||||||
|
new() { Name = "Input", Position = "Bottom", Height = 3, ShowBorder = true, BorderTitle = "Message Input" }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
ScreenId = "F2_Channels",
|
||||||
|
Title = "Channels",
|
||||||
|
ShortcutKey = "F2",
|
||||||
|
Description = "Browse and switch chat channels",
|
||||||
|
Panels = new List<PanelDefinition>
|
||||||
|
{
|
||||||
|
new() { Name = "Header", Position = "Top", Height = 3, ShowBorder = true, BorderTitle = "Channels Browser" },
|
||||||
|
new() { Name = "ChannelList", Position = "Center", ShowBorder = true, BorderTitle = "Available Channels" },
|
||||||
|
new() { Name = "Help", Position = "Bottom", Height = 3, ShowBorder = true, BorderTitle = "Navigation" }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
ScreenId = "F3_Users",
|
||||||
|
Title = "Users",
|
||||||
|
ShortcutKey = "F3",
|
||||||
|
Description = "User directory and online presence",
|
||||||
|
Panels = new List<PanelDefinition>
|
||||||
|
{
|
||||||
|
new() { Name = "Header", Position = "Top", Height = 3, ShowBorder = true, BorderTitle = "Community Members" },
|
||||||
|
new() { Name = "UserList", Position = "Center", ShowBorder = true, BorderTitle = "Members Directory" },
|
||||||
|
new() { Name = "Help", Position = "Bottom", Height = 3, ShowBorder = true, BorderTitle = "Commands" }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
ScreenId = "F4_Files",
|
||||||
|
Title = "Files",
|
||||||
|
ShortcutKey = "F4",
|
||||||
|
Description = "Shared files and download browser",
|
||||||
|
Panels = new List<PanelDefinition>
|
||||||
|
{
|
||||||
|
new() { Name = "Header", Position = "Top", Height = 3, ShowBorder = true, BorderTitle = "Shared Files" },
|
||||||
|
new() { Name = "FileList", Position = "Center", ShowBorder = true, BorderTitle = "Available Files" },
|
||||||
|
new() { Name = "Actions", Position = "Bottom", Height = 3, ShowBorder = true, BorderTitle = "Transfer Commands" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
57
src/GsDChat.Core/Security/PasswordHasher.cs
Normal file
57
src/GsDChat.Core/Security/PasswordHasher.cs
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
using System;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Security;
|
||||||
|
|
||||||
|
public static class PasswordHasher
|
||||||
|
{
|
||||||
|
private const int SaltByteLength = 32;
|
||||||
|
private const int HashByteLength = 64; // SHA512 produces 64 bytes
|
||||||
|
private const int Iterations = 100_000;
|
||||||
|
|
||||||
|
public static (string Hash, string Salt) HashPassword(string password)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(password);
|
||||||
|
|
||||||
|
byte[] salt = RandomNumberGenerator.GetBytes(SaltByteLength);
|
||||||
|
byte[] hash = Rfc2898DeriveBytes.Pbkdf2(
|
||||||
|
password,
|
||||||
|
salt,
|
||||||
|
Iterations,
|
||||||
|
HashAlgorithmName.SHA512,
|
||||||
|
HashByteLength
|
||||||
|
);
|
||||||
|
|
||||||
|
return (Convert.ToHexString(hash), Convert.ToHexString(salt));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool VerifyPassword(string password, string storedHashHex, string storedSaltHex)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(password) ||
|
||||||
|
string.IsNullOrWhiteSpace(storedHashHex) ||
|
||||||
|
string.IsNullOrWhiteSpace(storedSaltHex))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
byte[] salt = Convert.FromHexString(storedSaltHex);
|
||||||
|
byte[] expectedHash = Convert.FromHexString(storedHashHex);
|
||||||
|
|
||||||
|
byte[] actualHash = Rfc2898DeriveBytes.Pbkdf2(
|
||||||
|
password,
|
||||||
|
salt,
|
||||||
|
Iterations,
|
||||||
|
HashAlgorithmName.SHA512,
|
||||||
|
expectedHash.Length
|
||||||
|
);
|
||||||
|
|
||||||
|
return CryptographicOperations.FixedTimeEquals(actualHash, expectedHash);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/GsDChat.Core/Security/TokenGenerator.cs
Normal file
13
src/GsDChat.Core/Security/TokenGenerator.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
using System;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
|
||||||
|
namespace GsDChat.Core.Security;
|
||||||
|
|
||||||
|
public static class TokenGenerator
|
||||||
|
{
|
||||||
|
public static string GenerateSecureToken(int byteLength = 32)
|
||||||
|
{
|
||||||
|
byte[] bytes = RandomNumberGenerator.GetBytes(byteLength);
|
||||||
|
return Convert.ToHexString(bytes).ToLowerInvariant();
|
||||||
|
}
|
||||||
|
}
|
||||||
32
src/GsDChat.Modding/CommandRegistry.cs
Normal file
32
src/GsDChat.Modding/CommandRegistry.cs
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public class CommandRegistry : ICommandRegistry
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<string, (string Description, Func<CommandContext, Task<CommandResult>> Handler)> _commands = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
public void RegisterCommand(string name, string description, Func<CommandContext, Task<CommandResult>> handler)
|
||||||
|
{
|
||||||
|
string clean = name.TrimStart('/').ToLowerInvariant();
|
||||||
|
_commands[clean] = (description, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<CommandResult?> ExecuteCommandAsync(CommandContext context)
|
||||||
|
{
|
||||||
|
string clean = context.Command.TrimStart('/').ToLowerInvariant();
|
||||||
|
if (_commands.TryGetValue(clean, out var entry))
|
||||||
|
{
|
||||||
|
return await entry.Handler(context);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool HasCommand(string name)
|
||||||
|
{
|
||||||
|
string clean = name.TrimStart('/').ToLowerInvariant();
|
||||||
|
return _commands.ContainsKey(clean);
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/GsDChat.Modding/GsDChat.Modding.csproj
Normal file
13
src/GsDChat.Modding/GsDChat.Modding.csproj
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\GsDChat.Core\GsDChat.Core.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
30
src/GsDChat.Modding/ICommandRegistry.cs
Normal file
30
src/GsDChat.Modding/ICommandRegistry.cs
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public class CommandContext
|
||||||
|
{
|
||||||
|
public string Command { get; set; } = string.Empty;
|
||||||
|
public string Args { get; set; } = string.Empty;
|
||||||
|
public string UserId { get; set; } = string.Empty;
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public string UserRole { get; set; } = string.Empty;
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class CommandResult
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string Output { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public static CommandResult Ok(string output) => new() { Success = true, Output = output };
|
||||||
|
public static CommandResult Fail(string error) => new() { Success = false, Output = error };
|
||||||
|
}
|
||||||
|
|
||||||
|
public interface ICommandRegistry
|
||||||
|
{
|
||||||
|
void RegisterCommand(string name, string description, Func<CommandContext, Task<CommandResult>> handler);
|
||||||
|
Task<CommandResult?> ExecuteCommandAsync(CommandContext context);
|
||||||
|
bool HasCommand(string name);
|
||||||
|
}
|
||||||
23
src/GsDChat.Modding/IMessagePipeline.cs
Normal file
23
src/GsDChat.Modding/IMessagePipeline.cs
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public class MessagePipelineContext
|
||||||
|
{
|
||||||
|
public ChatMessage Message { get; set; }
|
||||||
|
public bool IsCancelled { get; set; } = false;
|
||||||
|
public string? CancellationReason { get; set; }
|
||||||
|
|
||||||
|
public MessagePipelineContext(ChatMessage message)
|
||||||
|
{
|
||||||
|
Message = message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public interface IMessagePipeline
|
||||||
|
{
|
||||||
|
void Use(Func<MessagePipelineContext, Func<Task>, Task> middleware);
|
||||||
|
Task<MessagePipelineContext> ExecuteAsync(ChatMessage message);
|
||||||
|
}
|
||||||
14
src/GsDChat.Modding/IMod.cs
Normal file
14
src/GsDChat.Modding/IMod.cs
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public interface IMod
|
||||||
|
{
|
||||||
|
string Id { get; }
|
||||||
|
string Name { get; }
|
||||||
|
string Version { get; }
|
||||||
|
string Description { get; }
|
||||||
|
|
||||||
|
Task InitializeAsync(IModContext context);
|
||||||
|
Task ShutdownAsync();
|
||||||
|
}
|
||||||
16
src/GsDChat.Modding/IModContext.cs
Normal file
16
src/GsDChat.Modding/IModContext.cs
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public interface IModContext
|
||||||
|
{
|
||||||
|
IModEventBus Events { get; }
|
||||||
|
ICommandRegistry Commands { get; }
|
||||||
|
IMessagePipeline Pipeline { get; }
|
||||||
|
IUiRegistry Ui { get; }
|
||||||
|
string ModDataDirectory { get; }
|
||||||
|
|
||||||
|
void LogInfo(string message);
|
||||||
|
void LogWarning(string message);
|
||||||
|
void LogError(string message, Exception? ex = null);
|
||||||
|
}
|
||||||
18
src/GsDChat.Modding/IModEventBus.cs
Normal file
18
src/GsDChat.Modding/IModEventBus.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public interface IModEventBus
|
||||||
|
{
|
||||||
|
void SubscribeUserConnected(Func<User, Task> handler);
|
||||||
|
void SubscribeUserDisconnected(Func<User, Task> handler);
|
||||||
|
void SubscribeChannelCreated(Func<Channel, Task> handler);
|
||||||
|
void SubscribeFileUploaded(Func<FileRecord, Task> handler);
|
||||||
|
|
||||||
|
Task PublishUserConnectedAsync(User user);
|
||||||
|
Task PublishUserDisconnectedAsync(User user);
|
||||||
|
Task PublishChannelCreatedAsync(Channel channel);
|
||||||
|
Task PublishFileUploadedAsync(FileRecord file);
|
||||||
|
}
|
||||||
11
src/GsDChat.Modding/IUiRegistry.cs
Normal file
11
src/GsDChat.Modding/IUiRegistry.cs
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public interface IUiRegistry
|
||||||
|
{
|
||||||
|
void RegisterScreen(ScreenDefinition screen);
|
||||||
|
void SetMotd(string motd);
|
||||||
|
void SetTheme(ThemeDefinition theme);
|
||||||
|
ServerUiSync GetUiSync();
|
||||||
|
}
|
||||||
34
src/GsDChat.Modding/MessagePipeline.cs
Normal file
34
src/GsDChat.Modding/MessagePipeline.cs
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public class MessagePipeline : IMessagePipeline
|
||||||
|
{
|
||||||
|
private readonly List<Func<MessagePipelineContext, Func<Task>, Task>> _middlewares = new();
|
||||||
|
|
||||||
|
public void Use(Func<MessagePipelineContext, Func<Task>, Task> middleware)
|
||||||
|
{
|
||||||
|
_middlewares.Add(middleware);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<MessagePipelineContext> ExecuteAsync(ChatMessage message)
|
||||||
|
{
|
||||||
|
var context = new MessagePipelineContext(message);
|
||||||
|
|
||||||
|
int index = 0;
|
||||||
|
async Task Next()
|
||||||
|
{
|
||||||
|
if (index < _middlewares.Count && !context.IsCancelled)
|
||||||
|
{
|
||||||
|
var current = _middlewares[index++];
|
||||||
|
await current(context, Next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await Next();
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
}
|
||||||
32
src/GsDChat.Modding/ModContext.cs
Normal file
32
src/GsDChat.Modding/ModContext.cs
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public class ModContext : IModContext
|
||||||
|
{
|
||||||
|
public IModEventBus Events { get; }
|
||||||
|
public ICommandRegistry Commands { get; }
|
||||||
|
public IMessagePipeline Pipeline { get; }
|
||||||
|
public IUiRegistry Ui { get; }
|
||||||
|
public string ModDataDirectory { get; }
|
||||||
|
|
||||||
|
public ModContext(
|
||||||
|
IModEventBus events,
|
||||||
|
ICommandRegistry commands,
|
||||||
|
IMessagePipeline pipeline,
|
||||||
|
IUiRegistry ui,
|
||||||
|
string modDataDirectory)
|
||||||
|
{
|
||||||
|
Events = events;
|
||||||
|
Commands = commands;
|
||||||
|
Pipeline = pipeline;
|
||||||
|
Ui = ui;
|
||||||
|
ModDataDirectory = modDataDirectory;
|
||||||
|
Directory.CreateDirectory(modDataDirectory);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void LogInfo(string message) => Console.WriteLine($"[Mod INFO] {message}");
|
||||||
|
public void LogWarning(string message) => Console.WriteLine($"[Mod WARN] {message}");
|
||||||
|
public void LogError(string message, Exception? ex = null) => Console.WriteLine($"[Mod ERROR] {message} {ex?.Message}");
|
||||||
|
}
|
||||||
51
src/GsDChat.Modding/ModEventBus.cs
Normal file
51
src/GsDChat.Modding/ModEventBus.cs
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public class ModEventBus : IModEventBus
|
||||||
|
{
|
||||||
|
private readonly List<Func<User, Task>> _userConnectedHandlers = new();
|
||||||
|
private readonly List<Func<User, Task>> _userDisconnectedHandlers = new();
|
||||||
|
private readonly List<Func<Channel, Task>> _channelCreatedHandlers = new();
|
||||||
|
private readonly List<Func<FileRecord, Task>> _fileUploadedHandlers = new();
|
||||||
|
|
||||||
|
public void SubscribeUserConnected(Func<User, Task> handler) => _userConnectedHandlers.Add(handler);
|
||||||
|
public void SubscribeUserDisconnected(Func<User, Task> handler) => _userDisconnectedHandlers.Add(handler);
|
||||||
|
public void SubscribeChannelCreated(Func<Channel, Task> handler) => _channelCreatedHandlers.Add(handler);
|
||||||
|
public void SubscribeFileUploaded(Func<FileRecord, Task> handler) => _fileUploadedHandlers.Add(handler);
|
||||||
|
|
||||||
|
public async Task PublishUserConnectedAsync(User user)
|
||||||
|
{
|
||||||
|
foreach (var h in _userConnectedHandlers)
|
||||||
|
{
|
||||||
|
try { await h(user); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task PublishUserDisconnectedAsync(User user)
|
||||||
|
{
|
||||||
|
foreach (var h in _userDisconnectedHandlers)
|
||||||
|
{
|
||||||
|
try { await h(user); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task PublishChannelCreatedAsync(Channel channel)
|
||||||
|
{
|
||||||
|
foreach (var h in _channelCreatedHandlers)
|
||||||
|
{
|
||||||
|
try { await h(channel); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task PublishFileUploadedAsync(FileRecord file)
|
||||||
|
{
|
||||||
|
foreach (var h in _fileUploadedHandlers)
|
||||||
|
{
|
||||||
|
try { await h(file); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
40
src/GsDChat.Modding/UiRegistry.cs
Normal file
40
src/GsDChat.Modding/UiRegistry.cs
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
namespace GsDChat.Modding;
|
||||||
|
|
||||||
|
public class UiRegistry : IUiRegistry
|
||||||
|
{
|
||||||
|
private readonly ServerUiSync _sync;
|
||||||
|
|
||||||
|
public UiRegistry(string serverName, string defaultMotd)
|
||||||
|
{
|
||||||
|
_sync = ServerUiSync.CreateDefault(serverName, defaultMotd);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RegisterScreen(ScreenDefinition screen)
|
||||||
|
{
|
||||||
|
// Replace if exists, or append
|
||||||
|
int existingIndex = _sync.Screens.FindIndex(s => s.ScreenId == screen.ScreenId);
|
||||||
|
if (existingIndex >= 0)
|
||||||
|
{
|
||||||
|
_sync.Screens[existingIndex] = screen;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_sync.Screens.Add(screen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetMotd(string motd)
|
||||||
|
{
|
||||||
|
_sync.Motd = motd;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetTheme(ThemeDefinition theme)
|
||||||
|
{
|
||||||
|
_sync.Theme = theme;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ServerUiSync GetUiSync() => _sync;
|
||||||
|
}
|
||||||
17
src/GsDChat.Mods.SampleBot/GsDChat.Mods.SampleBot.csproj
Normal file
17
src/GsDChat.Mods.SampleBot/GsDChat.Mods.SampleBot.csproj
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\GsDChat.Modding\GsDChat.Modding.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<Target Name="CopyModToServer" AfterTargets="Build">
|
||||||
|
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(MSBuildThisFileDirectory)../GsDChat.Server/mods" SkipUnchangedFiles="true" />
|
||||||
|
</Target>
|
||||||
|
|
||||||
|
</Project>
|
||||||
134
src/GsDChat.Mods.SampleBot/SampleBotMod.cs
Normal file
134
src/GsDChat.Mods.SampleBot/SampleBotMod.cs
Normal file
|
|
@ -0,0 +1,134 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
using GsDChat.Modding;
|
||||||
|
|
||||||
|
namespace GsDChat.Mods.SampleBot;
|
||||||
|
|
||||||
|
public class SampleBotMod : IMod
|
||||||
|
{
|
||||||
|
public string Id => "gsdchat.mods.samplebot";
|
||||||
|
public string Name => "Sample Bot & Utilities Mod";
|
||||||
|
public string Version => "1.0.0";
|
||||||
|
public string Description => "Reference mod featuring /roll, /announce, emoji transformation, and custom F5 UI screen.";
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, string> Replacements = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
{ ":shrug:", "¯\\_(ツ)_/¯" },
|
||||||
|
{ ":tableflip:", "(╯°□°)╯︵ ┻━┻" },
|
||||||
|
{ ":heart:", "❤️" },
|
||||||
|
{ ":fire:", "🔥" },
|
||||||
|
{ ":check:", "✅" }
|
||||||
|
};
|
||||||
|
|
||||||
|
public Task InitializeAsync(IModContext context)
|
||||||
|
{
|
||||||
|
context.LogInfo($"{Name} initializing...");
|
||||||
|
|
||||||
|
// 1. Register /roll command
|
||||||
|
context.Commands.RegisterCommand("roll", "Roll dice in format NdM (e.g. 2d6, 1d20, or /roll)", async cmdCtx =>
|
||||||
|
{
|
||||||
|
string arg = string.IsNullOrWhiteSpace(cmdCtx.Args) ? "1d6" : cmdCtx.Args.Trim().ToLowerInvariant();
|
||||||
|
var match = Regex.Match(arg, @"^(\d+)?d?(\d+)$");
|
||||||
|
|
||||||
|
if (!match.Success)
|
||||||
|
{
|
||||||
|
return CommandResult.Fail("Invalid dice format. Examples: /roll, /roll 20, /roll 2d6, /roll 3d10");
|
||||||
|
}
|
||||||
|
|
||||||
|
int count = string.IsNullOrEmpty(match.Groups[1].Value) ? 1 : int.Parse(match.Groups[1].Value);
|
||||||
|
int sides = int.Parse(match.Groups[2].Value);
|
||||||
|
|
||||||
|
if (count < 1 || count > 50 || sides < 2 || sides > 1000)
|
||||||
|
{
|
||||||
|
return CommandResult.Fail("Dice count must be 1-50, sides must be 2-1000.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var rolls = new List<int>();
|
||||||
|
int sum = 0;
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
int val = Random.Shared.Next(1, sides + 1);
|
||||||
|
rolls.Add(val);
|
||||||
|
sum += val;
|
||||||
|
}
|
||||||
|
|
||||||
|
string rollsStr = count == 1 ? rolls[0].ToString() : $"[{string.Join(", ", rolls)}] = Total: {sum}";
|
||||||
|
string result = $"🎲 @{cmdCtx.Username} rolled {count}d{sides}: {rollsStr}";
|
||||||
|
return CommandResult.Ok(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. Register /announce command
|
||||||
|
context.Commands.RegisterCommand("announce", "Broadcast an official announcement (Admin only)", async cmdCtx =>
|
||||||
|
{
|
||||||
|
if (cmdCtx.UserRole != UserRoles.Owner && cmdCtx.UserRole != UserRoles.Admin)
|
||||||
|
{
|
||||||
|
return CommandResult.Fail("Only Admins and Owners can use /announce.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(cmdCtx.Args))
|
||||||
|
{
|
||||||
|
return CommandResult.Fail("Usage: /announce <announcement_message>");
|
||||||
|
}
|
||||||
|
|
||||||
|
string banner = $"\n╔══════════════════════════════════════════════════════╗\n" +
|
||||||
|
$"║ 📢 OFFICIAL ANNOUNCEMENT by @{cmdCtx.Username}\n" +
|
||||||
|
$"╠══════════════════════════════════════════════════════╣\n" +
|
||||||
|
$"║ {cmdCtx.Args}\n" +
|
||||||
|
$"╚══════════════════════════════════════════════════════╝";
|
||||||
|
|
||||||
|
return CommandResult.Ok(banner);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 3. Register Message Pipeline Middleware (Transform text shortcuts)
|
||||||
|
context.Pipeline.Use(async (msgCtx, next) =>
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrEmpty(msgCtx.Message.Content))
|
||||||
|
{
|
||||||
|
string text = msgCtx.Message.Content;
|
||||||
|
foreach (var (shortcut, replacement) in Replacements)
|
||||||
|
{
|
||||||
|
if (text.Contains(shortcut, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
text = Regex.Replace(text, Regex.Escape(shortcut), replacement, RegexOptions.IgnoreCase);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
msgCtx.Message.Content = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 4. Register Custom F5 UI Screen
|
||||||
|
context.Ui.RegisterScreen(new ScreenDefinition
|
||||||
|
{
|
||||||
|
ScreenId = "F5_Custom",
|
||||||
|
Title = "Server Status",
|
||||||
|
ShortcutKey = "F5",
|
||||||
|
Description = "Custom Mod Widget & Server Health",
|
||||||
|
Panels = new List<PanelDefinition>
|
||||||
|
{
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
Name = "SampleBotPanel",
|
||||||
|
Position = "Center",
|
||||||
|
ShowBorder = true,
|
||||||
|
BorderTitle = "SampleBot Status",
|
||||||
|
ContentTemplate = "Mod Active: SampleBot v1.0.0 | Commands: /roll, /announce | Emojis: :shrug:, :tableflip:, :heart:, :fire:"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
context.LogInfo($"{Name} initialized successfully!");
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task ShutdownAsync()
|
||||||
|
{
|
||||||
|
Console.WriteLine($"[SampleBot] Shutting down {Name}...");
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
16
src/GsDChat.Server/Configuration/ServerOptions.cs
Normal file
16
src/GsDChat.Server/Configuration/ServerOptions.cs
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
namespace GsDChat.Server.Configuration;
|
||||||
|
|
||||||
|
public class ServerOptions
|
||||||
|
{
|
||||||
|
public string Host { get; set; } = "0.0.0.0";
|
||||||
|
public int Port { get; set; } = 5000;
|
||||||
|
public bool UseTls { get; set; } = false;
|
||||||
|
public string? CertificatePath { get; set; }
|
||||||
|
public string? CertificatePassword { get; set; }
|
||||||
|
public string? ServerWidePassword { get; set; }
|
||||||
|
public string RegistrationMode { get; set; } = "Open"; // Open or InviteOnly
|
||||||
|
public string DataDirectory { get; set; } = "data";
|
||||||
|
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.";
|
||||||
|
}
|
||||||
574
src/GsDChat.Server/Data/ChatDatabase.cs
Normal file
574
src/GsDChat.Server/Data/ChatDatabase.cs
Normal file
|
|
@ -0,0 +1,574 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Data;
|
||||||
|
|
||||||
|
public class ChatDatabase : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _connectionString;
|
||||||
|
private readonly string _dbPath;
|
||||||
|
|
||||||
|
public ChatDatabase(string dataDirectory)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(dataDirectory);
|
||||||
|
_dbPath = Path.Combine(dataDirectory, "chat.db");
|
||||||
|
_connectionString = $"Data Source={_dbPath};Cache=Shared";
|
||||||
|
}
|
||||||
|
|
||||||
|
private SqliteConnection CreateConnection()
|
||||||
|
{
|
||||||
|
var conn = new SqliteConnection(_connectionString);
|
||||||
|
conn.Open();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;";
|
||||||
|
cmd.ExecuteNonQuery();
|
||||||
|
return conn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
|
||||||
|
var sql = """
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
password_salt TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
is_banned INTEGER NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS channels (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||||
|
topic TEXT NOT NULL,
|
||||||
|
is_private INTEGER NOT NULL DEFAULT 0,
|
||||||
|
allowed_roles TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
channel_id TEXT NOT NULL,
|
||||||
|
sender_id TEXT NOT NULL,
|
||||||
|
sender_username TEXT NOT NULL,
|
||||||
|
sender_role TEXT NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
attachment_id TEXT,
|
||||||
|
attachment_name TEXT,
|
||||||
|
attachment_size INTEGER,
|
||||||
|
FOREIGN KEY (channel_id) REFERENCES channels (id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_channel_created
|
||||||
|
ON messages(channel_id, created_at);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS files (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
channel_id TEXT NOT NULL,
|
||||||
|
uploader_id TEXT NOT NULL,
|
||||||
|
uploader_username TEXT NOT NULL,
|
||||||
|
original_name TEXT NOT NULL,
|
||||||
|
content_type TEXT NOT NULL,
|
||||||
|
size_bytes INTEGER NOT NULL,
|
||||||
|
storage_path TEXT NOT NULL,
|
||||||
|
sha256 TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_files_created ON files(created_at);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
token TEXT PRIMARY KEY,
|
||||||
|
user_id TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
expires_at TEXT NOT NULL,
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS server_settings (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
""";
|
||||||
|
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = sql;
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
|
||||||
|
// Seed default channels if none exist
|
||||||
|
var channelsCountCmd = conn.CreateCommand();
|
||||||
|
channelsCountCmd.CommandText = "SELECT COUNT(*) FROM channels;";
|
||||||
|
long count = (long)(await channelsCountCmd.ExecuteScalarAsync() ?? 0L);
|
||||||
|
|
||||||
|
if (count == 0)
|
||||||
|
{
|
||||||
|
await CreateChannelInternalAsync(conn, new Channel
|
||||||
|
{
|
||||||
|
Name = "general",
|
||||||
|
Topic = "General discussion and chat",
|
||||||
|
IsPrivate = false,
|
||||||
|
AllowedRoles = string.Empty
|
||||||
|
});
|
||||||
|
|
||||||
|
await CreateChannelInternalAsync(conn, new Channel
|
||||||
|
{
|
||||||
|
Name = "announcements",
|
||||||
|
Topic = "Official server announcements and news",
|
||||||
|
IsPrivate = false,
|
||||||
|
AllowedRoles = string.Empty
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<bool> CreateChannelInternalAsync(SqliteConnection conn, Channel channel)
|
||||||
|
{
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
INSERT INTO channels (id, name, topic, is_private, allowed_roles, created_at)
|
||||||
|
VALUES (@id, @name, @topic, @is_private, @allowed_roles, @created_at);
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@id", channel.Id);
|
||||||
|
cmd.Parameters.AddWithValue("@name", channel.Name);
|
||||||
|
cmd.Parameters.AddWithValue("@topic", channel.Topic);
|
||||||
|
cmd.Parameters.AddWithValue("@is_private", channel.IsPrivate ? 1 : 0);
|
||||||
|
cmd.Parameters.AddWithValue("@allowed_roles", channel.AllowedRoles);
|
||||||
|
cmd.Parameters.AddWithValue("@created_at", channel.CreatedAt.ToString("O"));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||||
|
}
|
||||||
|
catch (SqliteException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#region User Operations
|
||||||
|
|
||||||
|
public async Task<int> GetUserCountAsync()
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "SELECT COUNT(*) FROM users;";
|
||||||
|
var result = await cmd.ExecuteScalarAsync();
|
||||||
|
return Convert.ToInt32(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> CreateUserAsync(User user)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
INSERT INTO users (id, username, password_hash, password_salt, role, created_at, is_banned)
|
||||||
|
VALUES (@id, @username, @hash, @salt, @role, @created_at, @is_banned);
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@id", user.Id);
|
||||||
|
cmd.Parameters.AddWithValue("@username", user.Username);
|
||||||
|
cmd.Parameters.AddWithValue("@hash", user.PasswordHash);
|
||||||
|
cmd.Parameters.AddWithValue("@salt", user.PasswordSalt);
|
||||||
|
cmd.Parameters.AddWithValue("@role", user.Role);
|
||||||
|
cmd.Parameters.AddWithValue("@created_at", user.CreatedAt.ToString("O"));
|
||||||
|
cmd.Parameters.AddWithValue("@is_banned", user.IsBanned ? 1 : 0);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||||
|
}
|
||||||
|
catch (SqliteException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<User?> GetUserByUsernameAsync(string username)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "SELECT id, username, password_hash, password_salt, role, created_at, is_banned FROM users WHERE username = @username LIMIT 1;";
|
||||||
|
cmd.Parameters.AddWithValue("@username", username);
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
if (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
return new User
|
||||||
|
{
|
||||||
|
Id = reader.GetString(0),
|
||||||
|
Username = reader.GetString(1),
|
||||||
|
PasswordHash = reader.GetString(2),
|
||||||
|
PasswordSalt = reader.GetString(3),
|
||||||
|
Role = reader.GetString(4),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(5)),
|
||||||
|
IsBanned = reader.GetInt32(6) == 1
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<User?> GetUserByIdAsync(string id)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "SELECT id, username, password_hash, password_salt, role, created_at, is_banned FROM users WHERE id = @id LIMIT 1;";
|
||||||
|
cmd.Parameters.AddWithValue("@id", id);
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
if (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
return new User
|
||||||
|
{
|
||||||
|
Id = reader.GetString(0),
|
||||||
|
Username = reader.GetString(1),
|
||||||
|
PasswordHash = reader.GetString(2),
|
||||||
|
PasswordSalt = reader.GetString(3),
|
||||||
|
Role = reader.GetString(4),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(5)),
|
||||||
|
IsBanned = reader.GetInt32(6) == 1
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<UserSummary>> GetAllUsersAsync()
|
||||||
|
{
|
||||||
|
var users = new List<UserSummary>();
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "SELECT id, username, role FROM users ORDER BY username ASC;";
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
while (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
users.Add(new UserSummary
|
||||||
|
{
|
||||||
|
Id = reader.GetString(0),
|
||||||
|
Username = reader.GetString(1),
|
||||||
|
Role = reader.GetString(2),
|
||||||
|
IsOnline = false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> UpdateUserRoleAsync(string userId, string newRole)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "UPDATE users SET role = @role WHERE id = @id;";
|
||||||
|
cmd.Parameters.AddWithValue("@role", newRole);
|
||||||
|
cmd.Parameters.AddWithValue("@id", userId);
|
||||||
|
return (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> BanUserAsync(string userId, bool isBanned)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "UPDATE users SET is_banned = @banned WHERE id = @id;";
|
||||||
|
cmd.Parameters.AddWithValue("@banned", isBanned ? 1 : 0);
|
||||||
|
cmd.Parameters.AddWithValue("@id", userId);
|
||||||
|
return (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Session Operations
|
||||||
|
|
||||||
|
public async Task CreateSessionAsync(Session session)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
INSERT INTO sessions (token, user_id, created_at, expires_at)
|
||||||
|
VALUES (@token, @user_id, @created_at, @expires_at)
|
||||||
|
ON CONFLICT(token) DO UPDATE SET expires_at = @expires_at;
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@token", session.Token);
|
||||||
|
cmd.Parameters.AddWithValue("@user_id", session.UserId);
|
||||||
|
cmd.Parameters.AddWithValue("@created_at", session.CreatedAt.ToString("O"));
|
||||||
|
cmd.Parameters.AddWithValue("@expires_at", session.ExpiresAt.ToString("O"));
|
||||||
|
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Session?> GetSessionAsync(string token)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "SELECT token, user_id, created_at, expires_at FROM sessions WHERE token = @token LIMIT 1;";
|
||||||
|
cmd.Parameters.AddWithValue("@token", token);
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
if (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
return new Session
|
||||||
|
{
|
||||||
|
Token = reader.GetString(0),
|
||||||
|
UserId = reader.GetString(1),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(2)),
|
||||||
|
ExpiresAt = DateTime.Parse(reader.GetString(3))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DeleteSessionAsync(string token)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "DELETE FROM sessions WHERE token = @token;";
|
||||||
|
cmd.Parameters.AddWithValue("@token", token);
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Channel Operations
|
||||||
|
|
||||||
|
public async Task<List<Channel>> GetChannelsAsync()
|
||||||
|
{
|
||||||
|
var channels = new List<Channel>();
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "SELECT id, name, topic, is_private, allowed_roles, created_at FROM channels ORDER BY name ASC;";
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
while (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
channels.Add(new Channel
|
||||||
|
{
|
||||||
|
Id = reader.GetString(0),
|
||||||
|
Name = reader.GetString(1),
|
||||||
|
Topic = reader.GetString(2),
|
||||||
|
IsPrivate = reader.GetInt32(3) == 1,
|
||||||
|
AllowedRoles = reader.GetString(4),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(5))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return channels;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Channel?> GetChannelByIdAsync(string id)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "SELECT id, name, topic, is_private, allowed_roles, created_at FROM channels WHERE id = @id LIMIT 1;";
|
||||||
|
cmd.Parameters.AddWithValue("@id", id);
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
if (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
return new Channel
|
||||||
|
{
|
||||||
|
Id = reader.GetString(0),
|
||||||
|
Name = reader.GetString(1),
|
||||||
|
Topic = reader.GetString(2),
|
||||||
|
IsPrivate = reader.GetInt32(3) == 1,
|
||||||
|
AllowedRoles = reader.GetString(4),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(5))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Channel?> GetChannelByNameAsync(string name)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "SELECT id, name, topic, is_private, allowed_roles, created_at FROM channels WHERE name = @name LIMIT 1;";
|
||||||
|
cmd.Parameters.AddWithValue("@name", name);
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
if (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
return new Channel
|
||||||
|
{
|
||||||
|
Id = reader.GetString(0),
|
||||||
|
Name = reader.GetString(1),
|
||||||
|
Topic = reader.GetString(2),
|
||||||
|
IsPrivate = reader.GetInt32(3) == 1,
|
||||||
|
AllowedRoles = reader.GetString(4),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(5))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> CreateChannelAsync(Channel channel)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
return await CreateChannelInternalAsync(conn, channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DeleteChannelAsync(string channelId)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "DELETE FROM channels WHERE id = @id;";
|
||||||
|
cmd.Parameters.AddWithValue("@id", channelId);
|
||||||
|
return (await cmd.ExecuteNonQueryAsync()) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Message Operations
|
||||||
|
|
||||||
|
public async Task SaveMessageAsync(ChatMessage message)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
INSERT INTO messages (id, channel_id, sender_id, sender_username, sender_role, content, created_at, attachment_id, attachment_name, attachment_size)
|
||||||
|
VALUES (@id, @channel_id, @sender_id, @sender_username, @sender_role, @content, @created_at, @attachment_id, @attachment_name, @attachment_size);
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@id", message.Id);
|
||||||
|
cmd.Parameters.AddWithValue("@channel_id", message.ChannelId);
|
||||||
|
cmd.Parameters.AddWithValue("@sender_id", message.SenderId);
|
||||||
|
cmd.Parameters.AddWithValue("@sender_username", message.SenderUsername);
|
||||||
|
cmd.Parameters.AddWithValue("@sender_role", message.SenderRole);
|
||||||
|
cmd.Parameters.AddWithValue("@content", message.Content);
|
||||||
|
cmd.Parameters.AddWithValue("@created_at", message.CreatedAt.ToString("O"));
|
||||||
|
cmd.Parameters.AddWithValue("@attachment_id", (object?)message.AttachmentId ?? DBNull.Value);
|
||||||
|
cmd.Parameters.AddWithValue("@attachment_name", (object?)message.AttachmentName ?? DBNull.Value);
|
||||||
|
cmd.Parameters.AddWithValue("@attachment_size", (object?)message.AttachmentSizeBytes ?? DBNull.Value);
|
||||||
|
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<ChatMessage>> GetRecentMessagesAsync(string channelId, int limit = 50)
|
||||||
|
{
|
||||||
|
var messages = new List<ChatMessage>();
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
SELECT id, channel_id, sender_id, sender_username, sender_role, content, created_at, attachment_id, attachment_name, attachment_size
|
||||||
|
FROM (
|
||||||
|
SELECT * FROM messages
|
||||||
|
WHERE channel_id = @channel_id
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT @limit
|
||||||
|
)
|
||||||
|
ORDER BY created_at ASC;
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@channel_id", channelId);
|
||||||
|
cmd.Parameters.AddWithValue("@limit", limit);
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
while (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
messages.Add(new ChatMessage
|
||||||
|
{
|
||||||
|
Id = reader.GetString(0),
|
||||||
|
ChannelId = reader.GetString(1),
|
||||||
|
SenderId = reader.GetString(2),
|
||||||
|
SenderUsername = reader.GetString(3),
|
||||||
|
SenderRole = reader.GetString(4),
|
||||||
|
Content = reader.GetString(5),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(6)),
|
||||||
|
AttachmentId = reader.IsDBNull(7) ? null : reader.GetString(7),
|
||||||
|
AttachmentName = reader.IsDBNull(8) ? null : reader.GetString(8),
|
||||||
|
AttachmentSizeBytes = reader.IsDBNull(9) ? null : reader.GetInt64(9)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region File Operations
|
||||||
|
|
||||||
|
public async Task SaveFileRecordAsync(FileRecord file)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
INSERT INTO files (id, channel_id, uploader_id, uploader_username, original_name, content_type, size_bytes, storage_path, sha256, created_at)
|
||||||
|
VALUES (@id, @channel_id, @uploader_id, @uploader_username, @original_name, @content_type, @size_bytes, @storage_path, @sha256, @created_at);
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@id", file.Id);
|
||||||
|
cmd.Parameters.AddWithValue("@channel_id", file.ChannelId);
|
||||||
|
cmd.Parameters.AddWithValue("@uploader_id", file.UploaderId);
|
||||||
|
cmd.Parameters.AddWithValue("@uploader_username", file.UploaderUsername);
|
||||||
|
cmd.Parameters.AddWithValue("@original_name", file.OriginalFileName);
|
||||||
|
cmd.Parameters.AddWithValue("@content_type", file.ContentType);
|
||||||
|
cmd.Parameters.AddWithValue("@size_bytes", file.FileSizeBytes);
|
||||||
|
cmd.Parameters.AddWithValue("@storage_path", file.StoragePath);
|
||||||
|
cmd.Parameters.AddWithValue("@sha256", file.Sha256Checksum);
|
||||||
|
cmd.Parameters.AddWithValue("@created_at", file.CreatedAt.ToString("O"));
|
||||||
|
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<FileRecord?> GetFileRecordAsync(string fileId)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = "SELECT id, channel_id, uploader_id, uploader_username, original_name, content_type, size_bytes, storage_path, sha256, created_at FROM files WHERE id = @id LIMIT 1;";
|
||||||
|
cmd.Parameters.AddWithValue("@id", fileId);
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
if (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
return new FileRecord
|
||||||
|
{
|
||||||
|
Id = reader.GetString(0),
|
||||||
|
ChannelId = reader.GetString(1),
|
||||||
|
UploaderId = reader.GetString(2),
|
||||||
|
UploaderUsername = reader.GetString(3),
|
||||||
|
OriginalFileName = reader.GetString(4),
|
||||||
|
ContentType = reader.GetString(5),
|
||||||
|
FileSizeBytes = reader.GetInt64(6),
|
||||||
|
StoragePath = reader.GetString(7),
|
||||||
|
Sha256Checksum = reader.GetString(8),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(9))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<FileSummary>> GetRecentFilesAsync(int limit = 100)
|
||||||
|
{
|
||||||
|
var files = new List<FileSummary>();
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
SELECT id, channel_id, original_name, content_type, size_bytes, uploader_username, created_at
|
||||||
|
FROM files
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT @limit;
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@limit", limit);
|
||||||
|
|
||||||
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
|
while (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
files.Add(new FileSummary
|
||||||
|
{
|
||||||
|
Id = reader.GetString(0),
|
||||||
|
ChannelId = reader.GetString(1),
|
||||||
|
OriginalFileName = reader.GetString(2),
|
||||||
|
ContentType = reader.GetString(3),
|
||||||
|
FileSizeBytes = reader.GetInt64(4),
|
||||||
|
UploaderUsername = reader.GetString(5),
|
||||||
|
CreatedAt = DateTime.Parse(reader.GetString(6))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
// SQLite in-process connections are pooled and closed as needed
|
||||||
|
}
|
||||||
|
}
|
||||||
27
src/GsDChat.Server/GsDChat.Server.csproj
Normal file
27
src/GsDChat.Server/GsDChat.Server.csproj
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.12" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\GsDChat.Core\GsDChat.Core.csproj" />
|
||||||
|
<ProjectReference Include="..\GsDChat.Modding\GsDChat.Modding.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="serversettings.json">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
<None Update="mods\**\*">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
302
src/GsDChat.Server/Program.cs
Normal file
302
src/GsDChat.Server/Program.cs
Normal file
|
|
@ -0,0 +1,302 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
using GsDChat.Server.Configuration;
|
||||||
|
using GsDChat.Server.Data;
|
||||||
|
using GsDChat.Server.Services;
|
||||||
|
using GsDChat.Server.WebSockets;
|
||||||
|
|
||||||
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
|
// Load Server Configuration
|
||||||
|
var configPath = Path.Combine(AppContext.BaseDirectory, "serversettings.json");
|
||||||
|
var serverOptions = new ServerOptions();
|
||||||
|
if (File.Exists(configPath))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var json = File.ReadAllText(configPath);
|
||||||
|
var loaded = JsonSerializer.Deserialize<ServerOptions>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||||
|
if (loaded != null) serverOptions = loaded;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"[Warning] Failed to read serversettings.json: {ex.Message}. Using defaults.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Environment variable overrides (convenient for Docker & Docker Compose)
|
||||||
|
string? envPort = Environment.GetEnvironmentVariable("GSDCHAT_PORT") ?? Environment.GetEnvironmentVariable("PORT");
|
||||||
|
if (!string.IsNullOrEmpty(envPort) && int.TryParse(envPort, out int ep)) serverOptions.Port = ep;
|
||||||
|
|
||||||
|
string? envHost = Environment.GetEnvironmentVariable("GSDCHAT_HOST");
|
||||||
|
if (!string.IsNullOrEmpty(envHost)) serverOptions.Host = envHost;
|
||||||
|
|
||||||
|
string? envTls = Environment.GetEnvironmentVariable("GSDCHAT_USE_TLS");
|
||||||
|
if (!string.IsNullOrEmpty(envTls) && bool.TryParse(envTls, out bool etls)) serverOptions.UseTls = etls;
|
||||||
|
|
||||||
|
string? envPass = Environment.GetEnvironmentVariable("GSDCHAT_SERVER_PASSWORD") ?? Environment.GetEnvironmentVariable("SERVER_PASSWORD");
|
||||||
|
if (envPass != null) serverOptions.ServerWidePassword = envPass;
|
||||||
|
|
||||||
|
string? envReg = Environment.GetEnvironmentVariable("GSDCHAT_REGISTRATION_MODE") ?? Environment.GetEnvironmentVariable("REGISTRATION_MODE");
|
||||||
|
if (!string.IsNullOrEmpty(envReg)) serverOptions.RegistrationMode = envReg;
|
||||||
|
|
||||||
|
string? envDataDir = Environment.GetEnvironmentVariable("GSDCHAT_DATA_DIR") ?? Environment.GetEnvironmentVariable("DATA_DIR");
|
||||||
|
if (!string.IsNullOrEmpty(envDataDir)) serverOptions.DataDirectory = envDataDir;
|
||||||
|
|
||||||
|
string? envMaxFile = Environment.GetEnvironmentVariable("GSDCHAT_MAX_FILE_SIZE_MB");
|
||||||
|
if (!string.IsNullOrEmpty(envMaxFile) && long.TryParse(envMaxFile, out long emf)) serverOptions.MaxFileSizeMb = emf;
|
||||||
|
|
||||||
|
string? envServerName = Environment.GetEnvironmentVariable("GSDCHAT_SERVER_NAME") ?? Environment.GetEnvironmentVariable("SERVER_NAME");
|
||||||
|
if (!string.IsNullOrEmpty(envServerName)) serverOptions.ServerName = envServerName;
|
||||||
|
|
||||||
|
string? envMotd = Environment.GetEnvironmentVariable("GSDCHAT_MOTD") ?? Environment.GetEnvironmentVariable("SERVER_MOTD");
|
||||||
|
if (!string.IsNullOrEmpty(envMotd)) serverOptions.Motd = envMotd;
|
||||||
|
|
||||||
|
string? envCertPath = Environment.GetEnvironmentVariable("GSDCHAT_CERT_PATH");
|
||||||
|
if (!string.IsNullOrEmpty(envCertPath)) serverOptions.CertificatePath = envCertPath;
|
||||||
|
|
||||||
|
string? envCertPass = Environment.GetEnvironmentVariable("GSDCHAT_CERT_PASSWORD");
|
||||||
|
if (!string.IsNullOrEmpty(envCertPass)) serverOptions.CertificatePassword = envCertPass;
|
||||||
|
|
||||||
|
// Allow CLI overrides e.g. --port 5000 --tls false
|
||||||
|
for (int i = 0; i < args.Length; i++)
|
||||||
|
{
|
||||||
|
if (args[i] == "--port" && i + 1 < args.Length && int.TryParse(args[i + 1], out int p)) serverOptions.Port = p;
|
||||||
|
if (args[i] == "--host" && i + 1 < args.Length) serverOptions.Host = args[i + 1];
|
||||||
|
if (args[i] == "--tls" && i + 1 < args.Length && bool.TryParse(args[i + 1], out bool tls)) serverOptions.UseTls = tls;
|
||||||
|
if (args[i] == "--server-password" && i + 1 < args.Length) serverOptions.ServerWidePassword = args[i + 1];
|
||||||
|
if (args[i] == "--data-dir" && i + 1 < args.Length) serverOptions.DataDirectory = args[i + 1];
|
||||||
|
if (args[i] == "--server-name" && i + 1 < args.Length) serverOptions.ServerName = args[i + 1];
|
||||||
|
if (args[i] == "--motd" && i + 1 < args.Length) serverOptions.Motd = args[i + 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Services.AddSingleton(serverOptions);
|
||||||
|
|
||||||
|
// Configure Kestrel bindings
|
||||||
|
builder.WebHost.ConfigureKestrel(kestrel =>
|
||||||
|
{
|
||||||
|
var ip = serverOptions.Host == "0.0.0.0" ? IPAddress.Any : IPAddress.Parse(serverOptions.Host);
|
||||||
|
|
||||||
|
kestrel.Listen(ip, serverOptions.Port, listenOptions =>
|
||||||
|
{
|
||||||
|
if (serverOptions.UseTls)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrEmpty(serverOptions.CertificatePath) && File.Exists(serverOptions.CertificatePath))
|
||||||
|
{
|
||||||
|
var cert = string.IsNullOrEmpty(serverOptions.CertificatePassword)
|
||||||
|
? X509CertificateLoader.LoadCertificateFromFile(serverOptions.CertificatePath)
|
||||||
|
: X509CertificateLoader.LoadPkcs12FromFile(serverOptions.CertificatePath, serverOptions.CertificatePassword);
|
||||||
|
listenOptions.UseHttps(cert);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Default development or system HTTPS
|
||||||
|
listenOptions.UseHttps();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Configure Services
|
||||||
|
builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory));
|
||||||
|
builder.Services.AddSingleton<IAuthService, AuthService>();
|
||||||
|
builder.Services.AddSingleton<FileStorageService>();
|
||||||
|
builder.Services.AddSingleton<ChatWebSocketManager>();
|
||||||
|
builder.Services.AddSingleton<ModLoaderService>();
|
||||||
|
|
||||||
|
builder.Logging.ClearProviders();
|
||||||
|
builder.Logging.AddConsole();
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
|
||||||
|
// Initialize Database
|
||||||
|
var db = app.Services.GetRequiredService<ChatDatabase>();
|
||||||
|
await db.InitializeAsync();
|
||||||
|
|
||||||
|
// Initialize Mod Loader
|
||||||
|
var modLoader = app.Services.GetRequiredService<ModLoaderService>();
|
||||||
|
string modsDirectory = Environment.GetEnvironmentVariable("GSDCHAT_MODS_DIR") ?? Path.Combine(AppContext.BaseDirectory, "mods");
|
||||||
|
await modLoader.LoadModsAsync(modsDirectory);
|
||||||
|
|
||||||
|
app.Lifetime.ApplicationStopping.Register(() =>
|
||||||
|
{
|
||||||
|
modLoader.ShutdownModsAsync().GetAwaiter().GetResult();
|
||||||
|
});
|
||||||
|
|
||||||
|
// WebSockets Middleware
|
||||||
|
app.UseWebSockets(new WebSocketOptions
|
||||||
|
{
|
||||||
|
KeepAliveInterval = TimeSpan.FromSeconds(30)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Helper for extracting bearer token
|
||||||
|
string? ExtractBearerToken(HttpRequest request)
|
||||||
|
{
|
||||||
|
if (request.Headers.TryGetValue("Authorization", out var authHeader))
|
||||||
|
{
|
||||||
|
string headerVal = authHeader.ToString();
|
||||||
|
if (headerVal.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return headerVal.Substring(7).Trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (request.Query.TryGetValue("token", out var queryToken))
|
||||||
|
{
|
||||||
|
return queryToken.ToString();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// REST Endpoints
|
||||||
|
app.MapGet("/api/info", (ServerOptions opt) =>
|
||||||
|
{
|
||||||
|
return Results.Ok(new ServerInfoResponse
|
||||||
|
{
|
||||||
|
ServerName = opt.ServerName,
|
||||||
|
Version = "1.0.0",
|
||||||
|
RegistrationMode = opt.RegistrationMode,
|
||||||
|
RequiresServerPassword = !string.IsNullOrWhiteSpace(opt.ServerWidePassword),
|
||||||
|
Motd = opt.Motd,
|
||||||
|
MaxFileSizeMb = opt.MaxFileSizeMb
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth) =>
|
||||||
|
{
|
||||||
|
var res = await auth.RegisterAsync(req);
|
||||||
|
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapPost("/api/auth/login", async (LoginRequest req, IAuthService auth) =>
|
||||||
|
{
|
||||||
|
var res = await auth.LoginAsync(req);
|
||||||
|
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
||||||
|
});
|
||||||
|
|
||||||
|
// File Upload
|
||||||
|
app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, FileStorageService fileService, ChatWebSocketManager wsManager) =>
|
||||||
|
{
|
||||||
|
string? token = ExtractBearerToken(req);
|
||||||
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return Results.Unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!req.HasFormContentType)
|
||||||
|
{
|
||||||
|
return Results.BadRequest(new UploadFileResponse { Success = false, ErrorMessage = "Request must be multipart/form-data." });
|
||||||
|
}
|
||||||
|
|
||||||
|
var form = await req.ReadFormAsync();
|
||||||
|
var file = form.Files.GetFile("file");
|
||||||
|
if (file == null || file.Length == 0)
|
||||||
|
{
|
||||||
|
return Results.BadRequest(new UploadFileResponse { Success = false, ErrorMessage = "No file provided in form field 'file'." });
|
||||||
|
}
|
||||||
|
|
||||||
|
string channelId = form["channelId"].ToString();
|
||||||
|
if (string.IsNullOrWhiteSpace(channelId))
|
||||||
|
{
|
||||||
|
return Results.BadRequest(new UploadFileResponse { Success = false, ErrorMessage = "channelId is required." });
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var stream = file.OpenReadStream();
|
||||||
|
var record = await fileService.StoreFileAsync(
|
||||||
|
channelId,
|
||||||
|
user.Id,
|
||||||
|
user.Username,
|
||||||
|
file.FileName,
|
||||||
|
file.ContentType,
|
||||||
|
stream,
|
||||||
|
file.Length
|
||||||
|
);
|
||||||
|
|
||||||
|
await wsManager.BroadcastFileUploadedAsync(record);
|
||||||
|
|
||||||
|
return Results.Ok(new UploadFileResponse
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
FileId = record.Id,
|
||||||
|
FileName = record.OriginalFileName,
|
||||||
|
FileSizeBytes = record.FileSizeBytes,
|
||||||
|
ChannelId = record.ChannelId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return Results.BadRequest(new UploadFileResponse { Success = false, ErrorMessage = ex.Message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// File Download
|
||||||
|
app.MapGet("/api/files/{id}", async (string id, HttpRequest req, IAuthService auth, FileStorageService fileService) =>
|
||||||
|
{
|
||||||
|
string? token = ExtractBearerToken(req);
|
||||||
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return Results.Unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
var record = await fileService.GetFileRecordAsync(id);
|
||||||
|
if (record == null)
|
||||||
|
{
|
||||||
|
return Results.NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
var stream = fileService.OpenFileStream(record);
|
||||||
|
if (stream == null)
|
||||||
|
{
|
||||||
|
return Results.NotFound("File contents missing on disk.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Results.File(stream, record.ContentType, record.OriginalFileName, enableRangeProcessing: true);
|
||||||
|
});
|
||||||
|
|
||||||
|
// WebSocket Chat Endpoint
|
||||||
|
app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager wsManager) =>
|
||||||
|
{
|
||||||
|
if (!context.WebSockets.IsWebSocketRequest)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string? token = ExtractBearerToken(context.Request);
|
||||||
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var ws = await context.WebSockets.AcceptWebSocketAsync();
|
||||||
|
await wsManager.HandleClientAsync(ws, user, context.RequestAborted);
|
||||||
|
});
|
||||||
|
|
||||||
|
Console.WriteLine($"==================================================");
|
||||||
|
Console.WriteLine($" GsDChat Server v1.0.0");
|
||||||
|
Console.WriteLine($" Listening on: {(serverOptions.UseTls ? "https" : "http")}://{serverOptions.Host}:{serverOptions.Port}");
|
||||||
|
Console.WriteLine($" Server Name: {serverOptions.ServerName}");
|
||||||
|
Console.WriteLine($" Registration: {serverOptions.RegistrationMode}");
|
||||||
|
Console.WriteLine($" Password Gated: {!string.IsNullOrWhiteSpace(serverOptions.ServerWidePassword)}");
|
||||||
|
Console.WriteLine($"==================================================");
|
||||||
|
|
||||||
|
app.Run();
|
||||||
|
|
||||||
|
// Make Program accessible for WebApplicationFactory in integration tests
|
||||||
|
public partial class Program { }
|
||||||
23
src/GsDChat.Server/Properties/launchSettings.json
Normal file
23
src/GsDChat.Server/Properties/launchSettings.json
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||||
|
"profiles": {
|
||||||
|
"http": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"dotnetRunMessages": true,
|
||||||
|
"launchBrowser": true,
|
||||||
|
"applicationUrl": "http://localhost:5208",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"https": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"dotnetRunMessages": true,
|
||||||
|
"launchBrowser": true,
|
||||||
|
"applicationUrl": "https://localhost:7082;http://localhost:5208",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
237
src/GsDChat.Server/Services/AuthService.cs
Normal file
237
src/GsDChat.Server/Services/AuthService.cs
Normal file
|
|
@ -0,0 +1,237 @@
|
||||||
|
using System;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
using GsDChat.Core.Security;
|
||||||
|
using GsDChat.Server.Configuration;
|
||||||
|
using GsDChat.Server.Data;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Services;
|
||||||
|
|
||||||
|
public class AuthService : IAuthService
|
||||||
|
{
|
||||||
|
private readonly ChatDatabase _db;
|
||||||
|
private readonly ServerOptions _options;
|
||||||
|
|
||||||
|
public AuthService(ChatDatabase db, ServerOptions options)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
_options = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<bool> ValidateServerPasswordAsync(string? serverPassword)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(_options.ServerWidePassword))
|
||||||
|
{
|
||||||
|
return Task.FromResult(true); // No server password configured
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(serverPassword))
|
||||||
|
{
|
||||||
|
return Task.FromResult(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] expected = Encoding.UTF8.GetBytes(_options.ServerWidePassword);
|
||||||
|
byte[] actual = Encoding.UTF8.GetBytes(serverPassword);
|
||||||
|
|
||||||
|
if (expected.Length != actual.Length)
|
||||||
|
{
|
||||||
|
return Task.FromResult(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.FromResult(CryptographicOperations.FixedTimeEquals(actual, expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AuthResponse> RegisterAsync(RegisterRequest request)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Username) || request.Username.Length < 3 || request.Username.Length > 32)
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Username must be between 3 and 32 characters."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Password) || request.Password.Length < 6)
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Password must be at least 6 characters long."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!await ValidateServerPasswordAsync(request.ServerPassword))
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Invalid server-wide password."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.Equals(_options.RegistrationMode, "InviteOnly", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
// For invite-only mode, if user count is 0, allow first user (server owner), otherwise check invite token
|
||||||
|
int currentCount = await _db.GetUserCountAsync();
|
||||||
|
if (currentCount > 0 && string.IsNullOrWhiteSpace(request.InviteToken))
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Registration is invite-only. A valid invite token is required."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var existingUser = await _db.GetUserByUsernameAsync(request.Username);
|
||||||
|
if (existingUser != null)
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Username is already taken."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
int totalUsers = await _db.GetUserCountAsync();
|
||||||
|
string assignedRole = totalUsers == 0 ? UserRoles.Owner : UserRoles.Member;
|
||||||
|
|
||||||
|
var (hash, salt) = PasswordHasher.HashPassword(request.Password);
|
||||||
|
|
||||||
|
var newUser = new User
|
||||||
|
{
|
||||||
|
Username = request.Username.Trim(),
|
||||||
|
PasswordHash = hash,
|
||||||
|
PasswordSalt = salt,
|
||||||
|
Role = assignedRole,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
IsBanned = false
|
||||||
|
};
|
||||||
|
|
||||||
|
bool created = await _db.CreateUserAsync(newUser);
|
||||||
|
if (!created)
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Failed to create user. Please try again."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
var sessionToken = TokenGenerator.GenerateSecureToken();
|
||||||
|
var session = new Session
|
||||||
|
{
|
||||||
|
Token = sessionToken,
|
||||||
|
UserId = newUser.Id,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
ExpiresAt = DateTime.UtcNow.AddDays(30)
|
||||||
|
};
|
||||||
|
|
||||||
|
await _db.CreateSessionAsync(session);
|
||||||
|
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
Token = sessionToken,
|
||||||
|
UserId = newUser.Id,
|
||||||
|
Username = newUser.Username,
|
||||||
|
Role = newUser.Role
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AuthResponse> LoginAsync(LoginRequest request)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Username) || string.IsNullOrWhiteSpace(request.Password))
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Username and password are required."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!await ValidateServerPasswordAsync(request.ServerPassword))
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Invalid server-wide password."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await _db.GetUserByUsernameAsync(request.Username);
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Invalid username or password."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.IsBanned)
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "This account has been banned from the server."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool validPassword = PasswordHasher.VerifyPassword(request.Password, user.PasswordHash, user.PasswordSalt);
|
||||||
|
if (!validPassword)
|
||||||
|
{
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "Invalid username or password."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
var sessionToken = TokenGenerator.GenerateSecureToken();
|
||||||
|
var session = new Session
|
||||||
|
{
|
||||||
|
Token = sessionToken,
|
||||||
|
UserId = user.Id,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
ExpiresAt = DateTime.UtcNow.AddDays(30)
|
||||||
|
};
|
||||||
|
|
||||||
|
await _db.CreateSessionAsync(session);
|
||||||
|
|
||||||
|
return new AuthResponse
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
Token = sessionToken,
|
||||||
|
UserId = user.Id,
|
||||||
|
Username = user.Username,
|
||||||
|
Role = user.Role
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<User?> ValidateSessionTokenAsync(string token)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(token))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var session = await _db.GetSessionAsync(token);
|
||||||
|
if (session == null || session.IsExpired)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await _db.GetUserByIdAsync(session.UserId);
|
||||||
|
if (user == null || user.IsBanned)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
}
|
||||||
135
src/GsDChat.Server/Services/FileStorageService.cs
Normal file
135
src/GsDChat.Server/Services/FileStorageService.cs
Normal file
|
|
@ -0,0 +1,135 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Server.Configuration;
|
||||||
|
using GsDChat.Server.Data;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Services;
|
||||||
|
|
||||||
|
public class FileStorageService
|
||||||
|
{
|
||||||
|
private readonly ChatDatabase _db;
|
||||||
|
private readonly ServerOptions _options;
|
||||||
|
private readonly string _filesDirectory;
|
||||||
|
|
||||||
|
public FileStorageService(ChatDatabase db, ServerOptions options)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
_options = options;
|
||||||
|
_filesDirectory = Path.Combine(options.DataDirectory, "files");
|
||||||
|
Directory.CreateDirectory(_filesDirectory);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<FileRecord> StoreFileAsync(
|
||||||
|
string channelId,
|
||||||
|
string uploaderId,
|
||||||
|
string uploaderUsername,
|
||||||
|
string originalFileName,
|
||||||
|
string contentType,
|
||||||
|
Stream stream,
|
||||||
|
long length)
|
||||||
|
{
|
||||||
|
long maxBytes = _options.MaxFileSizeMb * 1024 * 1024;
|
||||||
|
if (length > maxBytes)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"File exceeds maximum allowed size of {_options.MaxFileSizeMb} MB.");
|
||||||
|
}
|
||||||
|
|
||||||
|
string safeName = Path.GetFileName(originalFileName);
|
||||||
|
if (string.IsNullOrWhiteSpace(safeName))
|
||||||
|
{
|
||||||
|
safeName = "unnamed_file.bin";
|
||||||
|
}
|
||||||
|
|
||||||
|
string fileId = Guid.NewGuid().ToString("N");
|
||||||
|
string diskFileName = $"{fileId}_{safeName}";
|
||||||
|
string diskFilePath = Path.Combine(_filesDirectory, diskFileName);
|
||||||
|
|
||||||
|
string sha256Hex;
|
||||||
|
long writtenBytes = 0;
|
||||||
|
|
||||||
|
using (var sha256 = SHA256.Create())
|
||||||
|
using (var fileStream = new FileStream(diskFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true))
|
||||||
|
{
|
||||||
|
byte[] buffer = new byte[81920];
|
||||||
|
int read;
|
||||||
|
while ((read = await stream.ReadAsync(buffer)) > 0)
|
||||||
|
{
|
||||||
|
writtenBytes += read;
|
||||||
|
if (writtenBytes > maxBytes)
|
||||||
|
{
|
||||||
|
fileStream.Close();
|
||||||
|
File.Delete(diskFilePath);
|
||||||
|
throw new InvalidOperationException($"File exceeds maximum allowed size of {_options.MaxFileSizeMb} MB.");
|
||||||
|
}
|
||||||
|
|
||||||
|
await fileStream.WriteAsync(buffer.AsMemory(0, read));
|
||||||
|
sha256.TransformBlock(buffer, 0, read, null, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
sha256.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
|
||||||
|
sha256Hex = Convert.ToHexString(sha256.Hash ?? Array.Empty<byte>());
|
||||||
|
}
|
||||||
|
|
||||||
|
var record = new FileRecord
|
||||||
|
{
|
||||||
|
Id = fileId,
|
||||||
|
ChannelId = channelId,
|
||||||
|
UploaderId = uploaderId,
|
||||||
|
UploaderUsername = uploaderUsername,
|
||||||
|
OriginalFileName = safeName,
|
||||||
|
ContentType = string.IsNullOrWhiteSpace(contentType) ? "application/octet-stream" : contentType,
|
||||||
|
FileSizeBytes = writtenBytes,
|
||||||
|
StoragePath = diskFilePath,
|
||||||
|
Sha256Checksum = sha256Hex,
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
};
|
||||||
|
|
||||||
|
await _db.SaveFileRecordAsync(record);
|
||||||
|
|
||||||
|
// Also create a chat message in the channel announcing the file
|
||||||
|
var msg = new ChatMessage
|
||||||
|
{
|
||||||
|
ChannelId = channelId,
|
||||||
|
SenderId = uploaderId,
|
||||||
|
SenderUsername = uploaderUsername,
|
||||||
|
Content = $"Shared file: {safeName} ({FormatBytes(writtenBytes)})",
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
AttachmentId = record.Id,
|
||||||
|
AttachmentName = safeName,
|
||||||
|
AttachmentSizeBytes = writtenBytes
|
||||||
|
};
|
||||||
|
await _db.SaveMessageAsync(msg);
|
||||||
|
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<FileRecord?> GetFileRecordAsync(string fileId)
|
||||||
|
{
|
||||||
|
return await _db.GetFileRecordAsync(fileId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Stream? OpenFileStream(FileRecord record)
|
||||||
|
{
|
||||||
|
if (File.Exists(record.StoragePath))
|
||||||
|
{
|
||||||
|
return new FileStream(record.StoragePath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string FormatBytes(long bytes)
|
||||||
|
{
|
||||||
|
string[] suffixes = { "B", "KB", "MB", "GB" };
|
||||||
|
int order = 0;
|
||||||
|
double size = bytes;
|
||||||
|
while (size >= 1024 && order < suffixes.Length - 1)
|
||||||
|
{
|
||||||
|
order++;
|
||||||
|
size /= 1024;
|
||||||
|
}
|
||||||
|
return $"{size:0.##} {suffixes[order]}";
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/GsDChat.Server/Services/IAuthService.cs
Normal file
13
src/GsDChat.Server/Services/IAuthService.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Services;
|
||||||
|
|
||||||
|
public interface IAuthService
|
||||||
|
{
|
||||||
|
Task<AuthResponse> RegisterAsync(RegisterRequest request);
|
||||||
|
Task<AuthResponse> LoginAsync(LoginRequest request);
|
||||||
|
Task<User?> ValidateSessionTokenAsync(string token);
|
||||||
|
Task<bool> ValidateServerPasswordAsync(string? serverPassword);
|
||||||
|
}
|
||||||
159
src/GsDChat.Server/Services/ModLoaderService.cs
Normal file
159
src/GsDChat.Server/Services/ModLoaderService.cs
Normal file
|
|
@ -0,0 +1,159 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.Loader;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using GsDChat.Modding;
|
||||||
|
using GsDChat.Server.Configuration;
|
||||||
|
using GsDChat.Server.WebSockets;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.Services;
|
||||||
|
|
||||||
|
public class ModAssemblyLoadContext : AssemblyLoadContext
|
||||||
|
{
|
||||||
|
private readonly AssemblyDependencyResolver _resolver;
|
||||||
|
|
||||||
|
public ModAssemblyLoadContext(string pluginPath) : base(isCollectible: true)
|
||||||
|
{
|
||||||
|
_resolver = new AssemblyDependencyResolver(pluginPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override Assembly? Load(AssemblyName assemblyName)
|
||||||
|
{
|
||||||
|
string? assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
|
||||||
|
if (assemblyPath != null)
|
||||||
|
{
|
||||||
|
return LoadFromAssemblyPath(assemblyPath);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ModLoaderService
|
||||||
|
{
|
||||||
|
private readonly ServerOptions _options;
|
||||||
|
private readonly ChatWebSocketManager _wsManager;
|
||||||
|
private readonly ILogger<ModLoaderService> _logger;
|
||||||
|
|
||||||
|
public ModEventBus EventBus { get; } = new();
|
||||||
|
public CommandRegistry Commands { get; } = new();
|
||||||
|
public MessagePipeline Pipeline { get; } = new();
|
||||||
|
public UiRegistry Ui { get; }
|
||||||
|
|
||||||
|
private readonly List<(IMod Mod, AssemblyLoadContext Context)> _loadedMods = new();
|
||||||
|
|
||||||
|
public ModLoaderService(ServerOptions options, ChatWebSocketManager wsManager, ILogger<ModLoaderService> logger)
|
||||||
|
{
|
||||||
|
_options = options;
|
||||||
|
_wsManager = wsManager;
|
||||||
|
_logger = logger;
|
||||||
|
Ui = new UiRegistry(options.ServerName, options.Motd);
|
||||||
|
|
||||||
|
// Hook up to ChatWebSocketManager
|
||||||
|
_wsManager.UiSyncProvider = () => Ui.GetUiSync();
|
||||||
|
|
||||||
|
_wsManager.MessagePipelineInterceptor = async (msg) =>
|
||||||
|
{
|
||||||
|
var result = await Pipeline.ExecuteAsync(msg);
|
||||||
|
if (result.IsCancelled)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return result.Message;
|
||||||
|
};
|
||||||
|
|
||||||
|
_wsManager.CommandInterceptor = async (cmd, args, client) =>
|
||||||
|
{
|
||||||
|
var ctx = new CommandContext
|
||||||
|
{
|
||||||
|
Command = cmd,
|
||||||
|
Args = args,
|
||||||
|
UserId = client.User.Id,
|
||||||
|
Username = client.User.Username,
|
||||||
|
UserRole = client.User.Role,
|
||||||
|
ChannelId = client.ActiveChannelId
|
||||||
|
};
|
||||||
|
|
||||||
|
var res = await Commands.ExecuteCommandAsync(ctx);
|
||||||
|
if (res != null)
|
||||||
|
{
|
||||||
|
return new Core.Protocol.CommandResultPacket
|
||||||
|
{
|
||||||
|
Success = res.Success,
|
||||||
|
Output = res.Output
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task LoadModsAsync(string modsDirectory)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(modsDirectory);
|
||||||
|
|
||||||
|
var dllFiles = Directory.GetFiles(modsDirectory, "*.dll", SearchOption.AllDirectories);
|
||||||
|
_logger.LogInformation("Scanning for mods in {Dir} (found {Count} DLLs)", modsDirectory, dllFiles.Length);
|
||||||
|
|
||||||
|
foreach (var dllPath in dllFiles)
|
||||||
|
{
|
||||||
|
// Skip core dependencies if present in folder
|
||||||
|
string fileName = Path.GetFileName(dllPath);
|
||||||
|
if (fileName.StartsWith("GsDChat.Core") ||
|
||||||
|
fileName.StartsWith("GsDChat.Modding") ||
|
||||||
|
fileName.StartsWith("GsDChat.Server") ||
|
||||||
|
fileName.StartsWith("Microsoft.") ||
|
||||||
|
fileName.StartsWith("System."))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var loadContext = new ModAssemblyLoadContext(dllPath);
|
||||||
|
var assembly = loadContext.LoadFromAssemblyPath(Path.GetFullPath(dllPath));
|
||||||
|
|
||||||
|
foreach (var type in assembly.GetTypes())
|
||||||
|
{
|
||||||
|
if (typeof(IMod).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract)
|
||||||
|
{
|
||||||
|
var mod = (IMod?)Activator.CreateInstance(type);
|
||||||
|
if (mod != null)
|
||||||
|
{
|
||||||
|
string modDataDir = Path.Combine(modsDirectory, "data", mod.Id);
|
||||||
|
var ctx = new ModContext(EventBus, Commands, Pipeline, Ui, modDataDir);
|
||||||
|
|
||||||
|
await mod.InitializeAsync(ctx);
|
||||||
|
_loadedMods.Add((mod, loadContext));
|
||||||
|
|
||||||
|
_logger.LogInformation("Loaded Mod: {ModName} v{ModVersion} ({ModId}) - {Description}",
|
||||||
|
mod.Name, mod.Version, mod.Id, mod.Description);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Failed to load mod from {DllPath}", dllPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task ShutdownModsAsync()
|
||||||
|
{
|
||||||
|
foreach (var (mod, context) in _loadedMods)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await mod.ShutdownAsync();
|
||||||
|
context.Unload();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error shutting down mod {ModName}", mod.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_loadedMods.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
440
src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs
Normal file
440
src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs
Normal file
|
|
@ -0,0 +1,440 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
using GsDChat.Server.Configuration;
|
||||||
|
using GsDChat.Server.Data;
|
||||||
|
using GsDChat.Server.Services;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.WebSockets;
|
||||||
|
|
||||||
|
public class ChatWebSocketManager
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<string, ConnectedClient> _clients = new();
|
||||||
|
private readonly ChatDatabase _db;
|
||||||
|
private readonly ServerOptions _options;
|
||||||
|
private readonly ILogger<ChatWebSocketManager> _logger;
|
||||||
|
|
||||||
|
// Extensibility hooks for mod system
|
||||||
|
public Func<ChatMessage, Task<ChatMessage?>>? MessagePipelineInterceptor { get; set; }
|
||||||
|
public Func<string, string, ConnectedClient, Task<CommandResultPacket?>>? CommandInterceptor { get; set; }
|
||||||
|
public Func<ServerUiSync>? UiSyncProvider { get; set; }
|
||||||
|
|
||||||
|
public ChatWebSocketManager(ChatDatabase db, ServerOptions options, ILogger<ChatWebSocketManager> logger)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
_options = options;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int ConnectedCount => _clients.Count;
|
||||||
|
|
||||||
|
public async Task HandleClientAsync(WebSocket socket, User user, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var client = new ConnectedClient(socket, user);
|
||||||
|
_clients[client.ConnectionId] = client;
|
||||||
|
|
||||||
|
_logger.LogInformation("User '{Username}' connected (ConnId: {ConnId})", user.Username, client.ConnectionId);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Initial Sync: Select default channel
|
||||||
|
var channels = await _db.GetChannelsAsync();
|
||||||
|
var defaultChannel = channels.FirstOrDefault(c => c.Name == "general") ?? channels.FirstOrDefault();
|
||||||
|
if (defaultChannel != null)
|
||||||
|
{
|
||||||
|
client.ActiveChannelId = defaultChannel.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send UI Definition
|
||||||
|
var uiSync = UiSyncProvider?.Invoke() ?? ServerUiSync.CreateDefault(_options.ServerName, _options.Motd);
|
||||||
|
await client.SendMessageAsync(MessageTypes.UiSync, uiSync, cancellationToken);
|
||||||
|
|
||||||
|
// Send Channel List
|
||||||
|
await client.SendMessageAsync(MessageTypes.ChannelListSync, new ChannelListSyncPacket
|
||||||
|
{
|
||||||
|
Channels = channels,
|
||||||
|
ActiveChannelId = client.ActiveChannelId
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
|
// Send Initial Chat History
|
||||||
|
if (!string.IsNullOrEmpty(client.ActiveChannelId))
|
||||||
|
{
|
||||||
|
var messages = await _db.GetRecentMessagesAsync(client.ActiveChannelId, 50);
|
||||||
|
await client.SendMessageAsync(MessageTypes.HistorySync, new HistorySyncPacket
|
||||||
|
{
|
||||||
|
ChannelId = client.ActiveChannelId,
|
||||||
|
Messages = messages
|
||||||
|
}, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send Files List
|
||||||
|
var files = await _db.GetRecentFilesAsync(100);
|
||||||
|
await client.SendMessageAsync(MessageTypes.FileListSync, new FileListSyncPacket { Files = files }, cancellationToken);
|
||||||
|
|
||||||
|
// Broadcast Presence Update
|
||||||
|
await BroadcastUserListAsync();
|
||||||
|
await BroadcastSystemNoticeAsync($"[+] {user.Username} connected.", "Info");
|
||||||
|
|
||||||
|
// Main Receive Loop
|
||||||
|
var buffer = new byte[8192];
|
||||||
|
var messageAccumulator = new List<byte>();
|
||||||
|
|
||||||
|
while (socket.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken);
|
||||||
|
|
||||||
|
if (result.MessageType == WebSocketMessageType.Close)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.MessageType == WebSocketMessageType.Text)
|
||||||
|
{
|
||||||
|
messageAccumulator.AddRange(buffer.Take(result.Count));
|
||||||
|
|
||||||
|
if (result.EndOfMessage)
|
||||||
|
{
|
||||||
|
string json = Encoding.UTF8.GetString(messageAccumulator.ToArray());
|
||||||
|
messageAccumulator.Clear();
|
||||||
|
await ProcessClientMessageAsync(client, json, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch (WebSocketException ex)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("WebSocket error for {Username}: {Msg}", user.Username, ex.Message);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Unexpected error handling client {Username}", user.Username);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_clients.TryRemove(client.ConnectionId, out _);
|
||||||
|
_logger.LogInformation("User '{Username}' disconnected", user.Username);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (socket.State == WebSocketState.Open || socket.State == WebSocketState.CloseReceived)
|
||||||
|
{
|
||||||
|
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
|
||||||
|
await BroadcastUserListAsync();
|
||||||
|
await BroadcastSystemNoticeAsync($"[-] {user.Username} disconnected.", "Info");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ProcessClientMessageAsync(ConnectedClient client, string json, CancellationToken ct)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var envelope = JsonSerializer.Deserialize<NetworkEnvelope>(json);
|
||||||
|
if (envelope == null) return;
|
||||||
|
|
||||||
|
switch (envelope.Type)
|
||||||
|
{
|
||||||
|
case MessageTypes.SendMessage:
|
||||||
|
var sendMsg = envelope.Unpack<SendMessagePacket>();
|
||||||
|
if (sendMsg != null)
|
||||||
|
{
|
||||||
|
await HandleSendMessageAsync(client, sendMsg, ct);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.JoinChannel:
|
||||||
|
var joinPkg = envelope.Unpack<JoinChannelPacket>();
|
||||||
|
if (joinPkg != null)
|
||||||
|
{
|
||||||
|
await HandleJoinChannelAsync(client, joinPkg.ChannelId, ct);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.CreateChannel:
|
||||||
|
var createPkg = envelope.Unpack<CreateChannelPacket>();
|
||||||
|
if (createPkg != null)
|
||||||
|
{
|
||||||
|
await HandleCreateChannelAsync(client, createPkg, ct);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.DeleteChannel:
|
||||||
|
var deletePkg = envelope.Unpack<DeleteChannelPacket>();
|
||||||
|
if (deletePkg != null)
|
||||||
|
{
|
||||||
|
await HandleDeleteChannelAsync(client, deletePkg.ChannelId, ct);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.ExecuteCommand:
|
||||||
|
var cmdPkg = envelope.Unpack<ExecuteCommandPacket>();
|
||||||
|
if (cmdPkg != null)
|
||||||
|
{
|
||||||
|
await HandleCommandAsync(client, cmdPkg, ct);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case MessageTypes.Ping:
|
||||||
|
await client.SendMessageAsync(MessageTypes.Pong, new { }, ct);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex, "Failed to process message from client {Username}", client.User.Username);
|
||||||
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Failed to process message." }, ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleSendMessageAsync(ConnectedClient client, SendMessagePacket packet, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(packet.Content))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
||||||
|
var channel = await _db.GetChannelByIdAsync(channelId);
|
||||||
|
if (channel == null)
|
||||||
|
{
|
||||||
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Channel does not exist." }, ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var message = new ChatMessage
|
||||||
|
{
|
||||||
|
ChannelId = channelId,
|
||||||
|
SenderId = client.User.Id,
|
||||||
|
SenderUsername = client.User.Username,
|
||||||
|
SenderRole = client.User.Role,
|
||||||
|
Content = packet.Content.Trim(),
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pass through mod pipeline if present
|
||||||
|
if (MessagePipelineInterceptor != null)
|
||||||
|
{
|
||||||
|
var processed = await MessagePipelineInterceptor(message);
|
||||||
|
if (processed == null)
|
||||||
|
{
|
||||||
|
// Message dropped by pipeline
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
message = processed;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _db.SaveMessageAsync(message);
|
||||||
|
|
||||||
|
// Broadcast to all clients currently in this channel
|
||||||
|
await BroadcastToChannelAsync(channelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message });
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleJoinChannelAsync(ConnectedClient client, string channelId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var channel = await _db.GetChannelByIdAsync(channelId);
|
||||||
|
if (channel == null)
|
||||||
|
{
|
||||||
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Channel not found." }, ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
client.ActiveChannelId = channelId;
|
||||||
|
|
||||||
|
// Send confirmation and history
|
||||||
|
var channels = await _db.GetChannelsAsync();
|
||||||
|
await client.SendMessageAsync(MessageTypes.ChannelListSync, new ChannelListSyncPacket
|
||||||
|
{
|
||||||
|
Channels = channels,
|
||||||
|
ActiveChannelId = client.ActiveChannelId
|
||||||
|
}, ct);
|
||||||
|
|
||||||
|
var history = await _db.GetRecentMessagesAsync(channelId, 50);
|
||||||
|
await client.SendMessageAsync(MessageTypes.HistorySync, new HistorySyncPacket
|
||||||
|
{
|
||||||
|
ChannelId = channelId,
|
||||||
|
Messages = history
|
||||||
|
}, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleCreateChannelAsync(ConnectedClient client, CreateChannelPacket packet, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (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;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(packet.Name) || packet.Name.Length < 2)
|
||||||
|
{
|
||||||
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Invalid channel name." }, ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string cleanName = packet.Name.Trim().ToLowerInvariant().Replace(" ", "-").TrimStart('#');
|
||||||
|
var channel = new Channel
|
||||||
|
{
|
||||||
|
Name = cleanName,
|
||||||
|
Topic = packet.Topic?.Trim() ?? string.Empty,
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
};
|
||||||
|
|
||||||
|
bool created = await _db.CreateChannelAsync(channel);
|
||||||
|
if (!created)
|
||||||
|
{
|
||||||
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Channel name already exists." }, ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await BroadcastChannelListAsync();
|
||||||
|
await BroadcastSystemNoticeAsync($"Channel #{cleanName} was created by {client.User.Username}.", "Success");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleDeleteChannelAsync(ConnectedClient client, string channelId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (client.User.Role != UserRoles.Owner && client.User.Role != UserRoles.Admin)
|
||||||
|
{
|
||||||
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Only Admins can delete channels." }, ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var channel = await _db.GetChannelByIdAsync(channelId);
|
||||||
|
if (channel == null) return;
|
||||||
|
|
||||||
|
if (channel.Name == "general")
|
||||||
|
{
|
||||||
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Cannot delete the default #general channel." }, ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _db.DeleteChannelAsync(channelId);
|
||||||
|
await BroadcastChannelListAsync();
|
||||||
|
await BroadcastSystemNoticeAsync($"Channel #{channel.Name} was deleted.", "Warning");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleCommandAsync(ConnectedClient client, ExecuteCommandPacket packet, CancellationToken ct)
|
||||||
|
{
|
||||||
|
string cmd = packet.Command.TrimStart('/').ToLowerInvariant();
|
||||||
|
|
||||||
|
// Check mod command interceptor first
|
||||||
|
if (CommandInterceptor != null)
|
||||||
|
{
|
||||||
|
var modResult = await CommandInterceptor(cmd, packet.Args, client);
|
||||||
|
if (modResult != null)
|
||||||
|
{
|
||||||
|
await client.SendMessageAsync(MessageTypes.CommandResult, modResult, ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Built-in commands
|
||||||
|
switch (cmd)
|
||||||
|
{
|
||||||
|
case "help":
|
||||||
|
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" +
|
||||||
|
" /delete <name> - Delete a channel (Admin)\n" +
|
||||||
|
" /users - List all registered users\n" +
|
||||||
|
" /motd - Display message of the day";
|
||||||
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText }, ct);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "motd":
|
||||||
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"MOTD: {_options.Motd}" }, ct);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "users":
|
||||||
|
var users = await _db.GetAllUsersAsync();
|
||||||
|
var userListStr = string.Join("\n", users.Select(u => $" • {u.Username} [{u.Role}]"));
|
||||||
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"Users:\n{userListStr}" }, ct);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Unknown command '/{cmd}'. Type /help for available commands." }, ct);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task BroadcastToChannelAsync<T>(string channelId, string type, T payload)
|
||||||
|
{
|
||||||
|
var envelope = NetworkEnvelope.Create(type, payload);
|
||||||
|
var tasks = _clients.Values
|
||||||
|
.Where(c => c.ActiveChannelId == channelId)
|
||||||
|
.Select(c => c.SendEnvelopeAsync(envelope));
|
||||||
|
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task BroadcastToAllAsync<T>(string type, T payload)
|
||||||
|
{
|
||||||
|
var envelope = NetworkEnvelope.Create(type, payload);
|
||||||
|
var tasks = _clients.Values.Select(c => c.SendEnvelopeAsync(envelope));
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task BroadcastUserListAsync()
|
||||||
|
{
|
||||||
|
var allUsers = await _db.GetAllUsersAsync();
|
||||||
|
var onlineUserIds = new HashSet<string>(_clients.Values.Select(c => c.User.Id));
|
||||||
|
|
||||||
|
foreach (var u in allUsers)
|
||||||
|
{
|
||||||
|
u.IsOnline = onlineUserIds.Contains(u.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
await BroadcastToAllAsync(MessageTypes.UserListSync, new UserListSyncPacket { Users = allUsers });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task BroadcastChannelListAsync()
|
||||||
|
{
|
||||||
|
var channels = await _db.GetChannelsAsync();
|
||||||
|
foreach (var client in _clients.Values)
|
||||||
|
{
|
||||||
|
await client.SendMessageAsync(MessageTypes.ChannelListSync, new ChannelListSyncPacket
|
||||||
|
{
|
||||||
|
Channels = channels,
|
||||||
|
ActiveChannelId = client.ActiveChannelId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task BroadcastSystemNoticeAsync(string text, string level = "Info")
|
||||||
|
{
|
||||||
|
return BroadcastToAllAsync(MessageTypes.SystemNotice, new SystemNoticePacket { Text = text, Level = level });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task BroadcastFileUploadedAsync(FileRecord file)
|
||||||
|
{
|
||||||
|
var files = await _db.GetRecentFilesAsync(100);
|
||||||
|
await BroadcastToAllAsync(MessageTypes.FileListSync, new FileListSyncPacket { Files = files });
|
||||||
|
|
||||||
|
// Broadcast message to channel
|
||||||
|
var msg = new ChatMessage
|
||||||
|
{
|
||||||
|
ChannelId = file.ChannelId,
|
||||||
|
SenderId = file.UploaderId,
|
||||||
|
SenderUsername = file.UploaderUsername,
|
||||||
|
Content = $"Shared file: {file.OriginalFileName} ({FileStorageService.FormatBytes(file.FileSizeBytes)})",
|
||||||
|
CreatedAt = file.CreatedAt,
|
||||||
|
AttachmentId = file.Id,
|
||||||
|
AttachmentName = file.OriginalFileName,
|
||||||
|
AttachmentSizeBytes = file.FileSizeBytes
|
||||||
|
};
|
||||||
|
|
||||||
|
await BroadcastToChannelAsync(file.ChannelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = msg });
|
||||||
|
}
|
||||||
|
}
|
||||||
61
src/GsDChat.Server/WebSockets/ConnectedClient.cs
Normal file
61
src/GsDChat.Server/WebSockets/ConnectedClient.cs
Normal file
|
|
@ -0,0 +1,61 @@
|
||||||
|
using System;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
namespace GsDChat.Server.WebSockets;
|
||||||
|
|
||||||
|
public class ConnectedClient
|
||||||
|
{
|
||||||
|
private readonly SemaphoreSlim _sendLock = new(1, 1);
|
||||||
|
|
||||||
|
public string ConnectionId { get; } = Guid.NewGuid().ToString("N");
|
||||||
|
public WebSocket Socket { get; }
|
||||||
|
public User User { get; }
|
||||||
|
public string ActiveChannelId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public ConnectedClient(WebSocket socket, User user)
|
||||||
|
{
|
||||||
|
Socket = socket;
|
||||||
|
User = user;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SendEnvelopeAsync(NetworkEnvelope envelope, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (Socket.State != WebSocketState.Open)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string json = JsonSerializer.Serialize(envelope);
|
||||||
|
byte[] bytes = Encoding.UTF8.GetBytes(json);
|
||||||
|
|
||||||
|
await _sendLock.WaitAsync(cancellationToken);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Socket.State == WebSocketState.Open)
|
||||||
|
{
|
||||||
|
await Socket.SendAsync(
|
||||||
|
new ArraySegment<byte>(bytes),
|
||||||
|
WebSocketMessageType.Text,
|
||||||
|
true,
|
||||||
|
cancellationToken
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_sendLock.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task SendMessageAsync<T>(string type, T payload, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var envelope = NetworkEnvelope.Create(type, payload);
|
||||||
|
return SendEnvelopeAsync(envelope, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
8
src/GsDChat.Server/appsettings.Development.json
Normal file
8
src/GsDChat.Server/appsettings.Development.json
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
9
src/GsDChat.Server/appsettings.json
Normal file
9
src/GsDChat.Server/appsettings.json
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"AllowedHosts": "*"
|
||||||
|
}
|
||||||
13
src/GsDChat.Server/serversettings.json
Normal file
13
src/GsDChat.Server/serversettings.json
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
{
|
||||||
|
"Host": "0.0.0.0",
|
||||||
|
"Port": 5000,
|
||||||
|
"UseTls": false,
|
||||||
|
"CertificatePath": "",
|
||||||
|
"CertificatePassword": "",
|
||||||
|
"ServerWidePassword": "",
|
||||||
|
"RegistrationMode": "Open",
|
||||||
|
"DataDirectory": "data",
|
||||||
|
"MaxFileSizeMb": 50,
|
||||||
|
"ServerName": "GsDChat Community Server",
|
||||||
|
"Motd": "Welcome to GsDChat! Enjoy private and modular messaging."
|
||||||
|
}
|
||||||
136
tests/GsDChat.Tests/AuthServiceTests.cs
Normal file
136
tests/GsDChat.Tests/AuthServiceTests.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
using GsDChat.Server.Configuration;
|
||||||
|
using GsDChat.Server.Data;
|
||||||
|
using GsDChat.Server.Services;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace GsDChat.Tests;
|
||||||
|
|
||||||
|
public class AuthServiceTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _testDir;
|
||||||
|
private readonly ChatDatabase _db;
|
||||||
|
private readonly ServerOptions _options;
|
||||||
|
private readonly AuthService _auth;
|
||||||
|
|
||||||
|
public AuthServiceTests()
|
||||||
|
{
|
||||||
|
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_auth_test_" + Guid.NewGuid().ToString("N"));
|
||||||
|
_db = new ChatDatabase(_testDir);
|
||||||
|
_db.InitializeAsync().GetAwaiter().GetResult();
|
||||||
|
_options = new ServerOptions
|
||||||
|
{
|
||||||
|
ServerWidePassword = "SecretServerPass"
|
||||||
|
};
|
||||||
|
_auth = new AuthService(_db, _options);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_db.Dispose();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Directory.Exists(_testDir))
|
||||||
|
{
|
||||||
|
Directory.Delete(_testDir, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Register_FailsWithInvalidServerPassword()
|
||||||
|
{
|
||||||
|
var req = new RegisterRequest
|
||||||
|
{
|
||||||
|
Username = "TestUser",
|
||||||
|
Password = "Password123!",
|
||||||
|
ServerPassword = "WrongServerPassword"
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await _auth.RegisterAsync(req);
|
||||||
|
Assert.False(result.Success);
|
||||||
|
Assert.Contains("server-wide password", result.ErrorMessage, StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Register_FirstUserBecomesOwner_SecondUserBecomesMember()
|
||||||
|
{
|
||||||
|
// First user
|
||||||
|
var req1 = new RegisterRequest
|
||||||
|
{
|
||||||
|
Username = "OwnerUser",
|
||||||
|
Password = "Password123!",
|
||||||
|
ServerPassword = "SecretServerPass"
|
||||||
|
};
|
||||||
|
var res1 = await _auth.RegisterAsync(req1);
|
||||||
|
Assert.True(res1.Success);
|
||||||
|
Assert.Equal(UserRoles.Owner, res1.Role);
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(res1.Token));
|
||||||
|
|
||||||
|
// Second user
|
||||||
|
var req2 = new RegisterRequest
|
||||||
|
{
|
||||||
|
Username = "MemberUser",
|
||||||
|
Password = "Password123!",
|
||||||
|
ServerPassword = "SecretServerPass"
|
||||||
|
};
|
||||||
|
var res2 = await _auth.RegisterAsync(req2);
|
||||||
|
Assert.True(res2.Success);
|
||||||
|
Assert.Equal(UserRoles.Member, res2.Role);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Login_ValidCredentials_ReturnsValidSessionToken()
|
||||||
|
{
|
||||||
|
var reg = new RegisterRequest
|
||||||
|
{
|
||||||
|
Username = "LoginTestUser",
|
||||||
|
Password = "ValidPassword123!",
|
||||||
|
ServerPassword = "SecretServerPass"
|
||||||
|
};
|
||||||
|
var regRes = await _auth.RegisterAsync(reg);
|
||||||
|
Assert.True(regRes.Success);
|
||||||
|
|
||||||
|
var loginReq = new LoginRequest
|
||||||
|
{
|
||||||
|
Username = "LoginTestUser",
|
||||||
|
Password = "ValidPassword123!",
|
||||||
|
ServerPassword = "SecretServerPass"
|
||||||
|
};
|
||||||
|
var loginRes = await _auth.LoginAsync(loginReq);
|
||||||
|
Assert.True(loginRes.Success);
|
||||||
|
Assert.NotNull(loginRes.Token);
|
||||||
|
|
||||||
|
// Validate session token
|
||||||
|
var user = await _auth.ValidateSessionTokenAsync(loginRes.Token);
|
||||||
|
Assert.NotNull(user);
|
||||||
|
Assert.Equal("LoginTestUser", user.Username);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Login_InvalidPassword_Fails()
|
||||||
|
{
|
||||||
|
var reg = new RegisterRequest
|
||||||
|
{
|
||||||
|
Username = "FailUser",
|
||||||
|
Password = "CorrectPassword123!",
|
||||||
|
ServerPassword = "SecretServerPass"
|
||||||
|
};
|
||||||
|
await _auth.RegisterAsync(reg);
|
||||||
|
|
||||||
|
var loginReq = new LoginRequest
|
||||||
|
{
|
||||||
|
Username = "FailUser",
|
||||||
|
Password = "WrongPassword",
|
||||||
|
ServerPassword = "SecretServerPass"
|
||||||
|
};
|
||||||
|
var loginRes = await _auth.LoginAsync(loginReq);
|
||||||
|
Assert.False(loginRes.Success);
|
||||||
|
Assert.Equal("Invalid username or password.", loginRes.ErrorMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
61
tests/GsDChat.Tests/CryptoTests.cs
Normal file
61
tests/GsDChat.Tests/CryptoTests.cs
Normal file
|
|
@ -0,0 +1,61 @@
|
||||||
|
using GsDChat.Core.Security;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace GsDChat.Tests;
|
||||||
|
|
||||||
|
public class CryptoTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void HashPassword_ShouldReturnValidHashAndSalt()
|
||||||
|
{
|
||||||
|
var password = "SuperSecretPassword123!";
|
||||||
|
var (hash, salt) = PasswordHasher.HashPassword(password);
|
||||||
|
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(hash));
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(salt));
|
||||||
|
Assert.Equal(128, hash.Length); // 64 bytes hex
|
||||||
|
Assert.Equal(64, salt.Length); // 32 bytes hex
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void VerifyPassword_ShouldSucceedForCorrectPassword()
|
||||||
|
{
|
||||||
|
var password = "MyP@ssw0rd!#2026";
|
||||||
|
var (hash, salt) = PasswordHasher.HashPassword(password);
|
||||||
|
|
||||||
|
bool isValid = PasswordHasher.VerifyPassword(password, hash, salt);
|
||||||
|
Assert.True(isValid);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void VerifyPassword_ShouldFailForIncorrectPassword()
|
||||||
|
{
|
||||||
|
var password = "CorrectPassword";
|
||||||
|
var (hash, salt) = PasswordHasher.HashPassword(password);
|
||||||
|
|
||||||
|
bool isValid = PasswordHasher.VerifyPassword("WrongPassword", hash, salt);
|
||||||
|
Assert.False(isValid);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void HashPassword_SamePassword_ShouldGenerateDifferentSaltsAndHashes()
|
||||||
|
{
|
||||||
|
var password = "IdenticalPassword";
|
||||||
|
var (hash1, salt1) = PasswordHasher.HashPassword(password);
|
||||||
|
var (hash2, salt2) = PasswordHasher.HashPassword(password);
|
||||||
|
|
||||||
|
Assert.NotEqual(salt1, salt2);
|
||||||
|
Assert.NotEqual(hash1, hash2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void GenerateSecureToken_ShouldGenerateUniqueHexStrings()
|
||||||
|
{
|
||||||
|
var token1 = TokenGenerator.GenerateSecureToken(32);
|
||||||
|
var token2 = TokenGenerator.GenerateSecureToken(32);
|
||||||
|
|
||||||
|
Assert.Equal(64, token1.Length);
|
||||||
|
Assert.Equal(64, token2.Length);
|
||||||
|
Assert.NotEqual(token1, token2);
|
||||||
|
}
|
||||||
|
}
|
||||||
127
tests/GsDChat.Tests/DatabaseTests.cs
Normal file
127
tests/GsDChat.Tests/DatabaseTests.cs
Normal file
|
|
@ -0,0 +1,127 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Server.Data;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace GsDChat.Tests;
|
||||||
|
|
||||||
|
public class DatabaseTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _testDir;
|
||||||
|
private readonly ChatDatabase _db;
|
||||||
|
|
||||||
|
public DatabaseTests()
|
||||||
|
{
|
||||||
|
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_test_" + Guid.NewGuid().ToString("N"));
|
||||||
|
_db = new ChatDatabase(_testDir);
|
||||||
|
_db.InitializeAsync().GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_db.Dispose();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Directory.Exists(_testDir))
|
||||||
|
{
|
||||||
|
Directory.Delete(_testDir, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InitializeAsync_ShouldSeedDefaultChannels()
|
||||||
|
{
|
||||||
|
var channels = await _db.GetChannelsAsync();
|
||||||
|
Assert.NotNull(channels);
|
||||||
|
Assert.True(channels.Count >= 2);
|
||||||
|
Assert.Contains(channels, c => c.Name == "general");
|
||||||
|
Assert.Contains(channels, c => c.Name == "announcements");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task CreateUser_AndGetUserByUsername_ShouldPersistCorrectly()
|
||||||
|
{
|
||||||
|
var user = new User
|
||||||
|
{
|
||||||
|
Username = "Alice",
|
||||||
|
PasswordHash = "hash123",
|
||||||
|
PasswordSalt = "salt123",
|
||||||
|
Role = UserRoles.Owner
|
||||||
|
};
|
||||||
|
|
||||||
|
bool created = await _db.CreateUserAsync(user);
|
||||||
|
Assert.True(created);
|
||||||
|
|
||||||
|
var retrieved = await _db.GetUserByUsernameAsync("Alice");
|
||||||
|
Assert.NotNull(retrieved);
|
||||||
|
Assert.Equal("Alice", retrieved.Username);
|
||||||
|
Assert.Equal(UserRoles.Owner, retrieved.Role);
|
||||||
|
|
||||||
|
// Case insensitivity
|
||||||
|
var retrievedLower = await _db.GetUserByUsernameAsync("alice");
|
||||||
|
Assert.NotNull(retrievedLower);
|
||||||
|
Assert.Equal(retrieved.Id, retrievedLower.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SaveMessage_AndGetRecentMessages_ShouldPreserveOrder()
|
||||||
|
{
|
||||||
|
var channels = await _db.GetChannelsAsync();
|
||||||
|
var general = channels.First(c => c.Name == "general");
|
||||||
|
|
||||||
|
var msg1 = new ChatMessage
|
||||||
|
{
|
||||||
|
ChannelId = general.Id,
|
||||||
|
SenderId = "u1",
|
||||||
|
SenderUsername = "Alice",
|
||||||
|
Content = "First message",
|
||||||
|
CreatedAt = DateTime.UtcNow.AddSeconds(-10)
|
||||||
|
};
|
||||||
|
var msg2 = new ChatMessage
|
||||||
|
{
|
||||||
|
ChannelId = general.Id,
|
||||||
|
SenderId = "u2",
|
||||||
|
SenderUsername = "Bob",
|
||||||
|
Content = "Second message",
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
};
|
||||||
|
|
||||||
|
await _db.SaveMessageAsync(msg1);
|
||||||
|
await _db.SaveMessageAsync(msg2);
|
||||||
|
|
||||||
|
var messages = await _db.GetRecentMessagesAsync(general.Id, 10);
|
||||||
|
Assert.True(messages.Count >= 2);
|
||||||
|
Assert.Equal("First message", messages[^2].Content);
|
||||||
|
Assert.Equal("Second message", messages[^1].Content);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ChannelOperations_CreateAndDuplicateAndGet()
|
||||||
|
{
|
||||||
|
var channel = new Channel
|
||||||
|
{
|
||||||
|
Name = "gaming",
|
||||||
|
Topic = "Gaming discussion"
|
||||||
|
};
|
||||||
|
|
||||||
|
bool created = await _db.CreateChannelAsync(channel);
|
||||||
|
Assert.True(created);
|
||||||
|
|
||||||
|
// Duplicate name should fail
|
||||||
|
var dup = new Channel
|
||||||
|
{
|
||||||
|
Name = "gaming",
|
||||||
|
Topic = "Duplicate"
|
||||||
|
};
|
||||||
|
bool dupCreated = await _db.CreateChannelAsync(dup);
|
||||||
|
Assert.False(dupCreated);
|
||||||
|
|
||||||
|
var found = await _db.GetChannelByNameAsync("gaming");
|
||||||
|
Assert.NotNull(found);
|
||||||
|
Assert.Equal("Gaming discussion", found.Topic);
|
||||||
|
}
|
||||||
|
}
|
||||||
272
tests/GsDChat.Tests/EndToEndChatTests.cs
Normal file
272
tests/GsDChat.Tests/EndToEndChatTests.cs
Normal file
|
|
@ -0,0 +1,272 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using GsDChat.Client.Network;
|
||||||
|
using GsDChat.Client.State;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
using GsDChat.Server.Configuration;
|
||||||
|
using GsDChat.Server.Data;
|
||||||
|
using GsDChat.Server.Services;
|
||||||
|
using GsDChat.Server.WebSockets;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace GsDChat.Tests;
|
||||||
|
|
||||||
|
public class EndToEndChatTests : IAsyncLifetime
|
||||||
|
{
|
||||||
|
private readonly string _testDir;
|
||||||
|
private WebApplication? _app;
|
||||||
|
private int _port;
|
||||||
|
private string _serverUrl = string.Empty;
|
||||||
|
|
||||||
|
public EndToEndChatTests()
|
||||||
|
{
|
||||||
|
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_e2e_" + Guid.NewGuid().ToString("N"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
// Pick an unused local port
|
||||||
|
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();
|
||||||
|
builder.WebHost.UseUrls(_serverUrl);
|
||||||
|
builder.Logging.ClearProviders(); // Keep test output clean
|
||||||
|
|
||||||
|
var serverOptions = new ServerOptions
|
||||||
|
{
|
||||||
|
Host = "127.0.0.1",
|
||||||
|
Port = _port,
|
||||||
|
UseTls = false,
|
||||||
|
DataDirectory = _testDir,
|
||||||
|
ServerName = "E2E Test Server",
|
||||||
|
Motd = "Testing GsDChat E2E"
|
||||||
|
};
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
var db = _app.Services.GetRequiredService<ChatDatabase>();
|
||||||
|
await db.InitializeAsync();
|
||||||
|
|
||||||
|
_app.UseWebSockets();
|
||||||
|
|
||||||
|
string? ExtractToken(HttpRequest req)
|
||||||
|
{
|
||||||
|
if (req.Headers.TryGetValue("Authorization", out var h) && h.ToString().StartsWith("Bearer "))
|
||||||
|
return h.ToString().Substring(7).Trim();
|
||||||
|
if (req.Query.TryGetValue("token", out var q))
|
||||||
|
return q.ToString();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
_app.MapGet("/api/info", (ServerOptions opt) => Results.Ok(new ServerInfoResponse
|
||||||
|
{
|
||||||
|
ServerName = opt.ServerName,
|
||||||
|
Version = "1.0.0",
|
||||||
|
RegistrationMode = opt.RegistrationMode,
|
||||||
|
RequiresServerPassword = !string.IsNullOrWhiteSpace(opt.ServerWidePassword),
|
||||||
|
Motd = opt.Motd,
|
||||||
|
MaxFileSizeMb = opt.MaxFileSizeMb
|
||||||
|
}));
|
||||||
|
|
||||||
|
_app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth) =>
|
||||||
|
{
|
||||||
|
var res = await auth.RegisterAsync(req);
|
||||||
|
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
||||||
|
});
|
||||||
|
|
||||||
|
_app.MapPost("/api/auth/login", async (LoginRequest req, IAuthService auth) =>
|
||||||
|
{
|
||||||
|
var res = await auth.LoginAsync(req);
|
||||||
|
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
||||||
|
});
|
||||||
|
|
||||||
|
_app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, FileStorageService fileSvc, ChatWebSocketManager ws) =>
|
||||||
|
{
|
||||||
|
string? token = ExtractToken(req);
|
||||||
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
|
if (user == null) return Results.Unauthorized();
|
||||||
|
|
||||||
|
var form = await req.ReadFormAsync();
|
||||||
|
var file = form.Files.GetFile("file");
|
||||||
|
if (file == null) return Results.BadRequest();
|
||||||
|
string chId = form["channelId"].ToString();
|
||||||
|
|
||||||
|
using var stream = file.OpenReadStream();
|
||||||
|
var record = await fileSvc.StoreFileAsync(chId, user.Id, user.Username, file.FileName, file.ContentType, stream, file.Length);
|
||||||
|
await ws.BroadcastFileUploadedAsync(record);
|
||||||
|
|
||||||
|
return Results.Ok(new UploadFileResponse
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
FileId = record.Id,
|
||||||
|
FileName = record.OriginalFileName,
|
||||||
|
FileSizeBytes = record.FileSizeBytes,
|
||||||
|
ChannelId = record.ChannelId
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
_app.MapGet("/api/files/{id}", async (string id, HttpRequest req, IAuthService auth, FileStorageService fileSvc) =>
|
||||||
|
{
|
||||||
|
string? token = ExtractToken(req);
|
||||||
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
|
if (user == null) return Results.Unauthorized();
|
||||||
|
|
||||||
|
var record = await fileSvc.GetFileRecordAsync(id);
|
||||||
|
if (record == null) return Results.NotFound();
|
||||||
|
|
||||||
|
var stream = fileSvc.OpenFileStream(record);
|
||||||
|
if (stream == null) return Results.NotFound();
|
||||||
|
|
||||||
|
return Results.File(stream, record.ContentType, record.OriginalFileName);
|
||||||
|
});
|
||||||
|
|
||||||
|
_app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager ws) =>
|
||||||
|
{
|
||||||
|
if (!context.WebSockets.IsWebSocketRequest)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 400;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
string? token = ExtractToken(context.Request);
|
||||||
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 401;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var socket = await context.WebSockets.AcceptWebSocketAsync();
|
||||||
|
await ws.HandleClientAsync(socket, user, context.RequestAborted);
|
||||||
|
});
|
||||||
|
|
||||||
|
await _app.StartAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DisposeAsync()
|
||||||
|
{
|
||||||
|
if (_app != null)
|
||||||
|
{
|
||||||
|
await _app.StopAsync();
|
||||||
|
await _app.DisposeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Directory.Exists(_testDir))
|
||||||
|
{
|
||||||
|
Directory.Delete(_testDir, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task FullChatAndFileTransferFlow_ShouldSucceed()
|
||||||
|
{
|
||||||
|
// 1. Client 1 (Alice): Register
|
||||||
|
var stateAlice = new ClientState { ServerUrl = _serverUrl };
|
||||||
|
using var connAlice = new ChatClientConnection(stateAlice);
|
||||||
|
|
||||||
|
var regAlice = await connAlice.RegisterAsync("Alice", "AliceSecretPassword123");
|
||||||
|
Assert.True(regAlice.Success);
|
||||||
|
Assert.Equal(UserRoles.Owner, regAlice.Role);
|
||||||
|
stateAlice.Token = regAlice.Token!;
|
||||||
|
stateAlice.CurrentUserId = regAlice.UserId!;
|
||||||
|
stateAlice.CurrentUsername = regAlice.Username!;
|
||||||
|
stateAlice.CurrentUserRole = regAlice.Role!;
|
||||||
|
|
||||||
|
// 2. Client 2 (Bob): Register
|
||||||
|
var stateBob = new ClientState { ServerUrl = _serverUrl };
|
||||||
|
using var connBob = new ChatClientConnection(stateBob);
|
||||||
|
|
||||||
|
var regBob = await connBob.RegisterAsync("Bob", "BobSecretPassword123");
|
||||||
|
Assert.True(regBob.Success);
|
||||||
|
Assert.Equal(UserRoles.Member, regBob.Role);
|
||||||
|
stateBob.Token = regBob.Token!;
|
||||||
|
stateBob.CurrentUserId = regBob.UserId!;
|
||||||
|
stateBob.CurrentUsername = regBob.Username!;
|
||||||
|
stateBob.CurrentUserRole = regBob.Role!;
|
||||||
|
|
||||||
|
// 3. Connect both clients to WebSockets
|
||||||
|
await connAlice.StartWebSocketAsync();
|
||||||
|
await connBob.StartWebSocketAsync();
|
||||||
|
|
||||||
|
// Allow initial sync to complete
|
||||||
|
await Task.Delay(300);
|
||||||
|
|
||||||
|
Assert.True(stateAlice.Channels.Count > 0);
|
||||||
|
Assert.True(stateBob.Channels.Count > 0);
|
||||||
|
Assert.False(string.IsNullOrEmpty(stateAlice.ActiveChannelId));
|
||||||
|
string generalChannelId = stateAlice.ActiveChannelId;
|
||||||
|
|
||||||
|
// 4. Alice sends a chat message
|
||||||
|
await connAlice.SendChatMessageAsync(generalChannelId, "Hello Bob, welcome to GsDChat!");
|
||||||
|
|
||||||
|
// Wait for broadcast to reach Bob
|
||||||
|
for (int i = 0; i < 20; i++)
|
||||||
|
{
|
||||||
|
if (stateBob.ChannelMessages.TryGetValue(generalChannelId, out var msgs) && msgs.Exists(m => m.Content.Contains("Hello Bob")))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await Task.Delay(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.True(stateBob.ChannelMessages.TryGetValue(generalChannelId, out var bobMsgs));
|
||||||
|
Assert.Contains(bobMsgs, m => m.Content == "Hello Bob, welcome to GsDChat!" && m.SenderUsername == "Alice");
|
||||||
|
|
||||||
|
// 5. Alice uploads a test file
|
||||||
|
string localFilePath = Path.Combine(_testDir, "shared_document.txt");
|
||||||
|
string fileContent = "This is a confidential community file uploaded over secure HTTPS.";
|
||||||
|
await File.WriteAllTextAsync(localFilePath, fileContent);
|
||||||
|
|
||||||
|
bool uploadSuccess = await connAlice.UploadFileAsync(localFilePath, generalChannelId);
|
||||||
|
Assert.True(uploadSuccess);
|
||||||
|
|
||||||
|
// Wait for file list sync to reach Bob
|
||||||
|
for (int i = 0; i < 20; i++)
|
||||||
|
{
|
||||||
|
if (stateBob.Files.Exists(f => f.OriginalFileName == "shared_document.txt"))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await Task.Delay(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
var sharedFile = stateBob.Files.Find(f => f.OriginalFileName == "shared_document.txt");
|
||||||
|
Assert.NotNull(sharedFile);
|
||||||
|
|
||||||
|
// 6. Bob downloads the file
|
||||||
|
string bobDownloadsDir = Path.Combine(_testDir, "bob_downloads");
|
||||||
|
bool downloadSuccess = await connBob.DownloadFileAsync(sharedFile.Id, bobDownloadsDir);
|
||||||
|
Assert.True(downloadSuccess);
|
||||||
|
|
||||||
|
string downloadedFilePath = Path.Combine(bobDownloadsDir, "shared_document.txt");
|
||||||
|
Assert.True(File.Exists(downloadedFilePath));
|
||||||
|
string downloadedText = await File.ReadAllTextAsync(downloadedFilePath);
|
||||||
|
Assert.Equal(fileContent, downloadedText);
|
||||||
|
}
|
||||||
|
}
|
||||||
81
tests/GsDChat.Tests/FileStorageServiceTests.cs
Normal file
81
tests/GsDChat.Tests/FileStorageServiceTests.cs
Normal file
|
|
@ -0,0 +1,81 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GsDChat.Server.Configuration;
|
||||||
|
using GsDChat.Server.Data;
|
||||||
|
using GsDChat.Server.Services;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace GsDChat.Tests;
|
||||||
|
|
||||||
|
public class FileStorageServiceTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _testDir;
|
||||||
|
private readonly ChatDatabase _db;
|
||||||
|
private readonly ServerOptions _options;
|
||||||
|
private readonly FileStorageService _fileService;
|
||||||
|
|
||||||
|
public FileStorageServiceTests()
|
||||||
|
{
|
||||||
|
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_file_test_" + Guid.NewGuid().ToString("N"));
|
||||||
|
_db = new ChatDatabase(_testDir);
|
||||||
|
_db.InitializeAsync().GetAwaiter().GetResult();
|
||||||
|
_options = new ServerOptions
|
||||||
|
{
|
||||||
|
DataDirectory = _testDir,
|
||||||
|
MaxFileSizeMb = 5
|
||||||
|
};
|
||||||
|
_fileService = new FileStorageService(_db, _options);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_db.Dispose();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Directory.Exists(_testDir))
|
||||||
|
{
|
||||||
|
Directory.Delete(_testDir, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task StoreAndReadFile_ShouldPreserveExactContentAndComputeSha256()
|
||||||
|
{
|
||||||
|
var channels = await _db.GetChannelsAsync();
|
||||||
|
var general = channels[0];
|
||||||
|
|
||||||
|
string fileContent = "Hello from GsDChat test file storage! Secure and modular.";
|
||||||
|
byte[] fileBytes = Encoding.UTF8.GetBytes(fileContent);
|
||||||
|
|
||||||
|
using var memoryStream = new MemoryStream(fileBytes);
|
||||||
|
var record = await _fileService.StoreFileAsync(
|
||||||
|
general.Id,
|
||||||
|
"uploader-1",
|
||||||
|
"Tester",
|
||||||
|
"test_note.txt",
|
||||||
|
"text/plain",
|
||||||
|
memoryStream,
|
||||||
|
fileBytes.Length
|
||||||
|
);
|
||||||
|
|
||||||
|
Assert.NotNull(record);
|
||||||
|
Assert.Equal("test_note.txt", record.OriginalFileName);
|
||||||
|
Assert.Equal(fileBytes.Length, record.FileSizeBytes);
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(record.Sha256Checksum));
|
||||||
|
|
||||||
|
// Read file back
|
||||||
|
var fetchedRecord = await _fileService.GetFileRecordAsync(record.Id);
|
||||||
|
Assert.NotNull(fetchedRecord);
|
||||||
|
Assert.Equal(record.Sha256Checksum, fetchedRecord.Sha256Checksum);
|
||||||
|
|
||||||
|
using var stream = _fileService.OpenFileStream(fetchedRecord);
|
||||||
|
Assert.NotNull(stream);
|
||||||
|
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||||
|
string readBack = await reader.ReadToEndAsync();
|
||||||
|
Assert.Equal(fileContent, readBack);
|
||||||
|
}
|
||||||
|
}
|
||||||
29
tests/GsDChat.Tests/GsDChat.Tests.csproj
Normal file
29
tests/GsDChat.Tests/GsDChat.Tests.csproj
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||||
|
<PackageReference Include="xunit" Version="2.9.3" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="Xunit" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\src\GsDChat.Core\GsDChat.Core.csproj" />
|
||||||
|
<ProjectReference Include="..\..\src\GsDChat.Server\GsDChat.Server.csproj" />
|
||||||
|
<ProjectReference Include="..\..\src\GsDChat.Client\GsDChat.Client.csproj" />
|
||||||
|
<ProjectReference Include="..\..\src\GsDChat.Modding\GsDChat.Modding.csproj" />
|
||||||
|
<ProjectReference Include="..\..\src\GsDChat.Mods.SampleBot\GsDChat.Mods.SampleBot.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
199
tests/GsDChat.Tests/ModSystemTests.cs
Normal file
199
tests/GsDChat.Tests/ModSystemTests.cs
Normal file
|
|
@ -0,0 +1,199 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using GsDChat.Core.Models;
|
||||||
|
using GsDChat.Modding;
|
||||||
|
using GsDChat.Mods.SampleBot;
|
||||||
|
using GsDChat.Server.Configuration;
|
||||||
|
using GsDChat.Server.Data;
|
||||||
|
using GsDChat.Server.Services;
|
||||||
|
using GsDChat.Server.WebSockets;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace GsDChat.Tests;
|
||||||
|
|
||||||
|
public class ModSystemTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _testDir;
|
||||||
|
private readonly ChatDatabase _db;
|
||||||
|
private readonly ServerOptions _options;
|
||||||
|
private readonly ChatWebSocketManager _wsManager;
|
||||||
|
private readonly ModLoaderService _modLoader;
|
||||||
|
|
||||||
|
public ModSystemTests()
|
||||||
|
{
|
||||||
|
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_mod_test_" + Guid.NewGuid().ToString("N"));
|
||||||
|
_options = new ServerOptions
|
||||||
|
{
|
||||||
|
DataDirectory = _testDir,
|
||||||
|
ServerName = "Mod Test Server",
|
||||||
|
Motd = "Initial MOTD"
|
||||||
|
};
|
||||||
|
_db = new ChatDatabase(_testDir);
|
||||||
|
_db.InitializeAsync().GetAwaiter().GetResult();
|
||||||
|
_wsManager = new ChatWebSocketManager(_db, _options, NullLogger<ChatWebSocketManager>.Instance);
|
||||||
|
_modLoader = new ModLoaderService(_options, _wsManager, NullLogger<ModLoaderService>.Instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_modLoader.ShutdownModsAsync().GetAwaiter().GetResult();
|
||||||
|
_db.Dispose();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Directory.Exists(_testDir))
|
||||||
|
{
|
||||||
|
Directory.Delete(_testDir, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task MessagePipeline_ShouldTransformAndAllowChain()
|
||||||
|
{
|
||||||
|
var pipeline = new MessagePipeline();
|
||||||
|
|
||||||
|
// Middleware 1: Appends "[Verified]"
|
||||||
|
pipeline.Use(async (ctx, next) =>
|
||||||
|
{
|
||||||
|
ctx.Message.Content += " [Verified]";
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Middleware 2: Replaces "foo" with "bar"
|
||||||
|
pipeline.Use(async (ctx, next) =>
|
||||||
|
{
|
||||||
|
ctx.Message.Content = ctx.Message.Content.Replace("foo", "bar");
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
var msg = new ChatMessage { Content = "This is foo" };
|
||||||
|
var result = await pipeline.ExecuteAsync(msg);
|
||||||
|
|
||||||
|
Assert.False(result.IsCancelled);
|
||||||
|
Assert.Equal("This is bar [Verified]", result.Message.Content);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task MessagePipeline_Cancellation_ShouldDropMessage()
|
||||||
|
{
|
||||||
|
var pipeline = new MessagePipeline();
|
||||||
|
|
||||||
|
pipeline.Use(async (ctx, next) =>
|
||||||
|
{
|
||||||
|
if (ctx.Message.Content.Contains("spam"))
|
||||||
|
{
|
||||||
|
ctx.IsCancelled = true;
|
||||||
|
ctx.CancellationReason = "Spam detected";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
var msg = new ChatMessage { Content = "Buy cheap spam now!" };
|
||||||
|
var result = await pipeline.ExecuteAsync(msg);
|
||||||
|
|
||||||
|
Assert.True(result.IsCancelled);
|
||||||
|
Assert.Equal("Spam detected", result.CancellationReason);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SampleBotMod_DirectInitialization_CommandsAndPipeline()
|
||||||
|
{
|
||||||
|
var botMod = new SampleBotMod();
|
||||||
|
var context = new ModContext(
|
||||||
|
_modLoader.EventBus,
|
||||||
|
_modLoader.Commands,
|
||||||
|
_modLoader.Pipeline,
|
||||||
|
_modLoader.Ui,
|
||||||
|
Path.Combine(_testDir, "bot_data")
|
||||||
|
);
|
||||||
|
|
||||||
|
await botMod.InitializeAsync(context);
|
||||||
|
|
||||||
|
// Test /roll command
|
||||||
|
var rollResult = await _modLoader.Commands.ExecuteCommandAsync(new CommandContext
|
||||||
|
{
|
||||||
|
Command = "roll",
|
||||||
|
Args = "2d6",
|
||||||
|
Username = "Alice",
|
||||||
|
UserRole = UserRoles.Member
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.NotNull(rollResult);
|
||||||
|
Assert.True(rollResult.Success);
|
||||||
|
Assert.Contains("rolled 2d6", rollResult.Output);
|
||||||
|
|
||||||
|
// Test /announce command (Member forbidden, Admin allowed)
|
||||||
|
var memberAnnounce = await _modLoader.Commands.ExecuteCommandAsync(new CommandContext
|
||||||
|
{
|
||||||
|
Command = "announce",
|
||||||
|
Args = "Server restart soon",
|
||||||
|
Username = "Bob",
|
||||||
|
UserRole = UserRoles.Member
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.NotNull(memberAnnounce);
|
||||||
|
Assert.False(memberAnnounce.Success);
|
||||||
|
|
||||||
|
var adminAnnounce = await _modLoader.Commands.ExecuteCommandAsync(new CommandContext
|
||||||
|
{
|
||||||
|
Command = "announce",
|
||||||
|
Args = "Server restart soon",
|
||||||
|
Username = "Alice",
|
||||||
|
UserRole = UserRoles.Admin
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.NotNull(adminAnnounce);
|
||||||
|
Assert.True(adminAnnounce.Success);
|
||||||
|
Assert.Contains("OFFICIAL ANNOUNCEMENT", adminAnnounce.Output);
|
||||||
|
|
||||||
|
// Test Pipeline transformation (shorthand emoji replacement)
|
||||||
|
var testMsg = new ChatMessage { Content = "I don't know :shrug: and rage :tableflip: with :heart:" };
|
||||||
|
var pipelineRes = await _modLoader.Pipeline.ExecuteAsync(testMsg);
|
||||||
|
|
||||||
|
Assert.False(pipelineRes.IsCancelled);
|
||||||
|
Assert.Contains("¯\\_(ツ)_/¯", pipelineRes.Message.Content);
|
||||||
|
Assert.Contains("(╯°□°)╯︵ ┻━┻", pipelineRes.Message.Content);
|
||||||
|
Assert.Contains("❤️", pipelineRes.Message.Content);
|
||||||
|
|
||||||
|
// Test F5 Screen registration
|
||||||
|
var ui = _modLoader.Ui.GetUiSync();
|
||||||
|
Assert.Contains(ui.Screens, s => s.ScreenId == "F5_Custom" && s.Title == "Server Status");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ModLoaderService_LoadsDllFromDirectoryViaAssemblyLoadContext()
|
||||||
|
{
|
||||||
|
// Copy built GsDChat.Mods.SampleBot.dll into a temporary mods folder
|
||||||
|
string modsDir = Path.Combine(_testDir, "mods");
|
||||||
|
Directory.CreateDirectory(modsDir);
|
||||||
|
|
||||||
|
string sampleBotDll = typeof(SampleBotMod).Assembly.Location;
|
||||||
|
Assert.True(File.Exists(sampleBotDll));
|
||||||
|
|
||||||
|
string targetDllPath = Path.Combine(modsDir, "GsDChat.Mods.SampleBot.dll");
|
||||||
|
File.Copy(sampleBotDll, targetDllPath, overwrite: true);
|
||||||
|
|
||||||
|
// Load via ModLoaderService
|
||||||
|
await _modLoader.LoadModsAsync(modsDir);
|
||||||
|
|
||||||
|
// Verify that the command registered via dynamically loaded assembly works
|
||||||
|
Assert.True(_modLoader.Commands.HasCommand("roll"));
|
||||||
|
Assert.True(_modLoader.Commands.HasCommand("announce"));
|
||||||
|
|
||||||
|
var cmdRes = await _modLoader.Commands.ExecuteCommandAsync(new CommandContext
|
||||||
|
{
|
||||||
|
Command = "roll",
|
||||||
|
Args = "1d20",
|
||||||
|
Username = "Tester",
|
||||||
|
UserRole = UserRoles.Member
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.NotNull(cmdRes);
|
||||||
|
Assert.True(cmdRes.Success);
|
||||||
|
Assert.Contains("rolled 1d20", cmdRes.Output);
|
||||||
|
}
|
||||||
|
}
|
||||||
42
tests/GsDChat.Tests/NetworkProtocolTests.cs
Normal file
42
tests/GsDChat.Tests/NetworkProtocolTests.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
using GsDChat.Core.Protocol;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace GsDChat.Tests;
|
||||||
|
|
||||||
|
public class NetworkProtocolTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void NetworkEnvelope_PackingAndUnpacking_ShouldPreserveData()
|
||||||
|
{
|
||||||
|
var authPacket = new AuthPacket
|
||||||
|
{
|
||||||
|
Token = "test_token_12345",
|
||||||
|
ServerPassword = "server_secret"
|
||||||
|
};
|
||||||
|
|
||||||
|
var envelope = NetworkEnvelope.Create(MessageTypes.Auth, authPacket);
|
||||||
|
Assert.Equal(MessageTypes.Auth, envelope.Type);
|
||||||
|
Assert.Contains("test_token_12345", envelope.Payload);
|
||||||
|
|
||||||
|
var unpacked = envelope.Unpack<AuthPacket>();
|
||||||
|
Assert.NotNull(unpacked);
|
||||||
|
Assert.Equal("test_token_12345", unpacked.Token);
|
||||||
|
Assert.Equal("server_secret", unpacked.ServerPassword);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ServerUiSync_DefaultSchema_ContainsAllStandardScreens()
|
||||||
|
{
|
||||||
|
var sync = ServerUiSync.CreateDefault("TestServer", "Welcome MOTD");
|
||||||
|
|
||||||
|
Assert.Equal("TestServer", sync.ServerName);
|
||||||
|
Assert.Equal("Welcome MOTD", sync.Motd);
|
||||||
|
Assert.NotNull(sync.Screens);
|
||||||
|
Assert.Equal(4, sync.Screens.Count);
|
||||||
|
|
||||||
|
Assert.Contains(sync.Screens, s => s.ScreenId == "F1_Chat");
|
||||||
|
Assert.Contains(sync.Screens, s => s.ScreenId == "F2_Channels");
|
||||||
|
Assert.Contains(sync.Screens, s => s.ScreenId == "F3_Users");
|
||||||
|
Assert.Contains(sync.Screens, s => s.ScreenId == "F4_Files");
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue