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

@ -1,3 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using GsDChat.Core.Models;
namespace GsDChat.Server.Configuration;
public class ServerOptions
@ -17,6 +21,59 @@ public class ServerOptions
public bool AllowDmE2ee { get; set; } = true;
public int MaxGroupChatUsers { get; set; } = 10;
// Voice Call & P2P STUN/TURN + Single-Port Relay Settings
public bool EnableVoiceCalls { get; set; } = true;
public bool AllowVoiceRelayFallback { get; set; } = true;
public int MaxVoiceCallUsers { get; set; } = 10;
public List<string> StunServers { get; set; } = new()
{
"stun:stun.cloudflare.com:3478",
"stun:stun.l.google.com:19302"
};
public List<IceServerConfig> TurnServers { get; set; } = new()
{
new IceServerConfig
{
Urls = new List<string>
{
"turn:openrelay.metered.ca:80",
"turn:openrelay.metered.ca:443",
"turn:openrelay.metered.ca:443?transport=tcp",
"turns:openrelay.metered.ca:443?transport=tcp"
},
Username = "openrelayproject",
Credential = "openrelayproject"
}
};
public List<IceServerConfig> GetIceServers()
{
var list = new List<IceServerConfig>();
var validStun = (StunServers ?? new List<string>())
.Where(s => !string.IsNullOrWhiteSpace(s))
.Select(s => s.Trim())
.Distinct()
.ToList();
if (validStun.Count > 0)
{
list.Add(new IceServerConfig { Urls = validStun });
}
if (TurnServers != null)
{
foreach (var t in TurnServers)
{
if (t != null && t.Urls != null && t.Urls.Any(u => !string.IsNullOrWhiteSpace(u)))
{
list.Add(t);
}
}
}
return list;
}
// Web Push (VAPID RFC 8292)
public string? VapidPublicKey { get; set; }
public string? VapidPrivateKey { get; set; }

View file

