This commit is contained in:
tyuXX 2026-10-10 16:40:35 +00:00
commit f25ba8adcd
64 changed files with 5959 additions and 0 deletions

View 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.";
}

View 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
}
}

View 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>

View 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 { }

View 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"
}
}
}
}

View 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;
}
}

View 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]}";
}
}

View 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);
}

View 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();
}
}

View 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 });
}
}

View 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);
}
}

View file

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View file

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View 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."
}