diff --git a/serversettings.json b/serversettings.json index bc8a901..67a96cd 100644 --- a/serversettings.json +++ b/serversettings.json @@ -12,5 +12,24 @@ "Motd": "Welcome to GsDChat! Enjoy private and modular messaging.", "AllowMemberChannelCreation": true, "AllowDmE2ee": true, - "MaxGroupChatUsers": 10 + "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" + } + ] } diff --git a/src/GsDChat.Client/Network/ChatClientConnection.cs b/src/GsDChat.Client/Network/ChatClientConnection.cs index 29ccdae..50ce710 100644 --- a/src/GsDChat.Client/Network/ChatClientConnection.cs +++ b/src/GsDChat.Client/Network/ChatClientConnection.cs @@ -26,10 +26,13 @@ public class ChatClientConnection : IDisposable private CancellationTokenSource? _cts; private readonly SemaphoreSlim _sendLock = new(1, 1); + public VoiceCallManager VoiceManager { get; } + public ChatClientConnection(ClientState state, bool allowInsecure = false) { _state = state; _allowInsecure = allowInsecure; + VoiceManager = new VoiceCallManager(state, this); var handler = new HttpClientHandler(); if (allowInsecure) @@ -95,6 +98,13 @@ public class ChatClientConnection : IDisposable { _state.AllowDmE2ee = info.AllowDmE2ee; _state.MaxGroupChatUsers = info.MaxGroupChatUsers; + _state.EnableVoiceCalls = info.EnableVoiceCalls; + _state.AllowVoiceRelayFallback = info.AllowVoiceRelayFallback; + _state.MaxVoiceCallUsers = info.MaxVoiceCallUsers; + if (info.IceServers != null && info.IceServers.Count > 0) + { + _state.IceServers = info.IceServers; + } } return info; } @@ -410,6 +420,13 @@ public class ChatClientConnection : IDisposable _state.Motd = ui.Motd; _state.AllowDmE2ee = ui.AllowDmE2ee; _state.MaxGroupChatUsers = ui.MaxGroupChatUsers; + _state.EnableVoiceCalls = ui.EnableVoiceCalls; + _state.AllowVoiceRelayFallback = ui.AllowVoiceRelayFallback; + _state.MaxVoiceCallUsers = ui.MaxVoiceCallUsers; + if (ui.IceServers != null && ui.IceServers.Count > 0) + { + _state.IceServers = ui.IceServers; + } _state.CheckLazyDmE2eePrompt(); _state.NeedsRedraw = true; } @@ -491,6 +508,37 @@ public class ChatClientConnection : IDisposable } break; + case MessageTypes.VoiceCallState: + var vcState = envelope.Unpack(); + if (vcState != null) + { + _state.UpdateVoiceCallState(vcState.ChannelId, vcState.Session, vcState.IceServers, vcState.AllowVoiceRelayFallback); + VoiceManager.OnVoiceCallStateUpdated(vcState); + if (vcState.Session != null && + vcState.Session.Status == VoiceCallStatus.Ringing && + string.Equals(vcState.Session.RingingTargetUserId, _state.CurrentUserId, StringComparison.OrdinalIgnoreCase)) + { + _state.SetStatus($"📞 Incoming voice call from @{vcState.Session.InitiatorUsername}! Type /accept or /decline", 10); + } + } + break; + + case MessageTypes.VoiceSignal: + var vcSig = envelope.Unpack(); + if (vcSig != null) + { + VoiceManager.OnVoiceSignalReceived(vcSig); + } + break; + + case MessageTypes.VoiceAudioFrame: + var vcAudio = envelope.Unpack(); + if (vcAudio != null) + { + VoiceManager.OnVoiceAudioFrameReceived(vcAudio); + } + break; + case MessageTypes.SystemNotice: var notice = envelope.Unpack(); if (notice != null) @@ -852,6 +900,124 @@ public class ChatClientConnection : IDisposable return SendEnvelopeAsync(envelope); } + public Task StartVoiceCallAsync(string? channelId = null) + { + var envelope = NetworkEnvelope.Create(MessageTypes.VoiceCallStart, new VoiceCallStartPacket + { + ChannelId = string.IsNullOrWhiteSpace(channelId) ? _state.ActiveChannelId : channelId, + ClientType = VoiceClientTypes.Tui + }); + return SendEnvelopeAsync(envelope); + } + + public Task AcceptVoiceCallAsync(string? channelId = null) + { + string targetChId = channelId ?? string.Empty; + if (string.IsNullOrWhiteSpace(targetChId)) + { + var ringing = _state.GetRingingIncomingCall(); + targetChId = ringing?.ChannelId ?? _state.ActiveChannelId; + } + + var envelope = NetworkEnvelope.Create(MessageTypes.VoiceCallAccept, new VoiceCallAcceptPacket + { + ChannelId = targetChId, + ClientType = VoiceClientTypes.Tui + }); + return SendEnvelopeAsync(envelope); + } + + public Task DeclineVoiceCallAsync(string? channelId = null) + { + string targetChId = channelId ?? string.Empty; + if (string.IsNullOrWhiteSpace(targetChId)) + { + var ringing = _state.GetRingingIncomingCall(); + targetChId = ringing?.ChannelId ?? _state.ActiveChannelId; + } + + var envelope = NetworkEnvelope.Create(MessageTypes.VoiceCallDecline, new VoiceCallDeclinePacket + { + ChannelId = targetChId + }); + return SendEnvelopeAsync(envelope); + } + + public Task LeaveVoiceCallAsync(string? channelId = null) + { + string targetChId = !string.IsNullOrWhiteSpace(channelId) + ? channelId + : (_state.ActiveVoiceCallChannelId ?? _state.ActiveChannelId); + + VoiceManager.StopLocalVoiceSession(); + var envelope = NetworkEnvelope.Create(MessageTypes.VoiceCallLeave, new VoiceCallLeavePacket + { + ChannelId = targetChId + }); + return SendEnvelopeAsync(envelope); + } + + public Task ToggleVoiceMuteAsync(bool? mute = null) + { + _state.IsVoiceMuted = mute ?? !_state.IsVoiceMuted; + _state.NeedsRedraw = true; + string targetChId = _state.ActiveVoiceCallChannelId ?? _state.ActiveChannelId; + return SendVoiceStateUpdateAsync(new VoiceStateUpdatePacket + { + ChannelId = targetChId, + IsMuted = _state.IsVoiceMuted, + IsDeafened = _state.IsVoiceDeafened + }); + } + + public Task ToggleVoiceDeafenAsync(bool? deafen = null) + { + _state.IsVoiceDeafened = deafen ?? !_state.IsVoiceDeafened; + if (_state.IsVoiceDeafened) + { + _state.IsVoiceMuted = true; + } + _state.NeedsRedraw = true; + string targetChId = _state.ActiveVoiceCallChannelId ?? _state.ActiveChannelId; + return SendVoiceStateUpdateAsync(new VoiceStateUpdatePacket + { + ChannelId = targetChId, + IsMuted = _state.IsVoiceMuted, + IsDeafened = _state.IsVoiceDeafened + }); + } + + public Task ToggleVoiceRelayModeAsync(bool? forceRelay = null) + { + _state.VoiceForceRelay = forceRelay ?? !_state.VoiceForceRelay; + _state.VoiceActiveTransportMode = _state.VoiceForceRelay ? VoiceTransportModes.Relay : VoiceTransportModes.P2P; + _state.NeedsRedraw = true; + string targetChId = _state.ActiveVoiceCallChannelId ?? _state.ActiveChannelId; + return SendVoiceStateUpdateAsync(new VoiceStateUpdatePacket + { + ChannelId = targetChId, + TransportMode = _state.VoiceActiveTransportMode + }); + } + + public Task SendVoiceStateUpdateAsync(VoiceStateUpdatePacket packet) + { + var envelope = NetworkEnvelope.Create(MessageTypes.VoiceStateUpdate, packet); + return SendEnvelopeAsync(envelope); + } + + public Task SendVoiceSignalAsync(VoiceSignalPacket packet) + { + var envelope = NetworkEnvelope.Create(MessageTypes.VoiceSignal, packet); + return SendEnvelopeAsync(envelope); + } + + public Task SendVoiceAudioFrameAsync(VoiceAudioFramePacket packet) + { + var envelope = NetworkEnvelope.Create(MessageTypes.VoiceAudioFrame, packet); + return SendEnvelopeAsync(envelope); + } + public async Task UploadFileAsync(string localFilePath, string channelId) { if (!File.Exists(localFilePath)) @@ -930,6 +1096,7 @@ public class ChatClientConnection : IDisposable public void Dispose() { + VoiceManager.Dispose(); _cts?.Cancel(); _webSocket?.Dispose(); _httpClient.Dispose(); diff --git a/src/GsDChat.Client/Network/VoiceCallManager.cs b/src/GsDChat.Client/Network/VoiceCallManager.cs new file mode 100644 index 0000000..d5282d6 --- /dev/null +++ b/src/GsDChat.Client/Network/VoiceCallManager.cs @@ -0,0 +1,649 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using GsDChat.Client.State; +using GsDChat.Core.Models; +using GsDChat.Core.Protocol; +using GsDChat.Core.Security; + +namespace GsDChat.Client.Network; + +public class VoiceCallManager : IDisposable +{ + private readonly ClientState _state; + private readonly ChatClientConnection _connection; + private CancellationTokenSource? _callCts; + private UdpClient? _udpClient; + private string? _activeCallId; + private string? _activeChannelId; + private readonly byte[] _localSessionKey = RandomNumberGenerator.GetBytes(32); + private string? _discoveredEndpointStr; + private long _txSequence; + + private Process? _captureProcess; + private Process? _playbackProcess; + + private readonly ConcurrentDictionary _peers = new(StringComparer.OrdinalIgnoreCase); + + private class PeerUdpState + { + public string UserId { get; set; } = string.Empty; + public IPEndPoint? Endpoint { get; set; } + public byte[]? SessionKey { get; set; } + public DateTime LastReceivedUtc { get; set; } = DateTime.MinValue; + public bool IsDirectUdpActive => Endpoint != null && (DateTime.UtcNow - LastReceivedUtc).TotalSeconds < 6; + } + + private class UdpCandidatePayload + { + public string Endpoint { get; set; } = string.Empty; + public string SessionKeyBase64 { get; set; } = string.Empty; + } + + public VoiceCallManager(ClientState state, ChatClientConnection connection) + { + _state = state; + _connection = connection; + } + + public void OnVoiceCallStateUpdated(VoiceCallStatePacket packet) + { + var session = packet.Session; + if (session == null || session.Status == VoiceCallStatus.Ended) + { + if (string.Equals(_activeChannelId, packet.ChannelId, StringComparison.OrdinalIgnoreCase)) + { + StopLocalVoiceSession(); + } + return; + } + + bool amIParticipant = session.Status == VoiceCallStatus.Active && + session.Participants.Any(p => string.Equals(p.UserId, _state.CurrentUserId, StringComparison.OrdinalIgnoreCase)); + + if (amIParticipant) + { + if (!string.Equals(_activeCallId, session.CallId, StringComparison.Ordinal)) + { + StartLocalVoiceSession(session); + } + else + { + // Send UDP candidate to any newly joined TUI peers + _ = AnnounceUdpCandidateToPeersAsync(session); + } + } + else if (string.Equals(_activeChannelId, packet.ChannelId, StringComparison.OrdinalIgnoreCase)) + { + StopLocalVoiceSession(); + } + } + + public void OnVoiceSignalReceived(VoiceSignalPacket signal) + { + if (!string.Equals(signal.ChannelId, _activeChannelId, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + if (string.Equals(signal.SignalType, "udp-candidate", StringComparison.OrdinalIgnoreCase)) + { + try + { + var cand = JsonSerializer.Deserialize(signal.Payload, new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }); + if (cand != null && IPEndPoint.TryParse(cand.Endpoint, out var ep)) + { + var peerState = _peers.GetOrAdd(signal.SenderUserId, id => new PeerUdpState { UserId = id }); + peerState.Endpoint = ep; + if (!string.IsNullOrWhiteSpace(cand.SessionKeyBase64)) + { + peerState.SessionKey = Convert.FromBase64String(cand.SessionKeyBase64); + } + + // Send hole-punching packet immediately + _ = SendUdpPunchAsync(ep); + } + } + catch { } + } + else if (string.Equals(signal.SignalType, "relay-switch", StringComparison.OrdinalIgnoreCase)) + { + if (_peers.TryGetValue(signal.SenderUserId, out var peerState)) + { + peerState.LastReceivedUtc = DateTime.MinValue; + } + _state.VoiceActiveTransportMode = VoiceTransportModes.Relay; + _state.NeedsRedraw = true; + } + } + + public void OnVoiceAudioFrameReceived(VoiceAudioFramePacket frame) + { + if (_state.IsVoiceDeafened) return; + if (!string.Equals(frame.ChannelId, _activeChannelId, StringComparison.OrdinalIgnoreCase)) return; + + // Skip duplicate audio if direct P2P UDP is actively streaming from this peer + if (!_state.VoiceForceRelay && + _peers.TryGetValue(frame.SenderUserId, out var peerState) && + peerState.IsDirectUdpActive) + { + return; + } + + byte[]? ulawBytes = DecodeIncomingPayload(frame.DataBase64, frame.IsEncrypted, frame.ChannelId, frame.SenderUserId, frame.SenderPublicKey); + if (ulawBytes == null || ulawBytes.Length == 0) return; + + ProcessReceivedMuLawAudio(frame.SenderUserId, frame.SenderUsername, ulawBytes, frame.SpeakingLevel, isFromRelay: true); + } + + /// + /// Sends a single 16-bit PCM mono frame (or mu-law frame) to active call participants. + /// Automatically uses P2P UDP if connected, or falls back to the single-port WebSocket relay. + /// + public async Task SendAudioFrameAsync(byte[] muLawBytes, float speakingLevel = 0f) + { + if (string.IsNullOrEmpty(_activeChannelId) || _state.IsVoiceMuted || muLawBytes.Length == 0) + { + return; + } + + var session = _state.GetVoiceCallForChannel(_activeChannelId); + if (session == null || session.Status != VoiceCallStatus.Active) + { + return; + } + + long seq = Interlocked.Increment(ref _txSequence); + float level = speakingLevel > 0f ? speakingLevel : G711AudioCodec.ComputeRmsLevelFromMuLaw(muLawBytes); + _state.SetParticipantSpeaking(_state.CurrentUserId, level > 0.03f); + + var otherParticipants = session.Participants + .Where(p => !string.Equals(p.UserId, _state.CurrentUserId, StringComparison.OrdinalIgnoreCase)) + .ToList(); + + if (otherParticipants.Count == 0) return; + + var conv = _state.GetConversationById(_activeChannelId); + bool isDm = conv != null && conv.Type == ChannelTypes.DirectMessage; + bool shouldE2ee = isDm && (session.IsE2ee || conv!.IsE2ee) && _state.AllowDmE2ee && _state.AccountE2eeEnabled && _state.HasUnlockedE2eeKey; + + bool sentAnyViaRelay = false; + bool sentAnyViaP2p = false; + + foreach (var peer in otherParticipants) + { + string? peerPubKey = peer.PublicKey; + if (string.IsNullOrWhiteSpace(peerPubKey) && conv != null && isDm) + { + peerPubKey = _state.GetPeerPublicKeyForDm(conv); + } + if (string.IsNullOrWhiteSpace(peerPubKey)) + { + var u = _state.Users.FirstOrDefault(x => string.Equals(x.Id, peer.UserId, StringComparison.OrdinalIgnoreCase)); + peerPubKey = u?.PublicKey; + } + + bool canUseDirectUdp = !_state.VoiceForceRelay && + string.Equals(peer.ClientType, VoiceClientTypes.Tui, StringComparison.OrdinalIgnoreCase) && + _peers.TryGetValue(peer.UserId, out var udpState) && + udpState.IsDirectUdpActive && + udpState.Endpoint != null && + _udpClient != null; + + if (canUseDirectUdp && _peers.TryGetValue(peer.UserId, out var activePeerUdp) && activePeerUdp.Endpoint != null) + { + string encryptedPayload = shouldE2ee && !string.IsNullOrWhiteSpace(peerPubKey) + ? E2eeCrypto.EncryptAudioFrame(muLawBytes, _state.PrivateKeyBase64, peerPubKey) + : E2eeCrypto.EncryptWithSessionKey(muLawBytes, _localSessionKey); + + string udpMsg = $"VUDP|{_state.CurrentUserId}|{seq}|{level:0.###}|{encryptedPayload}"; + byte[] datagram = Encoding.UTF8.GetBytes(udpMsg); + try + { + await _udpClient!.SendAsync(datagram, activePeerUdp.Endpoint); + sentAnyViaP2p = true; + continue; + } + catch + { + // Fall through to single-port WebSocket relay + } + } + + // Fallback to Single-Port WebSocket TURN-like Relay (/ws) + string dataPayload; + bool isEncrypted = false; + if (shouldE2ee && !string.IsNullOrWhiteSpace(peerPubKey)) + { + dataPayload = E2eeCrypto.EncryptAudioFrame(muLawBytes, _state.PrivateKeyBase64, peerPubKey); + isEncrypted = true; + } + else + { + dataPayload = Convert.ToBase64String(muLawBytes); + } + + await _connection.SendVoiceAudioFrameAsync(new VoiceAudioFramePacket + { + ChannelId = _activeChannelId, + SenderUserId = _state.CurrentUserId, + SenderUsername = _state.CurrentUsername, + TargetUserId = peer.UserId, + Sequence = seq, + Codec = "ulaw-16k", + DataBase64 = dataPayload, + IsEncrypted = isEncrypted, + SenderPublicKey = isEncrypted ? _state.PublicKeyBase64 : null, + SpeakingLevel = level + }); + sentAnyViaRelay = true; + } + + string newMode = sentAnyViaP2p && !sentAnyViaRelay ? VoiceTransportModes.P2P : VoiceTransportModes.Relay; + if (_state.VoiceActiveTransportMode != newMode) + { + _state.VoiceActiveTransportMode = newMode; + _state.NeedsRedraw = true; + } + } + + private void StartLocalVoiceSession(VoiceCallSessionInfo session) + { + StopLocalVoiceSession(); + + _activeCallId = session.CallId; + _activeChannelId = session.ChannelId; + _callCts = new CancellationTokenSource(); + var ct = _callCts.Token; + + _state.ActiveVoiceCallChannelId = session.ChannelId; + _state.VoiceActiveTransportMode = _state.VoiceForceRelay ? VoiceTransportModes.Relay : VoiceTransportModes.P2P; + _state.NeedsRedraw = true; + + _ = Task.Run(() => RunVoiceSessionAsync(session, ct), ct); + } + + private async Task RunVoiceSessionAsync(VoiceCallSessionInfo session, CancellationToken ct) + { + try + { + _udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 0)); + int localPort = ((IPEndPoint)_udpClient.Client.LocalEndPoint!).Port; + + // 1. Query STUN servers to discover public reflexive IP:Port (RFC 5389) + IPEndPoint? reflexiveEp = null; + var stunUrls = _state.IceServers + .SelectMany(s => s.Urls ?? new List()) + .Where(u => u.StartsWith("stun:", StringComparison.OrdinalIgnoreCase)) + .ToList(); + + foreach (var stunUrl in stunUrls) + { + reflexiveEp = await StunClient.QueryPublicEndpointAsync(_udpClient, stunUrl, ct); + if (reflexiveEp != null) break; + } + + _discoveredEndpointStr = reflexiveEp != null + ? reflexiveEp.ToString() + : $"127.0.0.1:{localPort}"; + + await _connection.SendVoiceStateUpdateAsync(new VoiceStateUpdatePacket + { + ChannelId = session.ChannelId, + IsMuted = _state.IsVoiceMuted, + IsDeafened = _state.IsVoiceDeafened, + TransportMode = _state.VoiceActiveTransportMode, + UdpEndpoint = _discoveredEndpointStr + }); + + await AnnounceUdpCandidateToPeersAsync(session); + + // Start UDP Receive + Hole-Punch Keepalive loop + _ = Task.Run(() => UdpReceiveLoopAsync(ct), ct); + _ = Task.Run(() => UdpKeepAliveLoopAsync(ct), ct); + + // Start OS Audio Capture & Playback if enabled and not disabled by env + if (!string.Equals(Environment.GetEnvironmentVariable("GSDCHAT_DISABLE_OS_AUDIO"), "1", StringComparison.OrdinalIgnoreCase)) + { + StartOsAudioProcesses(ct); + } + } + catch (OperationCanceledException) { } + catch + { + // Fallback to WebSocket relay if UDP socket creation fails + _state.VoiceActiveTransportMode = VoiceTransportModes.Relay; + _state.NeedsRedraw = true; + } + } + + private async Task AnnounceUdpCandidateToPeersAsync(VoiceCallSessionInfo session) + { + if (string.IsNullOrEmpty(_discoveredEndpointStr)) return; + + string payloadJson = JsonSerializer.Serialize(new UdpCandidatePayload + { + Endpoint = _discoveredEndpointStr, + SessionKeyBase64 = Convert.ToBase64String(_localSessionKey) + }); + + foreach (var part in session.Participants) + { + if (string.Equals(part.UserId, _state.CurrentUserId, StringComparison.OrdinalIgnoreCase)) continue; + if (string.Equals(part.ClientType, VoiceClientTypes.Tui, StringComparison.OrdinalIgnoreCase)) + { + await _connection.SendVoiceSignalAsync(new VoiceSignalPacket + { + ChannelId = session.ChannelId, + TargetUserId = part.UserId, + SignalType = "udp-candidate", + Payload = payloadJson + }); + } + } + } + + private async Task SendUdpPunchAsync(IPEndPoint target) + { + if (_udpClient == null) return; + try + { + byte[] punch = Encoding.UTF8.GetBytes($"PUNCH|{_state.CurrentUserId}"); + await _udpClient.SendAsync(punch, target); + } + catch { } + } + + private async Task UdpKeepAliveLoopAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested && _udpClient != null) + { + try + { + foreach (var peer in _peers.Values) + { + if (peer.Endpoint != null) + { + await SendUdpPunchAsync(peer.Endpoint); + } + } + await Task.Delay(1500, ct); + } + catch (OperationCanceledException) { break; } + catch { } + } + } + + private async Task UdpReceiveLoopAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested && _udpClient != null) + { + try + { + var result = await _udpClient.ReceiveAsync(ct); + string text = Encoding.UTF8.GetString(result.Buffer); + + if (text.StartsWith("PUNCH|", StringComparison.Ordinal)) + { + string senderId = text.Substring(6).Trim(); + if (_peers.TryGetValue(senderId, out var peer) && (peer.Endpoint == null || peer.Endpoint.Address.Equals(result.RemoteEndPoint.Address))) + { + peer.Endpoint = result.RemoteEndPoint; + peer.LastReceivedUtc = DateTime.UtcNow; + + // Reply with PUNCH_ACK so both sides confirm bidirectional hole punch + byte[] ack = Encoding.UTF8.GetBytes($"PUNCH_ACK|{_state.CurrentUserId}"); + await _udpClient.SendAsync(ack, result.RemoteEndPoint, ct); + } + } + else if (text.StartsWith("PUNCH_ACK|", StringComparison.Ordinal)) + { + string senderId = text.Substring(10).Trim(); + if (_peers.TryGetValue(senderId, out var peer) && (peer.Endpoint == null || peer.Endpoint.Address.Equals(result.RemoteEndPoint.Address))) + { + peer.Endpoint = result.RemoteEndPoint; + peer.LastReceivedUtc = DateTime.UtcNow; + } + } + else if (text.StartsWith("VUDP|", StringComparison.Ordinal)) + { + if (_state.IsVoiceDeafened) continue; + string[] parts = text.Split('|', 5); + if (parts.Length == 5) + { + string senderId = parts[1]; + if (_peers.TryGetValue(senderId, out var peer)) + { + float.TryParse(parts[3], out float level); + string encryptedPayload = parts[4]; + + byte[]? ulaw = DecodeIncomingUdpPayload(encryptedPayload, senderId, peer.SessionKey); + if (ulaw != null && ulaw.Length > 0) + { + peer.Endpoint = result.RemoteEndPoint; + peer.LastReceivedUtc = DateTime.UtcNow; + var u = _state.Users.FirstOrDefault(x => string.Equals(x.Id, senderId, StringComparison.OrdinalIgnoreCase)); + ProcessReceivedMuLawAudio(senderId, u?.Username ?? senderId, ulaw, level, isFromRelay: false); + } + } + } + } + } + catch (OperationCanceledException) { break; } + catch { } + } + } + + private byte[]? DecodeIncomingUdpPayload(string payload, string senderUserId, byte[]? peerSessionKey) + { + if (string.IsNullOrEmpty(_activeChannelId)) return null; + + // First try E2EE DM key if unlocked + if (_state.HasUnlockedE2eeKey) + { + string? peerPubKey = ResolvePeerPublicKey(_activeChannelId, senderUserId, null); + if (!string.IsNullOrWhiteSpace(peerPubKey)) + { + byte[]? e2eeDecrypted = E2eeCrypto.DecryptAudioFrame(payload, _state.PrivateKeyBase64, peerPubKey); + if (e2eeDecrypted != null) return e2eeDecrypted; + } + } + + // Next try peer's ephemeral UDP session key + if (peerSessionKey != null) + { + return E2eeCrypto.DecryptWithSessionKey(payload, peerSessionKey); + } + + return null; + } + + private byte[]? DecodeIncomingPayload(string dataBase64, bool isEncrypted, string channelId, string senderUserId, string? senderPubKey) + { + if (string.IsNullOrWhiteSpace(dataBase64)) return null; + + if (isEncrypted || E2eeCrypto.IsVoiceEncryptedPayload(dataBase64)) + { + if (!_state.HasUnlockedE2eeKey) return null; + string? peerPubKey = ResolvePeerPublicKey(channelId, senderUserId, senderPubKey); + if (string.IsNullOrWhiteSpace(peerPubKey)) return null; + return E2eeCrypto.DecryptAudioFrame(dataBase64, _state.PrivateKeyBase64, peerPubKey); + } + + try + { + return Convert.FromBase64String(dataBase64); + } + catch + { + return null; + } + } + + private string? ResolvePeerPublicKey(string channelId, string senderUserId, string? packetSenderPubKey) + { + if (!string.IsNullOrWhiteSpace(packetSenderPubKey)) return packetSenderPubKey; + var conv = _state.GetConversationById(channelId); + if (conv != null && conv.MemberPublicKeys.TryGetValue(senderUserId, out var key) && !string.IsNullOrWhiteSpace(key)) + { + return key; + } + var u = _state.Users.FirstOrDefault(x => string.Equals(x.Id, senderUserId, StringComparison.OrdinalIgnoreCase)); + if (!string.IsNullOrWhiteSpace(u?.PublicKey)) return u.PublicKey; + if (conv != null && conv.Type == ChannelTypes.DirectMessage) + { + return _state.GetPeerPublicKeyForDm(conv); + } + return null; + } + + private void ProcessReceivedMuLawAudio(string senderUserId, string senderUsername, byte[] ulawBytes, float speakingLevel, bool isFromRelay) + { + byte[] pcm16 = G711AudioCodec.DecodeMuLawToPcm16(ulawBytes); + _state.RecordReceivedVoiceFrame(senderUserId, ulawBytes, pcm16, speakingLevel > 0f ? speakingLevel : G711AudioCodec.ComputeRmsLevelFromMuLaw(ulawBytes), isFromRelay); + + try + { + if (_playbackProcess != null && !_playbackProcess.HasExited) + { + _playbackProcess.StandardInput.BaseStream.Write(pcm16, 0, pcm16.Length); + _playbackProcess.StandardInput.BaseStream.Flush(); + } + } + catch { } + } + + private void StartOsAudioProcesses(CancellationToken ct) + { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return; + } + + // Try PipeWire (pw-cat), PulseAudio (parec/pacat), or ALSA (arecord/aplay) + (string FileName, string CaptureArgs, string PlaybackArgs)[] candidates = + { + ("pw-cat", "--record --rate 16000 --channels 1 --format s16 -", "--playback --rate 16000 --channels 1 --format s16 -"), + ("parec", "--rate=16000 --channels=1 --format=s16le --latency-msec=20", ""), + ("arecord", "-q -f S16_LE -r 16000 -c 1 -t raw -", "-q -f S16_LE -r 16000 -c 1 -t raw -") + }; + + foreach (var cand in candidates) + { + try + { + string playBin = cand.FileName == "parec" ? "pacat" : cand.FileName; + string playArgs = cand.FileName == "parec" ? "--playback --rate=16000 --channels=1 --format=s16le --latency-msec=20" : cand.PlaybackArgs; + + _playbackProcess = Process.Start(new ProcessStartInfo + { + FileName = playBin, + Arguments = playArgs, + RedirectStandardInput = true, + RedirectStandardError = true, + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }); + + _captureProcess = Process.Start(new ProcessStartInfo + { + FileName = cand.FileName, + Arguments = cand.CaptureArgs, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + }); + + if (_captureProcess != null && !_captureProcess.HasExited) + { + _ = Task.Run(() => CaptureReadLoopAsync(_captureProcess.StandardOutput.BaseStream, ct), ct); + break; + } + } + catch + { + KillProcessSafely(ref _captureProcess); + KillProcessSafely(ref _playbackProcess); + } + } + } + + private async Task CaptureReadLoopAsync(Stream stdout, CancellationToken ct) + { + byte[] pcmBuffer = new byte[640]; // 20ms at 16000 Hz, 16-bit mono + try + { + while (!ct.IsCancellationRequested) + { + int offset = 0; + while (offset < pcmBuffer.Length && !ct.IsCancellationRequested) + { + int read = await stdout.ReadAsync(pcmBuffer.AsMemory(offset, pcmBuffer.Length - offset), ct); + if (read <= 0) return; + offset += read; + } + + if (!_state.IsVoiceMuted) + { + float rms = G711AudioCodec.ComputeRmsLevelFromPcm16(pcmBuffer); + byte[] ulaw = G711AudioCodec.EncodePcm16ToMuLaw(pcmBuffer); + await SendAudioFrameAsync(ulaw, rms); + } + } + } + catch (OperationCanceledException) { } + catch { } + } + + public void StopLocalVoiceSession() + { + try { _callCts?.Cancel(); } catch { } + _callCts?.Dispose(); + _callCts = null; + + try { _udpClient?.Dispose(); } catch { } + _udpClient = null; + + KillProcessSafely(ref _captureProcess); + KillProcessSafely(ref _playbackProcess); + + _peers.Clear(); + _activeCallId = null; + _activeChannelId = null; + _state.ActiveVoiceCallChannelId = null; + _state.NeedsRedraw = true; + } + + private static void KillProcessSafely(ref Process? proc) + { + if (proc == null) return; + try + { + if (!proc.HasExited) proc.Kill(); + } + catch { } + try { proc.Dispose(); } catch { } + proc = null; + } + + public void Dispose() + { + StopLocalVoiceSession(); + } +} diff --git a/src/GsDChat.Client/Screens/ChatScreen.cs b/src/GsDChat.Client/Screens/ChatScreen.cs index 631b52d..ef4a762 100644 --- a/src/GsDChat.Client/Screens/ChatScreen.cs +++ b/src/GsDChat.Client/Screens/ChatScreen.cs @@ -83,8 +83,53 @@ public class ChatScreen : IScreen sb.AppendLine(PadOrTruncate(header, width)); sb.AppendLine(new string('─', Math.Max(0, width - 1))); - // Messages area: height minus (Header: 2, Footer/Input: 3, Tab bar & status: 3) = height - 8 - int msgAreaHeight = Math.Max(3, height - 8); + int extraVoiceLines = 0; + var incomingRinging = _state.GetRingingIncomingCall(); + var activeConvCall = _state.GetVoiceCallForChannel(_state.ActiveChannelId); + + if (incomingRinging != null) + { + string e2eeBadge = incomingRinging.IsE2ee ? $"{Ansi.BrightGreen}[🔒 E2EE]{Ansi.Reset} " : ""; + string ringBanner = $" {Ansi.BrightYellow}{Ansi.Bold}📞 INCOMING VOICE CALL from @{incomingRinging.InitiatorUsername}{Ansi.Reset} {e2eeBadge}— Type {Ansi.BrightGreen}/accept{Ansi.Reset} or {Ansi.Red}/decline{Ansi.Reset}"; + sb.AppendLine(PadOrTruncate(ringBanner, width)); + sb.AppendLine(new string('─', Math.Max(0, width - 1))); + extraVoiceLines += 2; + } + else if (activeConvCall != null) + { + bool amInCall = activeConvCall.Participants.Any(p => string.Equals(p.UserId, _state.CurrentUserId, StringComparison.OrdinalIgnoreCase)); + string transportBadge = _state.VoiceActiveTransportMode == VoiceTransportModes.Relay + ? $"{Ansi.BrightMagenta}[WS TURN Relay]{Ansi.Reset}" + : $"{Ansi.BrightCyan}[P2P STUN/UDP]{Ansi.Reset}"; + string e2eeBadge = activeConvCall.IsE2ee ? $" {Ansi.BrightGreen}[🔒 E2EE Voice]{Ansi.Reset}" : ""; + string selfAudioState = amInCall + ? $" │ {(_state.IsVoiceMuted ? $"{Ansi.Red}🔇 Muted{Ansi.Reset}" : $"{Ansi.BrightGreen}🎤 Mic ON{Ansi.Reset}")}{(_state.IsVoiceDeafened ? $" {Ansi.Red}🔕 Deafened{Ansi.Reset}" : "")}" + : ""; + + var partTags = activeConvCall.Participants.Select(p => + { + bool speaking = _state.IsParticipantSpeaking(p.UserId); + string dot = speaking ? $"{Ansi.BrightGreen}◉{Ansi.Reset}" : "●"; + string muteIcon = p.IsDeafened ? "🔕" : (p.IsMuted ? "🔇" : ""); + return $"{dot} @{p.Username}{muteIcon}"; + }); + + string statusPrefix = activeConvCall.Status == VoiceCallStatus.Ringing + ? $"{Ansi.BrightYellow}📞 Calling @{activeConvCall.RingingTargetUsername ?? "peer"}...{Ansi.Reset}" + : $"{Ansi.BrightGreen}📞 VOICE CALL ({activeConvCall.Participants.Count}){Ansi.Reset} {transportBadge}{e2eeBadge}{selfAudioState}"; + + string actionHint = amInCall + ? $"{Ansi.Gray}(/mute /deafen /relay /hangup){Ansi.Reset}" + : $"{Ansi.BrightGreen}(Type /call to join){Ansi.Reset}"; + + string callBanner = $" {statusPrefix} │ {string.Join(", ", partTags)} {actionHint}"; + sb.AppendLine(PadOrTruncate(callBanner, width)); + sb.AppendLine(new string('─', Math.Max(0, width - 1))); + extraVoiceLines += 2; + } + + // Messages area: height minus (Header: 2, Footer/Input: 3, Tab bar & status: 3, VoiceBanner: extraVoiceLines) + int msgAreaHeight = Math.Max(3, height - 8 - extraVoiceLines); List messages = _state.GetMessagesForChannel(_state.ActiveChannelId); @@ -444,10 +489,66 @@ public class ChatScreen : IScreen case "follow": case "unfollow": - case "mute": await _connection.ExecuteCommandAsync(cmd, args, _state.ActiveChannelId); break; + case "call": + case "voice": + if (string.IsNullOrEmpty(_state.ActiveChannelId)) + { + _state.SetStatus("Select a conversation first before starting a voice call."); + return; + } + await _connection.StartVoiceCallAsync(_state.ActiveChannelId); + _state.SetStatus("📞 Starting / joining voice call...", 3); + break; + + case "accept": + case "answer": + await _connection.AcceptVoiceCallAsync(); + _state.SetStatus("📞 Accepting voice call...", 3); + break; + + case "decline": + case "reject": + await _connection.DeclineVoiceCallAsync(); + _state.SetStatus("📞 Declined voice call.", 3); + break; + + case "hangup": + case "leavecall": + await _connection.LeaveVoiceCallAsync(); + _state.SetStatus("📞 Left voice call.", 3); + break; + + case "vmute": + case "mute": + // If user passes a channel name (or is not in an active voice call and used /mute), mute channel notifications + if (cmd == "mute" && (!string.IsNullOrWhiteSpace(args) || string.IsNullOrEmpty(_state.ActiveVoiceCallChannelId))) + { + await _connection.ExecuteCommandAsync(cmd, args, _state.ActiveChannelId); + } + else + { + await _connection.ToggleVoiceMuteAsync(); + _state.SetStatus(_state.IsVoiceMuted ? "🔇 Microphone muted." : "🎤 Microphone unmuted.", 3); + } + break; + + case "deafen": + case "vdeafen": + await _connection.ToggleVoiceDeafenAsync(); + _state.SetStatus(_state.IsVoiceDeafened ? "🔕 Voice audio deafened (and mic muted)." : "🎧 Voice audio undeafened.", 3); + break; + + case "relay": + case "vrelay": + await _connection.ToggleVoiceRelayModeAsync(); + _state.SetStatus(_state.VoiceForceRelay + ? "⇄ Switched voice transport to Single-Port WebSocket TURN Relay." + : "⇄ Switched voice transport to Direct P2P (STUN/UDP) with automatic relay fallback.", 4); + break; + case "upload": if (string.IsNullOrEmpty(args)) { diff --git a/src/GsDChat.Client/State/ClientState.cs b/src/GsDChat.Client/State/ClientState.cs index 8e260fc..40c14d0 100644 --- a/src/GsDChat.Client/State/ClientState.cs +++ b/src/GsDChat.Client/State/ClientState.cs @@ -32,8 +32,47 @@ public class ClientState public string Motd { get; set; } = string.Empty; public bool AllowDmE2ee { get; set; } = true; public int MaxGroupChatUsers { get; set; } = 10; + public bool EnableVoiceCalls { get; set; } = true; + public bool AllowVoiceRelayFallback { get; set; } = true; + public int MaxVoiceCallUsers { get; set; } = 10; + public List IceServers { get; set; } = new() + { + new IceServerConfig + { + Urls = new List + { + "stun:stun.cloudflare.com:3478", + "stun:stun.l.google.com:19302" + } + }, + new IceServerConfig + { + Urls = new List + { + "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 ServerUiSync UiSync { get; set; } = ServerUiSync.CreateDefault(); + // Voice Call State + public Dictionary ActiveVoiceCalls { get; } = new(StringComparer.OrdinalIgnoreCase); + public Dictionary SpeakingParticipantsUntil { get; } = new(StringComparer.OrdinalIgnoreCase); + public string? ActiveVoiceCallChannelId { get; set; } + public bool IsVoiceMuted { get; set; } = false; + public bool IsVoiceDeafened { get; set; } = false; + public bool VoiceForceRelay { get; set; } = false; + public string VoiceActiveTransportMode { get; set; } = VoiceTransportModes.P2P; + public int VoiceFramesReceivedCount { get; private set; } = 0; + public byte[]? LastReceivedVoiceMuLaw { get; private set; } + public byte[]? LastReceivedVoicePcm16 { get; private set; } + public string? LastVoiceFrameSenderId { get; private set; } + public string ActiveScreenId { get; set; } = "F1_Chat"; public string ActiveChannelId { get; set; } = string.Empty; @@ -496,4 +535,103 @@ public class ClientState return !InboxPreferences.MutedChannelIds.Contains(ch.Id, StringComparer.OrdinalIgnoreCase); } } + + public void UpdateVoiceCallState(string channelId, VoiceCallSessionInfo? session, List? iceServers = null, bool? allowRelay = null) + { + lock (_lock) + { + if (iceServers != null && iceServers.Count > 0) + { + IceServers = new List(iceServers); + } + if (allowRelay.HasValue) + { + AllowVoiceRelayFallback = allowRelay.Value; + } + + if (session == null || session.Status == VoiceCallStatus.Ended) + { + ActiveVoiceCalls.Remove(channelId); + if (string.Equals(ActiveVoiceCallChannelId, channelId, StringComparison.OrdinalIgnoreCase)) + { + ActiveVoiceCallChannelId = null; + } + } + else + { + ActiveVoiceCalls[channelId] = session; + bool inCall = session.Status == VoiceCallStatus.Active && + session.Participants.Any(p => string.Equals(p.UserId, CurrentUserId, StringComparison.OrdinalIgnoreCase)); + if (inCall) + { + ActiveVoiceCallChannelId = channelId; + } + } + NeedsRedraw = true; + } + } + + public VoiceCallSessionInfo? GetVoiceCallForChannel(string channelId) + { + if (string.IsNullOrEmpty(channelId)) return null; + lock (_lock) + { + if (ActiveVoiceCalls.TryGetValue(channelId, out var session) && session.Status != VoiceCallStatus.Ended) + { + return session; + } + return null; + } + } + + public VoiceCallSessionInfo? GetRingingIncomingCall() + { + lock (_lock) + { + return ActiveVoiceCalls.Values.FirstOrDefault(s => + s.Status == VoiceCallStatus.Ringing && + string.Equals(s.RingingTargetUserId, CurrentUserId, StringComparison.OrdinalIgnoreCase)); + } + } + + public void SetParticipantSpeaking(string userId, bool isSpeaking) + { + lock (_lock) + { + if (isSpeaking) + { + SpeakingParticipantsUntil[userId] = DateTime.UtcNow.AddMilliseconds(450); + } + else + { + SpeakingParticipantsUntil.Remove(userId); + } + NeedsRedraw = true; + } + } + + public bool IsParticipantSpeaking(string userId) + { + lock (_lock) + { + return SpeakingParticipantsUntil.TryGetValue(userId, out var until) && until > DateTime.UtcNow; + } + } + + public void RecordReceivedVoiceFrame(string senderUserId, byte[] ulaw, byte[] pcm16, float speakingLevel, bool isFromRelay) + { + lock (_lock) + { + VoiceFramesReceivedCount++; + LastVoiceFrameSenderId = senderUserId; + LastReceivedVoiceMuLaw = ulaw; + LastReceivedVoicePcm16 = pcm16; + VoiceActiveTransportMode = isFromRelay ? VoiceTransportModes.Relay : VoiceTransportModes.P2P; + if (speakingLevel > 0.02f) + { + SpeakingParticipantsUntil[senderUserId] = DateTime.UtcNow.AddMilliseconds(450); + } + NeedsRedraw = true; + } + } } diff --git a/src/GsDChat.Core/Models/VoiceCallModels.cs b/src/GsDChat.Core/Models/VoiceCallModels.cs new file mode 100644 index 0000000..cf6f074 --- /dev/null +++ b/src/GsDChat.Core/Models/VoiceCallModels.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; + +namespace GsDChat.Core.Models; + +public class IceServerConfig +{ + public List Urls { get; set; } = new(); + public string? Username { get; set; } + public string? Credential { get; set; } +} + +public static class VoiceCallStatus +{ + public const string Ringing = "Ringing"; + public const string Active = "Active"; + public const string Ended = "Ended"; +} + +public static class VoiceClientTypes +{ + public const string Web = "web"; + public const string Tui = "tui"; +} + +public static class VoiceTransportModes +{ + public const string P2P = "p2p"; + public const string Relay = "relay"; +} + +public class VoiceParticipant +{ + public string UserId { get; set; } = string.Empty; + public string Username { get; set; } = string.Empty; + public string ClientType { get; set; } = VoiceClientTypes.Web; + public bool IsMuted { get; set; } = false; + public bool IsDeafened { get; set; } = false; + public string TransportMode { get; set; } = VoiceTransportModes.P2P; + public string? PublicKey { get; set; } + public string? UdpEndpoint { get; set; } + public DateTime JoinedAt { get; set; } = DateTime.UtcNow; +} + +public class VoiceCallSessionInfo +{ + public string CallId { get; set; } = Guid.NewGuid().ToString("N"); + public string ChannelId { get; set; } = string.Empty; + public string ChannelType { get; set; } = ChannelTypes.Channel; + public string InitiatorUserId { get; set; } = string.Empty; + public string InitiatorUsername { get; set; } = string.Empty; + public string Status { get; set; } = VoiceCallStatus.Active; + public bool IsE2ee { get; set; } = false; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public string? RingingTargetUserId { get; set; } + public string? RingingTargetUsername { get; set; } + public List Participants { get; set; } = new(); +} diff --git a/src/GsDChat.Core/Protocol/HttpModels.cs b/src/GsDChat.Core/Protocol/HttpModels.cs index 3157aa6..5c9b392 100644 --- a/src/GsDChat.Core/Protocol/HttpModels.cs +++ b/src/GsDChat.Core/Protocol/HttpModels.cs @@ -46,6 +46,10 @@ public class ServerInfoResponse public bool AllowDmE2ee { get; set; } = true; public int MaxGroupChatUsers { get; set; } = 10; public string? VapidPublicKey { get; set; } + public bool EnableVoiceCalls { get; set; } = true; + public bool AllowVoiceRelayFallback { get; set; } = true; + public int MaxVoiceCallUsers { get; set; } = 10; + public List IceServers { get; set; } = new(); } public class PushSubscribeRequest diff --git a/src/GsDChat.Core/Protocol/NetworkMessages.cs b/src/GsDChat.Core/Protocol/NetworkMessages.cs index 9c9a961..13c39b5 100644 --- a/src/GsDChat.Core/Protocol/NetworkMessages.cs +++ b/src/GsDChat.Core/Protocol/NetworkMessages.cs @@ -35,6 +35,14 @@ public static class MessageTypes public const string InboxAction = "INBOX_ACTION"; public const string UpdateInboxPreferences = "UPDATE_INBOX_PREFERENCES"; public const string ToggleFollowChannel = "TOGGLE_FOLLOW_CHANNEL"; + public const string VoiceCallStart = "VOICE_CALL_START"; + public const string VoiceCallAccept = "VOICE_CALL_ACCEPT"; + public const string VoiceCallDecline = "VOICE_CALL_DECLINE"; + public const string VoiceCallLeave = "VOICE_CALL_LEAVE"; + public const string VoiceCallState = "VOICE_CALL_STATE"; + public const string VoiceStateUpdate = "VOICE_STATE_UPDATE"; + public const string VoiceSignal = "VOICE_SIGNAL"; + public const string VoiceAudioFrame = "VOICE_AUDIO_FRAME"; public const string Ping = "PING"; public const string Pong = "PONG"; } @@ -272,3 +280,66 @@ public class ToggleFollowChannelPacket public string ChannelId { get; set; } = string.Empty; public bool? Follow { get; set; } } + +public class VoiceCallStartPacket +{ + public string ChannelId { get; set; } = string.Empty; + public string ClientType { get; set; } = VoiceClientTypes.Web; + public string? TargetUserId { get; set; } +} + +public class VoiceCallAcceptPacket +{ + public string ChannelId { get; set; } = string.Empty; + public string ClientType { get; set; } = VoiceClientTypes.Web; +} + +public class VoiceCallDeclinePacket +{ + public string ChannelId { get; set; } = string.Empty; +} + +public class VoiceCallLeavePacket +{ + public string ChannelId { get; set; } = string.Empty; +} + +public class VoiceCallStatePacket +{ + public string ChannelId { get; set; } = string.Empty; + public VoiceCallSessionInfo? Session { get; set; } + public List IceServers { get; set; } = new(); + public bool AllowVoiceRelayFallback { get; set; } = true; +} + +public class VoiceStateUpdatePacket +{ + public string ChannelId { get; set; } = string.Empty; + public bool? IsMuted { get; set; } + public bool? IsDeafened { get; set; } + public string? TransportMode { get; set; } // "p2p" or "relay" + public string? UdpEndpoint { get; set; } +} + +public class VoiceSignalPacket +{ + public string ChannelId { get; set; } = string.Empty; + public string SenderUserId { get; set; } = string.Empty; + public string TargetUserId { get; set; } = string.Empty; + public string SignalType { get; set; } = string.Empty; // "sdp-offer", "sdp-answer", "ice-candidate", "udp-candidate", "relay-switch" + public string Payload { get; set; } = string.Empty; +} + +public class VoiceAudioFramePacket +{ + public string ChannelId { get; set; } = string.Empty; + public string SenderUserId { get; set; } = string.Empty; + public string SenderUsername { get; set; } = string.Empty; + public string? TargetUserId { get; set; } + public long Sequence { get; set; } + public string Codec { get; set; } = "ulaw-16k"; // "ulaw-16k" or "pcm-16k" + public string DataBase64 { get; set; } = string.Empty; + public bool IsEncrypted { get; set; } = false; + public string? SenderPublicKey { get; set; } + public float SpeakingLevel { get; set; } +} diff --git a/src/GsDChat.Core/Protocol/StunClient.cs b/src/GsDChat.Core/Protocol/StunClient.cs new file mode 100644 index 0000000..6f03095 --- /dev/null +++ b/src/GsDChat.Core/Protocol/StunClient.cs @@ -0,0 +1,251 @@ +using System; +using System.Buffers.Binary; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; + +namespace GsDChat.Core.Protocol; + +/// +/// Pure .NET RFC 5389 STUN Binding client for discovering reflexive public UDP endpoints (srflx) +/// to enable P2P UDP hole-punching in the C# TUI client without third-party libraries. +/// +public static class StunClient +{ + public const uint MagicCookie = 0x2112A442; + public const ushort BindingRequestType = 0x0001; + public const ushort BindingSuccessResponseType = 0x0101; + public const ushort AttrMappedAddress = 0x0001; + public const ushort AttrXorMappedAddress = 0x0020; + public const ushort AttrXorMappedAddressAlt = 0x8020; + + /// + /// Creates a 20-byte RFC 5389 STUN Binding Request packet and outputs the 12-byte transaction ID. + /// + public static byte[] CreateBindingRequest(out byte[] transactionId) + { + transactionId = RandomNumberGenerator.GetBytes(12); + byte[] packet = new byte[20]; + BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(0, 2), BindingRequestType); + BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(2, 2), 0); // Message Length = 0 + BinaryPrimitives.WriteUInt32BigEndian(packet.AsSpan(4, 4), MagicCookie); + Buffer.BlockCopy(transactionId, 0, packet, 8, 12); + return packet; + } + + /// + /// Builds a valid RFC 5389 STUN Binding Success Response with XOR-MAPPED-ADDRESS (useful for local STUN responder or tests). + /// + public static byte[] CreateBindingSuccessResponse(ReadOnlySpan transactionId, IPEndPoint reflexiveEndpoint) + { + if (transactionId.Length != 12) + { + throw new ArgumentException("Transaction ID must be 12 bytes.", nameof(transactionId)); + } + + byte[] ipBytes = reflexiveEndpoint.Address.GetAddressBytes(); + bool isIpv6 = reflexiveEndpoint.Address.AddressFamily == AddressFamily.InterNetworkV6; + int attrValueLen = isIpv6 ? 20 : 8; + int totalLen = 20 + 4 + attrValueLen; + + byte[] packet = new byte[totalLen]; + BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(0, 2), BindingSuccessResponseType); + BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(2, 2), (ushort)(4 + attrValueLen)); + BinaryPrimitives.WriteUInt32BigEndian(packet.AsSpan(4, 4), MagicCookie); + transactionId.CopyTo(packet.AsSpan(8, 12)); + + // Attribute header: XOR-MAPPED-ADDRESS (0x0020) + BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(20, 2), AttrXorMappedAddress); + BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(22, 2), (ushort)attrValueLen); + packet[24] = 0; // Reserved + packet[25] = (byte)(isIpv6 ? 0x02 : 0x01); + + ushort xPort = (ushort)(reflexiveEndpoint.Port ^ (ushort)(MagicCookie >> 16)); + BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(26, 2), xPort); + + byte[] cookieBytes = new byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(cookieBytes, MagicCookie); + + if (!isIpv6) + { + for (int i = 0; i < 4; i++) + { + packet[28 + i] = (byte)(ipBytes[i] ^ cookieBytes[i]); + } + } + else + { + for (int i = 0; i < 4; i++) + { + packet[28 + i] = (byte)(ipBytes[i] ^ cookieBytes[i]); + } + for (int i = 0; i < 12; i++) + { + packet[32 + i] = (byte)(ipBytes[4 + i] ^ transactionId[i]); + } + } + + return packet; + } + + /// + /// Parses a STUN Binding Success Response packet and extracts the reflexive IPEndPoint. + /// + public static IPEndPoint? ParseBindingResponse(ReadOnlySpan response, ReadOnlySpan expectedTransactionId) + { + if (response.Length < 20) return null; + + ushort msgType = BinaryPrimitives.ReadUInt16BigEndian(response.Slice(0, 2)); + ushort msgLen = BinaryPrimitives.ReadUInt16BigEndian(response.Slice(2, 2)); + uint cookie = BinaryPrimitives.ReadUInt32BigEndian(response.Slice(4, 4)); + + if (msgType != BindingSuccessResponseType || cookie != MagicCookie) + { + return null; + } + + if (expectedTransactionId.Length == 12 && !response.Slice(8, 12).SequenceEqual(expectedTransactionId)) + { + return null; + } + + int offset = 20; + int end = Math.Min(response.Length, 20 + msgLen); + IPEndPoint? fallbackMapped = null; + + byte[] cookieBytes = new byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(cookieBytes, MagicCookie); + + while (offset + 4 <= end) + { + ushort attrType = BinaryPrimitives.ReadUInt16BigEndian(response.Slice(offset, 2)); + ushort attrLen = BinaryPrimitives.ReadUInt16BigEndian(response.Slice(offset + 2, 2)); + offset += 4; + + if (offset + attrLen > end) break; + + var attrVal = response.Slice(offset, attrLen); + + if ((attrType == AttrXorMappedAddress || attrType == AttrXorMappedAddressAlt) && attrLen >= 8) + { + byte family = attrVal[1]; + ushort xPort = BinaryPrimitives.ReadUInt16BigEndian(attrVal.Slice(2, 2)); + int port = xPort ^ (int)(MagicCookie >> 16); + + if (family == 0x01 && attrLen >= 8) + { + byte[] ip = new byte[4]; + for (int i = 0; i < 4; i++) + { + ip[i] = (byte)(attrVal[4 + i] ^ cookieBytes[i]); + } + return new IPEndPoint(new IPAddress(ip), port); + } + else if (family == 0x02 && attrLen >= 20) + { + byte[] ip = new byte[16]; + for (int i = 0; i < 4; i++) + { + ip[i] = (byte)(attrVal[4 + i] ^ cookieBytes[i]); + } + for (int i = 0; i < 12; i++) + { + ip[4 + i] = (byte)(attrVal[8 + i] ^ response[8 + i]); + } + return new IPEndPoint(new IPAddress(ip), port); + } + } + else if (attrType == AttrMappedAddress && attrLen >= 8) + { + byte family = attrVal[1]; + int port = BinaryPrimitives.ReadUInt16BigEndian(attrVal.Slice(2, 2)); + if (family == 0x01) + { + byte[] ip = attrVal.Slice(4, 4).ToArray(); + fallbackMapped = new IPEndPoint(new IPAddress(ip), port); + } + } + + // STUN attributes are padded to 4-byte boundaries + int paddedLen = (attrLen + 3) & ~3; + offset += paddedLen; + } + + return fallbackMapped; + } + + /// + /// Parses a STUN URI (e.g. "stun:stun.cloudflare.com:3478") into host and port. + /// + public static (string Host, int Port) ParseStunUri(string stunUri) + { + if (string.IsNullOrWhiteSpace(stunUri)) + { + return ("stun.cloudflare.com", 3478); + } + + string clean = stunUri.Trim(); + if (clean.StartsWith("stun:", StringComparison.OrdinalIgnoreCase)) + { + clean = clean.Substring(5); + } + else if (clean.StartsWith("stuns:", StringComparison.OrdinalIgnoreCase)) + { + clean = clean.Substring(6); + } + + clean = clean.TrimStart('/'); + int qIdx = clean.IndexOf('?'); + if (qIdx >= 0) clean = clean.Substring(0, qIdx); + + int colonIdx = clean.LastIndexOf(':'); + if (colonIdx > 0 && int.TryParse(clean.Substring(colonIdx + 1), out int port) && port > 0 && port <= 65535) + { + return (clean.Substring(0, colonIdx), port); + } + + return (clean, 3478); + } + + /// + /// Queries a STUN server using the provided UdpClient to discover its public reflexive IP and port. + /// + public static async Task QueryPublicEndpointAsync(UdpClient udpClient, string stunUri, CancellationToken ct = default) + { + try + { + var (host, port) = ParseStunUri(stunUri); + IPAddress[] addresses = await Dns.GetHostAddressesAsync(host, ct); + var targetIp = addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork) + ?? addresses.FirstOrDefault(); + if (targetIp == null) return null; + + var stunEndpoint = new IPEndPoint(targetIp, port); + byte[] req = CreateBindingRequest(out byte[] txId); + + await udpClient.SendAsync(req, stunEndpoint, ct); + + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeoutCts.CancelAfter(TimeSpan.FromMilliseconds(1500)); + + while (!timeoutCts.IsCancellationRequested) + { + var result = await udpClient.ReceiveAsync(timeoutCts.Token); + var parsed = ParseBindingResponse(result.Buffer, txId); + if (parsed != null) + { + return parsed; + } + } + } + catch + { + // STUN unreachable or timed out; caller will fall back to next STUN server or WebSocket relay + } + + return null; + } +} diff --git a/src/GsDChat.Core/Protocol/UiProtocol.cs b/src/GsDChat.Core/Protocol/UiProtocol.cs index 5fa111d..96f4dcd 100644 --- a/src/GsDChat.Core/Protocol/UiProtocol.cs +++ b/src/GsDChat.Core/Protocol/UiProtocol.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using GsDChat.Core.Models; namespace GsDChat.Core.Protocol; @@ -40,6 +41,10 @@ public class ServerUiSync public string Motd { get; set; } = "Welcome to GsDChat!"; public bool AllowDmE2ee { get; set; } = true; public int MaxGroupChatUsers { get; set; } = 10; + public bool EnableVoiceCalls { get; set; } = true; + public bool AllowVoiceRelayFallback { get; set; } = true; + public int MaxVoiceCallUsers { get; set; } = 10; + public List IceServers { get; set; } = new(); public ThemeDefinition Theme { get; set; } = new(); public List Screens { get; set; } = new(); @@ -47,7 +52,11 @@ public class ServerUiSync string serverName = "GsDChat Server", string motd = "Welcome to GsDChat!", bool allowDmE2ee = true, - int maxGroupChatUsers = 10) + int maxGroupChatUsers = 10, + bool enableVoiceCalls = true, + bool allowVoiceRelayFallback = true, + int maxVoiceCallUsers = 10, + List? iceServers = null) { return new ServerUiSync { @@ -55,6 +64,10 @@ public class ServerUiSync Motd = motd, AllowDmE2ee = allowDmE2ee, MaxGroupChatUsers = maxGroupChatUsers, + EnableVoiceCalls = enableVoiceCalls, + AllowVoiceRelayFallback = allowVoiceRelayFallback, + MaxVoiceCallUsers = maxVoiceCallUsers, + IceServers = iceServers ?? new List(), Theme = new ThemeDefinition(), Screens = new List { diff --git a/src/GsDChat.Core/Security/E2eeCrypto.cs b/src/GsDChat.Core/Security/E2eeCrypto.cs index c116157..7ae32d0 100644 --- a/src/GsDChat.Core/Security/E2eeCrypto.cs +++ b/src/GsDChat.Core/Security/E2eeCrypto.cs @@ -7,6 +7,7 @@ namespace GsDChat.Core.Security; public static class E2eeCrypto { public const string EncryptedPrefix = "E2EE:v1:"; + public const string VoiceEncryptedPrefix = "VENC:v1:"; private const string WrappedKeyPrefix = "WRAP:v1:"; private const int NonceByteLength = 12; private const int TagByteLength = 16; @@ -170,6 +171,98 @@ public static class E2eeCrypto return !string.IsNullOrEmpty(content) && content.StartsWith(EncryptedPrefix, StringComparison.Ordinal); } + public static bool IsVoiceEncryptedPayload(string? content) + { + return !string.IsNullOrEmpty(content) && content.StartsWith(VoiceEncryptedPrefix, StringComparison.Ordinal); + } + + public static string EncryptAudioFrame(byte[] audioBytes, string myPrivateKeyBase64, string peerPublicKeyBase64) + { + byte[] aesKey = DeriveSharedAesKey(myPrivateKeyBase64, peerPublicKeyBase64); + return EncryptWithAesGcmKey(audioBytes, aesKey, VoiceEncryptedPrefix); + } + + public static byte[]? DecryptAudioFrame(string payload, string myPrivateKeyBase64, string peerPublicKeyBase64) + { + if (!IsVoiceEncryptedPayload(payload)) return null; + try + { + byte[] aesKey = DeriveSharedAesKey(myPrivateKeyBase64, peerPublicKeyBase64); + return DecryptWithAesGcmKey(payload, aesKey, VoiceEncryptedPrefix); + } + catch + { + return null; + } + } + + public static string EncryptWithSessionKey(byte[] audioBytes, byte[] sessionKey) + { + return EncryptWithAesGcmKey(audioBytes, sessionKey, VoiceEncryptedPrefix); + } + + public static byte[]? DecryptWithSessionKey(string payload, byte[] sessionKey) + { + if (!IsVoiceEncryptedPayload(payload)) return null; + try + { + return DecryptWithAesGcmKey(payload, sessionKey, VoiceEncryptedPrefix); + } + catch + { + return null; + } + } + + private static string EncryptWithAesGcmKey(byte[] plaintext, byte[] aesKey, string prefix) + { + byte[] nonce = RandomNumberGenerator.GetBytes(NonceByteLength); + byte[] cipherBytes = new byte[plaintext.Length]; + byte[] tag = new byte[TagByteLength]; + + using var aes = new AesGcm(aesKey, TagByteLength); + aes.Encrypt(nonce, plaintext, cipherBytes, tag); + + byte[] combined = new byte[NonceByteLength + cipherBytes.Length + TagByteLength]; + Buffer.BlockCopy(nonce, 0, combined, 0, NonceByteLength); + Buffer.BlockCopy(cipherBytes, 0, combined, NonceByteLength, cipherBytes.Length); + Buffer.BlockCopy(tag, 0, combined, NonceByteLength + cipherBytes.Length, TagByteLength); + + return $"{prefix}{Convert.ToBase64String(combined)}"; + } + + private static byte[]? DecryptWithAesGcmKey(string payload, byte[] aesKey, string prefix) + { + if (string.IsNullOrWhiteSpace(payload) || !payload.StartsWith(prefix, StringComparison.Ordinal)) + { + return null; + } + + string rawBase64 = payload.Substring(prefix.Length); + byte[] combined = Convert.FromBase64String(rawBase64); + + if (combined.Length < NonceByteLength + TagByteLength) + { + return null; + } + + byte[] nonce = new byte[NonceByteLength]; + Buffer.BlockCopy(combined, 0, nonce, 0, NonceByteLength); + + int cipherLen = combined.Length - NonceByteLength - TagByteLength; + byte[] cipherBytes = new byte[cipherLen]; + byte[] tag = new byte[TagByteLength]; + + Buffer.BlockCopy(combined, NonceByteLength, cipherBytes, 0, cipherLen); + Buffer.BlockCopy(combined, NonceByteLength + cipherLen, tag, 0, TagByteLength); + + byte[] plainBytes = new byte[cipherLen]; + using var aes = new AesGcm(aesKey, TagByteLength); + aes.Decrypt(nonce, cipherBytes, tag, plainBytes); + + return plainBytes; + } + private static byte[] DeriveWrappingKey(string password, string username) { byte[] salt = SHA256.HashData(Encoding.UTF8.GetBytes($"GsDChat-E2EE-KeyWrap:{username.Trim().ToLowerInvariant()}")); diff --git a/src/GsDChat.Core/Security/G711AudioCodec.cs b/src/GsDChat.Core/Security/G711AudioCodec.cs new file mode 100644 index 0000000..81f6e57 --- /dev/null +++ b/src/GsDChat.Core/Security/G711AudioCodec.cs @@ -0,0 +1,125 @@ +using System; + +namespace GsDChat.Core.Security; + +/// +/// Pure .NET ITU-T G.711 mu-law (PCMU) audio encoder/decoder and RMS voice level calculator. +/// Compresses 16-bit signed linear PCM (s16le) 2:1 into 8-bit mu-law samples for low-latency +/// interoperability between the browser WebAudio engine and the C# TUI voice engine. +/// +public static class G711AudioCodec +{ + private const int Bias = 0x84; // 132 + private const int Clip = 32635; + + public static byte LinearToMuLawSample(short sample) + { + int sign = (sample >> 8) & 0x80; + if (sign != 0) + { + sample = (short)(sample == short.MinValue ? Clip : -sample); + } + + if (sample > Clip) + { + sample = Clip; + } + + sample = (short)(sample + Bias); + + int exponent = 7; + for (int expMask = 0x4000; (sample & expMask) == 0 && exponent > 0; exponent--, expMask >>= 1) + { + } + + int mantissa = (sample >> (exponent + 3)) & 0x0F; + byte muLawByte = (byte)(~(sign | (exponent << 4) | mantissa)); + return muLawByte; + } + + public static short MuLawToLinearSample(byte muLawByte) + { + muLawByte = (byte)(~muLawByte); + int sign = muLawByte & 0x80; + int exponent = (muLawByte >> 4) & 0x07; + int mantissa = muLawByte & 0x0F; + + int sample = ((mantissa << 3) + Bias) << exponent; + sample -= Bias; + + return (short)(sign != 0 ? -sample : sample); + } + + /// + /// Encodes little-endian 16-bit signed PCM bytes (s16le) into 8-bit G.711 mu-law bytes. + /// + public static byte[] EncodePcm16ToMuLaw(ReadOnlySpan pcm16LeBytes) + { + int sampleCount = pcm16LeBytes.Length / 2; + byte[] output = new byte[sampleCount]; + + for (int i = 0; i < sampleCount; i++) + { + short sample = (short)(pcm16LeBytes[i * 2] | (pcm16LeBytes[i * 2 + 1] << 8)); + output[i] = LinearToMuLawSample(sample); + } + + return output; + } + + /// + /// Decodes 8-bit G.711 mu-law bytes into little-endian 16-bit signed PCM bytes (s16le). + /// + public static byte[] DecodeMuLawToPcm16(ReadOnlySpan muLawBytes) + { + byte[] output = new byte[muLawBytes.Length * 2]; + + for (int i = 0; i < muLawBytes.Length; i++) + { + short sample = MuLawToLinearSample(muLawBytes[i]); + output[i * 2] = (byte)(sample & 0xFF); + output[i * 2 + 1] = (byte)((sample >> 8) & 0xFF); + } + + return output; + } + + /// + /// Computes normalized RMS speaking level (0.0 to 1.0) from 16-bit signed little-endian PCM bytes. + /// + public static float ComputeRmsLevelFromPcm16(ReadOnlySpan pcm16LeBytes) + { + int sampleCount = pcm16LeBytes.Length / 2; + if (sampleCount == 0) return 0f; + + double sumSquares = 0; + for (int i = 0; i < sampleCount; i++) + { + short sample = (short)(pcm16LeBytes[i * 2] | (pcm16LeBytes[i * 2 + 1] << 8)); + double norm = sample / 32768.0; + sumSquares += norm * norm; + } + + double rms = Math.Sqrt(sumSquares / sampleCount); + return (float)Math.Clamp(rms * 3.0, 0.0, 1.0); + } + + /// + /// Computes normalized RMS speaking level (0.0 to 1.0) from 8-bit G.711 mu-law bytes. + /// + public static float ComputeRmsLevelFromMuLaw(ReadOnlySpan muLawBytes) + { + if (muLawBytes.Length == 0) return 0f; + + double sumSquares = 0; + for (int i = 0; i < muLawBytes.Length; i++) + { + short sample = MuLawToLinearSample(muLawBytes[i]); + double norm = sample / 32768.0; + sumSquares += norm * norm; + } + + double rms = Math.Sqrt(sumSquares / muLawBytes.Length); + return (float)Math.Clamp(rms * 3.0, 0.0, 1.0); + } +} diff --git a/src/GsDChat.Server/Configuration/ServerOptions.cs b/src/GsDChat.Server/Configuration/ServerOptions.cs index 0ed18a8..0a6382b 100644 --- a/src/GsDChat.Server/Configuration/ServerOptions.cs +++ b/src/GsDChat.Server/Configuration/ServerOptions.cs @@ -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 StunServers { get; set; } = new() + { + "stun:stun.cloudflare.com:3478", + "stun:stun.l.google.com:19302" + }; + public List TurnServers { get; set; } = new() + { + new IceServerConfig + { + Urls = new List + { + "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 GetIceServers() + { + var list = new List(); + var validStun = (StunServers ?? new List()) + .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; } diff --git a/src/GsDChat.Server/Configuration/ServerSettingsManager.cs b/src/GsDChat.Server/Configuration/ServerSettingsManager.cs index 3446a5a..06771b2 100644 --- a/src/GsDChat.Server/Configuration/ServerSettingsManager.cs +++ b/src/GsDChat.Server/Configuration/ServerSettingsManager.cs @@ -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(); diff --git a/src/GsDChat.Server/Program.cs b/src/GsDChat.Server/Program.cs index 9ca1dce..f625092 100644 --- a/src/GsDChat.Server/Program.cs +++ b/src/GsDChat.Server/Program.cs @@ -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( + 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( + 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( + 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() }); }); diff --git a/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs b/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs index e4b770b..914170e 100644 --- a/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs +++ b/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs @@ -21,6 +21,8 @@ namespace GsDChat.Server.WebSockets; public class ChatWebSocketManager { private readonly ConcurrentDictionary _clients = new(); + private readonly ConcurrentDictionary _activeCalls = new(StringComparer.OrdinalIgnoreCase); + private readonly object _voiceLock = new(); private readonly ChatDatabase _db; private readonly ServerOptions _options; private readonly ILogger _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(_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(); + if (vcStart != null) + { + await HandleVoiceCallStartAsync(client, vcStart, ct); + } + break; + + case MessageTypes.VoiceCallAccept: + var vcAccept = envelope.Unpack(); + if (vcAccept != null) + { + await HandleVoiceCallAcceptAsync(client, vcAccept, ct); + } + break; + + case MessageTypes.VoiceCallDecline: + var vcDecline = envelope.Unpack(); + if (vcDecline != null) + { + await HandleVoiceCallDeclineAsync(client, vcDecline, ct); + } + break; + + case MessageTypes.VoiceCallLeave: + var vcLeave = envelope.Unpack(); + if (vcLeave != null) + { + await HandleVoiceCallLeaveAsync(client, vcLeave, ct); + } + break; + + case MessageTypes.VoiceStateUpdate: + var vcStateUpd = envelope.Unpack(); + if (vcStateUpd != null) + { + await HandleVoiceStateUpdateAsync(client, vcStateUpd, ct); + } + break; + + case MessageTypes.VoiceSignal: + var vcSignal = envelope.Unpack(); + if (vcSignal != null) + { + await HandleVoiceSignalAsync(client, vcSignal, ct); + } + break; + + case MessageTypes.VoiceAudioFrame: + var vcAudio = envelope.Unpack(); + 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 - 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 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 + { + 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 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 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); + } + + /// + /// 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. + /// + 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 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 } diff --git a/src/GsDChat.Server/serversettings.json b/src/GsDChat.Server/serversettings.json index 2fa898a..4166636 100644 --- a/src/GsDChat.Server/serversettings.json +++ b/src/GsDChat.Server/serversettings.json @@ -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, diff --git a/src/GsDChat.Server/wwwroot/app.css b/src/GsDChat.Server/wwwroot/app.css index 8f0bfb6..feaf729 100644 --- a/src/GsDChat.Server/wwwroot/app.css +++ b/src/GsDChat.Server/wwwroot/app.css @@ -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 ========================================================================== */ diff --git a/src/GsDChat.Server/wwwroot/app.js b/src/GsDChat.Server/wwwroot/app.js index ddabb4c..130446d 100644 --- a/src/GsDChat.Server/wwwroot/app.js +++ b/src/GsDChat.Server/wwwroot/app.js @@ -35,6 +35,43 @@ vapidPublicKey: null, swRegistration: null, pushSubscribed: false, + enableVoiceCalls: true, + allowVoiceRelayFallback: true, + maxVoiceCallUsers: 10, + iceServers: [ + { urls: ['stun:stun.l.google.com:19302', 'stun:stun.cloudflare.com:3478'] }, + { + 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' + } + ], + activeVoiceCalls: {}, // channelId -> VoiceCallSessionInfo + currentVoiceChannelId: null, + incomingRingingChannelId: null, + voiceMuted: false, + voiceDeafened: false, + voiceForceRelay: false, + voiceTransportMode: 'p2p', + voicePeerConnections: {}, // peerUserId -> { pc, candidateQueue, audioEl, connected, fallbackTimer, useRelay } + voiceSpeakingUntil: {}, // userId -> timestamp ms + voiceLocalStream: null, + voiceAudioCtx: null, + voiceCaptureSource: null, + voiceCaptureProcessor: null, + voiceMuteGain: null, + voiceRelayPlaybackNextTime: {}, // peerUserId -> audioCtx time + voiceCallTimerInterval: null, + voiceRingtoneInterval: null, + voiceRingtoneCtx: null, + voiceFrameSeq: 0, + selectedMicDeviceId: localStorage.getItem('gsdchat_voice_mic') || '', + selectedSpeakerDeviceId: localStorage.getItem('gsdchat_voice_speaker') || '', socket: null, isRegister: false, reconnectTimer: null @@ -59,10 +96,31 @@ channelSelectDropdown: document.getElementById('channelSelectDropdown'), chatSecurityBadge: document.getElementById('chatSecurityBadge'), activeChannelTopic: document.getElementById('activeChannelTopic'), + voiceCallBtn: document.getElementById('voiceCallBtn'), toggleFollowBtn: document.getElementById('toggleFollowBtn'), toggleDmE2eeBtn: document.getElementById('toggleDmE2eeBtn'), inviteGroupBtn: document.getElementById('inviteGroupBtn'), leaveGroupBtn: document.getElementById('leaveGroupBtn'), + voiceCallBar: document.getElementById('voiceCallBar'), + voiceStatusDot: document.getElementById('voiceStatusDot'), + voiceCallStatusText: document.getElementById('voiceCallStatusText'), + voiceTransportBadge: document.getElementById('voiceTransportBadge'), + voiceE2eeBadge: document.getElementById('voiceE2eeBadge'), + voiceCallTimer: document.getElementById('voiceCallTimer'), + voiceParticipantsList: document.getElementById('voiceParticipantsList'), + voiceJoinRoomBtn: document.getElementById('voiceJoinRoomBtn'), + voiceMuteBtn: document.getElementById('voiceMuteBtn'), + voiceDeafenBtn: document.getElementById('voiceDeafenBtn'), + voiceForceRelayBtn: document.getElementById('voiceForceRelayBtn'), + voiceMicSelect: document.getElementById('voiceMicSelect'), + voiceSpeakerSelect: document.getElementById('voiceSpeakerSelect'), + voiceHangupBtn: document.getElementById('voiceHangupBtn'), + voiceRemoteAudioContainer: document.getElementById('voiceRemoteAudioContainer'), + incomingCallModal: document.getElementById('incomingCallModal'), + incomingCallerName: document.getElementById('incomingCallerName'), + incomingCallSecurityHint: document.getElementById('incomingCallSecurityHint'), + acceptIncomingCallBtn: document.getElementById('acceptIncomingCallBtn'), + declineIncomingCallBtn: document.getElementById('declineIncomingCallBtn'), chatMessages: document.getElementById('chatMessages'), messageInput: document.getElementById('messageInput'), sendBtn: document.getElementById('sendBtn'), @@ -229,6 +287,8 @@ // ========================================== const E2EE_PREFIX = 'E2EE:v1:'; const WRAP_PREFIX = 'WRAP:v1:'; + const VOICE_ENC_PREFIX = 'VENC:v1:'; + const sharedAesKeyCache = new Map(); function bytesToBase64(bytes) { let bin = ''; @@ -330,6 +390,11 @@ } async function deriveSharedAesGcmKey(myPrivateKeyB64, peerPublicKeyB64) { + const cacheKey = `${myPrivateKeyB64}:${peerPublicKeyB64}`; + if (sharedAesKeyCache.has(cacheKey)) { + return sharedAesKeyCache.get(cacheKey); + } + const privBytes = base64ToBytes(myPrivateKeyB64); const pubBytes = base64ToBytes(peerPublicKeyB64); @@ -356,13 +421,128 @@ ); const keyHash = await window.crypto.subtle.digest('SHA-256', rawSecret); - return window.crypto.subtle.importKey( + const aesKey = await window.crypto.subtle.importKey( 'raw', keyHash, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'] ); + sharedAesKeyCache.set(cacheKey, aesKey); + return aesKey; + } + + async function encryptVoiceFrame(audioBytes, myPrivateKeyB64, peerPublicKeyB64) { + if (!window.crypto || !window.crypto.subtle || !myPrivateKeyB64 || !peerPublicKeyB64) { + return null; + } + try { + const aesKey = await deriveSharedAesGcmKey(myPrivateKeyB64, peerPublicKeyB64); + const nonce = window.crypto.getRandomValues(new Uint8Array(12)); + const cipherBuf = await window.crypto.subtle.encrypt( + { name: 'AES-GCM', iv: nonce, tagLength: 128 }, + aesKey, + audioBytes + ); + const cipherBytes = new Uint8Array(cipherBuf); + const combined = new Uint8Array(12 + cipherBytes.length); + combined.set(nonce, 0); + combined.set(cipherBytes, 12); + return `${VOICE_ENC_PREFIX}${bytesToBase64(combined)}`; + } catch { + return null; + } + } + + async function decryptVoiceFrame(payload, myPrivateKeyB64, peerPublicKeyB64) { + if (!payload || !payload.startsWith(VOICE_ENC_PREFIX)) return null; + if (!window.crypto || !window.crypto.subtle || !myPrivateKeyB64 || !peerPublicKeyB64) { + return null; + } + try { + const combined = base64ToBytes(payload.substring(VOICE_ENC_PREFIX.length)); + if (combined.length < 28) return null; + const nonce = combined.subarray(0, 12); + const cipherAndTag = combined.subarray(12); + const aesKey = await deriveSharedAesGcmKey(myPrivateKeyB64, peerPublicKeyB64); + const plainBuf = await window.crypto.subtle.decrypt( + { name: 'AES-GCM', iv: nonce, tagLength: 128 }, + aesKey, + cipherAndTag + ); + return new Uint8Array(plainBuf); + } catch { + return null; + } + } + + // ========================================== + // ITU-T G.711 μ-law Audio Codec (16 kHz Mono) + // Binary-compatible with GsDChat.Core.Security.G711AudioCodec + // ========================================== + function linearToMuLawSample(sample) { + const BIAS = 0x84; + const CLIP = 32635; + const sign = (sample >> 8) & 0x80; + if (sign !== 0) { + sample = -sample; + } + if (sample > CLIP) { + sample = CLIP; + } + sample += BIAS; + + let exponent = 7; + for (let expMask = 0x4000; (sample & expMask) === 0 && exponent > 0; exponent--, expMask >>= 1) { + // find segment + } + const mantissa = (sample >> (exponent + 3)) & 0x0F; + const muLawByte = ~(sign | (exponent << 4) | mantissa) & 0xFF; + return muLawByte; + } + + function muLawToLinearSample(muLawByte) { + const BIAS = 0x84; + const u = (~muLawByte) & 0xFF; + const sign = u & 0x80; + const exponent = (u >> 4) & 0x07; + const mantissa = u & 0x0F; + let sample = (((mantissa << 3) + BIAS) << exponent) - BIAS; + if (sign !== 0) { + sample = -sample; + } + if (sample > 32767) sample = 32767; + if (sample < -32768) sample = -32768; + return sample; + } + + function encodeFloat32ToMuLaw(float32Samples) { + const out = new Uint8Array(float32Samples.length); + for (let i = 0; i < float32Samples.length; i++) { + const clamped = Math.max(-1, Math.min(1, float32Samples[i])); + const pcm16 = clamped < 0 ? Math.round(clamped * 32768) : Math.round(clamped * 32767); + out[i] = linearToMuLawSample(pcm16); + } + return out; + } + + function decodeMuLawToFloat32(muLawBytes) { + const out = new Float32Array(muLawBytes.length); + for (let i = 0; i < muLawBytes.length; i++) { + const pcm16 = muLawToLinearSample(muLawBytes[i]); + out[i] = pcm16 / 32768.0; + } + return out; + } + + function computeFloat32RmsLevel(float32Samples) { + if (!float32Samples || float32Samples.length === 0) return 0; + let sumSq = 0; + for (let i = 0; i < float32Samples.length; i++) { + const v = float32Samples[i]; + sumSq += v * v; + } + return Math.sqrt(sumSq / float32Samples.length); } async function encryptDmMessage(plaintext, myPrivateKeyB64, peerPublicKeyB64) { @@ -875,6 +1055,19 @@ ? state.serverInfo.allowDmE2ee : (state.serverInfo.AllowDmE2ee !== undefined ? state.serverInfo.AllowDmE2ee : true); state.maxGroupChatUsers = state.serverInfo.maxGroupChatUsers || state.serverInfo.MaxGroupChatUsers || 10; + if (state.serverInfo.enableVoiceCalls !== undefined || state.serverInfo.EnableVoiceCalls !== undefined) { + state.enableVoiceCalls = state.serverInfo.enableVoiceCalls ?? state.serverInfo.EnableVoiceCalls; + } + if (state.serverInfo.allowVoiceRelayFallback !== undefined || state.serverInfo.AllowVoiceRelayFallback !== undefined) { + state.allowVoiceRelayFallback = state.serverInfo.allowVoiceRelayFallback ?? state.serverInfo.AllowVoiceRelayFallback; + } + if (state.serverInfo.maxVoiceCallUsers || state.serverInfo.MaxVoiceCallUsers) { + state.maxVoiceCallUsers = state.serverInfo.maxVoiceCallUsers || state.serverInfo.MaxVoiceCallUsers; + } + const srvIce = state.serverInfo.iceServers || state.serverInfo.IceServers; + if (Array.isArray(srvIce) && srvIce.length > 0) { + state.iceServers = normalizeIceServers(srvIce); + } if (state.serverInfo.vapidPublicKey || state.serverInfo.VapidPublicKey) { state.vapidPublicKey = state.serverInfo.vapidPublicKey || state.serverInfo.VapidPublicKey; } @@ -1121,8 +1314,21 @@ if (payload.maxGroupChatUsers || payload.MaxGroupChatUsers) { state.maxGroupChatUsers = payload.maxGroupChatUsers || payload.MaxGroupChatUsers; } + if (payload.enableVoiceCalls !== undefined || payload.EnableVoiceCalls !== undefined) { + state.enableVoiceCalls = payload.enableVoiceCalls ?? payload.EnableVoiceCalls; + } + if (payload.allowVoiceRelayFallback !== undefined || payload.AllowVoiceRelayFallback !== undefined) { + state.allowVoiceRelayFallback = payload.allowVoiceRelayFallback ?? payload.AllowVoiceRelayFallback; + } + if (payload.maxVoiceCallUsers || payload.MaxVoiceCallUsers) { + state.maxVoiceCallUsers = payload.maxVoiceCallUsers || payload.MaxVoiceCallUsers; + } + if (Array.isArray(payload.iceServers || payload.IceServers)) { + state.iceServers = normalizeIceServers(payload.iceServers || payload.IceServers); + } updateSettingsBadges(); updateActiveChannelHeader(); + updateVoiceCallUI(); break; case 'CHANNEL_LIST_SYNC': @@ -1299,6 +1505,18 @@ break; } + case 'VOICE_CALL_STATE': + await handleVoiceCallState(payload); + break; + + case 'VOICE_SIGNAL': + await handleVoiceSignal(payload); + break; + + case 'VOICE_AUDIO_FRAME': + await handleVoiceAudioFrame(payload); + break; + case 'SYSTEM_NOTICE': const noticeText = payload.text || payload.Text; if (noticeText) { @@ -1737,6 +1955,8 @@ el.activeChannelTopic.textContent = chTopic ? ` - ${chTopic}` : ''; el.messageInput.placeholder = `Message #${chName}... (or /help)`; } + + updateVoiceCallUI(); } function renderChannels() { @@ -2308,6 +2528,1120 @@ setTimeout(() => toast.remove(), 3500); } + // ========================================== + // Voice Call Engine (Hybrid WebRTC STUN/TURN P2P + Single-Port WS Relay) + // ========================================== + function normalizeIceServers(list) { + if (!Array.isArray(list) || list.length === 0) { + return [{ urls: ['stun:stun.l.google.com:19302', 'stun:stun1.l.google.com:19302'] }]; + } + const out = []; + for (const item of list) { + if (!item) continue; + const urls = item.urls || item.Urls; + if (!urls || (Array.isArray(urls) && urls.length === 0)) continue; + const entry = { urls: urls }; + const username = item.username || item.Username; + const credential = item.credential || item.Credential; + if (username) entry.username = username; + if (credential) entry.credential = credential; + out.push(entry); + } + return out.length > 0 + ? out + : [{ urls: ['stun:stun.l.google.com:19302', 'stun:stun1.l.google.com:19302'] }]; + } + + function isUserInCallSession(session, userId) { + if (!session || !userId) return false; + const parts = session.participants || session.Participants || []; + return parts.some(p => (p.userId || p.UserId || '').toLowerCase() === userId.toLowerCase()); + } + + function isChannelVoiceE2eeActive(channelId) { + const conv = getConversationById(channelId); + if (!conv || getConversationType(conv) !== 'DM') return false; + const isDmE2ee = (conv.isE2ee ?? conv.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled; + return !!(isDmE2ee && state.privateKey && getPeerPublicKeyForDm(conv)); + } + + function startRingtone() { + stopRingtone(); + try { + const AudioCtx = window.AudioContext || window.webkitAudioContext; + if (!AudioCtx) return; + const ctx = new AudioCtx(); + state.voiceRingtoneCtx = ctx; + + const playChime = () => { + if (!state.voiceRingtoneCtx) return; + try { + const now = ctx.currentTime; + const osc1 = ctx.createOscillator(); + const osc2 = ctx.createOscillator(); + const gain = ctx.createGain(); + osc1.type = 'sine'; + osc2.type = 'sine'; + osc1.frequency.setValueAtTime(523.25, now); // C5 + osc2.frequency.setValueAtTime(659.25, now + 0.18); // E5 + gain.gain.setValueAtTime(0.08, now); + gain.gain.exponentialRampToValueAtTime(0.001, now + 0.45); + osc1.connect(gain); + osc2.connect(gain); + gain.connect(ctx.destination); + osc1.start(now); + osc1.stop(now + 0.18); + osc2.start(now + 0.18); + osc2.stop(now + 0.45); + } catch { + // Ignore audio context chime error + } + }; + + playChime(); + state.voiceRingtoneInterval = setInterval(playChime, 2000); + } catch { + // Ignore ringtone error if autoplay blocked + } + } + + function stopRingtone() { + if (state.voiceRingtoneInterval) { + clearInterval(state.voiceRingtoneInterval); + state.voiceRingtoneInterval = null; + } + if (state.voiceRingtoneCtx) { + try { + state.voiceRingtoneCtx.close(); + } catch { + // Ignore close error + } + state.voiceRingtoneCtx = null; + } + } + + async function enumerateVoiceDevices() { + if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) return; + try { + const devices = await navigator.mediaDevices.enumerateDevices(); + const inputs = devices.filter(d => d.kind === 'audioinput'); + const outputs = devices.filter(d => d.kind === 'audiooutput'); + + if (el.voiceMicSelect) { + el.voiceMicSelect.innerHTML = ''; + const defOpt = document.createElement('option'); + defOpt.value = ''; + defOpt.textContent = '🎤 Default Mic'; + el.voiceMicSelect.appendChild(defOpt); + inputs.forEach((d, idx) => { + if (!d.deviceId || d.deviceId === 'default') return; + const opt = document.createElement('option'); + opt.value = d.deviceId; + opt.textContent = `🎤 ${d.label || `Microphone ${idx + 1}`}`; + if (d.deviceId === state.selectedMicDeviceId) opt.selected = true; + el.voiceMicSelect.appendChild(opt); + }); + } + + if (el.voiceSpeakerSelect) { + if (outputs.length > 0) { + el.voiceSpeakerSelect.style.display = 'inline-block'; + el.voiceSpeakerSelect.innerHTML = ''; + const defOut = document.createElement('option'); + defOut.value = ''; + defOut.textContent = '🔈 Default Speaker'; + el.voiceSpeakerSelect.appendChild(defOut); + outputs.forEach((d, idx) => { + if (!d.deviceId || d.deviceId === 'default') return; + const opt = document.createElement('option'); + opt.value = d.deviceId; + opt.textContent = `🔈 ${d.label || `Speaker ${idx + 1}`}`; + if (d.deviceId === state.selectedSpeakerDeviceId) opt.selected = true; + el.voiceSpeakerSelect.appendChild(opt); + }); + } else { + el.voiceSpeakerSelect.style.display = 'none'; + } + } + } catch { + // Ignore device enumeration errors + } + } + + async function ensureLocalVoiceMedia() { + const AudioCtx = window.AudioContext || window.webkitAudioContext; + if (!state.voiceAudioCtx && AudioCtx) { + try { + state.voiceAudioCtx = new AudioCtx({ sampleRate: 16000 }); + } catch { + try { + state.voiceAudioCtx = new AudioCtx(); + } catch { + // No WebAudio support + } + } + } + if (state.voiceAudioCtx && state.voiceAudioCtx.state === 'suspended') { + try { + await state.voiceAudioCtx.resume(); + } catch { + // Ignore resume failure + } + } + + if (!state.voiceLocalStream && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { + try { + const audioConstraints = { + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true, + channelCount: 1, + sampleRate: 16000 + }; + if (state.selectedMicDeviceId) { + audioConstraints.deviceId = { ideal: state.selectedMicDeviceId }; + } + state.voiceLocalStream = await navigator.mediaDevices.getUserMedia({ audio: audioConstraints, video: false }); + await enumerateVoiceDevices(); + } catch (err) { + showToast('⚠️ Microphone unavailable or permission denied. Joined in listen-only mode.'); + } + } + + if (state.voiceLocalStream) { + state.voiceLocalStream.getAudioTracks().forEach(t => { + t.enabled = !state.voiceMuted && !state.voiceDeafened; + }); + } + + // Set up WebAudio 16 kHz capture pipeline for VAD speaking indicator + Single-Port WS Relay fallback + if (state.voiceAudioCtx && state.voiceLocalStream && !state.voiceCaptureProcessor) { + try { + const source = state.voiceAudioCtx.createMediaStreamSource(state.voiceLocalStream); + const processor = state.voiceAudioCtx.createScriptProcessor(1024, 1, 1); + const muteGain = state.voiceAudioCtx.createGain(); + muteGain.gain.value = 0; + + let resampleAccum = []; + const ctxSampleRate = state.voiceAudioCtx.sampleRate || 16000; + const targetRate = 16000; + const frameSamples = 640; // 40ms @ 16kHz + + processor.onaudioprocess = async (e) => { + if (!state.currentVoiceChannelId || state.voiceMuted || state.voiceDeafened) return; + const inputData = e.inputBuffer.getChannelData(0); + const rms = computeFloat32RmsLevel(inputData); + if (rms >= 0.015 && state.user && state.user.id) { + state.voiceSpeakingUntil[state.user.id.toLowerCase()] = Date.now() + 350; + } + + if (!shouldTransmitViaWebSocketRelay()) { + resampleAccum = []; + return; + } + + // Downsample to 16 kHz if browser AudioContext opened at 44.1/48 kHz + if (ctxSampleRate === targetRate) { + for (let i = 0; i < inputData.length; i++) { + resampleAccum.push(inputData[i]); + } + } else { + const ratio = ctxSampleRate / targetRate; + for (let i = 0; i < inputData.length; i += ratio) { + const idx = Math.min(inputData.length - 1, Math.floor(i)); + resampleAccum.push(inputData[idx]); + } + } + + while (resampleAccum.length >= frameSamples) { + const chunk = new Float32Array(resampleAccum.splice(0, frameSamples)); + const chunkRms = computeFloat32RmsLevel(chunk); + if (chunkRms < 0.006) continue; // Silence suppression to save bandwidth + + const muLawBytes = encodeFloat32ToMuLaw(chunk); + await transmitRelayedVoiceFrame(muLawBytes, chunkRms); + } + }; + + source.connect(processor); + processor.connect(muteGain); + muteGain.connect(state.voiceAudioCtx.destination); + + state.voiceCaptureSource = source; + state.voiceCaptureProcessor = processor; + state.voiceMuteGain = muteGain; + } catch { + // Ignore script processor setup errors + } + } + } + + function stopLocalVoiceMedia() { + if (state.voiceCaptureProcessor) { + try { + state.voiceCaptureProcessor.disconnect(); + state.voiceCaptureProcessor.onaudioprocess = null; + } catch { + // Ignore + } + state.voiceCaptureProcessor = null; + } + if (state.voiceCaptureSource) { + try { + state.voiceCaptureSource.disconnect(); + } catch { + // Ignore + } + state.voiceCaptureSource = null; + } + if (state.voiceMuteGain) { + try { + state.voiceMuteGain.disconnect(); + } catch { + // Ignore + } + state.voiceMuteGain = null; + } + if (state.voiceLocalStream) { + state.voiceLocalStream.getTracks().forEach(t => { + try { + t.stop(); + } catch { + // Ignore + } + }); + state.voiceLocalStream = null; + } + state.voiceRelayPlaybackNextTime = {}; + } + + function shouldTransmitViaWebSocketRelay() { + if (!state.currentVoiceChannelId || !state.allowVoiceRelayFallback) return false; + if (state.voiceForceRelay) return true; + + const session = state.activeVoiceCalls[state.currentVoiceChannelId]; + if (!session) return false; + + const myId = state.user ? (state.user.id || '').toLowerCase() : ''; + const participants = session.participants || session.Participants || []; + const otherPeers = participants.filter(p => (p.userId || p.UserId || '').toLowerCase() !== myId); + if (otherPeers.length === 0) return false; + + for (const p of otherPeers) { + const peerId = (p.userId || p.UserId || '').toLowerCase(); + const clientType = (p.clientType || p.ClientType || 'web').toLowerCase(); + const transport = (p.transportMode || p.TransportMode || 'p2p').toLowerCase(); + if (clientType === 'tui' || transport === 'relay' || transport === 'ws-relay') { + return true; + } + const peerConn = state.voicePeerConnections[peerId]; + if (!peerConn || !peerConn.connected || peerConn.useRelay) { + return true; + } + } + return false; + } + + async function transmitRelayedVoiceFrame(muLawBytes, speakingLevel = 0) { + if (!state.currentVoiceChannelId || !state.socket || state.socket.readyState !== WebSocket.OPEN) return; + + const chId = state.currentVoiceChannelId; + const conv = getConversationById(chId); + const isDm = conv && getConversationType(conv) === 'DM'; + const isDmE2ee = isDm && (conv.isE2ee ?? conv.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled; + + let frameData = ''; + let isEncrypted = false; + let senderPubKey = null; + + if (isDmE2ee && state.privateKey) { + const peerPubKey = getPeerPublicKeyForDm(conv); + if (peerPubKey) { + const encrypted = await encryptVoiceFrame(muLawBytes, state.privateKey, peerPubKey); + if (encrypted) { + frameData = encrypted; + isEncrypted = true; + senderPubKey = state.publicKey; + } + } + } + + if (!frameData) { + frameData = bytesToBase64(muLawBytes); + } + + state.voiceFrameSeq = (state.voiceFrameSeq + 1) & 0x7FFFFFFF; + sendEnvelope('VOICE_AUDIO_FRAME', { + channelId: chId, + sequence: state.voiceFrameSeq, + codec: 'ulaw-16k', + sampleRate: 16000, + channels: 1, + dataBase64: frameData, + frameData: frameData, + isEncrypted: isEncrypted, + senderPublicKey: senderPubKey, + speakingLevel: Math.min(1.0, (speakingLevel || 0) * 3.0) + }); + } + + async function handleVoiceAudioFrame(payload) { + const chId = payload.channelId || payload.ChannelId; + if (!chId || chId !== state.currentVoiceChannelId) return; + + const senderId = (payload.senderUserId || payload.SenderUserId || '').toLowerCase(); + if (!senderId) return; + if (state.user && senderId === (state.user.id || '').toLowerCase()) return; + + state.voiceSpeakingUntil[senderId] = Date.now() + 380; + + if (state.voiceDeafened) return; + + // If we already have a connected direct WebRTC P2P audio stream from this peer and relay isn't forced, skip duplicate playback + const peerConn = state.voicePeerConnections[senderId]; + if (!state.voiceForceRelay && peerConn && peerConn.connected && !peerConn.useRelay) { + return; + } + + const rawFrameData = payload.dataBase64 || payload.DataBase64 || payload.frameData || payload.FrameData || ''; + if (!rawFrameData) return; + + let muLawBytes = null; + if (rawFrameData.startsWith(VOICE_ENC_PREFIX)) { + if (!state.privateKey) return; + let peerPubKey = payload.senderPublicKey || payload.SenderPublicKey || null; + if (!peerPubKey) { + const conv = getConversationById(chId); + if (conv) peerPubKey = getPeerPublicKeyForDm(conv); + } + if (!peerPubKey) return; + muLawBytes = await decryptVoiceFrame(rawFrameData, state.privateKey, peerPubKey); + } else { + try { + muLawBytes = base64ToBytes(rawFrameData); + } catch { + return; + } + } + + if (!muLawBytes || muLawBytes.length === 0) return; + + const AudioCtx = window.AudioContext || window.webkitAudioContext; + if (!state.voiceAudioCtx && AudioCtx) { + try { + state.voiceAudioCtx = new AudioCtx({ sampleRate: 16000 }); + } catch { + try { + state.voiceAudioCtx = new AudioCtx(); + } catch { + return; + } + } + } + if (!state.voiceAudioCtx) return; + if (state.voiceAudioCtx.state === 'suspended') { + try { + await state.voiceAudioCtx.resume(); + } catch { + // Ignore + } + } + + const floatSamples = decodeMuLawToFloat32(muLawBytes); + const sampleRate = payload.sampleRate || payload.SampleRate || 16000; + try { + const audioBuffer = state.voiceAudioCtx.createBuffer(1, floatSamples.length, sampleRate); + audioBuffer.getChannelData(0).set(floatSamples); + + const src = state.voiceAudioCtx.createBufferSource(); + src.buffer = audioBuffer; + src.connect(state.voiceAudioCtx.destination); + + const now = state.voiceAudioCtx.currentTime; + let startAt = state.voiceRelayPlaybackNextTime[senderId] || 0; + if (startAt < now || startAt > now + 0.35) { + startAt = now + 0.025; // 25ms jitter buffer + } + src.start(startAt); + state.voiceRelayPlaybackNextTime[senderId] = startAt + audioBuffer.duration; + } catch { + // Ignore playback scheduling errors + } + } + + function closePeerConnection(peerId) { + const key = (peerId || '').toLowerCase(); + const entry = state.voicePeerConnections[key]; + if (!entry) return; + if (entry.fallbackTimer) { + clearTimeout(entry.fallbackTimer); + } + if (entry.pc) { + try { + entry.pc.onicecandidate = null; + entry.pc.ontrack = null; + entry.pc.onconnectionstatechange = null; + entry.pc.oniceconnectionstatechange = null; + entry.pc.close(); + } catch { + // Ignore + } + } + if (entry.audioEl) { + try { + entry.audioEl.pause(); + entry.audioEl.srcObject = null; + entry.audioEl.remove(); + } catch { + // Ignore + } + } + delete state.voicePeerConnections[key]; + } + + function closeAllPeerConnections() { + for (const peerId of Object.keys(state.voicePeerConnections)) { + closePeerConnection(peerId); + } + state.voicePeerConnections = {}; + } + + function updateEffectiveVoiceTransportMode() { + if (!state.currentVoiceChannelId) return; + const nextMode = shouldTransmitViaWebSocketRelay() ? 'relay' : 'p2p'; + if (state.voiceTransportMode !== nextMode) { + state.voiceTransportMode = nextMode; + sendEnvelope('VOICE_STATE_UPDATE', { + channelId: state.currentVoiceChannelId, + isMuted: state.voiceMuted, + isDeafened: state.voiceDeafened, + transportMode: state.voiceTransportMode + }); + updateVoiceCallUI(); + } + } + + function createOrGetPeerConnection(peerUserId, channelId) { + const key = (peerUserId || '').toLowerCase(); + if (state.voicePeerConnections[key] && state.voicePeerConnections[key].pc) { + return state.voicePeerConnections[key]; + } + + if (typeof window.RTCPeerConnection !== 'function') { + return null; + } + + const pc = new window.RTCPeerConnection({ + iceServers: state.iceServers + }); + + const entry = { + pc: pc, + peerUserId: peerUserId, + channelId: channelId, + candidateQueue: [], + audioEl: null, + connected: false, + useRelay: false, + fallbackTimer: null + }; + state.voicePeerConnections[key] = entry; + + if (state.voiceLocalStream) { + state.voiceLocalStream.getTracks().forEach(track => { + try { + pc.addTrack(track, state.voiceLocalStream); + } catch { + // Ignore duplicate track + } + }); + } + + pc.onicecandidate = (event) => { + if (event.candidate && state.currentVoiceChannelId === channelId) { + sendEnvelope('VOICE_SIGNAL', { + channelId: channelId, + targetUserId: peerUserId, + signalType: 'ice-candidate', + payload: JSON.stringify(event.candidate) + }); + } + }; + + pc.ontrack = async (event) => { + const remoteStream = event.streams && event.streams[0] ? event.streams[0] : new MediaStream([event.track]); + if (!entry.audioEl) { + const audio = document.createElement('audio'); + audio.autoplay = true; + audio.playsInline = true; + audio.muted = state.voiceDeafened; + if (state.selectedSpeakerDeviceId && typeof audio.setSinkId === 'function') { + try { + await audio.setSinkId(state.selectedSpeakerDeviceId); + } catch { + // Ignore sinkId error + } + } + if (el.voiceRemoteAudioContainer) { + el.voiceRemoteAudioContainer.appendChild(audio); + } + entry.audioEl = audio; + } + entry.audioEl.srcObject = remoteStream; + entry.audioEl.muted = state.voiceDeafened; + try { + await entry.audioEl.play(); + } catch { + // Ignore autoplay restriction + } + }; + + const handleStateChange = () => { + const connState = pc.connectionState || pc.iceConnectionState || ''; + if (connState === 'connected' || connState === 'completed') { + entry.connected = true; + entry.useRelay = false; + if (entry.fallbackTimer) { + clearTimeout(entry.fallbackTimer); + entry.fallbackTimer = null; + } + updateEffectiveVoiceTransportMode(); + updateVoiceCallUI(); + } else if (connState === 'failed' || connState === 'disconnected' || connState === 'closed') { + entry.connected = false; + if (state.allowVoiceRelayFallback) { + entry.useRelay = true; + updateEffectiveVoiceTransportMode(); + updateVoiceCallUI(); + } + } + }; + + pc.onconnectionstatechange = handleStateChange; + pc.oniceconnectionstatechange = handleStateChange; + + // 6-second single-port WebSocket relay fallback timer if direct STUN/TURN P2P fails to connect + entry.fallbackTimer = setTimeout(() => { + if (!entry.connected && state.currentVoiceChannelId === channelId && state.allowVoiceRelayFallback) { + entry.useRelay = true; + updateEffectiveVoiceTransportMode(); + updateVoiceCallUI(); + } + }, 6000); + + return entry; + } + + async function syncVoicePeersForCurrentCall(session) { + if (!session || !state.currentVoiceChannelId) return; + const chId = session.channelId || session.ChannelId; + if (chId !== state.currentVoiceChannelId) return; + + const status = (session.status || session.Status || '').toLowerCase(); + if (status === 'ended') return; + + const myId = state.user ? (state.user.id || '') : ''; + const myIdLower = myId.toLowerCase(); + const participants = session.participants || session.Participants || []; + const activePeerIds = new Set(); + + for (const p of participants) { + const pId = p.userId || p.UserId || ''; + const pIdLower = pId.toLowerCase(); + if (!pId || pIdLower === myIdLower) continue; + activePeerIds.add(pIdLower); + + const pClientType = (p.clientType || p.ClientType || 'web').toLowerCase(); + if (state.voiceForceRelay || pClientType !== 'web' || typeof window.RTCPeerConnection !== 'function') { + continue; + } + + // Deterministic offerer based on userId lexical order to avoid SDP glare + if (myIdLower.localeCompare(pIdLower) < 0 && !state.voicePeerConnections[pIdLower]) { + const entry = createOrGetPeerConnection(pId, chId); + if (entry && entry.pc) { + try { + const offer = await entry.pc.createOffer({ + offerToReceiveAudio: true, + offerToReceiveVideo: false + }); + await entry.pc.setLocalDescription(offer); + sendEnvelope('VOICE_SIGNAL', { + channelId: chId, + targetUserId: pId, + signalType: 'sdp-offer', + payload: JSON.stringify(entry.pc.localDescription) + }); + } catch { + entry.useRelay = true; + } + } + } + } + + // Cleanup peers that left the call + for (const existingPeerId of Object.keys(state.voicePeerConnections)) { + if (!activePeerIds.has(existingPeerId)) { + closePeerConnection(existingPeerId); + } + } + + updateEffectiveVoiceTransportMode(); + } + + async function handleVoiceSignal(payload) { + const chId = payload.channelId || payload.ChannelId; + const senderId = payload.senderUserId || payload.SenderUserId; + const signalType = (payload.signalType || payload.SignalType || '').toLowerCase(); + const rawData = payload.payload || payload.Payload || ''; + + if (!chId || !senderId || chId !== state.currentVoiceChannelId) return; + if (state.voiceForceRelay || typeof window.RTCPeerConnection !== 'function') return; + + const entry = createOrGetPeerConnection(senderId, chId); + if (!entry || !entry.pc) return; + + try { + if (signalType === 'sdp-offer') { + const desc = JSON.parse(rawData); + await entry.pc.setRemoteDescription(new window.RTCSessionDescription(desc)); + while (entry.candidateQueue.length > 0) { + const cand = entry.candidateQueue.shift(); + await entry.pc.addIceCandidate(new window.RTCIceCandidate(cand)); + } + const answer = await entry.pc.createAnswer(); + await entry.pc.setLocalDescription(answer); + sendEnvelope('VOICE_SIGNAL', { + channelId: chId, + targetUserId: senderId, + signalType: 'sdp-answer', + payload: JSON.stringify(entry.pc.localDescription) + }); + } else if (signalType === 'sdp-answer') { + const desc = JSON.parse(rawData); + await entry.pc.setRemoteDescription(new window.RTCSessionDescription(desc)); + while (entry.candidateQueue.length > 0) { + const cand = entry.candidateQueue.shift(); + await entry.pc.addIceCandidate(new window.RTCIceCandidate(cand)); + } + } else if (signalType === 'ice-candidate') { + const cand = JSON.parse(rawData); + if (entry.pc.remoteDescription && entry.pc.remoteDescription.type) { + await entry.pc.addIceCandidate(new window.RTCIceCandidate(cand)); + } else { + entry.candidateQueue.push(cand); + } + } + } catch { + if (state.allowVoiceRelayFallback) { + entry.useRelay = true; + updateEffectiveVoiceTransportMode(); + } + } + } + + async function handleVoiceCallState(payload) { + if (Array.isArray(payload.iceServers || payload.IceServers)) { + state.iceServers = normalizeIceServers(payload.iceServers || payload.IceServers); + } + if (payload.allowVoiceRelayFallback !== undefined || payload.AllowVoiceRelayFallback !== undefined) { + state.allowVoiceRelayFallback = payload.allowVoiceRelayFallback ?? payload.AllowVoiceRelayFallback; + } + + const session = payload.session || payload.Session; + const chId = (session && (session.channelId || session.ChannelId)) || payload.channelId || payload.ChannelId; + if (!chId) return; + + const status = session ? (session.status || session.Status || '').toLowerCase() : 'ended'; + const myId = state.user ? (state.user.id || '') : ''; + const amInSession = session ? isUserInCallSession(session, myId) : false; + + if (!session || status === 'ended') { + delete state.activeVoiceCalls[chId]; + if (state.incomingRingingChannelId === chId) { + state.incomingRingingChannelId = null; + stopRingtone(); + hideIncomingCallModal(); + } + if (state.currentVoiceChannelId === chId) { + cleanupCurrentVoiceSession(); + } + updateVoiceCallUI(); + return; + } + + state.activeVoiceCalls[chId] = session; + + // Check if this is an incoming 1-on-1 DM call ringing us + const conv = getConversationById(chId); + const convType = getConversationType(conv); + const callerId = session.initiatorUserId || session.InitiatorUserId || session.callerUserId || session.CallerUserId || ''; + const callerName = session.initiatorUsername || session.InitiatorUsername || session.callerUsername || session.CallerUsername || 'User'; + + if (status === 'ringing' && convType === 'DM' && callerId.toLowerCase() !== myId.toLowerCase() && !amInSession) { + state.incomingRingingChannelId = chId; + startRingtone(); + showIncomingCallModal(callerName, chId); + } else if (state.incomingRingingChannelId === chId && (status !== 'ringing' || amInSession)) { + state.incomingRingingChannelId = null; + stopRingtone(); + hideIncomingCallModal(); + } + + if (amInSession) { + state.currentVoiceChannelId = chId; + await ensureLocalVoiceMedia(); + await syncVoicePeersForCurrentCall(session); + ensureVoiceUiLoopRunning(); + } else if (state.currentVoiceChannelId === chId) { + cleanupCurrentVoiceSession(); + } + + updateVoiceCallUI(); + } + + function showIncomingCallModal(callerUsername, channelId) { + initElements(); + if (!el.incomingCallModal) return; + if (el.incomingCallerName) { + el.incomingCallerName.textContent = `@${callerUsername} is calling you...`; + } + if (el.incomingCallSecurityHint) { + const isE2ee = isChannelVoiceE2eeActive(channelId); + el.incomingCallSecurityHint.textContent = isE2ee + ? '🔒 End-to-End Encrypted P2P / Zero-Knowledge Relayed Voice Call' + : 'P2P STUN/TURN Voice Call with Single-Port WebSocket Fallback'; + } + el.incomingCallModal.style.display = 'flex'; + } + + function hideIncomingCallModal() { + if (el.incomingCallModal) { + el.incomingCallModal.style.display = 'none'; + } + } + + function ensureVoiceUiLoopRunning() { + if (state.voiceCallTimerInterval) return; + state.voiceCallTimerInterval = setInterval(() => { + if (!state.currentVoiceChannelId && Object.keys(state.activeVoiceCalls).length === 0) { + clearInterval(state.voiceCallTimerInterval); + state.voiceCallTimerInterval = null; + return; + } + updateVoiceCallUI(); + }, 250); + } + + function cleanupCurrentVoiceSession() { + stopRingtone(); + hideIncomingCallModal(); + closeAllPeerConnections(); + stopLocalVoiceMedia(); + state.currentVoiceChannelId = null; + state.voiceSpeakingUntil = {}; + } + + async function startOrJoinVoiceCall(channelId) { + const targetChId = channelId || state.activeChannelId; + if (!targetChId) { + showToast('Select a conversation first to start a voice call.'); + return; + } + if (!state.enableVoiceCalls) { + showToast('Voice calls are disabled on this server.'); + return; + } + + if (state.currentVoiceChannelId && state.currentVoiceChannelId !== targetChId) { + sendEnvelope('VOICE_CALL_LEAVE', { + channelId: state.currentVoiceChannelId, + reason: 'Switched voice call' + }); + cleanupCurrentVoiceSession(); + } + + state.currentVoiceChannelId = targetChId; + state.voiceTransportMode = state.voiceForceRelay ? 'ws-relay' : 'p2p'; + await ensureLocalVoiceMedia(); + + sendEnvelope('VOICE_CALL_START', { + channelId: targetChId, + clientType: 'web', + transportMode: state.voiceTransportMode + }); + ensureVoiceUiLoopRunning(); + updateVoiceCallUI(); + } + + async function acceptVoiceCall(channelId) { + const targetChId = channelId || state.incomingRingingChannelId || state.activeChannelId; + if (!targetChId) { + showToast('No incoming voice call to accept.'); + return; + } + stopRingtone(); + hideIncomingCallModal(); + state.incomingRingingChannelId = null; + + if (state.activeChannelId !== targetChId) { + joinChannel(targetChId); + } + + state.currentVoiceChannelId = targetChId; + state.voiceTransportMode = state.voiceForceRelay ? 'ws-relay' : 'p2p'; + await ensureLocalVoiceMedia(); + + sendEnvelope('VOICE_CALL_ACCEPT', { + channelId: targetChId, + clientType: 'web', + transportMode: state.voiceTransportMode + }); + ensureVoiceUiLoopRunning(); + updateVoiceCallUI(); + } + + function declineVoiceCall(channelId) { + const targetChId = channelId || state.incomingRingingChannelId || state.activeChannelId; + if (!targetChId) { + showToast('No incoming voice call to decline.'); + return; + } + stopRingtone(); + hideIncomingCallModal(); + state.incomingRingingChannelId = null; + sendEnvelope('VOICE_CALL_DECLINE', { + channelId: targetChId, + reason: 'Declined' + }); + updateVoiceCallUI(); + } + + function leaveVoiceCall(reason = 'Left call') { + const targetChId = state.currentVoiceChannelId || state.activeChannelId; + if (!targetChId) { + showToast('You are not in an active voice call.'); + return; + } + sendEnvelope('VOICE_CALL_LEAVE', { + channelId: targetChId, + reason: reason + }); + cleanupCurrentVoiceSession(); + updateVoiceCallUI(); + } + + function toggleVoiceMute(explicitMute) { + state.voiceMuted = explicitMute !== undefined ? !!explicitMute : !state.voiceMuted; + if (state.voiceLocalStream) { + state.voiceLocalStream.getAudioTracks().forEach(t => { + t.enabled = !state.voiceMuted && !state.voiceDeafened; + }); + } + if (state.currentVoiceChannelId) { + sendEnvelope('VOICE_STATE_UPDATE', { + channelId: state.currentVoiceChannelId, + isMuted: state.voiceMuted, + isDeafened: state.voiceDeafened, + transportMode: state.voiceTransportMode + }); + } + updateVoiceCallUI(); + } + + function toggleVoiceDeafen(explicitDeafen) { + state.voiceDeafened = explicitDeafen !== undefined ? !!explicitDeafen : !state.voiceDeafened; + if (state.voiceDeafened) { + state.voiceMuted = true; + } + if (state.voiceLocalStream) { + state.voiceLocalStream.getAudioTracks().forEach(t => { + t.enabled = !state.voiceMuted && !state.voiceDeafened; + }); + } + for (const peerId of Object.keys(state.voicePeerConnections)) { + const entry = state.voicePeerConnections[peerId]; + if (entry && entry.audioEl) { + entry.audioEl.muted = state.voiceDeafened; + } + } + if (state.currentVoiceChannelId) { + sendEnvelope('VOICE_STATE_UPDATE', { + channelId: state.currentVoiceChannelId, + isMuted: state.voiceMuted, + isDeafened: state.voiceDeafened, + transportMode: state.voiceTransportMode + }); + } + updateVoiceCallUI(); + } + + async function toggleVoiceForceRelay(explicitRelay) { + state.voiceForceRelay = explicitRelay !== undefined ? !!explicitRelay : !state.voiceForceRelay; + state.voiceTransportMode = state.voiceForceRelay ? 'ws-relay' : 'p2p'; + if (state.voiceForceRelay) { + closeAllPeerConnections(); + } else if (state.currentVoiceChannelId && state.activeVoiceCalls[state.currentVoiceChannelId]) { + await syncVoicePeersForCurrentCall(state.activeVoiceCalls[state.currentVoiceChannelId]); + } + if (state.currentVoiceChannelId) { + sendEnvelope('VOICE_STATE_UPDATE', { + channelId: state.currentVoiceChannelId, + isMuted: state.voiceMuted, + isDeafened: state.voiceDeafened, + transportMode: state.voiceTransportMode + }); + } + showToast(state.voiceForceRelay + ? '🔁 Switched to Single-Port WebSocket Relay mode (/ws)' + : '⚡ Switched to Direct STUN/TURN P2P mode (with automatic WS Relay fallback)'); + updateVoiceCallUI(); + } + + function formatDurationClock(startedAtStr) { + if (!startedAtStr) return '00:00'; + const startMs = new Date(startedAtStr).getTime(); + if (isNaN(startMs)) return '00:00'; + const diffSec = Math.max(0, Math.floor((Date.now() - startMs) / 1000)); + const mins = String(Math.floor(diffSec / 60)).padStart(2, '0'); + const secs = String(diffSec % 60).padStart(2, '0'); + return `${mins}:${secs}`; + } + + function updateVoiceCallUI() { + initElements(); + const activeConv = getConversationById(state.activeChannelId); + const convType = getConversationType(activeConv); + const activeChSession = state.activeChannelId ? state.activeVoiceCalls[state.activeChannelId] : null; + const currentCallSession = state.currentVoiceChannelId ? state.activeVoiceCalls[state.currentVoiceChannelId] : null; + const displaySession = currentCallSession || activeChSession; + const myId = state.user ? (state.user.id || '') : ''; + const amInDisplaySession = displaySession ? isUserInCallSession(displaySession, myId) : false; + + // 1. Update header Call / Join Voice button + if (el.voiceCallBtn) { + if (!state.enableVoiceCalls || !activeConv) { + el.voiceCallBtn.style.display = 'none'; + } else { + el.voiceCallBtn.style.display = 'inline-flex'; + const amInActiveChCall = activeChSession && isUserInCallSession(activeChSession, myId); + if (amInActiveChCall) { + el.voiceCallBtn.textContent = '[📞 In Call]'; + el.voiceCallBtn.className = 'btn btn-primary btn-sm'; + } else if (activeChSession) { + const partCount = (activeChSession.participants || activeChSession.Participants || []).length; + el.voiceCallBtn.textContent = `[📞 Join Voice (${partCount})]`; + el.voiceCallBtn.className = 'btn btn-primary btn-sm'; + } else if (convType === 'DM') { + el.voiceCallBtn.textContent = '[📞 Call]'; + el.voiceCallBtn.className = 'btn btn-secondary btn-sm'; + } else { + el.voiceCallBtn.textContent = '[📞 Join Voice]'; + el.voiceCallBtn.className = 'btn btn-secondary btn-sm'; + } + } + } + + // 2. Update sticky Voice Call Status Bar + if (!el.voiceCallBar) return; + if (!displaySession || !state.enableVoiceCalls) { + el.voiceCallBar.style.display = 'none'; + return; + } + + el.voiceCallBar.style.display = 'flex'; + const sessionChId = displaySession.channelId || displaySession.ChannelId; + const sessionConv = getConversationById(sessionChId); + const sessionName = sessionConv ? (sessionConv.name || sessionConv.Name || 'Voice') : 'Voice'; + const status = (displaySession.status || displaySession.Status || 'active').toLowerCase(); + const participants = displaySession.participants || displaySession.Participants || []; + + if (el.voiceStatusDot) { + el.voiceStatusDot.className = 'user-dot ' + (status === 'ringing' ? '' : 'online'); + } + + if (el.voiceCallStatusText) { + if (status === 'ringing') { + el.voiceCallStatusText.textContent = `📞 Ringing ${sessionName}...`; + } else if (amInDisplaySession) { + el.voiceCallStatusText.textContent = `📞 Voice Connected (${sessionName})`; + } else { + el.voiceCallStatusText.textContent = `📞 Active Voice Room in ${sessionName} (${participants.length}/${state.maxVoiceCallUsers})`; + } + } + + if (el.voiceTransportBadge) { + const usingRelay = shouldTransmitViaWebSocketRelay(); + if (usingRelay) { + el.voiceTransportBadge.textContent = '[🔁 Single-Port WS Relay]'; + el.voiceTransportBadge.className = 'conv-security-badge group-badge'; + el.voiceTransportBadge.title = 'Audio is relayed over the single HTTP/HTTPS WebSocket port (/ws)'; + } else { + el.voiceTransportBadge.textContent = '[⚡ STUN/TURN P2P]'; + el.voiceTransportBadge.className = 'conv-security-badge e2ee-on'; + el.voiceTransportBadge.title = 'Direct peer-to-peer WebRTC DTLS-SRTP media stream'; + } + } + + if (el.voiceE2eeBadge) { + if (isChannelVoiceE2eeActive(sessionChId)) { + el.voiceE2eeBadge.style.display = 'inline-flex'; + el.voiceE2eeBadge.textContent = '🔒 E2EE Audio'; + } else { + el.voiceE2eeBadge.style.display = 'none'; + } + } + + if (el.voiceCallTimer) { + el.voiceCallTimer.textContent = formatDurationClock(displaySession.createdAt || displaySession.CreatedAt || displaySession.startedAt || displaySession.StartedAt); + } + + if (el.voiceParticipantsList) { + el.voiceParticipantsList.innerHTML = ''; + const now = Date.now(); + participants.forEach(p => { + const pId = (p.userId || p.UserId || '').toLowerCase(); + const pName = p.username || p.Username || 'User'; + const pMuted = !!(p.isMuted ?? p.IsMuted); + const pDeaf = !!(p.isDeafened ?? p.IsDeafened); + const pClient = (p.clientType || p.ClientType || 'web').toLowerCase(); + const isSpeaking = !pMuted && (state.voiceSpeakingUntil[pId] || 0) > now; + + const chip = document.createElement('span'); + chip.className = 'voice-participant-chip' + (isSpeaking ? ' speaking' : ''); + const icon = pDeaf ? '🔇' : (pMuted ? '🎙️✕' : (isSpeaking ? '🔊' : '🎙️')); + const clientTag = pClient === 'tui' ? ' [TUI]' : ''; + chip.textContent = `${icon} @${pName}${clientTag}`; + el.voiceParticipantsList.appendChild(chip); + }); + } + + if (el.voiceJoinRoomBtn) { + el.voiceJoinRoomBtn.style.display = amInDisplaySession ? 'none' : 'inline-flex'; + } + if (el.voiceMuteBtn) { + el.voiceMuteBtn.style.display = amInDisplaySession ? 'inline-flex' : 'none'; + el.voiceMuteBtn.textContent = state.voiceMuted ? '[🎙️ Unmute]' : '[🎙️ Mute]'; + el.voiceMuteBtn.className = state.voiceMuted ? 'btn btn-primary btn-sm' : 'btn btn-secondary btn-sm'; + } + if (el.voiceDeafenBtn) { + el.voiceDeafenBtn.style.display = amInDisplaySession ? 'inline-flex' : 'none'; + el.voiceDeafenBtn.textContent = state.voiceDeafened ? '[🔇 Undeafen]' : '[🎧 Deafen]'; + el.voiceDeafenBtn.className = state.voiceDeafened ? 'btn btn-primary btn-sm' : 'btn btn-secondary btn-sm'; + } + if (el.voiceForceRelayBtn) { + el.voiceForceRelayBtn.style.display = (amInDisplaySession && state.allowVoiceRelayFallback) ? 'inline-flex' : 'none'; + el.voiceForceRelayBtn.textContent = state.voiceForceRelay ? '[🔁 Relay: Forced]' : '[🔁 Relay: Auto]'; + el.voiceForceRelayBtn.className = state.voiceForceRelay ? 'btn btn-primary btn-sm' : 'btn btn-secondary btn-sm'; + } + if (el.voiceMicSelect) { + el.voiceMicSelect.style.display = amInDisplaySession ? 'inline-block' : 'none'; + } + if (el.voiceHangupBtn) { + el.voiceHangupBtn.style.display = amInDisplaySession ? 'inline-flex' : 'none'; + } + } + // ========================================== // Actions // ========================================== @@ -2495,6 +3829,41 @@ return; } + if (cmd === 'call' || cmd === 'voice') { + await startOrJoinVoiceCall(state.activeChannelId); + return; + } + + if (cmd === 'accept' || cmd === 'answer') { + await acceptVoiceCall(); + return; + } + + if (cmd === 'decline' || cmd === 'reject') { + declineVoiceCall(); + return; + } + + if (cmd === 'hangup' || cmd === 'leavecall') { + leaveVoiceCall('Ended call'); + return; + } + + if (cmd === 'mute' || cmd === 'vmute') { + toggleVoiceMute(); + return; + } + + if (cmd === 'deafen') { + toggleVoiceDeafen(); + return; + } + + if (cmd === 'relay') { + await toggleVoiceForceRelay(); + return; + } + if (cmd === 'inbox') { if (!args) { switchTab('inbox'); @@ -2598,6 +3967,8 @@ } function logout() { + cleanupCurrentVoiceSession(); + state.activeVoiceCalls = {}; state.token = null; state.user = null; state.publicKey = null; @@ -2609,6 +3980,7 @@ if (state.socket) state.socket.close(); hideE2eeModal(); updateUserUI(); + updateVoiceCallUI(); showAuthModal(); } @@ -2665,6 +4037,84 @@ el.toggleFollowBtn.addEventListener('click', () => toggleFollowConversation(state.activeChannelId)); } + // Voice Call Controls + if (el.voiceCallBtn) { + el.voiceCallBtn.addEventListener('click', () => { + const myId = state.user ? (state.user.id || '') : ''; + const activeSession = state.activeChannelId ? state.activeVoiceCalls[state.activeChannelId] : null; + if (activeSession && isUserInCallSession(activeSession, myId)) { + leaveVoiceCall('Left call'); + } else { + startOrJoinVoiceCall(state.activeChannelId); + } + }); + } + if (el.voiceJoinRoomBtn) { + el.voiceJoinRoomBtn.addEventListener('click', () => { + startOrJoinVoiceCall(state.activeChannelId); + }); + } + if (el.voiceMuteBtn) { + el.voiceMuteBtn.addEventListener('click', () => toggleVoiceMute()); + } + if (el.voiceDeafenBtn) { + el.voiceDeafenBtn.addEventListener('click', () => toggleVoiceDeafen()); + } + if (el.voiceForceRelayBtn) { + el.voiceForceRelayBtn.addEventListener('click', () => toggleVoiceForceRelay()); + } + if (el.voiceHangupBtn) { + el.voiceHangupBtn.addEventListener('click', () => leaveVoiceCall('Hung up')); + } + if (el.acceptIncomingCallBtn) { + el.acceptIncomingCallBtn.addEventListener('click', () => acceptVoiceCall()); + } + if (el.declineIncomingCallBtn) { + el.declineIncomingCallBtn.addEventListener('click', () => declineVoiceCall()); + } + if (el.voiceMicSelect) { + el.voiceMicSelect.addEventListener('change', async (e) => { + state.selectedMicDeviceId = e.target.value || ''; + localStorage.setItem('gsdchat_voice_mic', state.selectedMicDeviceId); + if (state.currentVoiceChannelId) { + stopLocalVoiceMedia(); + await ensureLocalVoiceMedia(); + for (const peerId of Object.keys(state.voicePeerConnections)) { + const entry = state.voicePeerConnections[peerId]; + if (entry && entry.pc && state.voiceLocalStream) { + const audioTrack = state.voiceLocalStream.getAudioTracks()[0]; + if (audioTrack) { + const sender = entry.pc.getSenders().find(s => s.track && s.track.kind === 'audio'); + if (sender) { + try { + await sender.replaceTrack(audioTrack); + } catch { + // Ignore replaceTrack error + } + } + } + } + } + } + }); + } + if (el.voiceSpeakerSelect) { + el.voiceSpeakerSelect.addEventListener('change', async (e) => { + state.selectedSpeakerDeviceId = e.target.value || ''; + localStorage.setItem('gsdchat_voice_speaker', state.selectedSpeakerDeviceId); + for (const peerId of Object.keys(state.voicePeerConnections)) { + const entry = state.voicePeerConnections[peerId]; + if (entry && entry.audioEl && typeof entry.audioEl.setSinkId === 'function') { + try { + await entry.audioEl.setSinkId(state.selectedSpeakerDeviceId); + } catch { + // Ignore setSinkId error + } + } + } + }); + } + // Inbox & Web Push Controls if (el.markAllReadInboxBtn) { el.markAllReadInboxBtn.addEventListener('click', () => sendInboxAction('mark_all_read')); diff --git a/src/GsDChat.Server/wwwroot/index.html b/src/GsDChat.Server/wwwroot/index.html index d9c7aa3..36a18e8 100644 --- a/src/GsDChat.Server/wwwroot/index.html +++ b/src/GsDChat.Server/wwwroot/index.html @@ -78,6 +78,7 @@
+ @@ -88,6 +89,35 @@
+ + +
@@ -267,6 +297,24 @@
+ + + + + +