@ -88,6 +88,25 @@ public class ServerSettingsManager
options.MaxGroupChatUsers = 2;
}
if (options.MaxVoiceCallUsers < 2)
{
options.MaxVoiceCallUsers = 2;
}
if (options.StunServers == null || options.StunServers.Count == 0)
{
options.StunServers = new()
{
"stun:stun.cloudflare.com:3478",
"stun:stun.l.google.com:19302"
};
}
if (options.TurnServers == null)
{
options.TurnServers = new();
}
if (string.IsNullOrWhiteSpace(options.VapidPublicKey) || string.IsNullOrWhiteSpace(options.VapidPrivateKey))
{
var (pub, priv) = WebPushCrypto.GenerateVapidKeys();

View file

@ -67,6 +67,34 @@ if (!string.IsNullOrEmpty(envAllowDmE2ee) && bool.TryParse(envAllowDmE2ee, out b
string? envMaxGroupUsers = Environment.GetEnvironmentVariable("GSDCHAT_MAX_GROUP_USERS");
if (!string.IsNullOrEmpty(envMaxGroupUsers) && int.TryParse(envMaxGroupUsers, out int emgu)) serverOptions.MaxGroupChatUsers = emgu;
string? envEnableVoice = Environment.GetEnvironmentVariable("GSDCHAT_ENABLE_VOICE");
if (!string.IsNullOrEmpty(envEnableVoice) && bool.TryParse(envEnableVoice, out bool eev)) serverOptions.EnableVoiceCalls = eev;
string? envAllowVoiceRelay = Environment.GetEnvironmentVariable("GSDCHAT_ALLOW_VOICE_RELAY");
if (!string.IsNullOrEmpty(envAllowVoiceRelay) && bool.TryParse(envAllowVoiceRelay, out bool eavr)) serverOptions.AllowVoiceRelayFallback = eavr;
string? envMaxVoiceUsers = Environment.GetEnvironmentVariable("GSDCHAT_MAX_VOICE_USERS");
if (!string.IsNullOrEmpty(envMaxVoiceUsers) && int.TryParse(envMaxVoiceUsers, out int emvu)) serverOptions.MaxVoiceCallUsers = emvu;
string? envStunServers = Environment.GetEnvironmentVariable("GSDCHAT_STUN_SERVERS");
if (!string.IsNullOrEmpty(envStunServers))
{
serverOptions.StunServers = new System.Collections.Generic.List<string>(
envStunServers.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
}
string? envTurnUrl = Environment.GetEnvironmentVariable("GSDCHAT_TURN_URL");
if (!string.IsNullOrEmpty(envTurnUrl))
{
serverOptions.TurnServers.Add(new IceServerConfig
{
Urls = new System.Collections.Generic.List<string>(
envTurnUrl.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)),
Username = Environment.GetEnvironmentVariable("GSDCHAT_TURN_USER"),
Credential = Environment.GetEnvironmentVariable("GSDCHAT_TURN_CREDENTIAL")
});
}
// Allow CLI overrides e.g. --port 5000 --tls false
for (int i = 0; i < args.Length; i++)
{
@ -79,6 +107,14 @@ for (int i = 0; i < args.Length; i++)
if (args[i] == "--motd" && i + 1 < args.Length) serverOptions.Motd = args[i + 1];
if (args[i] == "--allow-dm-e2ee" && i + 1 < args.Length && bool.TryParse(args[i + 1], out bool dme2ee)) serverOptions.AllowDmE2ee = dme2ee;
if (args[i] == "--max-group-users" && i + 1 < args.Length && int.TryParse(args[i + 1], out int mgu)) serverOptions.MaxGroupChatUsers = mgu;
if (args[i] == "--enable-voice" && i + 1 < args.Length && bool.TryParse(args[i + 1], out bool evc)) serverOptions.EnableVoiceCalls = evc;
if (args[i] == "--allow-voice-relay" && i + 1 < args.Length && bool.TryParse(args[i + 1], out bool avr)) serverOptions.AllowVoiceRelayFallback = avr;
if (args[i] == "--max-voice-users" && i + 1 < args.Length && int.TryParse(args[i + 1], out int mvu)) serverOptions.MaxVoiceCallUsers = mvu;
if (args[i] == "--stun-server" && i + 1 < args.Length && !string.IsNullOrWhiteSpace(args[i + 1]))
{
serverOptions.StunServers = new System.Collections.Generic.List<string>(
args[i + 1].Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
}
}
builder.Services.AddSingleton(settingsManager);
@ -150,8 +186,9 @@ app.Use(async (context, next) =>
context.Response.Headers.Append("Content-Security-Policy",
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline'; " +
"worker-src 'self'; " +
"worker-src 'self' blob:; " +
"manifest-src 'self'; " +
"media-src 'self' blob:; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data:; " +
"font-src 'self'; " +
@ -218,7 +255,11 @@ app.MapGet("/api/info", (ServerOptions opt, IAuthService auth, HttpRequest req)
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
AllowDmE2ee = opt.AllowDmE2ee,
MaxGroupChatUsers = opt.MaxGroupChatUsers,
VapidPublicKey = opt.VapidPublicKey
VapidPublicKey = opt.VapidPublicKey,
EnableVoiceCalls = opt.EnableVoiceCalls,
AllowVoiceRelayFallback = opt.AllowVoiceRelayFallback,
MaxVoiceCallUsers = opt.MaxVoiceCallUsers,
IceServers = opt.GetIceServers()
});
});

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
}

View file

@ -13,6 +13,25 @@
"AllowMemberChannelCreation": true,
"AllowDmE2ee": true,
"MaxGroupChatUsers": 10,
"EnableVoiceCalls": true,
"AllowVoiceRelayFallback": true,
"MaxVoiceCallUsers": 10,
"StunServers": [
"stun:stun.cloudflare.com:3478",
"stun:stun.l.google.com:19302"
],
"TurnServers": [
{
"Urls": [
"turn:openrelay.metered.ca:80",
"turn:openrelay.metered.ca:443",
"turn:openrelay.metered.ca:443?transport=tcp",
"turns:openrelay.metered.ca:443?transport=tcp"
],
"Username": "openrelayproject",
"Credential": "openrelayproject"
}
],
"RateLimitRequestsPerMinute": 60,
"MaxConnectionsPerIp": 10,
"MaxGlobalConnections": 100,

View file

@ -1186,6 +1186,133 @@ html, body {
letter-spacing: 0.05em;
}
/* ==========================================================================
Voice Call Bar & Incoming Call Modal
========================================================================== */
.voice-call-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 6px 12px;
background-color: var(--ctp-mantle);
border-bottom: 1px solid var(--ctp-green);
font-size: 0.8rem;
}
.voice-call-info {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.voice-status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: var(--ctp-green);
display: inline-block;
}
.voice-status-dot.ringing {
background-color: var(--ctp-yellow);
animation: voicePulse 1s infinite alternate;
}
.voice-status-text {
font-weight: 700;
color: var(--ctp-green);
}
.voice-badge {
font-size: 0.72rem;
padding: 1px 6px;
border: 1px solid var(--ctp-surface2);
background-color: var(--ctp-crust);
color: var(--ctp-sapphire);
font-weight: 700;
}
.voice-transport-badge.relay {
color: var(--ctp-mauve);
border-color: var(--ctp-mauve);
}
.voice-e2ee-badge {
color: var(--ctp-green);
border-color: var(--ctp-green);
}
.voice-timer {
color: var(--ctp-subtext0);
font-size: 0.76rem;
}
.voice-participants-list {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
flex: 1;
}
.voice-participant-chip {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
background-color: var(--ctp-crust);
border: 1px solid var(--ctp-surface1);
color: var(--ctp-text);
font-size: 0.76rem;
transition: border-color 0.1s, color 0.1s;
}
.voice-participant-chip.speaking {
border-color: var(--ctp-green);
color: var(--ctp-green);
font-weight: 700;
}
.voice-participant-chip.muted {
color: var(--ctp-overlay0);
}
.voice-call-controls {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.voice-device-select {
background-color: var(--ctp-crust);
border: 1px solid var(--ctp-surface1);
color: var(--ctp-text);
font-family: var(--font-mono);
font-size: 0.74rem;
padding: 2px 6px;
max-width: 135px;
outline: none;
}
.incoming-call-card {
border-color: var(--ctp-green);
}
.incoming-call-pulse {
color: var(--ctp-green);
animation: voicePulse 0.8s infinite alternate;
}
@keyframes voicePulse {
from { opacity: 1; }
to { opacity: 0.45; }
}
/* ==========================================================================
Mobile Responsive Styles
========================================================================== */

File diff suppressed because it is too large Load diff

View file

@ -78,6 +78,7 @@
<span class="channel-topic" id="activeChannelTopic"></span>
</div>
<div class="chat-header-actions">
<button type="button" class="btn btn-sm btn-primary" id="voiceCallBtn" title="Start or Join Voice Call">[📞 Call]</button>
<button type="button" class="btn btn-sm btn-secondary" id="toggleFollowBtn" title="Follow or Mute notifications for this conversation">[🔔 Follow]</button>
<button type="button" class="btn btn-sm btn-secondary" id="toggleDmE2eeBtn" style="display:none;" title="Toggle E2EE for this Direct Message">[DM E2EE: ON]</button>
<button type="button" class="btn btn-sm btn-secondary" id="inviteGroupBtn" style="display:none;" title="Invite User to Group">[+ Invite]</button>
@ -88,6 +89,35 @@
</div>
</div>
<!-- Active Voice Call Bar -->
<div id="voiceCallBar" class="voice-call-bar" style="display:none;">
<div class="voice-call-info">
<span class="voice-status-dot" id="voiceStatusDot"></span>
<span class="voice-status-text" id="voiceCallStatusText">Voice Call Active</span>
<span class="voice-badge voice-transport-badge" id="voiceTransportBadge" title="Active VoIP Transport">[P2P STUN]</span>
<span class="voice-badge voice-e2ee-badge" id="voiceE2eeBadge" style="display:none;" title="End-to-End Encrypted Voice Stream">[🔒 E2EE Voice]</span>
<span class="voice-timer" id="voiceCallTimer">00:00</span>
</div>
<div class="voice-participants-list" id="voiceParticipantsList">
<!-- Populated by JS -->
</div>
<div class="voice-call-controls" id="voiceCallControls">
<button type="button" class="btn btn-sm btn-primary" id="voiceJoinRoomBtn" style="display:none;">[📞 Join Voice]</button>
<button type="button" class="btn btn-sm btn-secondary" id="voiceMuteBtn" title="Toggle Microphone Mute">[🎤 Mute]</button>
<button type="button" class="btn btn-sm btn-secondary" id="voiceDeafenBtn" title="Toggle Audio Deafen">[🎧 Deafen]</button>
<button type="button" class="btn btn-sm btn-secondary" id="voiceForceRelayBtn" title="Switch between Direct P2P (STUN/TURN) and Single-Port WebSocket TURN Relay">[⇄ Auto P2P]</button>
<select class="voice-device-select" id="voiceMicSelect" title="Select Microphone Input Device">
<option value="">Default Mic</option>
</select>
<select class="voice-device-select" id="voiceSpeakerSelect" title="Select Speaker Output Device">
<option value="">Default Speaker</option>
</select>
<button type="button" class="btn btn-sm btn-outline-danger" id="voiceHangupBtn" title="Hang Up / Leave Voice Call">[🔴 Hang Up]</button>
</div>
</div>
<div class="chat-content-container">
<div class="chat-main-area">
<div class="chat-messages" id="chatMessages">
@ -267,6 +297,24 @@
<!-- Toast Notification Overlay -->
<div id="toastContainer" class="toast-container"></div>
<!-- Hidden Remote Audio Elements Container -->
<div id="voiceRemoteAudioContainer" style="display:none;"></div>
<!-- Incoming Voice Call Modal -->
<div id="incomingCallModal" class="modal-backdrop" style="display:none;">
<div class="modal-card incoming-call-card">
<div class="modal-header">
<div class="modal-badge incoming-call-pulse">[ 📞 INCOMING VOICE CALL ]</div>
<h2 id="incomingCallerName">@username</h2>
<p class="modal-motd" id="incomingCallSecurityHint">Direct P2P STUN/TURN + Single-Port Relay Fallback</p>
</div>
<div class="form-actions" style="justify-content:center; gap:12px; margin-top:16px;">
<button type="button" class="btn btn-primary" id="acceptIncomingCallBtn">[ 📞 Accept Call ]</button>
<button type="button" class="btn btn-outline-danger" id="declineIncomingCallBtn">[ ✖ Decline ]</button>
</div>
</div>
</div>
<!-- E2EE PIN / Key Vault Modal -->
<div id="e2eeModal" class="modal-backdrop" style="display:none;">
<div class="modal-card">