1782 lines
78 KiB
C#
1782 lines
78 KiB
C#
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.Text.RegularExpressions;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using GsDChat.Core.Models;
|
|
using GsDChat.Core.Protocol;
|
|
using GsDChat.Core.Security;
|
|
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;
|
|
private readonly WebPushService? _webPush;
|
|
private readonly FileStorageService _fileService;
|
|
|
|
// 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,
|
|
WebPushService? webPush = null,
|
|
FileStorageService? fileStorage = null)
|
|
{
|
|
_db = db;
|
|
_options = options;
|
|
_logger = logger;
|
|
_webPush = webPush;
|
|
_fileService = fileStorage ?? new FileStorageService(db, options);
|
|
}
|
|
|
|
public int ConnectedCount => _clients.Count;
|
|
|
|
public async Task HandleClientAsync(WebSocket socket, User user, CancellationToken cancellationToken, int maxMessageSizeBytes = 1048576)
|
|
{
|
|
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,
|
|
_options.AllowDmE2ee,
|
|
_options.MaxGroupChatUsers);
|
|
uiSync.AllowDmE2ee = _options.AllowDmE2ee;
|
|
uiSync.MaxGroupChatUsers = _options.MaxGroupChatUsers;
|
|
|
|
// Send AuthResult with current E2EE key vault metadata so restored sessions have latest server state
|
|
await client.SendMessageAsync(MessageTypes.AuthResult, new AuthResultPacket
|
|
{
|
|
Success = true,
|
|
UserId = user.Id,
|
|
Username = user.Username,
|
|
Role = user.Role,
|
|
PublicKey = user.PublicKey,
|
|
EncryptedPrivateKey = user.EncryptedPrivateKey,
|
|
E2eeEnabled = user.E2eeEnabled,
|
|
UiSync = uiSync,
|
|
ActiveChannelId = client.ActiveChannelId
|
|
}, cancellationToken);
|
|
|
|
await client.SendMessageAsync(MessageTypes.UiSync, uiSync, cancellationToken);
|
|
|
|
// Send Channel, DM, and Group Chat Lists
|
|
await SendChannelListToClientAsync(client, cancellationToken);
|
|
|
|
// Send Initial Chat History (latest 50 messages, with HasMore flag for on-demand loading)
|
|
if (!string.IsNullOrEmpty(client.ActiveChannelId))
|
|
{
|
|
await SendHistoryPageAsync(client, client.ActiveChannelId, offset: 0, limit: 50, prepend: false, cancellationToken);
|
|
}
|
|
|
|
// Send Files List (filtered for user access)
|
|
await SendFileListToClientAsync(client, cancellationToken);
|
|
|
|
// Send Initial Inbox & Preferences Sync
|
|
await SendInboxSyncToClientAsync(client, cancellationToken);
|
|
|
|
// Send Initial User List
|
|
var initialUsers = await _db.GetAllUsersAsync();
|
|
var onlineIds = new HashSet<string>(_clients.Values.Select(c => c.User.Id), StringComparer.OrdinalIgnoreCase);
|
|
var onlineNames = new HashSet<string>(_clients.Values.Select(c => c.User.Username), StringComparer.OrdinalIgnoreCase);
|
|
foreach (var u in initialUsers)
|
|
{
|
|
u.IsOnline = onlineIds.Contains(u.Id) || onlineNames.Contains(u.Username);
|
|
}
|
|
await client.SendMessageAsync(MessageTypes.UserListSync, new UserListSyncPacket { Users = initialUsers }, cancellationToken);
|
|
|
|
// Broadcast Presence Update
|
|
await BroadcastUserListAsync();
|
|
await BroadcastSystemNoticeAsync($"[+] {InputSanitizer.SanitizeUsername(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));
|
|
|
|
// Check message size limit
|
|
if (messageAccumulator.Count > maxMessageSizeBytes)
|
|
{
|
|
messageAccumulator.Clear();
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Message too large." }, cancellationToken);
|
|
continue;
|
|
}
|
|
|
|
if (result.EndOfMessage)
|
|
{
|
|
string json = Encoding.UTF8.GetString(messageAccumulator.ToArray());
|
|
messageAccumulator.Clear();
|
|
await ProcessClientMessageAsync(client, json, cancellationToken);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (OperationCanceledException) { }
|
|
catch (WebSocketException ex)
|
|
{
|
|
SafeLogger.LogDebug(_logger, "WebSocket error for {Username}: {Msg}", InputSanitizer.SanitizeUsername(user.Username), ex.Message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
SafeLogger.LogError(_logger, ex, "Unexpected error handling client {Username}", InputSanitizer.SanitizeUsername(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($"[-] {InputSanitizer.SanitizeUsername(user.Username)} disconnected.", "Info");
|
|
}
|
|
}
|
|
|
|
private static readonly JsonSerializerOptions s_envelopeJsonOptions = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true
|
|
};
|
|
|
|
private async Task ProcessClientMessageAsync(ConnectedClient client, string json, CancellationToken ct)
|
|
{
|
|
try
|
|
{
|
|
var envelope = JsonSerializer.Deserialize<NetworkEnvelope>(json, s_envelopeJsonOptions);
|
|
if (envelope == null || string.IsNullOrWhiteSpace(envelope.Type)) return;
|
|
|
|
string msgType = envelope.Type.Trim().ToUpperInvariant();
|
|
|
|
switch (msgType)
|
|
{
|
|
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.FetchHistory:
|
|
var fetchPkg = envelope.Unpack<FetchHistoryPacket>();
|
|
if (fetchPkg != null)
|
|
{
|
|
await HandleFetchHistoryAsync(client, fetchPkg, 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.DeleteFile:
|
|
var delFilePkg = envelope.Unpack<DeleteFilePacket>();
|
|
if (delFilePkg != null && !string.IsNullOrWhiteSpace(delFilePkg.FileId))
|
|
{
|
|
await HandleDeleteFileAsync(client, delFilePkg.FileId, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.StartDm:
|
|
var dmPkg = envelope.Unpack<StartDmPacket>();
|
|
if (dmPkg != null)
|
|
{
|
|
await HandleStartDmAsync(client, dmPkg, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.CreateGroup:
|
|
var groupPkg = envelope.Unpack<CreateGroupPacket>();
|
|
if (groupPkg != null)
|
|
{
|
|
await HandleCreateGroupAsync(client, groupPkg, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.InviteToGroup:
|
|
var invitePkg = envelope.Unpack<InviteToGroupPacket>();
|
|
if (invitePkg != null)
|
|
{
|
|
await HandleInviteToGroupAsync(client, invitePkg, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.LeaveGroup:
|
|
var leavePkg = envelope.Unpack<LeaveGroupPacket>();
|
|
if (leavePkg != null)
|
|
{
|
|
await HandleLeaveGroupAsync(client, leavePkg, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.PublishPublicKey:
|
|
var keyPkg = envelope.Unpack<PublishPublicKeyPacket>();
|
|
if (keyPkg != null)
|
|
{
|
|
await HandlePublishPublicKeyAsync(client, keyPkg, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.ToggleE2ee:
|
|
var togglePkg = envelope.Unpack<ToggleE2eePacket>();
|
|
if (togglePkg != null)
|
|
{
|
|
await HandleToggleE2eeAsync(client, togglePkg, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.ExecuteCommand:
|
|
var cmdPkg = envelope.Unpack<ExecuteCommandPacket>();
|
|
if (cmdPkg != null)
|
|
{
|
|
await HandleCommandAsync(client, cmdPkg, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.InboxSync:
|
|
await SendInboxSyncToClientAsync(client, ct);
|
|
break;
|
|
|
|
case MessageTypes.InboxAction:
|
|
var inboxAct = envelope.Unpack<InboxActionPacket>();
|
|
if (inboxAct != null)
|
|
{
|
|
await HandleInboxActionAsync(client, inboxAct, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.UpdateInboxPreferences:
|
|
var prefsPkg = envelope.Unpack<UpdateInboxPreferencesPacket>();
|
|
if (prefsPkg != null)
|
|
{
|
|
await HandleUpdateInboxPreferencesAsync(client, prefsPkg, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.ToggleFollowChannel:
|
|
var followPkg = envelope.Unpack<ToggleFollowChannelPacket>();
|
|
if (followPkg != null)
|
|
{
|
|
await HandleToggleFollowChannelAsync(client, followPkg, ct);
|
|
}
|
|
break;
|
|
|
|
case MessageTypes.UserListSync:
|
|
case "GET_USERS":
|
|
await BroadcastUserListAsync();
|
|
break;
|
|
|
|
case MessageTypes.Ping:
|
|
await client.SendMessageAsync(MessageTypes.Pong, new { }, ct);
|
|
break;
|
|
}
|
|
}
|
|
catch (Exception)
|
|
{
|
|
SafeLogger.LogWarning(_logger, "Failed to process message from client {Username}", InputSanitizer.SanitizeUsername(client.User.Username));
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Failed to process message." }, ct);
|
|
}
|
|
}
|
|
|
|
private async Task SendHistoryPageAsync(ConnectedClient client, string channelId, int offset, int limit, bool prepend, CancellationToken ct)
|
|
{
|
|
int clampedLimit = Math.Clamp(limit <= 0 ? 50 : limit, 1, 200);
|
|
int clampedOffset = Math.Max(0, offset);
|
|
int totalCount = await _db.GetMessageCountAsync(channelId);
|
|
var history = await _db.GetRecentMessagesAsync(channelId, clampedLimit, clampedOffset);
|
|
bool hasMore = totalCount > (clampedOffset + history.Count);
|
|
|
|
await client.SendMessageAsync(MessageTypes.HistorySync, new HistorySyncPacket
|
|
{
|
|
ChannelId = channelId,
|
|
Messages = history,
|
|
Prepend = prepend,
|
|
HasMore = hasMore,
|
|
Offset = clampedOffset
|
|
}, ct);
|
|
}
|
|
|
|
private async Task HandleFetchHistoryAsync(ConnectedClient client, FetchHistoryPacket packet, CancellationToken ct)
|
|
{
|
|
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
|
if (string.IsNullOrWhiteSpace(channelId)) return;
|
|
|
|
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
|
if (channel == null)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Channel not found." }, ct);
|
|
return;
|
|
}
|
|
|
|
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
|
{
|
|
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
|
if (!isMember)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You are not a member of this conversation." }, ct);
|
|
return;
|
|
}
|
|
}
|
|
|
|
await SendHistoryPageAsync(client, channelId, packet.Offset, packet.Limit, prepend: true, ct);
|
|
}
|
|
|
|
private async Task HandlePublishPublicKeyAsync(ConnectedClient client, PublishPublicKeyPacket packet, CancellationToken ct)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(packet.PublicKey)) return;
|
|
|
|
var dbUser = await _db.GetUserByIdAsync(client.User.Id);
|
|
bool hasExistingKey = !string.IsNullOrWhiteSpace(dbUser?.PublicKey);
|
|
|
|
// Protect against accidental overwrite of an existing E2EE keypair unless ResetKeys is explicitly requested
|
|
if (hasExistingKey && !packet.ResetKeys && !string.Equals(dbUser!.PublicKey, packet.PublicKey, StringComparison.Ordinal))
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
|
{
|
|
Message = "An E2EE key vault already exists for your account. Unlock it with your E2EE PIN or explicitly reset your E2EE keys.",
|
|
Code = "E2EE_KEY_EXISTS"
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
await _db.UpdateUserKeysAsync(client.User.Id, packet.PublicKey, packet.EncryptedPrivateKey);
|
|
foreach (var c in _clients.Values.Where(x => string.Equals(x.User.Id, client.User.Id, StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
c.User.PublicKey = packet.PublicKey;
|
|
if (!string.IsNullOrWhiteSpace(packet.EncryptedPrivateKey))
|
|
{
|
|
c.User.EncryptedPrivateKey = packet.EncryptedPrivateKey;
|
|
}
|
|
}
|
|
|
|
await BroadcastUserListAsync();
|
|
await BroadcastChannelListAsync();
|
|
|
|
if (packet.ResetKeys)
|
|
{
|
|
var dms = await _db.GetDirectMessagesForUserAsync(client.User.Id, _options.AllowDmE2ee);
|
|
foreach (var dm in dms)
|
|
{
|
|
await BroadcastToMembersAsync(dm.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket
|
|
{
|
|
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} reset their E2EE keypair.",
|
|
Level = "Warning"
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task HandleToggleE2eeAsync(ConnectedClient client, ToggleE2eePacket packet, CancellationToken ct)
|
|
{
|
|
string scope = (packet.Scope ?? "dm").Trim().ToLowerInvariant();
|
|
if (scope == "account")
|
|
{
|
|
await _db.SetUserE2eeEnabledAsync(client.User.Id, packet.Enabled);
|
|
foreach (var c in _clients.Values.Where(x => string.Equals(x.User.Id, client.User.Id, StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
c.User.E2eeEnabled = packet.Enabled;
|
|
}
|
|
|
|
await BroadcastUserListAsync();
|
|
var dms = await _db.GetDirectMessagesForUserAsync(client.User.Id, _options.AllowDmE2ee);
|
|
var affectedUsers = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { client.User.Id };
|
|
foreach (var dm in dms)
|
|
{
|
|
foreach (var mid in dm.MemberIds) affectedUsers.Add(mid);
|
|
}
|
|
await SyncChannelListForUsersAsync(affectedUsers);
|
|
await BroadcastToMembersAsync(affectedUsers, MessageTypes.SystemNotice, new SystemNoticePacket
|
|
{
|
|
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} {(packet.Enabled ? "enabled" : "disabled")} E2EE for their account.",
|
|
Level = packet.Enabled ? "Success" : "Warning"
|
|
});
|
|
}
|
|
else
|
|
{
|
|
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
|
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
|
if (channel == null || channel.Type != ChannelTypes.DirectMessage)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Can only toggle per-DM E2EE on a Direct Message." }, ct);
|
|
return;
|
|
}
|
|
|
|
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
|
if (!isMember)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You are not a member of this Direct Message." }, ct);
|
|
return;
|
|
}
|
|
|
|
await _db.SetChannelE2eeAsync(channel.Id, packet.Enabled);
|
|
await SyncChannelListForUsersAsync(channel.MemberIds);
|
|
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket
|
|
{
|
|
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} {(packet.Enabled ? "enabled" : "disabled")} E2EE for this Direct Message.",
|
|
Level = packet.Enabled ? "Success" : "Warning"
|
|
});
|
|
}
|
|
}
|
|
|
|
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, _options.AllowDmE2ee);
|
|
if (channel == null)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Channel does not exist." }, ct);
|
|
return;
|
|
}
|
|
|
|
// Verify membership for DMs and Group Chats
|
|
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
|
{
|
|
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
|
if (!isMember)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You do not have access to this conversation." }, ct);
|
|
return;
|
|
}
|
|
}
|
|
|
|
bool isPayloadEncrypted = packet.IsEncrypted || E2eeCrypto.IsEncryptedPayload(packet.Content);
|
|
|
|
if (channel.Type == ChannelTypes.DirectMessage)
|
|
{
|
|
if (!_options.AllowDmE2ee && isPayloadEncrypted)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
|
{
|
|
Message = "Full E2EE for Direct Messages is disabled on this server.",
|
|
Code = "E2EE_DISABLED"
|
|
}, ct);
|
|
return;
|
|
}
|
|
}
|
|
|
|
string? recipientPubKey = packet.RecipientPublicKey;
|
|
if (string.IsNullOrWhiteSpace(recipientPubKey) && channel.Type == ChannelTypes.DirectMessage)
|
|
{
|
|
var peerId = channel.MemberIds.FirstOrDefault(id => !string.Equals(id, client.User.Id, StringComparison.OrdinalIgnoreCase)) ?? client.User.Id;
|
|
if (channel.MemberPublicKeys.TryGetValue(peerId, out var foundPeerKey))
|
|
{
|
|
recipientPubKey = foundPeerKey;
|
|
}
|
|
}
|
|
|
|
var message = new ChatMessage
|
|
{
|
|
ChannelId = channelId,
|
|
SenderId = client.User.Id,
|
|
SenderUsername = client.User.Username,
|
|
SenderRole = client.User.Role,
|
|
Content = packet.Content.Trim(),
|
|
IsEncrypted = isPayloadEncrypted,
|
|
SenderPublicKey = packet.SenderPublicKey ?? client.User.PublicKey,
|
|
RecipientPublicKey = recipientPubKey,
|
|
CreatedAt = DateTime.UtcNow
|
|
};
|
|
|
|
// Pass through mod pipeline only if not E2EE encrypted
|
|
if (!message.IsEncrypted && MessagePipelineInterceptor != null)
|
|
{
|
|
var processed = await MessagePipelineInterceptor(message);
|
|
if (processed == null)
|
|
{
|
|
// Message dropped by pipeline
|
|
return;
|
|
}
|
|
message = processed;
|
|
}
|
|
|
|
await _db.SaveMessageAsync(message);
|
|
|
|
// If sender had unread inbox items in this conversation, mark them read
|
|
int senderMarked = await _db.MarkChannelInboxItemsReadAsync(client.User.Id, channelId);
|
|
if (senderMarked > 0)
|
|
{
|
|
await SyncInboxForUserAsync(client.User.Id, ct);
|
|
}
|
|
|
|
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
|
{
|
|
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message });
|
|
}
|
|
else
|
|
{
|
|
await BroadcastToChannelAsync(channelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message });
|
|
}
|
|
|
|
await ProcessMessageInboxNotificationsAsync(channel, message, ct);
|
|
}
|
|
|
|
private async Task HandleJoinChannelAsync(ConnectedClient client, string channelId, CancellationToken ct)
|
|
{
|
|
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
|
if (channel == null)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Channel not found." }, ct);
|
|
return;
|
|
}
|
|
|
|
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
|
{
|
|
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
|
if (!isMember)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You are not a member of this conversation." }, ct);
|
|
return;
|
|
}
|
|
}
|
|
|
|
client.ActiveChannelId = channelId;
|
|
|
|
int markedRead = await _db.MarkChannelInboxItemsReadAsync(client.User.Id, channelId);
|
|
if (markedRead > 0)
|
|
{
|
|
await SyncInboxForUserAsync(client.User.Id, ct);
|
|
}
|
|
|
|
await SendChannelListToClientAsync(client, ct);
|
|
await SendHistoryPageAsync(client, channelId, offset: 0, limit: 50, prepend: false, ct);
|
|
}
|
|
|
|
private async Task HandleStartDmAsync(ConnectedClient client, StartDmPacket packet, CancellationToken ct)
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(packet.TargetUserId) && !InputSanitizer.IsValidUserId(packet.TargetUserId))
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Invalid user ID." }, ct);
|
|
return;
|
|
}
|
|
|
|
User? targetUser = null;
|
|
if (!string.IsNullOrWhiteSpace(packet.TargetUserId))
|
|
{
|
|
targetUser = await _db.GetUserByIdAsync(packet.TargetUserId.Trim());
|
|
}
|
|
if (targetUser == null && !string.IsNullOrWhiteSpace(packet.TargetUsername))
|
|
{
|
|
string cleanName = InputSanitizer.SanitizeUsername(packet.TargetUsername.Trim().TrimStart('@'));
|
|
targetUser = await _db.GetUserByUsernameAsync(cleanName);
|
|
}
|
|
|
|
if (targetUser == null)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Target user not found." }, ct);
|
|
return;
|
|
}
|
|
|
|
var dmChannel = await _db.GetOrCreateDirectMessageAsync(client.User.Id, targetUser.Id, _options.AllowDmE2ee);
|
|
client.ActiveChannelId = dmChannel.Id;
|
|
|
|
// Sync channel lists for both participants
|
|
await SyncChannelListForUsersAsync(dmChannel.MemberIds);
|
|
|
|
// Send DM history (initial 50 messages, with HasMore flag) to initiating client
|
|
await SendHistoryPageAsync(client, dmChannel.Id, offset: 0, limit: 50, prepend: false, ct);
|
|
}
|
|
|
|
private async Task HandleCreateGroupAsync(ConnectedClient client, CreateGroupPacket packet, CancellationToken ct)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(packet.Name) || packet.Name.Trim().Length < 2)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Group name must be at least 2 characters." }, ct);
|
|
return;
|
|
}
|
|
|
|
string sanitizedName = InputSanitizer.SanitizeChannelName(packet.Name);
|
|
if (sanitizedName.Length < 2)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Group name contains invalid characters." }, ct);
|
|
return;
|
|
}
|
|
|
|
int serverMax = Math.Max(2, _options.MaxGroupChatUsers);
|
|
int groupMax = packet.MaxUsers.HasValue && packet.MaxUsers.Value > 0 ? packet.MaxUsers.Value : serverMax;
|
|
|
|
if (groupMax > serverMax)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
|
{
|
|
Message = $"Group max user count ({groupMax}) cannot exceed the server setting limit ({serverMax})."
|
|
}, ct);
|
|
return;
|
|
}
|
|
if (groupMax < 2) groupMax = 2;
|
|
|
|
var memberIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { client.User.Id };
|
|
if (packet.MemberUsernames != null)
|
|
{
|
|
foreach (var rawName in packet.MemberUsernames)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(rawName)) continue;
|
|
var parts = rawName.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
|
foreach (var p in parts)
|
|
{
|
|
string cleanUser = InputSanitizer.SanitizeUsername(p.Trim().TrimStart('@'));
|
|
if (string.IsNullOrWhiteSpace(cleanUser)) continue;
|
|
var u = await _db.GetUserByUsernameAsync(cleanUser);
|
|
if (u == null)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = $"User '@{cleanUser}' not found." }, ct);
|
|
return;
|
|
}
|
|
memberIds.Add(u.Id);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (memberIds.Count > groupMax)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
|
{
|
|
Message = $"Cannot create group chat with {memberIds.Count} members. Maximum allowed is {groupMax}."
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
var group = await _db.CreateGroupChatAsync(sanitizedName, InputSanitizer.SanitizeForDisplay(packet.Topic ?? string.Empty), client.User.Id, memberIds, groupMax);
|
|
client.ActiveChannelId = group.Id;
|
|
|
|
await SyncChannelListForUsersAsync(group.MemberIds);
|
|
await client.SendMessageAsync(MessageTypes.HistorySync, new HistorySyncPacket
|
|
{
|
|
ChannelId = group.Id,
|
|
Messages = new()
|
|
}, ct);
|
|
|
|
await BroadcastToMembersAsync(
|
|
group.MemberIds,
|
|
MessageTypes.SystemNotice,
|
|
new SystemNoticePacket
|
|
{
|
|
Text = $"Group chat '{InputSanitizer.SanitizeChannelName(group.Name)}' created by @{InputSanitizer.SanitizeUsername(client.User.Username)} ({group.MemberIds.Count}/{group.MaxUsers} members).",
|
|
Level = "Success"
|
|
});
|
|
|
|
// Notify initial invited members via Inbox & Web Push
|
|
foreach (var invitedUserId in group.MemberIds.Where(id => !string.Equals(id, client.User.Id, StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
await CreateGroupInviteInboxItemAsync(group, client.User, invitedUserId, ct);
|
|
}
|
|
}
|
|
|
|
private async Task HandleInviteToGroupAsync(ConnectedClient client, InviteToGroupPacket packet, CancellationToken ct)
|
|
{
|
|
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
|
var group = await _db.GetChannelByIdAsync(channelId);
|
|
if (group == null || group.Type != ChannelTypes.Group)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Active conversation is not a group chat." }, ct);
|
|
return;
|
|
}
|
|
|
|
if (!group.MemberIds.Contains(client.User.Id, StringComparer.OrdinalIgnoreCase))
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You are not a member of this group chat." }, ct);
|
|
return;
|
|
}
|
|
|
|
string targetName = (packet.TargetUsername ?? string.Empty).Trim().TrimStart('@');
|
|
if (string.IsNullOrWhiteSpace(targetName))
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Please specify a username to invite." }, ct);
|
|
return;
|
|
}
|
|
|
|
var targetUser = await _db.GetUserByUsernameAsync(targetName);
|
|
if (targetUser == null)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = $"User '@{targetName}' not found." }, ct);
|
|
return;
|
|
}
|
|
|
|
if (group.MemberIds.Contains(targetUser.Id, StringComparer.OrdinalIgnoreCase))
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = $"@{targetUser.Username} is already a member of '{group.Name}'." }, ct);
|
|
return;
|
|
}
|
|
|
|
int effectiveMax = group.MaxUsers > 0 ? Math.Min(group.MaxUsers, _options.MaxGroupChatUsers) : _options.MaxGroupChatUsers;
|
|
if (group.MemberIds.Count >= effectiveMax)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
|
{
|
|
Message = $"Group chat '{group.Name}' has reached the maximum user limit ({effectiveMax})."
|
|
}, ct);
|
|
return;
|
|
}
|
|
|
|
await _db.AddGroupMemberAsync(group.Id, targetUser.Id);
|
|
var updatedGroup = await _db.GetChannelByIdAsync(group.Id);
|
|
var memberIds = updatedGroup?.MemberIds ?? group.MemberIds;
|
|
|
|
await SyncChannelListForUsersAsync(memberIds);
|
|
await BroadcastToMembersAsync(
|
|
memberIds,
|
|
MessageTypes.SystemNotice,
|
|
new SystemNoticePacket
|
|
{
|
|
Text = $"@{InputSanitizer.SanitizeUsername(targetUser.Username)} was added to group '{InputSanitizer.SanitizeChannelName(group.Name)}' by @{InputSanitizer.SanitizeUsername(client.User.Username)}.",
|
|
Level = "Info"
|
|
});
|
|
|
|
await CreateGroupInviteInboxItemAsync(updatedGroup ?? group, client.User, targetUser.Id, ct);
|
|
}
|
|
|
|
private async Task HandleLeaveGroupAsync(ConnectedClient client, LeaveGroupPacket packet, CancellationToken ct)
|
|
{
|
|
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
|
var group = await _db.GetChannelByIdAsync(channelId);
|
|
if (group == null || group.Type != ChannelTypes.Group)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Specified conversation is not a group chat." }, ct);
|
|
return;
|
|
}
|
|
|
|
var previousMembers = new List<string>(group.MemberIds);
|
|
bool removed = await _db.RemoveGroupMemberAsync(group.Id, client.User.Id);
|
|
if (!removed)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You are not a member of this group chat." }, ct);
|
|
return;
|
|
}
|
|
|
|
if (client.ActiveChannelId == group.Id)
|
|
{
|
|
var channels = await _db.GetChannelsAsync();
|
|
var general = channels.FirstOrDefault(c => c.Name == "general") ?? channels.FirstOrDefault();
|
|
client.ActiveChannelId = general?.Id ?? string.Empty;
|
|
|
|
if (!string.IsNullOrEmpty(client.ActiveChannelId))
|
|
{
|
|
await SendHistoryPageAsync(client, client.ActiveChannelId, offset: 0, limit: 50, prepend: false, ct);
|
|
}
|
|
}
|
|
|
|
await SyncChannelListForUsersAsync(previousMembers);
|
|
await SendFileListToClientAsync(client, ct);
|
|
await BroadcastToMembersAsync(
|
|
previousMembers.Where(id => !string.Equals(id, client.User.Id, StringComparison.OrdinalIgnoreCase)),
|
|
MessageTypes.SystemNotice,
|
|
new SystemNoticePacket
|
|
{
|
|
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} left group '{InputSanitizer.SanitizeChannelName(group.Name)}'.",
|
|
Level = "Info"
|
|
});
|
|
}
|
|
|
|
private async Task HandleCreateChannelAsync(ConnectedClient client, CreateChannelPacket packet, CancellationToken ct)
|
|
{
|
|
if (!_options.AllowMemberChannelCreation && client.User.Role != UserRoles.Owner && client.User.Role != UserRoles.Admin)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Only Admins can create channels." }, ct);
|
|
return;
|
|
}
|
|
|
|
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,
|
|
Type = ChannelTypes.Channel,
|
|
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;
|
|
}
|
|
|
|
client.ActiveChannelId = channel.Id;
|
|
await BroadcastChannelListAsync();
|
|
await client.SendMessageAsync(MessageTypes.HistorySync, new HistorySyncPacket
|
|
{
|
|
ChannelId = channel.Id,
|
|
Messages = new()
|
|
}, ct);
|
|
await BroadcastSystemNoticeAsync($"Channel #{cleanName} was created by {InputSanitizer.SanitizeUsername(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" && channel.Type == ChannelTypes.Channel)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Cannot delete the default #general channel." }, ct);
|
|
return;
|
|
}
|
|
|
|
await _db.DeleteChannelAsync(channelId);
|
|
|
|
var channels = await _db.GetChannelsAsync();
|
|
var fallbackId = (channels.FirstOrDefault(c => c.Name == "general") ?? channels.FirstOrDefault())?.Id ?? string.Empty;
|
|
|
|
foreach (var c in _clients.Values.Where(x => x.ActiveChannelId == channelId))
|
|
{
|
|
c.ActiveChannelId = fallbackId;
|
|
if (!string.IsNullOrEmpty(fallbackId))
|
|
{
|
|
await SendHistoryPageAsync(c, fallbackId, offset: 0, limit: 50, prepend: false, ct);
|
|
}
|
|
}
|
|
|
|
await BroadcastChannelListAsync();
|
|
await Task.WhenAll(_clients.Values.Select(c => SendFileListToClientAsync(c, ct)));
|
|
await BroadcastSystemNoticeAsync($"Channel #{InputSanitizer.SanitizeChannelName(channel.Name)} was deleted.", "Warning");
|
|
}
|
|
|
|
private async Task HandleDeleteFileAsync(ConnectedClient client, string fileId, CancellationToken ct)
|
|
{
|
|
var record = await _fileService.GetFileRecordAsync(fileId);
|
|
if (record == null)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "File not found." }, ct);
|
|
return;
|
|
}
|
|
|
|
bool isUploader = string.Equals(client.User.Id, record.UploaderId, StringComparison.OrdinalIgnoreCase) ||
|
|
string.Equals(client.User.Username, record.UploaderUsername, StringComparison.OrdinalIgnoreCase);
|
|
bool isAdmin = client.User.Role == UserRoles.Owner || client.User.Role == UserRoles.Admin;
|
|
|
|
if (!isUploader && !isAdmin)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You do not have permission to delete this file. Only the uploader or an Admin can delete it." }, ct);
|
|
return;
|
|
}
|
|
|
|
await _fileService.DeleteFileAsync(fileId);
|
|
await BroadcastFileDeletedAsync(record, client.User.Username);
|
|
}
|
|
|
|
private async Task HandleCommandAsync(ConnectedClient client, ExecuteCommandPacket packet, CancellationToken ct)
|
|
{
|
|
string cmd = (packet.Command ?? string.Empty).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);
|
|
if (cmd == "announce" && modResult.Success && !string.IsNullOrWhiteSpace(packet.Args))
|
|
{
|
|
await CreateAnnouncementInboxItemsAsync(client.User, packet.Args.Trim(), packet.ChannelId, ct);
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Built-in commands
|
|
switch (cmd)
|
|
{
|
|
case "help":
|
|
string createDesc = _options.AllowMemberChannelCreation ? "Create a new channel" : "Create a new channel (Admin)";
|
|
string e2eeStatus = _options.AllowDmE2ee ? "Full E2EE Enabled" : "Server-Visible (E2EE Off)";
|
|
string helpText = "Available commands:\n" +
|
|
" /help - Show this help\n" +
|
|
" /join <channel> - Switch active channel\n" +
|
|
$" /create <name> [topic] - {createDesc}\n" +
|
|
" /delete <name> - Delete a channel (Admin)\n" +
|
|
$" /dm <username> - Open a Direct Message ({e2eeStatus})\n" +
|
|
" /e2ee pin <passphrase> - Create or unlock E2EE key vault with PIN\n" +
|
|
" /e2ee reset <new_pin> - Reset E2EE keypair & PIN\n" +
|
|
" /e2ee dm <on|off> - Toggle E2EE for the active DM\n" +
|
|
" /e2ee account <on|off> - Toggle E2EE for your entire account\n" +
|
|
$" /group create <name> [users] - Create a group chat (max {_options.MaxGroupChatUsers} users)\n" +
|
|
" /group invite <username> - Invite a user to the active group chat\n" +
|
|
" /group leave - Leave the active group chat\n" +
|
|
" /follow [channel] - Follow/unfollow a conversation for Inbox notifications\n" +
|
|
" /inbox [readall|clear] - Manage Inbox notifications & preferences\n" +
|
|
" /announce <message> - Broadcast an official announcement (Admin/Owner)\n" +
|
|
" /deletefile <file_id> - Delete an uploaded file (Uploader or 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, ChannelId = packet.ChannelId }, ct);
|
|
break;
|
|
|
|
case "announce":
|
|
if (client.User.Role != UserRoles.Owner && client.User.Role != UserRoles.Admin)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = false,
|
|
Output = "Only Admins and Owners can use /announce.",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
break;
|
|
}
|
|
if (string.IsNullOrWhiteSpace(packet.Args))
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = false,
|
|
Output = "Usage: /announce <announcement_message>",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
break;
|
|
}
|
|
string announceText = packet.Args.Trim();
|
|
await BroadcastSystemNoticeAsync($"📢 OFFICIAL ANNOUNCEMENT by @{InputSanitizer.SanitizeUsername(client.User.Username)}: {announceText}", "Warning");
|
|
await CreateAnnouncementInboxItemsAsync(client.User, announceText, packet.ChannelId, ct);
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = true,
|
|
Output = $"📢 Announcement broadcast: {announceText}",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
break;
|
|
|
|
case "deletefile":
|
|
if (string.IsNullOrWhiteSpace(packet.Args))
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = false,
|
|
Output = "Usage: /deletefile <file_id>",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
break;
|
|
}
|
|
string targetFileId = packet.Args.Trim();
|
|
var fileRec = await _fileService.GetFileRecordAsync(targetFileId);
|
|
if (fileRec == null)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = false,
|
|
Output = $"File '{targetFileId}' not found.",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
break;
|
|
}
|
|
|
|
bool canDel = string.Equals(client.User.Id, fileRec.UploaderId, StringComparison.OrdinalIgnoreCase) ||
|
|
string.Equals(client.User.Username, fileRec.UploaderUsername, StringComparison.OrdinalIgnoreCase) ||
|
|
client.User.Role == UserRoles.Owner || client.User.Role == UserRoles.Admin;
|
|
|
|
if (!canDel)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = false,
|
|
Output = "You do not have permission to delete this file. Only the uploader or an Admin/Owner can delete it.",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
break;
|
|
}
|
|
|
|
await _fileService.DeleteFileAsync(fileRec.Id);
|
|
await BroadcastFileDeletedAsync(fileRec, client.User.Username);
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = true,
|
|
Output = $"File '{fileRec.OriginalFileName}' was deleted successfully.",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
break;
|
|
|
|
case "follow":
|
|
case "unfollow":
|
|
case "mute":
|
|
string targetChArg = (packet.Args ?? string.Empty).Trim().TrimStart('#', '@');
|
|
string resolvedChId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
|
if (!string.IsNullOrWhiteSpace(targetChArg))
|
|
{
|
|
var byName = await _db.GetChannelByNameAsync(targetChArg);
|
|
if (byName != null)
|
|
{
|
|
resolvedChId = byName.Id;
|
|
}
|
|
else
|
|
{
|
|
var userGroups = await _db.GetGroupChatsForUserAsync(client.User.Id);
|
|
var userDms = await _db.GetDirectMessagesForUserAsync(client.User.Id, _options.AllowDmE2ee);
|
|
var matched = userGroups.FirstOrDefault(g => g.Name.Equals(targetChArg, StringComparison.OrdinalIgnoreCase))
|
|
?? userDms.FirstOrDefault(d => d.Name.TrimStart('@').Equals(targetChArg, StringComparison.OrdinalIgnoreCase));
|
|
if (matched != null)
|
|
{
|
|
resolvedChId = matched.Id;
|
|
}
|
|
}
|
|
}
|
|
bool? explicitFollow = cmd == "unfollow" || cmd == "mute" ? false : (cmd == "follow" && !string.IsNullOrWhiteSpace(targetChArg) ? true : null);
|
|
await HandleToggleFollowChannelAsync(client, new ToggleFollowChannelPacket
|
|
{
|
|
ChannelId = resolvedChId,
|
|
Follow = explicitFollow
|
|
}, ct);
|
|
break;
|
|
|
|
case "inbox":
|
|
var inboxArgs = (packet.Args ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
|
if (inboxArgs.Length == 0)
|
|
{
|
|
await SendInboxSyncToClientAsync(client, ct);
|
|
int unread = await _db.GetUnreadInboxCountAsync(client.User.Id);
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = true,
|
|
Output = $"Inbox synced ({unread} unread). Usage: /inbox readall | /inbox clear [all] | /inbox <mentions|announcements|dms|channels|push> <on|off>",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
break;
|
|
}
|
|
string inboxSub = inboxArgs[0].ToLowerInvariant();
|
|
if (inboxSub == "readall" || inboxSub == "read")
|
|
{
|
|
await HandleInboxActionAsync(client, new InboxActionPacket { Action = "mark_all_read" }, ct);
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = true,
|
|
Output = "All Inbox items marked as read.",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
}
|
|
else if (inboxSub == "clear")
|
|
{
|
|
bool clearAll = inboxArgs.Length > 1 && inboxArgs[1].Equals("all", StringComparison.OrdinalIgnoreCase);
|
|
await HandleInboxActionAsync(client, new InboxActionPacket { Action = clearAll ? "clear_all" : "clear_read" }, ct);
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = true,
|
|
Output = clearAll ? "Cleared all Inbox items." : "Cleared read Inbox items.",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
}
|
|
else if (inboxArgs.Length >= 2)
|
|
{
|
|
bool enablePref = inboxArgs[1].Equals("on", StringComparison.OrdinalIgnoreCase) ||
|
|
inboxArgs[1].Equals("true", StringComparison.OrdinalIgnoreCase) ||
|
|
inboxArgs[1].Equals("1", StringComparison.OrdinalIgnoreCase);
|
|
var prefUpdate = new UpdateInboxPreferencesPacket();
|
|
switch (inboxSub)
|
|
{
|
|
case "mentions": prefUpdate.MentionsEnabled = enablePref; break;
|
|
case "announcements": prefUpdate.AnnouncementsEnabled = enablePref; break;
|
|
case "dms":
|
|
case "dm": prefUpdate.DirectMessagesEnabled = enablePref; break;
|
|
case "channels":
|
|
case "followed": prefUpdate.FollowedChannelsEnabled = enablePref; break;
|
|
case "push": prefUpdate.PushNotificationsEnabled = enablePref; break;
|
|
}
|
|
await HandleUpdateInboxPreferencesAsync(client, prefUpdate, ct);
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = true,
|
|
Output = $"Updated Inbox setting '{inboxSub}' to {(enablePref ? "ON" : "OFF")}.",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
}
|
|
break;
|
|
|
|
case "motd":
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"MOTD: {_options.Motd}", ChannelId = packet.ChannelId }, 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}", ChannelId = packet.ChannelId }, ct);
|
|
break;
|
|
|
|
case "dm":
|
|
string dmTarget = (packet.Args ?? string.Empty).Trim().Split(' ', 2)[0].TrimStart('@');
|
|
if (string.IsNullOrEmpty(dmTarget))
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = "Usage: /dm <username>", ChannelId = packet.ChannelId }, ct);
|
|
break;
|
|
}
|
|
await HandleStartDmAsync(client, new StartDmPacket { TargetUsername = dmTarget }, ct);
|
|
break;
|
|
|
|
case "e2ee":
|
|
var e2eeParts = (packet.Args ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
|
if (e2eeParts.Length >= 2 && (e2eeParts[0].Equals("dm", StringComparison.OrdinalIgnoreCase) || e2eeParts[0].Equals("account", StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
bool enable = e2eeParts[1].Equals("on", StringComparison.OrdinalIgnoreCase) ||
|
|
e2eeParts[1].Equals("true", StringComparison.OrdinalIgnoreCase) ||
|
|
e2eeParts[1].Equals("1", StringComparison.OrdinalIgnoreCase);
|
|
await HandleToggleE2eeAsync(client, new ToggleE2eePacket
|
|
{
|
|
Scope = e2eeParts[0].ToLowerInvariant(),
|
|
ChannelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId,
|
|
Enabled = enable
|
|
}, ct);
|
|
}
|
|
else
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = false,
|
|
Output = "Usage: /e2ee dm <on|off> | /e2ee account <on|off> | /e2ee pin <pin> | /e2ee reset <new_pin>",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
}
|
|
break;
|
|
|
|
case "group":
|
|
case "gcreate":
|
|
string groupArgs = (packet.Args ?? string.Empty).Trim();
|
|
if (cmd == "gcreate")
|
|
{
|
|
groupArgs = "create " + groupArgs;
|
|
}
|
|
var gParts = groupArgs.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
|
if (gParts.Length == 0)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = false,
|
|
Output = "Usage: /group create <name> [user1,user2,...] | /group invite <username> | /group leave",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
break;
|
|
}
|
|
string subCmd = gParts[0].ToLowerInvariant();
|
|
if (subCmd == "create" && gParts.Length >= 2)
|
|
{
|
|
string gName = gParts[1];
|
|
var members = gParts.Skip(2).ToList();
|
|
await HandleCreateGroupAsync(client, new CreateGroupPacket { Name = gName, MemberUsernames = members }, ct);
|
|
}
|
|
else if (subCmd == "invite" && gParts.Length >= 2)
|
|
{
|
|
await HandleInviteToGroupAsync(client, new InviteToGroupPacket { ChannelId = client.ActiveChannelId, TargetUsername = gParts[1] }, ct);
|
|
}
|
|
else if (subCmd == "leave")
|
|
{
|
|
await HandleLeaveGroupAsync(client, new LeaveGroupPacket { ChannelId = client.ActiveChannelId }, ct);
|
|
}
|
|
else
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
|
{
|
|
Success = false,
|
|
Output = "Usage: /group create <name> [user1,user2,...] | /group invite <username> | /group leave",
|
|
ChannelId = packet.ChannelId
|
|
}, ct);
|
|
}
|
|
break;
|
|
|
|
case "invite":
|
|
string invTarget = (packet.Args ?? string.Empty).Trim();
|
|
await HandleInviteToGroupAsync(client, new InviteToGroupPacket { ChannelId = client.ActiveChannelId, TargetUsername = invTarget }, ct);
|
|
break;
|
|
|
|
case "leave":
|
|
await HandleLeaveGroupAsync(client, new LeaveGroupPacket { ChannelId = client.ActiveChannelId }, ct);
|
|
break;
|
|
|
|
case "delete":
|
|
string channelToDelete = (packet.Args ?? string.Empty).Trim().TrimStart('#');
|
|
if (string.IsNullOrEmpty(channelToDelete))
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = "Usage: /delete <channel_name>", ChannelId = packet.ChannelId }, ct);
|
|
break;
|
|
}
|
|
var chToDelete = await _db.GetChannelByNameAsync(channelToDelete);
|
|
if (chToDelete == null)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Channel #{channelToDelete} not found.", ChannelId = packet.ChannelId }, ct);
|
|
break;
|
|
}
|
|
await HandleDeleteChannelAsync(client, chToDelete.Id, ct);
|
|
break;
|
|
|
|
default:
|
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = false, Output = $"Unknown command '/{cmd}'. Type /help for available commands.", ChannelId = packet.ChannelId }, 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 BroadcastToMembersAsync<T>(IEnumerable<string> memberUserIds, string type, T payload)
|
|
{
|
|
var memberSet = new HashSet<string>(memberUserIds, StringComparer.OrdinalIgnoreCase);
|
|
var envelope = NetworkEnvelope.Create(type, payload);
|
|
var tasks = _clients.Values
|
|
.Where(c => memberSet.Contains(c.User.Id))
|
|
.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), StringComparer.OrdinalIgnoreCase);
|
|
var onlineUsernames = new HashSet<string>(_clients.Values.Select(c => c.User.Username), StringComparer.OrdinalIgnoreCase);
|
|
|
|
foreach (var u in allUsers)
|
|
{
|
|
u.IsOnline = onlineUserIds.Contains(u.Id) || onlineUsernames.Contains(u.Username);
|
|
}
|
|
|
|
await BroadcastToAllAsync(MessageTypes.UserListSync, new UserListSyncPacket { Users = allUsers });
|
|
}
|
|
|
|
public async Task SendChannelListToClientAsync(ConnectedClient client, CancellationToken ct = default)
|
|
{
|
|
var channels = await _db.GetChannelsAsync();
|
|
var dms = await _db.GetDirectMessagesForUserAsync(client.User.Id, _options.AllowDmE2ee);
|
|
var groups = await _db.GetGroupChatsForUserAsync(client.User.Id);
|
|
|
|
await client.SendMessageAsync(MessageTypes.ChannelListSync, new ChannelListSyncPacket
|
|
{
|
|
Channels = channels,
|
|
DirectMessages = dms,
|
|
GroupChats = groups,
|
|
ActiveChannelId = client.ActiveChannelId
|
|
}, ct);
|
|
}
|
|
|
|
public Task SyncChannelListForUsersAsync(IEnumerable<string> userIds)
|
|
{
|
|
var idSet = new HashSet<string>(userIds, StringComparer.OrdinalIgnoreCase);
|
|
var tasks = _clients.Values
|
|
.Where(c => idSet.Contains(c.User.Id))
|
|
.Select(c => SendChannelListToClientAsync(c));
|
|
return Task.WhenAll(tasks);
|
|
}
|
|
|
|
public Task BroadcastChannelListAsync()
|
|
{
|
|
var tasks = _clients.Values.Select(c => SendChannelListToClientAsync(c));
|
|
return Task.WhenAll(tasks);
|
|
}
|
|
|
|
private async Task SendFileListToClientAsync(ConnectedClient client, CancellationToken ct = default)
|
|
{
|
|
var allFiles = await _db.GetRecentFilesAsync(100);
|
|
var accessibleChannelIds = await _db.GetAccessibleChannelIdsForUserAsync(client.User.Id);
|
|
|
|
var visibleFiles = allFiles.Where(f => accessibleChannelIds.Contains(f.ChannelId)).ToList();
|
|
await client.SendMessageAsync(MessageTypes.FileListSync, new FileListSyncPacket { Files = visibleFiles }, ct);
|
|
}
|
|
|
|
public Task BroadcastSystemNoticeAsync(string text, string level = "Info")
|
|
{
|
|
return BroadcastToAllAsync(MessageTypes.SystemNotice, new SystemNoticePacket { Text = text, Level = level });
|
|
}
|
|
|
|
public async Task BroadcastFileUploadedAsync(FileRecord file, ChatMessage? savedMessage = null)
|
|
{
|
|
var channel = await _db.GetChannelByIdAsync(file.ChannelId);
|
|
bool isPrivateConv = channel != null && (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group);
|
|
|
|
if (isPrivateConv)
|
|
{
|
|
var memberSet = new HashSet<string>(channel!.MemberIds, StringComparer.OrdinalIgnoreCase);
|
|
await Task.WhenAll(_clients.Values
|
|
.Where(c => memberSet.Contains(c.User.Id))
|
|
.Select(c => SendFileListToClientAsync(c)));
|
|
}
|
|
else
|
|
{
|
|
await Task.WhenAll(_clients.Values.Select(c => SendFileListToClientAsync(c)));
|
|
}
|
|
|
|
// Broadcast message to channel or conversation members using the exact saved ChatMessage when available
|
|
var msg = savedMessage ?? 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
|
|
};
|
|
|
|
if (isPrivateConv)
|
|
{
|
|
await BroadcastToMembersAsync(channel!.MemberIds, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = msg });
|
|
}
|
|
else
|
|
{
|
|
await BroadcastToChannelAsync(file.ChannelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = msg });
|
|
}
|
|
|
|
if (channel != null)
|
|
{
|
|
await ProcessMessageInboxNotificationsAsync(channel, msg);
|
|
}
|
|
}
|
|
|
|
public async Task BroadcastFileDeletedAsync(FileRecord file, string? deletedByUsername = null)
|
|
{
|
|
var channel = await _db.GetChannelByIdAsync(file.ChannelId);
|
|
bool isPrivateConv = channel != null && (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group);
|
|
|
|
if (isPrivateConv)
|
|
{
|
|
var memberSet = new HashSet<string>(channel!.MemberIds, StringComparer.OrdinalIgnoreCase);
|
|
await Task.WhenAll(_clients.Values
|
|
.Where(c => memberSet.Contains(c.User.Id))
|
|
.Select(c => SendFileListToClientAsync(c)));
|
|
}
|
|
else
|
|
{
|
|
await Task.WhenAll(_clients.Values.Select(c => SendFileListToClientAsync(c)));
|
|
}
|
|
|
|
string deleterInfo = !string.IsNullOrWhiteSpace(deletedByUsername) ? $" by @{InputSanitizer.SanitizeUsername(deletedByUsername)}" : "";
|
|
string noticeText = $"File '{file.OriginalFileName}' was deleted{deleterInfo}.";
|
|
|
|
if (isPrivateConv)
|
|
{
|
|
await BroadcastToMembersAsync(channel!.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket { Text = noticeText, Level = "Warning" });
|
|
}
|
|
else
|
|
{
|
|
await BroadcastToChannelAsync(file.ChannelId, MessageTypes.SystemNotice, new SystemNoticePacket { Text = noticeText, Level = "Warning" });
|
|
}
|
|
}
|
|
|
|
#region Inbox & Notification Processing
|
|
|
|
public async Task SendInboxSyncToClientAsync(ConnectedClient client, CancellationToken ct = default)
|
|
{
|
|
var items = await _db.GetInboxItemsForUserAsync(client.User.Id, 100);
|
|
int unreadCount = await _db.GetUnreadInboxCountAsync(client.User.Id);
|
|
var prefs = await _db.GetInboxPreferencesAsync(client.User.Id);
|
|
|
|
await client.SendMessageAsync(MessageTypes.InboxSync, new InboxSyncPacket
|
|
{
|
|
Items = items,
|
|
UnreadCount = unreadCount,
|
|
Preferences = prefs
|
|
}, ct);
|
|
}
|
|
|
|
public async Task SyncInboxForUserAsync(string userId, CancellationToken ct = default)
|
|
{
|
|
var userClients = _clients.Values
|
|
.Where(c => string.Equals(c.User.Id, userId, StringComparison.OrdinalIgnoreCase))
|
|
.ToList();
|
|
if (userClients.Count == 0) return;
|
|
|
|
var items = await _db.GetInboxItemsForUserAsync(userId, 100);
|
|
int unreadCount = await _db.GetUnreadInboxCountAsync(userId);
|
|
var prefs = await _db.GetInboxPreferencesAsync(userId);
|
|
|
|
var packet = new InboxSyncPacket
|
|
{
|
|
Items = items,
|
|
UnreadCount = unreadCount,
|
|
Preferences = prefs
|
|
};
|
|
|
|
var envelope = NetworkEnvelope.Create(MessageTypes.InboxSync, packet);
|
|
await Task.WhenAll(userClients.Select(c => c.SendEnvelopeAsync(envelope, ct)));
|
|
}
|
|
|
|
private async Task HandleInboxActionAsync(ConnectedClient client, InboxActionPacket packet, CancellationToken ct)
|
|
{
|
|
string action = (packet.Action ?? string.Empty).Trim().ToLowerInvariant();
|
|
switch (action)
|
|
{
|
|
case "mark_read":
|
|
if (!string.IsNullOrWhiteSpace(packet.ItemId))
|
|
{
|
|
await _db.MarkInboxItemReadAsync(client.User.Id, packet.ItemId);
|
|
}
|
|
if (!string.IsNullOrWhiteSpace(packet.ChannelId))
|
|
{
|
|
await _db.MarkChannelInboxItemsReadAsync(client.User.Id, packet.ChannelId);
|
|
}
|
|
break;
|
|
|
|
case "mark_all_read":
|
|
await _db.MarkAllInboxItemsReadAsync(client.User.Id);
|
|
break;
|
|
|
|
case "dismiss":
|
|
case "delete":
|
|
if (!string.IsNullOrWhiteSpace(packet.ItemId))
|
|
{
|
|
await _db.DeleteInboxItemAsync(client.User.Id, packet.ItemId);
|
|
}
|
|
break;
|
|
|
|
case "clear_read":
|
|
await _db.ClearInboxItemsAsync(client.User.Id, onlyRead: true);
|
|
break;
|
|
|
|
case "clear_all":
|
|
await _db.ClearInboxItemsAsync(client.User.Id, onlyRead: false);
|
|
break;
|
|
}
|
|
|
|
await SyncInboxForUserAsync(client.User.Id, ct);
|
|
}
|
|
|
|
private async Task HandleUpdateInboxPreferencesAsync(ConnectedClient client, UpdateInboxPreferencesPacket packet, CancellationToken ct)
|
|
{
|
|
var prefs = await _db.GetInboxPreferencesAsync(client.User.Id);
|
|
|
|
if (packet.MentionsEnabled.HasValue) prefs.MentionsEnabled = packet.MentionsEnabled.Value;
|
|
if (packet.AnnouncementsEnabled.HasValue) prefs.AnnouncementsEnabled = packet.AnnouncementsEnabled.Value;
|
|
if (packet.DirectMessagesEnabled.HasValue) prefs.DirectMessagesEnabled = packet.DirectMessagesEnabled.Value;
|
|
if (packet.FollowedChannelsEnabled.HasValue) prefs.FollowedChannelsEnabled = packet.FollowedChannelsEnabled.Value;
|
|
if (packet.PushNotificationsEnabled.HasValue) prefs.PushNotificationsEnabled = packet.PushNotificationsEnabled.Value;
|
|
|
|
await _db.SaveInboxPreferencesAsync(prefs);
|
|
await SyncInboxForUserAsync(client.User.Id, ct);
|
|
}
|
|
|
|
private async Task HandleToggleFollowChannelAsync(ConnectedClient client, ToggleFollowChannelPacket packet, CancellationToken ct)
|
|
{
|
|
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
|
if (string.IsNullOrWhiteSpace(channelId))
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "No conversation selected to follow/unfollow." }, ct);
|
|
return;
|
|
}
|
|
|
|
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
|
if (channel == null)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Conversation not found." }, ct);
|
|
return;
|
|
}
|
|
|
|
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
|
{
|
|
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
|
if (!isMember)
|
|
{
|
|
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You do not have access to this conversation." }, ct);
|
|
return;
|
|
}
|
|
}
|
|
|
|
bool isNowFollowed = await _db.ToggleChannelFollowAsync(client.User.Id, channel, packet.Follow);
|
|
await SyncInboxForUserAsync(client.User.Id, ct);
|
|
|
|
string displayConv = channel.Type == ChannelTypes.Channel
|
|
? $"#{channel.Name}"
|
|
: channel.Name;
|
|
string statusText = isNowFollowed
|
|
? $"🔔 Following {displayConv} for Inbox & Push notifications."
|
|
: $"🔕 Muted / unfollowed {displayConv} notifications.";
|
|
|
|
await client.SendMessageAsync(MessageTypes.SystemNotice, new SystemNoticePacket
|
|
{
|
|
Text = statusText,
|
|
Level = isNowFollowed ? "Success" : "Info"
|
|
}, ct);
|
|
}
|
|
|
|
public static bool IsUserMentioned(string content, string username)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(content) || string.IsNullOrWhiteSpace(username))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (E2eeCrypto.IsEncryptedPayload(content))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (Regex.IsMatch(content, @"(^|[^\w])@(everyone|here)(?=$|[^\w])", RegexOptions.IgnoreCase))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
string pattern = $@"(^|[^\w])@{Regex.Escape(username.Trim().TrimStart('@'))}(?=$|[^\w])";
|
|
return Regex.IsMatch(content, pattern, RegexOptions.IgnoreCase);
|
|
}
|
|
|
|
private async Task ProcessMessageInboxNotificationsAsync(Channel channel, ChatMessage message, CancellationToken ct = default)
|
|
{
|
|
var allUsers = await _db.GetAllUsersAsync();
|
|
var userById = allUsers.ToDictionary(u => u.Id, StringComparer.OrdinalIgnoreCase);
|
|
|
|
IEnumerable<UserSummary> candidateUsers;
|
|
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
|
{
|
|
candidateUsers = channel.MemberIds
|
|
.Where(id => !string.Equals(id, message.SenderId, StringComparison.OrdinalIgnoreCase))
|
|
.Select(id => userById.GetValueOrDefault(id))
|
|
.Where(u => u != null)!;
|
|
}
|
|
else
|
|
{
|
|
candidateUsers = allUsers
|
|
.Where(u => !string.Equals(u.Id, message.SenderId, StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
|
|
bool isAnnouncementChannel = channel.Type == ChannelTypes.Channel &&
|
|
string.Equals(channel.Name, "announcements", StringComparison.OrdinalIgnoreCase);
|
|
|
|
foreach (var recipient in candidateUsers)
|
|
{
|
|
var prefs = await _db.GetInboxPreferencesAsync(recipient.Id);
|
|
string? matchedCategory = null;
|
|
|
|
bool isMention = !message.IsEncrypted && IsUserMentioned(message.Content, recipient.Username);
|
|
if (isMention && prefs.MentionsEnabled)
|
|
{
|
|
matchedCategory = InboxCategories.Mention;
|
|
}
|
|
else if (isAnnouncementChannel && prefs.AnnouncementsEnabled)
|
|
{
|
|
matchedCategory = InboxCategories.Announcement;
|
|
}
|
|
else if (channel.Type == ChannelTypes.DirectMessage)
|
|
{
|
|
bool isMuted = prefs.MutedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase);
|
|
if (prefs.DirectMessagesEnabled && !isMuted)
|
|
{
|
|
matchedCategory = InboxCategories.DirectMessage;
|
|
}
|
|
}
|
|
else if (channel.Type == ChannelTypes.Group)
|
|
{
|
|
bool isMuted = prefs.MutedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase);
|
|
if (prefs.DirectMessagesEnabled && !isMuted)
|
|
{
|
|
matchedCategory = InboxCategories.GroupMessage;
|
|
}
|
|
}
|
|
else if (channel.Type == ChannelTypes.Channel)
|
|
{
|
|
bool isFollowed = prefs.FollowedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase);
|
|
if (prefs.FollowedChannelsEnabled && isFollowed)
|
|
{
|
|
matchedCategory = InboxCategories.FollowedChannel;
|
|
}
|
|
}
|
|
|
|
if (matchedCategory == null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
string channelDisplayName = channel.Type == ChannelTypes.DirectMessage
|
|
? message.SenderUsername
|
|
: channel.Name;
|
|
|
|
var inboxItem = new InboxItem
|
|
{
|
|
UserId = recipient.Id,
|
|
ChannelId = channel.Id,
|
|
ChannelName = channelDisplayName,
|
|
ChannelType = channel.Type,
|
|
MessageId = message.Id,
|
|
SenderId = message.SenderId,
|
|
SenderUsername = message.SenderUsername,
|
|
Category = matchedCategory,
|
|
ContentPreview = message.Content,
|
|
IsEncrypted = message.IsEncrypted,
|
|
SenderPublicKey = message.SenderPublicKey,
|
|
RecipientPublicKey = message.RecipientPublicKey,
|
|
IsRead = false,
|
|
CreatedAt = message.CreatedAt
|
|
};
|
|
|
|
await DeliverInboxItemAsync(inboxItem, prefs, ct);
|
|
}
|
|
}
|
|
|
|
private async Task CreateGroupInviteInboxItemAsync(Channel group, User inviter, string targetUserId, CancellationToken ct)
|
|
{
|
|
if (string.Equals(inviter.Id, targetUserId, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return;
|
|
}
|
|
|
|
var prefs = await _db.GetInboxPreferencesAsync(targetUserId);
|
|
if (!prefs.DirectMessagesEnabled)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var item = new InboxItem
|
|
{
|
|
UserId = targetUserId,
|
|
ChannelId = group.Id,
|
|
ChannelName = group.Name,
|
|
ChannelType = ChannelTypes.Group,
|
|
SenderId = inviter.Id,
|
|
SenderUsername = inviter.Username,
|
|
Category = InboxCategories.GroupInvite,
|
|
ContentPreview = $"@{inviter.Username} added you to group chat '{group.Name}'.",
|
|
IsEncrypted = false,
|
|
IsRead = false,
|
|
CreatedAt = DateTime.UtcNow
|
|
};
|
|
|
|
await DeliverInboxItemAsync(item, prefs, ct);
|
|
}
|
|
|
|
private async Task CreateAnnouncementInboxItemsAsync(User sender, string announcementText, string fallbackChannelId, CancellationToken ct)
|
|
{
|
|
var announcementsCh = await _db.GetChannelByNameAsync("announcements");
|
|
string channelId = announcementsCh?.Id ?? fallbackChannelId;
|
|
string channelName = announcementsCh?.Name ?? "announcements";
|
|
|
|
var allUsers = await _db.GetAllUsersAsync();
|
|
foreach (var recipient in allUsers.Where(u => !string.Equals(u.Id, sender.Id, StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
var prefs = await _db.GetInboxPreferencesAsync(recipient.Id);
|
|
if (!prefs.AnnouncementsEnabled) continue;
|
|
|
|
var item = new InboxItem
|
|
{
|
|
UserId = recipient.Id,
|
|
ChannelId = channelId,
|
|
ChannelName = channelName,
|
|
ChannelType = ChannelTypes.Channel,
|
|
SenderId = sender.Id,
|
|
SenderUsername = sender.Username,
|
|
Category = InboxCategories.Announcement,
|
|
ContentPreview = announcementText,
|
|
IsEncrypted = false,
|
|
IsRead = false,
|
|
CreatedAt = DateTime.UtcNow
|
|
};
|
|
|
|
await DeliverInboxItemAsync(item, prefs, ct);
|
|
}
|
|
}
|
|
|
|
private async Task DeliverInboxItemAsync(InboxItem item, InboxPreferences prefs, CancellationToken ct)
|
|
{
|
|
await _db.CreateInboxItemAsync(item);
|
|
int unreadCount = await _db.GetUnreadInboxCountAsync(item.UserId);
|
|
|
|
var newPacket = new InboxNewItemPacket
|
|
{
|
|
Item = item,
|
|
UnreadCount = unreadCount
|
|
};
|
|
var envelope = NetworkEnvelope.Create(MessageTypes.InboxNewItem, newPacket);
|
|
|
|
var targetClients = _clients.Values
|
|
.Where(c => string.Equals(c.User.Id, item.UserId, StringComparison.OrdinalIgnoreCase))
|
|
.ToList();
|
|
|
|
if (targetClients.Count > 0)
|
|
{
|
|
await Task.WhenAll(targetClients.Select(c => c.SendEnvelopeAsync(envelope, ct)));
|
|
}
|
|
|
|
if (_webPush != null && prefs.PushNotificationsEnabled)
|
|
{
|
|
await _webPush.SendPushForInboxItemAsync(item, prefs, ct);
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
}
|