Add P2P STUN/TURN voice call feature with single-port WebSocket relay workaround

This commit is contained in:
tyuXX 2026-10-31 17:04:13 +03:00
parent 7cc9ba7f4d
commit 0d3817d7ea
22 changed files with 4757 additions and 9 deletions

View file

@ -21,6 +21,8 @@ namespace GsDChat.Server.WebSockets;
public class ChatWebSocketManager
{
private readonly ConcurrentDictionary<string, ConnectedClient> _clients = new();
private readonly ConcurrentDictionary<string, VoiceCallSessionInfo> _activeCalls = new(StringComparer.OrdinalIgnoreCase);
private readonly object _voiceLock = new();
private readonly ChatDatabase _db;
private readonly ServerOptions _options;
private readonly ILogger<ChatWebSocketManager> _logger;
@ -67,9 +69,17 @@ public class ChatWebSocketManager
_options.ServerName,
_options.Motd,
_options.AllowDmE2ee,
_options.MaxGroupChatUsers);
_options.MaxGroupChatUsers,
_options.EnableVoiceCalls,
_options.AllowVoiceRelayFallback,
_options.MaxVoiceCallUsers,
_options.GetIceServers());
uiSync.AllowDmE2ee = _options.AllowDmE2ee;
uiSync.MaxGroupChatUsers = _options.MaxGroupChatUsers;
uiSync.EnableVoiceCalls = _options.EnableVoiceCalls;
uiSync.AllowVoiceRelayFallback = _options.AllowVoiceRelayFallback;
uiSync.MaxVoiceCallUsers = _options.MaxVoiceCallUsers;
uiSync.IceServers = _options.GetIceServers();
// Send AuthResult with current E2EE key vault metadata so restored sessions have latest server state
await client.SendMessageAsync(MessageTypes.AuthResult, new AuthResultPacket
@ -102,6 +112,9 @@ public class ChatWebSocketManager
// Send Initial Inbox & Preferences Sync
await SendInboxSyncToClientAsync(client, cancellationToken);
// Send Active Voice Calls Sync
await SendActiveVoiceCallsToClientAsync(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);
@ -173,6 +186,12 @@ public class ChatWebSocketManager
}
catch { }
bool stillConnected = _clients.Values.Any(c => string.Equals(c.User.Id, user.Id, StringComparison.OrdinalIgnoreCase));
if (!stillConnected)
{
await RemoveUserFromAllVoiceCallsAsync(user.Id, user.Username);
}
await BroadcastUserListAsync();
await BroadcastSystemNoticeAsync($"[-] {InputSanitizer.SanitizeUsername(user.Username)} disconnected.", "Info");
}
@ -318,6 +337,62 @@ public class ChatWebSocketManager
}
break;
case MessageTypes.VoiceCallStart:
var vcStart = envelope.Unpack<VoiceCallStartPacket>();
if (vcStart != null)
{
await HandleVoiceCallStartAsync(client, vcStart, ct);
}
break;
case MessageTypes.VoiceCallAccept:
var vcAccept = envelope.Unpack<VoiceCallAcceptPacket>();
if (vcAccept != null)
{
await HandleVoiceCallAcceptAsync(client, vcAccept, ct);
}
break;
case MessageTypes.VoiceCallDecline:
var vcDecline = envelope.Unpack<VoiceCallDeclinePacket>();
if (vcDecline != null)
{
await HandleVoiceCallDeclineAsync(client, vcDecline, ct);
}
break;
case MessageTypes.VoiceCallLeave:
var vcLeave = envelope.Unpack<VoiceCallLeavePacket>();
if (vcLeave != null)
{
await HandleVoiceCallLeaveAsync(client, vcLeave, ct);
}
break;
case MessageTypes.VoiceStateUpdate:
var vcStateUpd = envelope.Unpack<VoiceStateUpdatePacket>();
if (vcStateUpd != null)
{
await HandleVoiceStateUpdateAsync(client, vcStateUpd, ct);
}
break;
case MessageTypes.VoiceSignal:
var vcSignal = envelope.Unpack<VoiceSignalPacket>();
if (vcSignal != null)
{
await HandleVoiceSignalAsync(client, vcSignal, ct);
}
break;
case MessageTypes.VoiceAudioFrame:
var vcAudio = envelope.Unpack<VoiceAudioFramePacket>();
if (vcAudio != null)
{
await HandleVoiceAudioFrameAsync(client, vcAudio, ct);
}
break;
case MessageTypes.UserListSync:
case "GET_USERS":
await BroadcastUserListAsync();
@ -944,6 +1019,9 @@ public class ChatWebSocketManager
" /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" +
" /call - Start or join a voice call in the active conversation\n" +
" /accept | /decline - Accept or decline an incoming DM voice call\n" +
" /hangup - Leave or end the active voice call\n" +
" /announce <message> - Broadcast an official announcement (Admin/Owner)\n" +
" /users - List all registered users\n" +
" /motd - Display message of the day";
@ -1174,6 +1252,40 @@ public class ChatWebSocketManager
await HandleLeaveGroupAsync(client, new LeaveGroupPacket { ChannelId = client.ActiveChannelId }, ct);
break;
case "call":
case "voice":
await HandleVoiceCallStartAsync(client, new VoiceCallStartPacket
{
ChannelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId,
ClientType = VoiceClientTypes.Tui
}, ct);
break;
case "accept":
case "answer":
await HandleVoiceCallAcceptAsync(client, new VoiceCallAcceptPacket
{
ChannelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId,
ClientType = VoiceClientTypes.Tui
}, ct);
break;
case "decline":
case "reject":
await HandleVoiceCallDeclineAsync(client, new VoiceCallDeclinePacket
{
ChannelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId
}, ct);
break;
case "hangup":
case "leavecall":
await HandleVoiceCallLeaveAsync(client, new VoiceCallLeavePacket
{
ChannelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId
}, ct);
break;
case "delete":
string channelToDelete = (packet.Args ?? string.Empty).Trim().TrimStart('#');
if (string.IsNullOrEmpty(channelToDelete))
@ -1665,4 +1777,665 @@ public class ChatWebSocketManager
}
#endregion
#region Voice Call & Single-Port Relay Management
public async Task SendActiveVoiceCallsToClientAsync(ConnectedClient client, CancellationToken ct = default)
{
if (!_options.EnableVoiceCalls) return;
var accessibleIds = await _db.GetAccessibleChannelIdsForUserAsync(client.User.Id);
List<VoiceCallSessionInfo> visibleCalls;
lock (_voiceLock)
{
visibleCalls = _activeCalls.Values
.Where(s => s.Status != VoiceCallStatus.Ended && accessibleIds.Contains(s.ChannelId))
.Select(CloneVoiceSession)
.ToList();
}
var iceServers = _options.GetIceServers();
foreach (var call in visibleCalls)
{
await client.SendMessageAsync(MessageTypes.VoiceCallState, new VoiceCallStatePacket
{
ChannelId = call.ChannelId,
Session = call,
IceServers = iceServers,
AllowVoiceRelayFallback = _options.AllowVoiceRelayFallback
}, ct);
}
}
private static VoiceCallSessionInfo CloneVoiceSession(VoiceCallSessionInfo src)
{
return new VoiceCallSessionInfo
{
CallId = src.CallId,
ChannelId = src.ChannelId,
ChannelType = src.ChannelType,
InitiatorUserId = src.InitiatorUserId,
InitiatorUsername = src.InitiatorUsername,
Status = src.Status,
IsE2ee = src.IsE2ee,
CreatedAt = src.CreatedAt,
RingingTargetUserId = src.RingingTargetUserId,
RingingTargetUsername = src.RingingTargetUsername,
Participants = src.Participants.Select(p => new VoiceParticipant
{
UserId = p.UserId,
Username = p.Username,
ClientType = p.ClientType,
IsMuted = p.IsMuted,
IsDeafened = p.IsDeafened,
TransportMode = p.TransportMode,
PublicKey = p.PublicKey,
UdpEndpoint = p.UdpEndpoint,
JoinedAt = p.JoinedAt
}).ToList()
};
}
private async Task BroadcastVoiceCallStateAsync(Channel channel, VoiceCallSessionInfo session)
{
var packet = new VoiceCallStatePacket
{
ChannelId = channel.Id,
Session = CloneVoiceSession(session),
IceServers = _options.GetIceServers(),
AllowVoiceRelayFallback = _options.AllowVoiceRelayFallback
};
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
{
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.VoiceCallState, packet);
}
else
{
await BroadcastToAllAsync(MessageTypes.VoiceCallState, packet);
}
}
private async Task BroadcastVoiceNoticeToConversationAsync(Channel channel, string text, string level = "Info")
{
var notice = new SystemNoticePacket { Text = text, Level = level };
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
{
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.SystemNotice, notice);
}
else
{
await BroadcastToChannelAsync(channel.Id, MessageTypes.SystemNotice, notice);
}
}
private async Task HandleVoiceCallStartAsync(ConnectedClient client, VoiceCallStartPacket packet, CancellationToken ct)
{
if (!_options.EnableVoiceCalls)
{
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Voice calls are disabled on this server." }, ct);
return;
}
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 for voice call." }, 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;
}
}
// Remove user from any other conversation's voice call first
await RemoveUserFromOtherVoiceCallsAsync(client.User.Id, client.User.Username, channel.Id);
string clientType = string.Equals(packet.ClientType, VoiceClientTypes.Tui, StringComparison.OrdinalIgnoreCase)
? VoiceClientTypes.Tui
: VoiceClientTypes.Web;
string defaultTransport = clientType == VoiceClientTypes.Tui ? VoiceTransportModes.P2P : VoiceTransportModes.P2P;
int maxUsers = Math.Max(2, _options.MaxVoiceCallUsers);
VoiceCallSessionInfo sessionToBroadcast;
bool isNewCall = false;
bool becameActive = false;
lock (_voiceLock)
{
if (_activeCalls.TryGetValue(channel.Id, out var existing) && existing.Status != VoiceCallStatus.Ended)
{
var existingPart = existing.Participants.FirstOrDefault(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
if (existingPart != null)
{
existingPart.ClientType = clientType;
existingPart.PublicKey = client.User.PublicKey;
}
else
{
if (existing.Participants.Count >= maxUsers)
{
sessionToBroadcast = existing;
goto MaxUsersReached;
}
existing.Participants.Add(new VoiceParticipant
{
UserId = client.User.Id,
Username = client.User.Username,
ClientType = clientType,
TransportMode = defaultTransport,
PublicKey = client.User.PublicKey,
JoinedAt = DateTime.UtcNow
});
if (existing.Status == VoiceCallStatus.Ringing &&
!string.Equals(existing.InitiatorUserId, client.User.Id, StringComparison.OrdinalIgnoreCase))
{
existing.Status = VoiceCallStatus.Active;
existing.RingingTargetUserId = null;
existing.RingingTargetUsername = null;
becameActive = true;
}
}
// If any participant is TUI and another is Web, mark relay hint or let clients auto-negotiate
sessionToBroadcast = CloneVoiceSession(existing);
}
else
{
isNewCall = true;
string? peerId = null;
string? peerName = null;
if (channel.Type == ChannelTypes.DirectMessage)
{
peerId = channel.MemberIds.FirstOrDefault(id => !string.Equals(id, client.User.Id, StringComparison.OrdinalIgnoreCase));
peerName = channel.MemberUsernames.FirstOrDefault(n => !string.Equals(n, client.User.Username, StringComparison.OrdinalIgnoreCase));
}
bool isDmRinging = channel.Type == ChannelTypes.DirectMessage && !string.IsNullOrEmpty(peerId);
bool isE2eeCall = channel.Type == ChannelTypes.DirectMessage && channel.IsE2ee && _options.AllowDmE2ee && client.User.E2eeEnabled;
var created = new VoiceCallSessionInfo
{
CallId = Guid.NewGuid().ToString("N"),
ChannelId = channel.Id,
ChannelType = channel.Type,
InitiatorUserId = client.User.Id,
InitiatorUsername = client.User.Username,
Status = isDmRinging ? VoiceCallStatus.Ringing : VoiceCallStatus.Active,
IsE2ee = isE2eeCall,
CreatedAt = DateTime.UtcNow,
RingingTargetUserId = peerId,
RingingTargetUsername = peerName,
Participants = new List<VoiceParticipant>
{
new()
{
UserId = client.User.Id,
Username = client.User.Username,
ClientType = clientType,
TransportMode = defaultTransport,
PublicKey = client.User.PublicKey,
JoinedAt = DateTime.UtcNow
}
}
};
_activeCalls[channel.Id] = created;
sessionToBroadcast = CloneVoiceSession(created);
}
}
await BroadcastVoiceCallStateAsync(channel, sessionToBroadcast);
if (isNewCall)
{
string msg = sessionToBroadcast.Status == VoiceCallStatus.Ringing
? $"📞 @{InputSanitizer.SanitizeUsername(client.User.Username)} is calling..."
: $"📞 @{InputSanitizer.SanitizeUsername(client.User.Username)} started a voice call.";
await BroadcastVoiceNoticeToConversationAsync(channel, msg, "Info");
}
else if (becameActive)
{
await BroadcastVoiceNoticeToConversationAsync(
channel,
$"📞 @{InputSanitizer.SanitizeUsername(client.User.Username)} answered the voice call.",
"Success");
}
return;
MaxUsersReached:
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
{
Message = $"Voice call has reached the maximum participant limit ({maxUsers})."
}, ct);
}
private async Task HandleVoiceCallAcceptAsync(ConnectedClient client, VoiceCallAcceptPacket packet, CancellationToken ct)
{
if (!_options.EnableVoiceCalls)
{
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Voice calls are disabled on this server." }, ct);
return;
}
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
if (string.IsNullOrWhiteSpace(channelId))
{
// Find any ringing call targeting this user
lock (_voiceLock)
{
var ringingForMe = _activeCalls.Values.FirstOrDefault(s =>
s.Status == VoiceCallStatus.Ringing &&
string.Equals(s.RingingTargetUserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
if (ringingForMe != null)
{
channelId = ringingForMe.ChannelId;
}
}
}
if (string.IsNullOrWhiteSpace(channelId))
{
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "No active or incoming voice call to accept." }, 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;
}
}
await RemoveUserFromOtherVoiceCallsAsync(client.User.Id, client.User.Username, channel.Id);
string clientType = string.Equals(packet.ClientType, VoiceClientTypes.Tui, StringComparison.OrdinalIgnoreCase)
? VoiceClientTypes.Tui
: VoiceClientTypes.Web;
int maxUsers = Math.Max(2, _options.MaxVoiceCallUsers);
VoiceCallSessionInfo? sessionToBroadcast = null;
lock (_voiceLock)
{
if (!_activeCalls.TryGetValue(channel.Id, out var session) || session.Status == VoiceCallStatus.Ended)
{
sessionToBroadcast = null;
}
else
{
var part = session.Participants.FirstOrDefault(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
if (part == null)
{
if (session.Participants.Count >= maxUsers)
{
goto MaxUsersReached;
}
session.Participants.Add(new VoiceParticipant
{
UserId = client.User.Id,
Username = client.User.Username,
ClientType = clientType,
TransportMode = VoiceTransportModes.P2P,
PublicKey = client.User.PublicKey,
JoinedAt = DateTime.UtcNow
});
}
else
{
part.ClientType = clientType;
part.PublicKey = client.User.PublicKey;
}
session.Status = VoiceCallStatus.Active;
session.RingingTargetUserId = null;
session.RingingTargetUsername = null;
sessionToBroadcast = CloneVoiceSession(session);
}
}
if (sessionToBroadcast == null)
{
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "No active voice call in this conversation." }, ct);
return;
}
await BroadcastVoiceCallStateAsync(channel, sessionToBroadcast);
await BroadcastVoiceNoticeToConversationAsync(
channel,
$"📞 @{InputSanitizer.SanitizeUsername(client.User.Username)} joined the voice call.",
"Success");
return;
MaxUsersReached:
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
{
Message = $"Voice call has reached the maximum participant limit ({maxUsers})."
}, ct);
}
private async Task HandleVoiceCallDeclineAsync(ConnectedClient client, VoiceCallDeclinePacket packet, CancellationToken ct)
{
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
if (string.IsNullOrWhiteSpace(channelId))
{
lock (_voiceLock)
{
var ringingForMe = _activeCalls.Values.FirstOrDefault(s =>
s.Status == VoiceCallStatus.Ringing &&
string.Equals(s.RingingTargetUserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
if (ringingForMe != null)
{
channelId = ringingForMe.ChannelId;
}
}
}
if (string.IsNullOrWhiteSpace(channelId)) return;
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
if (channel == null) return;
VoiceCallSessionInfo? endedSession = null;
lock (_voiceLock)
{
if (_activeCalls.TryGetValue(channel.Id, out var session))
{
if (channel.Type == ChannelTypes.DirectMessage || session.Status == VoiceCallStatus.Ringing)
{
session.Status = VoiceCallStatus.Ended;
session.Participants.Clear();
session.RingingTargetUserId = null;
_activeCalls.TryRemove(channel.Id, out _);
endedSession = CloneVoiceSession(session);
}
else
{
session.Participants.RemoveAll(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
if (session.Participants.Count == 0)
{
session.Status = VoiceCallStatus.Ended;
_activeCalls.TryRemove(channel.Id, out _);
}
endedSession = CloneVoiceSession(session);
}
}
}
if (endedSession != null)
{
await BroadcastVoiceCallStateAsync(channel, endedSession);
await BroadcastVoiceNoticeToConversationAsync(
channel,
$"📞 @{InputSanitizer.SanitizeUsername(client.User.Username)} declined the voice call.",
"Warning");
}
}
private async Task HandleVoiceCallLeaveAsync(ConnectedClient client, VoiceCallLeavePacket packet, CancellationToken ct)
{
string channelId = packet.ChannelId;
if (string.IsNullOrWhiteSpace(channelId))
{
lock (_voiceLock)
{
var myCall = _activeCalls.Values.FirstOrDefault(s =>
s.Participants.Any(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase)) ||
string.Equals(s.RingingTargetUserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
channelId = myCall?.ChannelId ?? client.ActiveChannelId;
}
}
if (string.IsNullOrWhiteSpace(channelId)) return;
await RemoveUserFromVoiceCallAsync(channelId, client.User.Id, client.User.Username);
}
private async Task RemoveUserFromOtherVoiceCallsAsync(string userId, string username, string exceptChannelId)
{
List<string> otherChannelIds;
lock (_voiceLock)
{
otherChannelIds = _activeCalls.Values
.Where(s => !string.Equals(s.ChannelId, exceptChannelId, StringComparison.OrdinalIgnoreCase) &&
s.Participants.Any(p => string.Equals(p.UserId, userId, StringComparison.OrdinalIgnoreCase)))
.Select(s => s.ChannelId)
.ToList();
}
foreach (var chId in otherChannelIds)
{
await RemoveUserFromVoiceCallAsync(chId, userId, username);
}
}
private async Task RemoveUserFromAllVoiceCallsAsync(string userId, string username)
{
List<string> channelIds;
lock (_voiceLock)
{
channelIds = _activeCalls.Values
.Where(s => s.Participants.Any(p => string.Equals(p.UserId, userId, StringComparison.OrdinalIgnoreCase)) ||
string.Equals(s.RingingTargetUserId, userId, StringComparison.OrdinalIgnoreCase))
.Select(s => s.ChannelId)
.ToList();
}
foreach (var chId in channelIds)
{
await RemoveUserFromVoiceCallAsync(chId, userId, username);
}
}
private async Task RemoveUserFromVoiceCallAsync(string channelId, string userId, string username)
{
VoiceCallSessionInfo? updatedSession = null;
bool callEnded = false;
lock (_voiceLock)
{
if (_activeCalls.TryGetValue(channelId, out var session))
{
int removed = session.Participants.RemoveAll(p => string.Equals(p.UserId, userId, StringComparison.OrdinalIgnoreCase));
bool wasRingingTarget = string.Equals(session.RingingTargetUserId, userId, StringComparison.OrdinalIgnoreCase);
bool wasInitiator = string.Equals(session.InitiatorUserId, userId, StringComparison.OrdinalIgnoreCase);
if (removed == 0 && !wasRingingTarget && !wasInitiator)
{
return;
}
// For 1-on-1 DMs, or if all participants left, or if initiator hangs up while ringing, end the call
if (session.ChannelType == ChannelTypes.DirectMessage || session.Participants.Count == 0 || (session.Status == VoiceCallStatus.Ringing && wasInitiator))
{
session.Status = VoiceCallStatus.Ended;
session.Participants.Clear();
session.RingingTargetUserId = null;
_activeCalls.TryRemove(channelId, out _);
callEnded = true;
}
updatedSession = CloneVoiceSession(session);
}
}
if (updatedSession != null)
{
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
if (channel != null)
{
await BroadcastVoiceCallStateAsync(channel, updatedSession);
string noticeText = callEnded
? $"📞 Voice call ended (@{InputSanitizer.SanitizeUsername(username)} hung up)."
: $"📞 @{InputSanitizer.SanitizeUsername(username)} left the voice call.";
await BroadcastVoiceNoticeToConversationAsync(channel, noticeText, "Info");
}
}
}
private async Task HandleVoiceStateUpdateAsync(ConnectedClient client, VoiceStateUpdatePacket packet, CancellationToken ct)
{
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
if (string.IsNullOrWhiteSpace(channelId)) return;
VoiceCallSessionInfo? updatedSession = null;
lock (_voiceLock)
{
if (_activeCalls.TryGetValue(channelId, out var session) && session.Status != VoiceCallStatus.Ended)
{
var part = session.Participants.FirstOrDefault(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
if (part != null)
{
if (packet.IsMuted.HasValue) part.IsMuted = packet.IsMuted.Value;
if (packet.IsDeafened.HasValue)
{
part.IsDeafened = packet.IsDeafened.Value;
if (part.IsDeafened) part.IsMuted = true;
}
if (!string.IsNullOrWhiteSpace(packet.TransportMode))
{
part.TransportMode = packet.TransportMode.Trim().ToLowerInvariant() == VoiceTransportModes.Relay
? VoiceTransportModes.Relay
: VoiceTransportModes.P2P;
}
if (packet.UdpEndpoint != null)
{
part.UdpEndpoint = packet.UdpEndpoint.Trim();
}
updatedSession = CloneVoiceSession(session);
}
}
}
if (updatedSession != null)
{
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
if (channel != null)
{
await BroadcastVoiceCallStateAsync(channel, updatedSession);
}
}
}
private async Task HandleVoiceSignalAsync(ConnectedClient client, VoiceSignalPacket packet, CancellationToken ct)
{
if (!_options.EnableVoiceCalls) return;
if (string.IsNullOrWhiteSpace(packet.TargetUserId) || string.IsNullOrWhiteSpace(packet.ChannelId)) return;
if (packet.Payload != null && packet.Payload.Length > 65536) return;
bool canSignal = false;
lock (_voiceLock)
{
if (_activeCalls.TryGetValue(packet.ChannelId, out var session) && session.Status != VoiceCallStatus.Ended)
{
bool senderInCall = session.Participants.Any(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
bool targetInCall = session.Participants.Any(p => string.Equals(p.UserId, packet.TargetUserId, StringComparison.OrdinalIgnoreCase)) ||
string.Equals(session.RingingTargetUserId, packet.TargetUserId, StringComparison.OrdinalIgnoreCase);
canSignal = senderInCall && targetInCall;
}
}
if (!canSignal) return;
var outbound = new VoiceSignalPacket
{
ChannelId = packet.ChannelId,
SenderUserId = client.User.Id,
TargetUserId = packet.TargetUserId,
SignalType = packet.SignalType,
Payload = packet.Payload ?? string.Empty
};
await BroadcastToMembersAsync(new[] { packet.TargetUserId }, MessageTypes.VoiceSignal, outbound);
}
/// <summary>
/// Single-Port WebSocket TURN-like Media Relay handler.
/// Relays audio frames (including E2EE AES-256-GCM encrypted frames) over the single HTTP/HTTPS /ws port
/// to active call participants when direct P2P STUN/UDP is unavailable or bridged across Web and TUI clients.
/// </summary>
private async Task HandleVoiceAudioFrameAsync(ConnectedClient client, VoiceAudioFramePacket packet, CancellationToken ct)
{
if (!_options.EnableVoiceCalls || !_options.AllowVoiceRelayFallback) return;
if (string.IsNullOrWhiteSpace(packet.ChannelId) || string.IsNullOrWhiteSpace(packet.DataBase64)) return;
if (packet.DataBase64.Length > 16384) return; // Drop abnormal/oversized audio frames to prevent memory bloat/DoS
List<string> recipientIds;
lock (_voiceLock)
{
if (!_activeCalls.TryGetValue(packet.ChannelId, out var session) || session.Status != VoiceCallStatus.Active)
{
return;
}
var senderPart = session.Participants.FirstOrDefault(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
if (senderPart == null || senderPart.IsMuted)
{
return;
}
if (!string.IsNullOrWhiteSpace(packet.TargetUserId))
{
recipientIds = session.Participants
.Where(p => string.Equals(p.UserId, packet.TargetUserId, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase) &&
!p.IsDeafened)
.Select(p => p.UserId)
.ToList();
}
else
{
recipientIds = session.Participants
.Where(p => !string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase) && !p.IsDeafened)
.Select(p => p.UserId)
.ToList();
}
}
if (recipientIds.Count == 0) return;
var relayPacket = new VoiceAudioFramePacket
{
ChannelId = packet.ChannelId,
SenderUserId = client.User.Id,
SenderUsername = client.User.Username,
TargetUserId = packet.TargetUserId,
Sequence = packet.Sequence,
Codec = string.IsNullOrWhiteSpace(packet.Codec) ? "ulaw-16k" : packet.Codec,
DataBase64 = packet.DataBase64,
IsEncrypted = packet.IsEncrypted || E2eeCrypto.IsVoiceEncryptedPayload(packet.DataBase64),
SenderPublicKey = !string.IsNullOrWhiteSpace(packet.SenderPublicKey) ? packet.SenderPublicKey : client.User.PublicKey,
SpeakingLevel = Math.Clamp(packet.SpeakingLevel, 0f, 1f)
};
await BroadcastToMembersAsync(recipientIds, MessageTypes.VoiceAudioFrame, relayPacket);
}
#endregion
}