Compare commits
No commits in common. "b8b98994d8d28c37c0f34a4db92e54266c909846" and "12bb2f98430301e2547f076297aa2573a914078e" have entirely different histories.
b8b98994d8
...
12bb2f9843
22 changed files with 12 additions and 4763 deletions
|
|
@ -12,24 +12,5 @@
|
||||||
"Motd": "Welcome to GsDChat! Enjoy private and modular messaging.",
|
"Motd": "Welcome to GsDChat! Enjoy private and modular messaging.",
|
||||||
"AllowMemberChannelCreation": true,
|
"AllowMemberChannelCreation": true,
|
||||||
"AllowDmE2ee": 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"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -26,13 +26,10 @@ public class ChatClientConnection : IDisposable
|
||||||
private CancellationTokenSource? _cts;
|
private CancellationTokenSource? _cts;
|
||||||
private readonly SemaphoreSlim _sendLock = new(1, 1);
|
private readonly SemaphoreSlim _sendLock = new(1, 1);
|
||||||
|
|
||||||
public VoiceCallManager VoiceManager { get; }
|
|
||||||
|
|
||||||
public ChatClientConnection(ClientState state, bool allowInsecure = false)
|
public ChatClientConnection(ClientState state, bool allowInsecure = false)
|
||||||
{
|
{
|
||||||
_state = state;
|
_state = state;
|
||||||
_allowInsecure = allowInsecure;
|
_allowInsecure = allowInsecure;
|
||||||
VoiceManager = new VoiceCallManager(state, this);
|
|
||||||
|
|
||||||
var handler = new HttpClientHandler();
|
var handler = new HttpClientHandler();
|
||||||
if (allowInsecure)
|
if (allowInsecure)
|
||||||
|
|
@ -98,13 +95,6 @@ public class ChatClientConnection : IDisposable
|
||||||
{
|
{
|
||||||
_state.AllowDmE2ee = info.AllowDmE2ee;
|
_state.AllowDmE2ee = info.AllowDmE2ee;
|
||||||
_state.MaxGroupChatUsers = info.MaxGroupChatUsers;
|
_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;
|
return info;
|
||||||
}
|
}
|
||||||
|
|
@ -420,13 +410,6 @@ public class ChatClientConnection : IDisposable
|
||||||
_state.Motd = ui.Motd;
|
_state.Motd = ui.Motd;
|
||||||
_state.AllowDmE2ee = ui.AllowDmE2ee;
|
_state.AllowDmE2ee = ui.AllowDmE2ee;
|
||||||
_state.MaxGroupChatUsers = ui.MaxGroupChatUsers;
|
_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.CheckLazyDmE2eePrompt();
|
||||||
_state.NeedsRedraw = true;
|
_state.NeedsRedraw = true;
|
||||||
}
|
}
|
||||||
|
|
@ -508,37 +491,6 @@ public class ChatClientConnection : IDisposable
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case MessageTypes.VoiceCallState:
|
|
||||||
var vcState = envelope.Unpack<VoiceCallStatePacket>();
|
|
||||||
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<VoiceSignalPacket>();
|
|
||||||
if (vcSig != null)
|
|
||||||
{
|
|
||||||
VoiceManager.OnVoiceSignalReceived(vcSig);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case MessageTypes.VoiceAudioFrame:
|
|
||||||
var vcAudio = envelope.Unpack<VoiceAudioFramePacket>();
|
|
||||||
if (vcAudio != null)
|
|
||||||
{
|
|
||||||
VoiceManager.OnVoiceAudioFrameReceived(vcAudio);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case MessageTypes.SystemNotice:
|
case MessageTypes.SystemNotice:
|
||||||
var notice = envelope.Unpack<SystemNoticePacket>();
|
var notice = envelope.Unpack<SystemNoticePacket>();
|
||||||
if (notice != null)
|
if (notice != null)
|
||||||
|
|
@ -901,124 +853,6 @@ public class ChatClientConnection : IDisposable
|
||||||
return SendEnvelopeAsync(envelope);
|
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<bool> UploadFileAsync(string localFilePath, string channelId)
|
public async Task<bool> UploadFileAsync(string localFilePath, string channelId)
|
||||||
{
|
{
|
||||||
if (!File.Exists(localFilePath))
|
if (!File.Exists(localFilePath))
|
||||||
|
|
@ -1052,7 +886,7 @@ public class ChatClientConnection : IDisposable
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
string errText = await res.Content.ReadAsStringAsync();
|
string errText = await res.Content.ReadAsStringAsync();
|
||||||
_state.SetStatus($"Upload failed: {(int)res.StatusCode} {res.StatusCode} - {errText}", 5);
|
_state.SetStatus($"Upload failed: {res.StatusCode} - {errText}", 5);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1074,7 +908,7 @@ public class ChatClientConnection : IDisposable
|
||||||
var res = await _httpClient.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
|
var res = await _httpClient.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
|
||||||
if (!res.IsSuccessStatusCode)
|
if (!res.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
_state.SetStatus($"Download failed: {(int)res.StatusCode} {res.StatusCode}", 4);
|
_state.SetStatus($"Download failed: {res.StatusCode}", 4);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1111,7 +945,7 @@ public class ChatClientConnection : IDisposable
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
string errText = await res.Content.ReadAsStringAsync();
|
string errText = await res.Content.ReadAsStringAsync();
|
||||||
_state.SetStatus($"Delete failed: {(int)res.StatusCode} {res.StatusCode} - {errText}", 5);
|
_state.SetStatus($"Delete failed: {res.StatusCode} - {errText}", 5);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1133,7 +967,6 @@ public class ChatClientConnection : IDisposable
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
VoiceManager.Dispose();
|
|
||||||
_cts?.Cancel();
|
_cts?.Cancel();
|
||||||
_webSocket?.Dispose();
|
_webSocket?.Dispose();
|
||||||
_httpClient.Dispose();
|
_httpClient.Dispose();
|
||||||
|
|
|
||||||
|
|
@ -1,649 +0,0 @@
|
||||||
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<string, PeerUdpState> _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<UdpCandidatePayload>(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);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 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.
|
|
||||||
/// </summary>
|
|
||||||
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<string>())
|
|
||||||
.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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -83,53 +83,8 @@ public class ChatScreen : IScreen
|
||||||
sb.AppendLine(PadOrTruncate(header, width));
|
sb.AppendLine(PadOrTruncate(header, width));
|
||||||
sb.AppendLine(new string('─', Math.Max(0, width - 1)));
|
sb.AppendLine(new string('─', Math.Max(0, width - 1)));
|
||||||
|
|
||||||
int extraVoiceLines = 0;
|
// Messages area: height minus (Header: 2, Footer/Input: 3, Tab bar & status: 3) = height - 8
|
||||||
var incomingRinging = _state.GetRingingIncomingCall();
|
int msgAreaHeight = Math.Max(3, height - 8);
|
||||||
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<ChatMessage> messages = _state.GetMessagesForChannel(_state.ActiveChannelId);
|
List<ChatMessage> messages = _state.GetMessagesForChannel(_state.ActiveChannelId);
|
||||||
|
|
||||||
|
|
@ -489,64 +444,8 @@ public class ChatScreen : IScreen
|
||||||
|
|
||||||
case "follow":
|
case "follow":
|
||||||
case "unfollow":
|
case "unfollow":
|
||||||
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":
|
case "mute":
|
||||||
// If user passes a channel name (or is not in an active voice call and used /mute), mute channel notifications
|
await _connection.ExecuteCommandAsync(cmd, args, _state.ActiveChannelId);
|
||||||
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;
|
break;
|
||||||
|
|
||||||
case "upload":
|
case "upload":
|
||||||
|
|
|
||||||
|
|
@ -32,47 +32,8 @@ public class ClientState
|
||||||
public string Motd { get; set; } = string.Empty;
|
public string Motd { get; set; } = string.Empty;
|
||||||
public bool AllowDmE2ee { get; set; } = true;
|
public bool AllowDmE2ee { get; set; } = true;
|
||||||
public int MaxGroupChatUsers { get; set; } = 10;
|
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<IceServerConfig> IceServers { get; set; } = new()
|
|
||||||
{
|
|
||||||
new IceServerConfig
|
|
||||||
{
|
|
||||||
Urls = new List<string>
|
|
||||||
{
|
|
||||||
"stun:stun.cloudflare.com:3478",
|
|
||||||
"stun:stun.l.google.com:19302"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
new IceServerConfig
|
|
||||||
{
|
|
||||||
Urls = new List<string>
|
|
||||||
{
|
|
||||||
"turn:openrelay.metered.ca:80",
|
|
||||||
"turn:openrelay.metered.ca:443",
|
|
||||||
"turn:openrelay.metered.ca:443?transport=tcp",
|
|
||||||
"turns:openrelay.metered.ca:443?transport=tcp"
|
|
||||||
},
|
|
||||||
Username = "openrelayproject",
|
|
||||||
Credential = "openrelayproject"
|
|
||||||
}
|
|
||||||
};
|
|
||||||
public ServerUiSync UiSync { get; set; } = ServerUiSync.CreateDefault();
|
public ServerUiSync UiSync { get; set; } = ServerUiSync.CreateDefault();
|
||||||
|
|
||||||
// Voice Call State
|
|
||||||
public Dictionary<string, VoiceCallSessionInfo> ActiveVoiceCalls { get; } = new(StringComparer.OrdinalIgnoreCase);
|
|
||||||
public Dictionary<string, DateTime> 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 ActiveScreenId { get; set; } = "F1_Chat";
|
||||||
public string ActiveChannelId { get; set; } = string.Empty;
|
public string ActiveChannelId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
|
@ -567,103 +528,4 @@ public class ClientState
|
||||||
return !InboxPreferences.MutedChannelIds.Contains(ch.Id, StringComparer.OrdinalIgnoreCase);
|
return !InboxPreferences.MutedChannelIds.Contains(ch.Id, StringComparer.OrdinalIgnoreCase);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void UpdateVoiceCallState(string channelId, VoiceCallSessionInfo? session, List<IceServerConfig>? iceServers = null, bool? allowRelay = null)
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
if (iceServers != null && iceServers.Count > 0)
|
|
||||||
{
|
|
||||||
IceServers = new List<IceServerConfig>(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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
|
|
||||||
namespace GsDChat.Core.Models;
|
|
||||||
|
|
||||||
public class IceServerConfig
|
|
||||||
{
|
|
||||||
public List<string> 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<VoiceParticipant> Participants { get; set; } = new();
|
|
||||||
}
|
|
||||||
|
|
@ -46,10 +46,6 @@ public class ServerInfoResponse
|
||||||
public bool AllowDmE2ee { get; set; } = true;
|
public bool AllowDmE2ee { get; set; } = true;
|
||||||
public int MaxGroupChatUsers { get; set; } = 10;
|
public int MaxGroupChatUsers { get; set; } = 10;
|
||||||
public string? VapidPublicKey { get; set; }
|
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<IceServerConfig> IceServers { get; set; } = new();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class PushSubscribeRequest
|
public class PushSubscribeRequest
|
||||||
|
|
|
||||||
|
|
@ -36,14 +36,6 @@ public static class MessageTypes
|
||||||
public const string InboxAction = "INBOX_ACTION";
|
public const string InboxAction = "INBOX_ACTION";
|
||||||
public const string UpdateInboxPreferences = "UPDATE_INBOX_PREFERENCES";
|
public const string UpdateInboxPreferences = "UPDATE_INBOX_PREFERENCES";
|
||||||
public const string ToggleFollowChannel = "TOGGLE_FOLLOW_CHANNEL";
|
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 Ping = "PING";
|
||||||
public const string Pong = "PONG";
|
public const string Pong = "PONG";
|
||||||
}
|
}
|
||||||
|
|
@ -287,66 +279,3 @@ public class ToggleFollowChannelPacket
|
||||||
public string ChannelId { get; set; } = string.Empty;
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
public bool? Follow { get; set; }
|
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<IceServerConfig> 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; }
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,251 +0,0 @@
|
||||||
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;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 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.
|
|
||||||
/// </summary>
|
|
||||||
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;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Creates a 20-byte RFC 5389 STUN Binding Request packet and outputs the 12-byte transaction ID.
|
|
||||||
/// </summary>
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Builds a valid RFC 5389 STUN Binding Success Response with XOR-MAPPED-ADDRESS (useful for local STUN responder or tests).
|
|
||||||
/// </summary>
|
|
||||||
public static byte[] CreateBindingSuccessResponse(ReadOnlySpan<byte> 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Parses a STUN Binding Success Response packet and extracts the reflexive IPEndPoint.
|
|
||||||
/// </summary>
|
|
||||||
public static IPEndPoint? ParseBindingResponse(ReadOnlySpan<byte> response, ReadOnlySpan<byte> 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Parses a STUN URI (e.g. "stun:stun.cloudflare.com:3478") into host and port.
|
|
||||||
/// </summary>
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Queries a STUN server using the provided UdpClient to discover its public reflexive IP and port.
|
|
||||||
/// </summary>
|
|
||||||
public static async Task<IPEndPoint?> 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using GsDChat.Core.Models;
|
|
||||||
|
|
||||||
namespace GsDChat.Core.Protocol;
|
namespace GsDChat.Core.Protocol;
|
||||||
|
|
||||||
|
|
@ -41,10 +40,6 @@ public class ServerUiSync
|
||||||
public string Motd { get; set; } = "Welcome to GsDChat!";
|
public string Motd { get; set; } = "Welcome to GsDChat!";
|
||||||
public bool AllowDmE2ee { get; set; } = true;
|
public bool AllowDmE2ee { get; set; } = true;
|
||||||
public int MaxGroupChatUsers { get; set; } = 10;
|
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<IceServerConfig> IceServers { get; set; } = new();
|
|
||||||
public ThemeDefinition Theme { get; set; } = new();
|
public ThemeDefinition Theme { get; set; } = new();
|
||||||
public List<ScreenDefinition> Screens { get; set; } = new();
|
public List<ScreenDefinition> Screens { get; set; } = new();
|
||||||
|
|
||||||
|
|
@ -52,11 +47,7 @@ public class ServerUiSync
|
||||||
string serverName = "GsDChat Server",
|
string serverName = "GsDChat Server",
|
||||||
string motd = "Welcome to GsDChat!",
|
string motd = "Welcome to GsDChat!",
|
||||||
bool allowDmE2ee = true,
|
bool allowDmE2ee = true,
|
||||||
int maxGroupChatUsers = 10,
|
int maxGroupChatUsers = 10)
|
||||||
bool enableVoiceCalls = true,
|
|
||||||
bool allowVoiceRelayFallback = true,
|
|
||||||
int maxVoiceCallUsers = 10,
|
|
||||||
List<IceServerConfig>? iceServers = null)
|
|
||||||
{
|
{
|
||||||
return new ServerUiSync
|
return new ServerUiSync
|
||||||
{
|
{
|
||||||
|
|
@ -64,10 +55,6 @@ public class ServerUiSync
|
||||||
Motd = motd,
|
Motd = motd,
|
||||||
AllowDmE2ee = allowDmE2ee,
|
AllowDmE2ee = allowDmE2ee,
|
||||||
MaxGroupChatUsers = maxGroupChatUsers,
|
MaxGroupChatUsers = maxGroupChatUsers,
|
||||||
EnableVoiceCalls = enableVoiceCalls,
|
|
||||||
AllowVoiceRelayFallback = allowVoiceRelayFallback,
|
|
||||||
MaxVoiceCallUsers = maxVoiceCallUsers,
|
|
||||||
IceServers = iceServers ?? new List<IceServerConfig>(),
|
|
||||||
Theme = new ThemeDefinition(),
|
Theme = new ThemeDefinition(),
|
||||||
Screens = new List<ScreenDefinition>
|
Screens = new List<ScreenDefinition>
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,6 @@ namespace GsDChat.Core.Security;
|
||||||
public static class E2eeCrypto
|
public static class E2eeCrypto
|
||||||
{
|
{
|
||||||
public const string EncryptedPrefix = "E2EE:v1:";
|
public const string EncryptedPrefix = "E2EE:v1:";
|
||||||
public const string VoiceEncryptedPrefix = "VENC:v1:";
|
|
||||||
private const string WrappedKeyPrefix = "WRAP:v1:";
|
private const string WrappedKeyPrefix = "WRAP:v1:";
|
||||||
private const int NonceByteLength = 12;
|
private const int NonceByteLength = 12;
|
||||||
private const int TagByteLength = 16;
|
private const int TagByteLength = 16;
|
||||||
|
|
@ -171,98 +170,6 @@ public static class E2eeCrypto
|
||||||
return !string.IsNullOrEmpty(content) && content.StartsWith(EncryptedPrefix, StringComparison.Ordinal);
|
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)
|
private static byte[] DeriveWrappingKey(string password, string username)
|
||||||
{
|
{
|
||||||
byte[] salt = SHA256.HashData(Encoding.UTF8.GetBytes($"GsDChat-E2EE-KeyWrap:{username.Trim().ToLowerInvariant()}"));
|
byte[] salt = SHA256.HashData(Encoding.UTF8.GetBytes($"GsDChat-E2EE-KeyWrap:{username.Trim().ToLowerInvariant()}"));
|
||||||
|
|
|
||||||
|
|
@ -1,125 +0,0 @@
|
||||||
using System;
|
|
||||||
|
|
||||||
namespace GsDChat.Core.Security;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 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.
|
|
||||||
/// </summary>
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Encodes little-endian 16-bit signed PCM bytes (s16le) into 8-bit G.711 mu-law bytes.
|
|
||||||
/// </summary>
|
|
||||||
public static byte[] EncodePcm16ToMuLaw(ReadOnlySpan<byte> 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Decodes 8-bit G.711 mu-law bytes into little-endian 16-bit signed PCM bytes (s16le).
|
|
||||||
/// </summary>
|
|
||||||
public static byte[] DecodeMuLawToPcm16(ReadOnlySpan<byte> 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Computes normalized RMS speaking level (0.0 to 1.0) from 16-bit signed little-endian PCM bytes.
|
|
||||||
/// </summary>
|
|
||||||
public static float ComputeRmsLevelFromPcm16(ReadOnlySpan<byte> 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Computes normalized RMS speaking level (0.0 to 1.0) from 8-bit G.711 mu-law bytes.
|
|
||||||
/// </summary>
|
|
||||||
public static float ComputeRmsLevelFromMuLaw(ReadOnlySpan<byte> 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,7 +1,3 @@
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using GsDChat.Core.Models;
|
|
||||||
|
|
||||||
namespace GsDChat.Server.Configuration;
|
namespace GsDChat.Server.Configuration;
|
||||||
|
|
||||||
public class ServerOptions
|
public class ServerOptions
|
||||||
|
|
@ -21,59 +17,6 @@ public class ServerOptions
|
||||||
public bool AllowDmE2ee { get; set; } = true;
|
public bool AllowDmE2ee { get; set; } = true;
|
||||||
public int MaxGroupChatUsers { get; set; } = 10;
|
public int MaxGroupChatUsers { get; set; } = 10;
|
||||||
|
|
||||||
// Voice Call & P2P STUN/TURN + Single-Port Relay Settings
|
|
||||||
public bool EnableVoiceCalls { get; set; } = true;
|
|
||||||
public bool AllowVoiceRelayFallback { get; set; } = true;
|
|
||||||
public int MaxVoiceCallUsers { get; set; } = 10;
|
|
||||||
public List<string> StunServers { get; set; } = new()
|
|
||||||
{
|
|
||||||
"stun:stun.cloudflare.com:3478",
|
|
||||||
"stun:stun.l.google.com:19302"
|
|
||||||
};
|
|
||||||
public List<IceServerConfig> TurnServers { get; set; } = new()
|
|
||||||
{
|
|
||||||
new IceServerConfig
|
|
||||||
{
|
|
||||||
Urls = new List<string>
|
|
||||||
{
|
|
||||||
"turn:openrelay.metered.ca:80",
|
|
||||||
"turn:openrelay.metered.ca:443",
|
|
||||||
"turn:openrelay.metered.ca:443?transport=tcp",
|
|
||||||
"turns:openrelay.metered.ca:443?transport=tcp"
|
|
||||||
},
|
|
||||||
Username = "openrelayproject",
|
|
||||||
Credential = "openrelayproject"
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
public List<IceServerConfig> GetIceServers()
|
|
||||||
{
|
|
||||||
var list = new List<IceServerConfig>();
|
|
||||||
var validStun = (StunServers ?? new List<string>())
|
|
||||||
.Where(s => !string.IsNullOrWhiteSpace(s))
|
|
||||||
.Select(s => s.Trim())
|
|
||||||
.Distinct()
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
if (validStun.Count > 0)
|
|
||||||
{
|
|
||||||
list.Add(new IceServerConfig { Urls = validStun });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (TurnServers != null)
|
|
||||||
{
|
|
||||||
foreach (var t in TurnServers)
|
|
||||||
{
|
|
||||||
if (t != null && t.Urls != null && t.Urls.Any(u => !string.IsNullOrWhiteSpace(u)))
|
|
||||||
{
|
|
||||||
list.Add(t);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return list;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Web Push (VAPID RFC 8292)
|
// Web Push (VAPID RFC 8292)
|
||||||
public string? VapidPublicKey { get; set; }
|
public string? VapidPublicKey { get; set; }
|
||||||
public string? VapidPrivateKey { get; set; }
|
public string? VapidPrivateKey { get; set; }
|
||||||
|
|
|
||||||
|
|
@ -88,25 +88,6 @@ public class ServerSettingsManager
|
||||||
options.MaxGroupChatUsers = 2;
|
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))
|
if (string.IsNullOrWhiteSpace(options.VapidPublicKey) || string.IsNullOrWhiteSpace(options.VapidPrivateKey))
|
||||||
{
|
{
|
||||||
var (pub, priv) = WebPushCrypto.GenerateVapidKeys();
|
var (pub, priv) = WebPushCrypto.GenerateVapidKeys();
|
||||||
|
|
|
||||||
|
|
@ -67,34 +67,6 @@ if (!string.IsNullOrEmpty(envAllowDmE2ee) && bool.TryParse(envAllowDmE2ee, out b
|
||||||
string? envMaxGroupUsers = Environment.GetEnvironmentVariable("GSDCHAT_MAX_GROUP_USERS");
|
string? envMaxGroupUsers = Environment.GetEnvironmentVariable("GSDCHAT_MAX_GROUP_USERS");
|
||||||
if (!string.IsNullOrEmpty(envMaxGroupUsers) && int.TryParse(envMaxGroupUsers, out int emgu)) serverOptions.MaxGroupChatUsers = emgu;
|
if (!string.IsNullOrEmpty(envMaxGroupUsers) && int.TryParse(envMaxGroupUsers, out int emgu)) serverOptions.MaxGroupChatUsers = emgu;
|
||||||
|
|
||||||
string? envEnableVoice = Environment.GetEnvironmentVariable("GSDCHAT_ENABLE_VOICE");
|
|
||||||
if (!string.IsNullOrEmpty(envEnableVoice) && bool.TryParse(envEnableVoice, out bool eev)) serverOptions.EnableVoiceCalls = eev;
|
|
||||||
|
|
||||||
string? envAllowVoiceRelay = Environment.GetEnvironmentVariable("GSDCHAT_ALLOW_VOICE_RELAY");
|
|
||||||
if (!string.IsNullOrEmpty(envAllowVoiceRelay) && bool.TryParse(envAllowVoiceRelay, out bool eavr)) serverOptions.AllowVoiceRelayFallback = eavr;
|
|
||||||
|
|
||||||
string? envMaxVoiceUsers = Environment.GetEnvironmentVariable("GSDCHAT_MAX_VOICE_USERS");
|
|
||||||
if (!string.IsNullOrEmpty(envMaxVoiceUsers) && int.TryParse(envMaxVoiceUsers, out int emvu)) serverOptions.MaxVoiceCallUsers = emvu;
|
|
||||||
|
|
||||||
string? envStunServers = Environment.GetEnvironmentVariable("GSDCHAT_STUN_SERVERS");
|
|
||||||
if (!string.IsNullOrEmpty(envStunServers))
|
|
||||||
{
|
|
||||||
serverOptions.StunServers = new System.Collections.Generic.List<string>(
|
|
||||||
envStunServers.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
|
|
||||||
}
|
|
||||||
|
|
||||||
string? envTurnUrl = Environment.GetEnvironmentVariable("GSDCHAT_TURN_URL");
|
|
||||||
if (!string.IsNullOrEmpty(envTurnUrl))
|
|
||||||
{
|
|
||||||
serverOptions.TurnServers.Add(new IceServerConfig
|
|
||||||
{
|
|
||||||
Urls = new System.Collections.Generic.List<string>(
|
|
||||||
envTurnUrl.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)),
|
|
||||||
Username = Environment.GetEnvironmentVariable("GSDCHAT_TURN_USER"),
|
|
||||||
Credential = Environment.GetEnvironmentVariable("GSDCHAT_TURN_CREDENTIAL")
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Allow CLI overrides e.g. --port 5000 --tls false
|
// Allow CLI overrides e.g. --port 5000 --tls false
|
||||||
for (int i = 0; i < args.Length; i++)
|
for (int i = 0; i < args.Length; i++)
|
||||||
{
|
{
|
||||||
|
|
@ -107,14 +79,6 @@ for (int i = 0; i < args.Length; i++)
|
||||||
if (args[i] == "--motd" && i + 1 < args.Length) serverOptions.Motd = args[i + 1];
|
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] == "--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] == "--max-group-users" && i + 1 < args.Length && int.TryParse(args[i + 1], out int mgu)) serverOptions.MaxGroupChatUsers = mgu;
|
||||||
if (args[i] == "--enable-voice" && i + 1 < args.Length && bool.TryParse(args[i + 1], out bool evc)) serverOptions.EnableVoiceCalls = evc;
|
|
||||||
if (args[i] == "--allow-voice-relay" && i + 1 < args.Length && bool.TryParse(args[i + 1], out bool avr)) serverOptions.AllowVoiceRelayFallback = avr;
|
|
||||||
if (args[i] == "--max-voice-users" && i + 1 < args.Length && int.TryParse(args[i + 1], out int mvu)) serverOptions.MaxVoiceCallUsers = mvu;
|
|
||||||
if (args[i] == "--stun-server" && i + 1 < args.Length && !string.IsNullOrWhiteSpace(args[i + 1]))
|
|
||||||
{
|
|
||||||
serverOptions.StunServers = new System.Collections.Generic.List<string>(
|
|
||||||
args[i + 1].Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
builder.Services.AddSingleton(settingsManager);
|
builder.Services.AddSingleton(settingsManager);
|
||||||
|
|
@ -186,9 +150,8 @@ app.Use(async (context, next) =>
|
||||||
context.Response.Headers.Append("Content-Security-Policy",
|
context.Response.Headers.Append("Content-Security-Policy",
|
||||||
"default-src 'self'; " +
|
"default-src 'self'; " +
|
||||||
"script-src 'self' 'unsafe-inline'; " +
|
"script-src 'self' 'unsafe-inline'; " +
|
||||||
"worker-src 'self' blob:; " +
|
"worker-src 'self'; " +
|
||||||
"manifest-src 'self'; " +
|
"manifest-src 'self'; " +
|
||||||
"media-src 'self' blob:; " +
|
|
||||||
"style-src 'self' 'unsafe-inline'; " +
|
"style-src 'self' 'unsafe-inline'; " +
|
||||||
"img-src 'self' data:; " +
|
"img-src 'self' data:; " +
|
||||||
"font-src 'self'; " +
|
"font-src 'self'; " +
|
||||||
|
|
@ -255,11 +218,7 @@ app.MapGet("/api/info", (ServerOptions opt, IAuthService auth, HttpRequest req)
|
||||||
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
|
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
|
||||||
AllowDmE2ee = opt.AllowDmE2ee,
|
AllowDmE2ee = opt.AllowDmE2ee,
|
||||||
MaxGroupChatUsers = opt.MaxGroupChatUsers,
|
MaxGroupChatUsers = opt.MaxGroupChatUsers,
|
||||||
VapidPublicKey = opt.VapidPublicKey,
|
VapidPublicKey = opt.VapidPublicKey
|
||||||
EnableVoiceCalls = opt.EnableVoiceCalls,
|
|
||||||
AllowVoiceRelayFallback = opt.AllowVoiceRelayFallback,
|
|
||||||
MaxVoiceCallUsers = opt.MaxVoiceCallUsers,
|
|
||||||
IceServers = opt.GetIceServers()
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,8 +21,6 @@ namespace GsDChat.Server.WebSockets;
|
||||||
public class ChatWebSocketManager
|
public class ChatWebSocketManager
|
||||||
{
|
{
|
||||||
private readonly ConcurrentDictionary<string, ConnectedClient> _clients = new();
|
private readonly ConcurrentDictionary<string, ConnectedClient> _clients = new();
|
||||||
private readonly ConcurrentDictionary<string, VoiceCallSessionInfo> _activeCalls = new(StringComparer.OrdinalIgnoreCase);
|
|
||||||
private readonly object _voiceLock = new();
|
|
||||||
private readonly ChatDatabase _db;
|
private readonly ChatDatabase _db;
|
||||||
private readonly ServerOptions _options;
|
private readonly ServerOptions _options;
|
||||||
private readonly ILogger<ChatWebSocketManager> _logger;
|
private readonly ILogger<ChatWebSocketManager> _logger;
|
||||||
|
|
@ -72,17 +70,9 @@ public class ChatWebSocketManager
|
||||||
_options.ServerName,
|
_options.ServerName,
|
||||||
_options.Motd,
|
_options.Motd,
|
||||||
_options.AllowDmE2ee,
|
_options.AllowDmE2ee,
|
||||||
_options.MaxGroupChatUsers,
|
_options.MaxGroupChatUsers);
|
||||||
_options.EnableVoiceCalls,
|
|
||||||
_options.AllowVoiceRelayFallback,
|
|
||||||
_options.MaxVoiceCallUsers,
|
|
||||||
_options.GetIceServers());
|
|
||||||
uiSync.AllowDmE2ee = _options.AllowDmE2ee;
|
uiSync.AllowDmE2ee = _options.AllowDmE2ee;
|
||||||
uiSync.MaxGroupChatUsers = _options.MaxGroupChatUsers;
|
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
|
// Send AuthResult with current E2EE key vault metadata so restored sessions have latest server state
|
||||||
await client.SendMessageAsync(MessageTypes.AuthResult, new AuthResultPacket
|
await client.SendMessageAsync(MessageTypes.AuthResult, new AuthResultPacket
|
||||||
|
|
@ -115,9 +105,6 @@ public class ChatWebSocketManager
|
||||||
// Send Initial Inbox & Preferences Sync
|
// Send Initial Inbox & Preferences Sync
|
||||||
await SendInboxSyncToClientAsync(client, cancellationToken);
|
await SendInboxSyncToClientAsync(client, cancellationToken);
|
||||||
|
|
||||||
// Send Active Voice Calls Sync
|
|
||||||
await SendActiveVoiceCallsToClientAsync(client, cancellationToken);
|
|
||||||
|
|
||||||
// Send Initial User List
|
// Send Initial User List
|
||||||
var initialUsers = await _db.GetAllUsersAsync();
|
var initialUsers = await _db.GetAllUsersAsync();
|
||||||
var onlineIds = new HashSet<string>(_clients.Values.Select(c => c.User.Id), StringComparer.OrdinalIgnoreCase);
|
var onlineIds = new HashSet<string>(_clients.Values.Select(c => c.User.Id), StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
@ -189,12 +176,6 @@ public class ChatWebSocketManager
|
||||||
}
|
}
|
||||||
catch { }
|
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 BroadcastUserListAsync();
|
||||||
await BroadcastSystemNoticeAsync($"[-] {InputSanitizer.SanitizeUsername(user.Username)} disconnected.", "Info");
|
await BroadcastSystemNoticeAsync($"[-] {InputSanitizer.SanitizeUsername(user.Username)} disconnected.", "Info");
|
||||||
}
|
}
|
||||||
|
|
@ -348,62 +329,6 @@ public class ChatWebSocketManager
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case MessageTypes.VoiceCallStart:
|
|
||||||
var vcStart = envelope.Unpack<VoiceCallStartPacket>();
|
|
||||||
if (vcStart != null)
|
|
||||||
{
|
|
||||||
await HandleVoiceCallStartAsync(client, vcStart, ct);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case MessageTypes.VoiceCallAccept:
|
|
||||||
var vcAccept = envelope.Unpack<VoiceCallAcceptPacket>();
|
|
||||||
if (vcAccept != null)
|
|
||||||
{
|
|
||||||
await HandleVoiceCallAcceptAsync(client, vcAccept, ct);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case MessageTypes.VoiceCallDecline:
|
|
||||||
var vcDecline = envelope.Unpack<VoiceCallDeclinePacket>();
|
|
||||||
if (vcDecline != null)
|
|
||||||
{
|
|
||||||
await HandleVoiceCallDeclineAsync(client, vcDecline, ct);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case MessageTypes.VoiceCallLeave:
|
|
||||||
var vcLeave = envelope.Unpack<VoiceCallLeavePacket>();
|
|
||||||
if (vcLeave != null)
|
|
||||||
{
|
|
||||||
await HandleVoiceCallLeaveAsync(client, vcLeave, ct);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case MessageTypes.VoiceStateUpdate:
|
|
||||||
var vcStateUpd = envelope.Unpack<VoiceStateUpdatePacket>();
|
|
||||||
if (vcStateUpd != null)
|
|
||||||
{
|
|
||||||
await HandleVoiceStateUpdateAsync(client, vcStateUpd, ct);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case MessageTypes.VoiceSignal:
|
|
||||||
var vcSignal = envelope.Unpack<VoiceSignalPacket>();
|
|
||||||
if (vcSignal != null)
|
|
||||||
{
|
|
||||||
await HandleVoiceSignalAsync(client, vcSignal, ct);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case MessageTypes.VoiceAudioFrame:
|
|
||||||
var vcAudio = envelope.Unpack<VoiceAudioFramePacket>();
|
|
||||||
if (vcAudio != null)
|
|
||||||
{
|
|
||||||
await HandleVoiceAudioFrameAsync(client, vcAudio, ct);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case MessageTypes.UserListSync:
|
case MessageTypes.UserListSync:
|
||||||
case "GET_USERS":
|
case "GET_USERS":
|
||||||
await BroadcastUserListAsync();
|
await BroadcastUserListAsync();
|
||||||
|
|
@ -1053,9 +978,6 @@ public class ChatWebSocketManager
|
||||||
" /group leave - Leave the active group chat\n" +
|
" /group leave - Leave the active group chat\n" +
|
||||||
" /follow [channel] - Follow/unfollow a conversation for Inbox notifications\n" +
|
" /follow [channel] - Follow/unfollow a conversation for Inbox notifications\n" +
|
||||||
" /inbox [readall|clear] - Manage Inbox notifications & preferences\n" +
|
" /inbox [readall|clear] - Manage Inbox notifications & preferences\n" +
|
||||||
" /call - Start or join a voice call in the active conversation\n" +
|
|
||||||
" /accept | /decline - Accept or decline an incoming DM voice call\n" +
|
|
||||||
" /hangup - Leave or end the active voice call\n" +
|
|
||||||
" /announce <message> - Broadcast an official announcement (Admin/Owner)\n" +
|
" /announce <message> - Broadcast an official announcement (Admin/Owner)\n" +
|
||||||
" /deletefile <file_id> - Delete an uploaded file (Uploader or Admin)\n" +
|
" /deletefile <file_id> - Delete an uploaded file (Uploader or Admin)\n" +
|
||||||
" /users - List all registered users\n" +
|
" /users - List all registered users\n" +
|
||||||
|
|
@ -1336,40 +1258,6 @@ public class ChatWebSocketManager
|
||||||
await HandleLeaveGroupAsync(client, new LeaveGroupPacket { ChannelId = client.ActiveChannelId }, ct);
|
await HandleLeaveGroupAsync(client, new LeaveGroupPacket { ChannelId = client.ActiveChannelId }, ct);
|
||||||
break;
|
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":
|
case "delete":
|
||||||
string channelToDelete = (packet.Args ?? string.Empty).Trim().TrimStart('#');
|
string channelToDelete = (packet.Args ?? string.Empty).Trim().TrimStart('#');
|
||||||
if (string.IsNullOrEmpty(channelToDelete))
|
if (string.IsNullOrEmpty(channelToDelete))
|
||||||
|
|
@ -1891,665 +1779,4 @@ public class ChatWebSocketManager
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Voice Call & Single-Port Relay Management
|
|
||||||
|
|
||||||
public async Task SendActiveVoiceCallsToClientAsync(ConnectedClient client, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
if (!_options.EnableVoiceCalls) return;
|
|
||||||
|
|
||||||
var accessibleIds = await _db.GetAccessibleChannelIdsForUserAsync(client.User.Id);
|
|
||||||
List<VoiceCallSessionInfo> visibleCalls;
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
visibleCalls = _activeCalls.Values
|
|
||||||
.Where(s => s.Status != VoiceCallStatus.Ended && accessibleIds.Contains(s.ChannelId))
|
|
||||||
.Select(CloneVoiceSession)
|
|
||||||
.ToList();
|
|
||||||
}
|
|
||||||
|
|
||||||
var iceServers = _options.GetIceServers();
|
|
||||||
foreach (var call in visibleCalls)
|
|
||||||
{
|
|
||||||
await client.SendMessageAsync(MessageTypes.VoiceCallState, new VoiceCallStatePacket
|
|
||||||
{
|
|
||||||
ChannelId = call.ChannelId,
|
|
||||||
Session = call,
|
|
||||||
IceServers = iceServers,
|
|
||||||
AllowVoiceRelayFallback = _options.AllowVoiceRelayFallback
|
|
||||||
}, ct);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static VoiceCallSessionInfo CloneVoiceSession(VoiceCallSessionInfo src)
|
|
||||||
{
|
|
||||||
return new VoiceCallSessionInfo
|
|
||||||
{
|
|
||||||
CallId = src.CallId,
|
|
||||||
ChannelId = src.ChannelId,
|
|
||||||
ChannelType = src.ChannelType,
|
|
||||||
InitiatorUserId = src.InitiatorUserId,
|
|
||||||
InitiatorUsername = src.InitiatorUsername,
|
|
||||||
Status = src.Status,
|
|
||||||
IsE2ee = src.IsE2ee,
|
|
||||||
CreatedAt = src.CreatedAt,
|
|
||||||
RingingTargetUserId = src.RingingTargetUserId,
|
|
||||||
RingingTargetUsername = src.RingingTargetUsername,
|
|
||||||
Participants = src.Participants.Select(p => new VoiceParticipant
|
|
||||||
{
|
|
||||||
UserId = p.UserId,
|
|
||||||
Username = p.Username,
|
|
||||||
ClientType = p.ClientType,
|
|
||||||
IsMuted = p.IsMuted,
|
|
||||||
IsDeafened = p.IsDeafened,
|
|
||||||
TransportMode = p.TransportMode,
|
|
||||||
PublicKey = p.PublicKey,
|
|
||||||
UdpEndpoint = p.UdpEndpoint,
|
|
||||||
JoinedAt = p.JoinedAt
|
|
||||||
}).ToList()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task BroadcastVoiceCallStateAsync(Channel channel, VoiceCallSessionInfo session)
|
|
||||||
{
|
|
||||||
var packet = new VoiceCallStatePacket
|
|
||||||
{
|
|
||||||
ChannelId = channel.Id,
|
|
||||||
Session = CloneVoiceSession(session),
|
|
||||||
IceServers = _options.GetIceServers(),
|
|
||||||
AllowVoiceRelayFallback = _options.AllowVoiceRelayFallback
|
|
||||||
};
|
|
||||||
|
|
||||||
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
|
||||||
{
|
|
||||||
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.VoiceCallState, packet);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
await BroadcastToAllAsync(MessageTypes.VoiceCallState, packet);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task BroadcastVoiceNoticeToConversationAsync(Channel channel, string text, string level = "Info")
|
|
||||||
{
|
|
||||||
var notice = new SystemNoticePacket { Text = text, Level = level };
|
|
||||||
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
|
||||||
{
|
|
||||||
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.SystemNotice, notice);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
await BroadcastToChannelAsync(channel.Id, MessageTypes.SystemNotice, notice);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandleVoiceCallStartAsync(ConnectedClient client, VoiceCallStartPacket packet, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (!_options.EnableVoiceCalls)
|
|
||||||
{
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Voice calls are disabled on this server." }, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
|
||||||
if (string.IsNullOrWhiteSpace(channelId))
|
|
||||||
{
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "No conversation selected for voice call." }, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
|
||||||
if (channel == null)
|
|
||||||
{
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Conversation not found." }, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
|
||||||
{
|
|
||||||
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
|
||||||
if (!isMember)
|
|
||||||
{
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You do not have access to this conversation." }, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove user from any other conversation's voice call first
|
|
||||||
await RemoveUserFromOtherVoiceCallsAsync(client.User.Id, client.User.Username, channel.Id);
|
|
||||||
|
|
||||||
string clientType = string.Equals(packet.ClientType, VoiceClientTypes.Tui, StringComparison.OrdinalIgnoreCase)
|
|
||||||
? VoiceClientTypes.Tui
|
|
||||||
: VoiceClientTypes.Web;
|
|
||||||
string defaultTransport = clientType == VoiceClientTypes.Tui ? VoiceTransportModes.P2P : VoiceTransportModes.P2P;
|
|
||||||
|
|
||||||
int maxUsers = Math.Max(2, _options.MaxVoiceCallUsers);
|
|
||||||
VoiceCallSessionInfo sessionToBroadcast;
|
|
||||||
bool isNewCall = false;
|
|
||||||
bool becameActive = false;
|
|
||||||
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
if (_activeCalls.TryGetValue(channel.Id, out var existing) && existing.Status != VoiceCallStatus.Ended)
|
|
||||||
{
|
|
||||||
var existingPart = existing.Participants.FirstOrDefault(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (existingPart != null)
|
|
||||||
{
|
|
||||||
existingPart.ClientType = clientType;
|
|
||||||
existingPart.PublicKey = client.User.PublicKey;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (existing.Participants.Count >= maxUsers)
|
|
||||||
{
|
|
||||||
sessionToBroadcast = existing;
|
|
||||||
goto MaxUsersReached;
|
|
||||||
}
|
|
||||||
|
|
||||||
existing.Participants.Add(new VoiceParticipant
|
|
||||||
{
|
|
||||||
UserId = client.User.Id,
|
|
||||||
Username = client.User.Username,
|
|
||||||
ClientType = clientType,
|
|
||||||
TransportMode = defaultTransport,
|
|
||||||
PublicKey = client.User.PublicKey,
|
|
||||||
JoinedAt = DateTime.UtcNow
|
|
||||||
});
|
|
||||||
|
|
||||||
if (existing.Status == VoiceCallStatus.Ringing &&
|
|
||||||
!string.Equals(existing.InitiatorUserId, client.User.Id, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
existing.Status = VoiceCallStatus.Active;
|
|
||||||
existing.RingingTargetUserId = null;
|
|
||||||
existing.RingingTargetUsername = null;
|
|
||||||
becameActive = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If any participant is TUI and another is Web, mark relay hint or let clients auto-negotiate
|
|
||||||
sessionToBroadcast = CloneVoiceSession(existing);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
isNewCall = true;
|
|
||||||
string? peerId = null;
|
|
||||||
string? peerName = null;
|
|
||||||
if (channel.Type == ChannelTypes.DirectMessage)
|
|
||||||
{
|
|
||||||
peerId = channel.MemberIds.FirstOrDefault(id => !string.Equals(id, client.User.Id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
peerName = channel.MemberUsernames.FirstOrDefault(n => !string.Equals(n, client.User.Username, StringComparison.OrdinalIgnoreCase));
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isDmRinging = channel.Type == ChannelTypes.DirectMessage && !string.IsNullOrEmpty(peerId);
|
|
||||||
bool isE2eeCall = channel.Type == ChannelTypes.DirectMessage && channel.IsE2ee && _options.AllowDmE2ee && client.User.E2eeEnabled;
|
|
||||||
|
|
||||||
var created = new VoiceCallSessionInfo
|
|
||||||
{
|
|
||||||
CallId = Guid.NewGuid().ToString("N"),
|
|
||||||
ChannelId = channel.Id,
|
|
||||||
ChannelType = channel.Type,
|
|
||||||
InitiatorUserId = client.User.Id,
|
|
||||||
InitiatorUsername = client.User.Username,
|
|
||||||
Status = isDmRinging ? VoiceCallStatus.Ringing : VoiceCallStatus.Active,
|
|
||||||
IsE2ee = isE2eeCall,
|
|
||||||
CreatedAt = DateTime.UtcNow,
|
|
||||||
RingingTargetUserId = peerId,
|
|
||||||
RingingTargetUsername = peerName,
|
|
||||||
Participants = new List<VoiceParticipant>
|
|
||||||
{
|
|
||||||
new()
|
|
||||||
{
|
|
||||||
UserId = client.User.Id,
|
|
||||||
Username = client.User.Username,
|
|
||||||
ClientType = clientType,
|
|
||||||
TransportMode = defaultTransport,
|
|
||||||
PublicKey = client.User.PublicKey,
|
|
||||||
JoinedAt = DateTime.UtcNow
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
_activeCalls[channel.Id] = created;
|
|
||||||
sessionToBroadcast = CloneVoiceSession(created);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await BroadcastVoiceCallStateAsync(channel, sessionToBroadcast);
|
|
||||||
|
|
||||||
if (isNewCall)
|
|
||||||
{
|
|
||||||
string msg = sessionToBroadcast.Status == VoiceCallStatus.Ringing
|
|
||||||
? $"📞 @{InputSanitizer.SanitizeUsername(client.User.Username)} is calling..."
|
|
||||||
: $"📞 @{InputSanitizer.SanitizeUsername(client.User.Username)} started a voice call.";
|
|
||||||
await BroadcastVoiceNoticeToConversationAsync(channel, msg, "Info");
|
|
||||||
}
|
|
||||||
else if (becameActive)
|
|
||||||
{
|
|
||||||
await BroadcastVoiceNoticeToConversationAsync(
|
|
||||||
channel,
|
|
||||||
$"📞 @{InputSanitizer.SanitizeUsername(client.User.Username)} answered the voice call.",
|
|
||||||
"Success");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
|
|
||||||
MaxUsersReached:
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
|
||||||
{
|
|
||||||
Message = $"Voice call has reached the maximum participant limit ({maxUsers})."
|
|
||||||
}, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandleVoiceCallAcceptAsync(ConnectedClient client, VoiceCallAcceptPacket packet, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (!_options.EnableVoiceCalls)
|
|
||||||
{
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Voice calls are disabled on this server." }, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
|
||||||
if (string.IsNullOrWhiteSpace(channelId))
|
|
||||||
{
|
|
||||||
// Find any ringing call targeting this user
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
var ringingForMe = _activeCalls.Values.FirstOrDefault(s =>
|
|
||||||
s.Status == VoiceCallStatus.Ringing &&
|
|
||||||
string.Equals(s.RingingTargetUserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (ringingForMe != null)
|
|
||||||
{
|
|
||||||
channelId = ringingForMe.ChannelId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(channelId))
|
|
||||||
{
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "No active or incoming voice call to accept." }, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
|
||||||
if (channel == null)
|
|
||||||
{
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Conversation not found." }, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
|
|
||||||
{
|
|
||||||
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
|
|
||||||
if (!isMember)
|
|
||||||
{
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You do not have access to this conversation." }, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await RemoveUserFromOtherVoiceCallsAsync(client.User.Id, client.User.Username, channel.Id);
|
|
||||||
|
|
||||||
string clientType = string.Equals(packet.ClientType, VoiceClientTypes.Tui, StringComparison.OrdinalIgnoreCase)
|
|
||||||
? VoiceClientTypes.Tui
|
|
||||||
: VoiceClientTypes.Web;
|
|
||||||
int maxUsers = Math.Max(2, _options.MaxVoiceCallUsers);
|
|
||||||
VoiceCallSessionInfo? sessionToBroadcast = null;
|
|
||||||
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
if (!_activeCalls.TryGetValue(channel.Id, out var session) || session.Status == VoiceCallStatus.Ended)
|
|
||||||
{
|
|
||||||
sessionToBroadcast = null;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
var part = session.Participants.FirstOrDefault(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (part == null)
|
|
||||||
{
|
|
||||||
if (session.Participants.Count >= maxUsers)
|
|
||||||
{
|
|
||||||
goto MaxUsersReached;
|
|
||||||
}
|
|
||||||
|
|
||||||
session.Participants.Add(new VoiceParticipant
|
|
||||||
{
|
|
||||||
UserId = client.User.Id,
|
|
||||||
Username = client.User.Username,
|
|
||||||
ClientType = clientType,
|
|
||||||
TransportMode = VoiceTransportModes.P2P,
|
|
||||||
PublicKey = client.User.PublicKey,
|
|
||||||
JoinedAt = DateTime.UtcNow
|
|
||||||
});
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
part.ClientType = clientType;
|
|
||||||
part.PublicKey = client.User.PublicKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
session.Status = VoiceCallStatus.Active;
|
|
||||||
session.RingingTargetUserId = null;
|
|
||||||
session.RingingTargetUsername = null;
|
|
||||||
sessionToBroadcast = CloneVoiceSession(session);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sessionToBroadcast == null)
|
|
||||||
{
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "No active voice call in this conversation." }, ct);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await BroadcastVoiceCallStateAsync(channel, sessionToBroadcast);
|
|
||||||
await BroadcastVoiceNoticeToConversationAsync(
|
|
||||||
channel,
|
|
||||||
$"📞 @{InputSanitizer.SanitizeUsername(client.User.Username)} joined the voice call.",
|
|
||||||
"Success");
|
|
||||||
return;
|
|
||||||
|
|
||||||
MaxUsersReached:
|
|
||||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket
|
|
||||||
{
|
|
||||||
Message = $"Voice call has reached the maximum participant limit ({maxUsers})."
|
|
||||||
}, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandleVoiceCallDeclineAsync(ConnectedClient client, VoiceCallDeclinePacket packet, CancellationToken ct)
|
|
||||||
{
|
|
||||||
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
|
||||||
if (string.IsNullOrWhiteSpace(channelId))
|
|
||||||
{
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
var ringingForMe = _activeCalls.Values.FirstOrDefault(s =>
|
|
||||||
s.Status == VoiceCallStatus.Ringing &&
|
|
||||||
string.Equals(s.RingingTargetUserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (ringingForMe != null)
|
|
||||||
{
|
|
||||||
channelId = ringingForMe.ChannelId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(channelId)) return;
|
|
||||||
|
|
||||||
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
|
||||||
if (channel == null) return;
|
|
||||||
|
|
||||||
VoiceCallSessionInfo? endedSession = null;
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
if (_activeCalls.TryGetValue(channel.Id, out var session))
|
|
||||||
{
|
|
||||||
if (channel.Type == ChannelTypes.DirectMessage || session.Status == VoiceCallStatus.Ringing)
|
|
||||||
{
|
|
||||||
session.Status = VoiceCallStatus.Ended;
|
|
||||||
session.Participants.Clear();
|
|
||||||
session.RingingTargetUserId = null;
|
|
||||||
_activeCalls.TryRemove(channel.Id, out _);
|
|
||||||
endedSession = CloneVoiceSession(session);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
session.Participants.RemoveAll(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (session.Participants.Count == 0)
|
|
||||||
{
|
|
||||||
session.Status = VoiceCallStatus.Ended;
|
|
||||||
_activeCalls.TryRemove(channel.Id, out _);
|
|
||||||
}
|
|
||||||
endedSession = CloneVoiceSession(session);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (endedSession != null)
|
|
||||||
{
|
|
||||||
await BroadcastVoiceCallStateAsync(channel, endedSession);
|
|
||||||
await BroadcastVoiceNoticeToConversationAsync(
|
|
||||||
channel,
|
|
||||||
$"📞 @{InputSanitizer.SanitizeUsername(client.User.Username)} declined the voice call.",
|
|
||||||
"Warning");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandleVoiceCallLeaveAsync(ConnectedClient client, VoiceCallLeavePacket packet, CancellationToken ct)
|
|
||||||
{
|
|
||||||
string channelId = packet.ChannelId;
|
|
||||||
if (string.IsNullOrWhiteSpace(channelId))
|
|
||||||
{
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
var myCall = _activeCalls.Values.FirstOrDefault(s =>
|
|
||||||
s.Participants.Any(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase)) ||
|
|
||||||
string.Equals(s.RingingTargetUserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
channelId = myCall?.ChannelId ?? client.ActiveChannelId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(channelId)) return;
|
|
||||||
|
|
||||||
await RemoveUserFromVoiceCallAsync(channelId, client.User.Id, client.User.Username);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task RemoveUserFromOtherVoiceCallsAsync(string userId, string username, string exceptChannelId)
|
|
||||||
{
|
|
||||||
List<string> otherChannelIds;
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
otherChannelIds = _activeCalls.Values
|
|
||||||
.Where(s => !string.Equals(s.ChannelId, exceptChannelId, StringComparison.OrdinalIgnoreCase) &&
|
|
||||||
s.Participants.Any(p => string.Equals(p.UserId, userId, StringComparison.OrdinalIgnoreCase)))
|
|
||||||
.Select(s => s.ChannelId)
|
|
||||||
.ToList();
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var chId in otherChannelIds)
|
|
||||||
{
|
|
||||||
await RemoveUserFromVoiceCallAsync(chId, userId, username);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task RemoveUserFromAllVoiceCallsAsync(string userId, string username)
|
|
||||||
{
|
|
||||||
List<string> channelIds;
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
channelIds = _activeCalls.Values
|
|
||||||
.Where(s => s.Participants.Any(p => string.Equals(p.UserId, userId, StringComparison.OrdinalIgnoreCase)) ||
|
|
||||||
string.Equals(s.RingingTargetUserId, userId, StringComparison.OrdinalIgnoreCase))
|
|
||||||
.Select(s => s.ChannelId)
|
|
||||||
.ToList();
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var chId in channelIds)
|
|
||||||
{
|
|
||||||
await RemoveUserFromVoiceCallAsync(chId, userId, username);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task RemoveUserFromVoiceCallAsync(string channelId, string userId, string username)
|
|
||||||
{
|
|
||||||
VoiceCallSessionInfo? updatedSession = null;
|
|
||||||
bool callEnded = false;
|
|
||||||
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
if (_activeCalls.TryGetValue(channelId, out var session))
|
|
||||||
{
|
|
||||||
int removed = session.Participants.RemoveAll(p => string.Equals(p.UserId, userId, StringComparison.OrdinalIgnoreCase));
|
|
||||||
bool wasRingingTarget = string.Equals(session.RingingTargetUserId, userId, StringComparison.OrdinalIgnoreCase);
|
|
||||||
bool wasInitiator = string.Equals(session.InitiatorUserId, userId, StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
if (removed == 0 && !wasRingingTarget && !wasInitiator)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// For 1-on-1 DMs, or if all participants left, or if initiator hangs up while ringing, end the call
|
|
||||||
if (session.ChannelType == ChannelTypes.DirectMessage || session.Participants.Count == 0 || (session.Status == VoiceCallStatus.Ringing && wasInitiator))
|
|
||||||
{
|
|
||||||
session.Status = VoiceCallStatus.Ended;
|
|
||||||
session.Participants.Clear();
|
|
||||||
session.RingingTargetUserId = null;
|
|
||||||
_activeCalls.TryRemove(channelId, out _);
|
|
||||||
callEnded = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
updatedSession = CloneVoiceSession(session);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (updatedSession != null)
|
|
||||||
{
|
|
||||||
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
|
||||||
if (channel != null)
|
|
||||||
{
|
|
||||||
await BroadcastVoiceCallStateAsync(channel, updatedSession);
|
|
||||||
string noticeText = callEnded
|
|
||||||
? $"📞 Voice call ended (@{InputSanitizer.SanitizeUsername(username)} hung up)."
|
|
||||||
: $"📞 @{InputSanitizer.SanitizeUsername(username)} left the voice call.";
|
|
||||||
await BroadcastVoiceNoticeToConversationAsync(channel, noticeText, "Info");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandleVoiceStateUpdateAsync(ConnectedClient client, VoiceStateUpdatePacket packet, CancellationToken ct)
|
|
||||||
{
|
|
||||||
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
|
|
||||||
if (string.IsNullOrWhiteSpace(channelId)) return;
|
|
||||||
|
|
||||||
VoiceCallSessionInfo? updatedSession = null;
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
if (_activeCalls.TryGetValue(channelId, out var session) && session.Status != VoiceCallStatus.Ended)
|
|
||||||
{
|
|
||||||
var part = session.Participants.FirstOrDefault(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (part != null)
|
|
||||||
{
|
|
||||||
if (packet.IsMuted.HasValue) part.IsMuted = packet.IsMuted.Value;
|
|
||||||
if (packet.IsDeafened.HasValue)
|
|
||||||
{
|
|
||||||
part.IsDeafened = packet.IsDeafened.Value;
|
|
||||||
if (part.IsDeafened) part.IsMuted = true;
|
|
||||||
}
|
|
||||||
if (!string.IsNullOrWhiteSpace(packet.TransportMode))
|
|
||||||
{
|
|
||||||
part.TransportMode = packet.TransportMode.Trim().ToLowerInvariant() == VoiceTransportModes.Relay
|
|
||||||
? VoiceTransportModes.Relay
|
|
||||||
: VoiceTransportModes.P2P;
|
|
||||||
}
|
|
||||||
if (packet.UdpEndpoint != null)
|
|
||||||
{
|
|
||||||
part.UdpEndpoint = packet.UdpEndpoint.Trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
updatedSession = CloneVoiceSession(session);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (updatedSession != null)
|
|
||||||
{
|
|
||||||
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
|
|
||||||
if (channel != null)
|
|
||||||
{
|
|
||||||
await BroadcastVoiceCallStateAsync(channel, updatedSession);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandleVoiceSignalAsync(ConnectedClient client, VoiceSignalPacket packet, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (!_options.EnableVoiceCalls) return;
|
|
||||||
if (string.IsNullOrWhiteSpace(packet.TargetUserId) || string.IsNullOrWhiteSpace(packet.ChannelId)) return;
|
|
||||||
if (packet.Payload != null && packet.Payload.Length > 65536) return;
|
|
||||||
|
|
||||||
bool canSignal = false;
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
if (_activeCalls.TryGetValue(packet.ChannelId, out var session) && session.Status != VoiceCallStatus.Ended)
|
|
||||||
{
|
|
||||||
bool senderInCall = session.Participants.Any(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
bool targetInCall = session.Participants.Any(p => string.Equals(p.UserId, packet.TargetUserId, StringComparison.OrdinalIgnoreCase)) ||
|
|
||||||
string.Equals(session.RingingTargetUserId, packet.TargetUserId, StringComparison.OrdinalIgnoreCase);
|
|
||||||
canSignal = senderInCall && targetInCall;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!canSignal) return;
|
|
||||||
|
|
||||||
var outbound = new VoiceSignalPacket
|
|
||||||
{
|
|
||||||
ChannelId = packet.ChannelId,
|
|
||||||
SenderUserId = client.User.Id,
|
|
||||||
TargetUserId = packet.TargetUserId,
|
|
||||||
SignalType = packet.SignalType,
|
|
||||||
Payload = packet.Payload ?? string.Empty
|
|
||||||
};
|
|
||||||
|
|
||||||
await BroadcastToMembersAsync(new[] { packet.TargetUserId }, MessageTypes.VoiceSignal, outbound);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Single-Port WebSocket TURN-like Media Relay handler.
|
|
||||||
/// Relays audio frames (including E2EE AES-256-GCM encrypted frames) over the single HTTP/HTTPS /ws port
|
|
||||||
/// to active call participants when direct P2P STUN/UDP is unavailable or bridged across Web and TUI clients.
|
|
||||||
/// </summary>
|
|
||||||
private async Task HandleVoiceAudioFrameAsync(ConnectedClient client, VoiceAudioFramePacket packet, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (!_options.EnableVoiceCalls || !_options.AllowVoiceRelayFallback) return;
|
|
||||||
if (string.IsNullOrWhiteSpace(packet.ChannelId) || string.IsNullOrWhiteSpace(packet.DataBase64)) return;
|
|
||||||
if (packet.DataBase64.Length > 16384) return; // Drop abnormal/oversized audio frames to prevent memory bloat/DoS
|
|
||||||
|
|
||||||
List<string> recipientIds;
|
|
||||||
lock (_voiceLock)
|
|
||||||
{
|
|
||||||
if (!_activeCalls.TryGetValue(packet.ChannelId, out var session) || session.Status != VoiceCallStatus.Active)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var senderPart = session.Participants.FirstOrDefault(p => string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (senderPart == null || senderPart.IsMuted)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(packet.TargetUserId))
|
|
||||||
{
|
|
||||||
recipientIds = session.Participants
|
|
||||||
.Where(p => string.Equals(p.UserId, packet.TargetUserId, StringComparison.OrdinalIgnoreCase) &&
|
|
||||||
!string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase) &&
|
|
||||||
!p.IsDeafened)
|
|
||||||
.Select(p => p.UserId)
|
|
||||||
.ToList();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
recipientIds = session.Participants
|
|
||||||
.Where(p => !string.Equals(p.UserId, client.User.Id, StringComparison.OrdinalIgnoreCase) && !p.IsDeafened)
|
|
||||||
.Select(p => p.UserId)
|
|
||||||
.ToList();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (recipientIds.Count == 0) return;
|
|
||||||
|
|
||||||
var relayPacket = new VoiceAudioFramePacket
|
|
||||||
{
|
|
||||||
ChannelId = packet.ChannelId,
|
|
||||||
SenderUserId = client.User.Id,
|
|
||||||
SenderUsername = client.User.Username,
|
|
||||||
TargetUserId = packet.TargetUserId,
|
|
||||||
Sequence = packet.Sequence,
|
|
||||||
Codec = string.IsNullOrWhiteSpace(packet.Codec) ? "ulaw-16k" : packet.Codec,
|
|
||||||
DataBase64 = packet.DataBase64,
|
|
||||||
IsEncrypted = packet.IsEncrypted || E2eeCrypto.IsVoiceEncryptedPayload(packet.DataBase64),
|
|
||||||
SenderPublicKey = !string.IsNullOrWhiteSpace(packet.SenderPublicKey) ? packet.SenderPublicKey : client.User.PublicKey,
|
|
||||||
SpeakingLevel = Math.Clamp(packet.SpeakingLevel, 0f, 1f)
|
|
||||||
};
|
|
||||||
|
|
||||||
await BroadcastToMembersAsync(recipientIds, MessageTypes.VoiceAudioFrame, relayPacket);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,25 +13,6 @@
|
||||||
"AllowMemberChannelCreation": true,
|
"AllowMemberChannelCreation": true,
|
||||||
"AllowDmE2ee": 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"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"RateLimitRequestsPerMinute": 60,
|
"RateLimitRequestsPerMinute": 60,
|
||||||
"MaxConnectionsPerIp": 10,
|
"MaxConnectionsPerIp": 10,
|
||||||
"MaxGlobalConnections": 100,
|
"MaxGlobalConnections": 100,
|
||||||
|
|
|
||||||
|
|
@ -1252,133 +1252,6 @@ html, body {
|
||||||
letter-spacing: 0.05em;
|
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
|
Mobile Responsive Styles
|
||||||
========================================================================== */
|
========================================================================== */
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -93,7 +93,6 @@
|
||||||
<span class="channel-topic" id="activeChannelTopic"></span>
|
<span class="channel-topic" id="activeChannelTopic"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="chat-header-actions">
|
<div class="chat-header-actions">
|
||||||
<button type="button" class="btn btn-sm btn-primary" id="voiceCallBtn" title="Start or Join Voice Call">[📞 Call]</button>
|
|
||||||
<button type="button" class="btn btn-sm btn-secondary" id="toggleFollowBtn" title="Follow or Mute notifications for this conversation">[🔔 Follow]</button>
|
<button type="button" class="btn btn-sm btn-secondary" id="toggleFollowBtn" title="Follow or Mute notifications for this conversation">[🔔 Follow]</button>
|
||||||
<button type="button" class="btn btn-sm btn-secondary" id="toggleDmE2eeBtn" style="display:none;" title="Toggle E2EE for this Direct Message">[DM E2EE: ON]</button>
|
<button type="button" class="btn btn-sm btn-secondary" id="toggleDmE2eeBtn" style="display:none;" title="Toggle E2EE for this Direct Message">[DM E2EE: ON]</button>
|
||||||
<button type="button" class="btn btn-sm btn-secondary" id="inviteGroupBtn" style="display:none;" title="Invite User to Group">[+ Invite]</button>
|
<button type="button" class="btn btn-sm btn-secondary" id="inviteGroupBtn" style="display:none;" title="Invite User to Group">[+ Invite]</button>
|
||||||
|
|
@ -104,35 +103,6 @@
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Active Voice Call Bar -->
|
|
||||||
<div id="voiceCallBar" class="voice-call-bar" style="display:none;">
|
|
||||||
<div class="voice-call-info">
|
|
||||||
<span class="voice-status-dot" id="voiceStatusDot"></span>
|
|
||||||
<span class="voice-status-text" id="voiceCallStatusText">Voice Call Active</span>
|
|
||||||
<span class="voice-badge voice-transport-badge" id="voiceTransportBadge" title="Active VoIP Transport">[P2P STUN]</span>
|
|
||||||
<span class="voice-badge voice-e2ee-badge" id="voiceE2eeBadge" style="display:none;" title="End-to-End Encrypted Voice Stream">[🔒 E2EE Voice]</span>
|
|
||||||
<span class="voice-timer" id="voiceCallTimer">00:00</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="voice-participants-list" id="voiceParticipantsList">
|
|
||||||
<!-- Populated by JS -->
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="voice-call-controls" id="voiceCallControls">
|
|
||||||
<button type="button" class="btn btn-sm btn-primary" id="voiceJoinRoomBtn" style="display:none;">[📞 Join Voice]</button>
|
|
||||||
<button type="button" class="btn btn-sm btn-secondary" id="voiceMuteBtn" title="Toggle Microphone Mute">[🎤 Mute]</button>
|
|
||||||
<button type="button" class="btn btn-sm btn-secondary" id="voiceDeafenBtn" title="Toggle Audio Deafen">[🎧 Deafen]</button>
|
|
||||||
<button type="button" class="btn btn-sm btn-secondary" id="voiceForceRelayBtn" title="Switch between Direct P2P (STUN/TURN) and Single-Port WebSocket TURN Relay">[⇄ Auto P2P]</button>
|
|
||||||
<select class="voice-device-select" id="voiceMicSelect" title="Select Microphone Input Device">
|
|
||||||
<option value="">Default Mic</option>
|
|
||||||
</select>
|
|
||||||
<select class="voice-device-select" id="voiceSpeakerSelect" title="Select Speaker Output Device">
|
|
||||||
<option value="">Default Speaker</option>
|
|
||||||
</select>
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-danger" id="voiceHangupBtn" title="Hang Up / Leave Voice Call">[🔴 Hang Up]</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="chat-content-container">
|
<div class="chat-content-container">
|
||||||
<div class="chat-main-area">
|
<div class="chat-main-area">
|
||||||
<div class="chat-messages" id="chatMessages">
|
<div class="chat-messages" id="chatMessages">
|
||||||
|
|
@ -312,24 +282,6 @@
|
||||||
<!-- Toast Notification Overlay -->
|
<!-- Toast Notification Overlay -->
|
||||||
<div id="toastContainer" class="toast-container"></div>
|
<div id="toastContainer" class="toast-container"></div>
|
||||||
|
|
||||||
<!-- Hidden Remote Audio Elements Container -->
|
|
||||||
<div id="voiceRemoteAudioContainer" style="display:none;"></div>
|
|
||||||
|
|
||||||
<!-- Incoming Voice Call Modal -->
|
|
||||||
<div id="incomingCallModal" class="modal-backdrop" style="display:none;">
|
|
||||||
<div class="modal-card incoming-call-card">
|
|
||||||
<div class="modal-header">
|
|
||||||
<div class="modal-badge incoming-call-pulse">[ 📞 INCOMING VOICE CALL ]</div>
|
|
||||||
<h2 id="incomingCallerName">@username</h2>
|
|
||||||
<p class="modal-motd" id="incomingCallSecurityHint">Direct P2P STUN/TURN + Single-Port Relay Fallback</p>
|
|
||||||
</div>
|
|
||||||
<div class="form-actions" style="justify-content:center; gap:12px; margin-top:16px;">
|
|
||||||
<button type="button" class="btn btn-primary" id="acceptIncomingCallBtn">[ 📞 Accept Call ]</button>
|
|
||||||
<button type="button" class="btn btn-outline-danger" id="declineIncomingCallBtn">[ ✖ Decline ]</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- E2EE PIN / Key Vault Modal -->
|
<!-- E2EE PIN / Key Vault Modal -->
|
||||||
<div id="e2eeModal" class="modal-backdrop" style="display:none;">
|
<div id="e2eeModal" class="modal-backdrop" style="display:none;">
|
||||||
<div class="modal-card">
|
<div class="modal-card">
|
||||||
|
|
|
||||||
|
|
@ -1,513 +0,0 @@
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.IO;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Net;
|
|
||||||
using System.Net.Sockets;
|
|
||||||
using System.Security.Cryptography;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using Microsoft.AspNetCore.Builder;
|
|
||||||
using Microsoft.AspNetCore.Hosting;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using GsDChat.Client.Network;
|
|
||||||
using GsDChat.Client.State;
|
|
||||||
using GsDChat.Core.Models;
|
|
||||||
using GsDChat.Core.Protocol;
|
|
||||||
using GsDChat.Core.Security;
|
|
||||||
using GsDChat.Server.Configuration;
|
|
||||||
using GsDChat.Server.Data;
|
|
||||||
using GsDChat.Server.Services;
|
|
||||||
using GsDChat.Server.WebSockets;
|
|
||||||
using Xunit;
|
|
||||||
|
|
||||||
namespace GsDChat.Tests;
|
|
||||||
|
|
||||||
public class VoiceCallTests : IAsyncLifetime
|
|
||||||
{
|
|
||||||
private readonly string _testDir;
|
|
||||||
private WebApplication? _app;
|
|
||||||
private int _port;
|
|
||||||
private string _serverUrl = string.Empty;
|
|
||||||
|
|
||||||
public VoiceCallTests()
|
|
||||||
{
|
|
||||||
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_voice_tests_" + Guid.NewGuid().ToString("N"));
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task InitializeAsync()
|
|
||||||
{
|
|
||||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
|
||||||
listener.Start();
|
|
||||||
_port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
||||||
listener.Stop();
|
|
||||||
|
|
||||||
_serverUrl = $"http://127.0.0.1:{_port}";
|
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder();
|
|
||||||
builder.WebHost.UseUrls(_serverUrl);
|
|
||||||
builder.Logging.ClearProviders();
|
|
||||||
|
|
||||||
var (vapidPub, vapidPriv) = WebPushCrypto.GenerateVapidKeys();
|
|
||||||
var serverOptions = new ServerOptions
|
|
||||||
{
|
|
||||||
Host = "127.0.0.1",
|
|
||||||
Port = _port,
|
|
||||||
UseTls = false,
|
|
||||||
DataDirectory = _testDir,
|
|
||||||
ServerName = "Voice Call Test Server",
|
|
||||||
EnableVoiceCalls = true,
|
|
||||||
AllowVoiceRelayFallback = true,
|
|
||||||
MaxVoiceCallUsers = 8,
|
|
||||||
StunServers = new List<string> { "stun:stun.l.google.com:19302" },
|
|
||||||
TurnServers = new List<IceServerConfig>
|
|
||||||
{
|
|
||||||
new IceServerConfig
|
|
||||||
{
|
|
||||||
Urls = new List<string> { "turn:turn.example.org:3478?transport=tcp" },
|
|
||||||
Username = "turnuser",
|
|
||||||
Credential = "turnpass"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
VapidPublicKey = vapidPub,
|
|
||||||
VapidPrivateKey = vapidPriv
|
|
||||||
};
|
|
||||||
|
|
||||||
builder.Services.AddSingleton(serverOptions);
|
|
||||||
builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory));
|
|
||||||
builder.Services.AddSingleton<InviteTokenService>();
|
|
||||||
builder.Services.AddSingleton<IAuthService, AuthService>();
|
|
||||||
builder.Services.AddSingleton<FileStorageService>();
|
|
||||||
builder.Services.AddSingleton<WebPushService>();
|
|
||||||
builder.Services.AddSingleton<ChatWebSocketManager>();
|
|
||||||
builder.Services.AddSingleton<CsrfProtectionService>();
|
|
||||||
|
|
||||||
_app = builder.Build();
|
|
||||||
|
|
||||||
var db = _app.Services.GetRequiredService<ChatDatabase>();
|
|
||||||
await db.InitializeAsync();
|
|
||||||
|
|
||||||
_app.UseWebSockets();
|
|
||||||
|
|
||||||
_app.MapGet("/api/csrf-token", (CsrfProtectionService csrf) =>
|
|
||||||
{
|
|
||||||
var token = csrf.GenerateToken();
|
|
||||||
return Results.Ok(new { token });
|
|
||||||
});
|
|
||||||
|
|
||||||
_app.MapGet("/api/info", (ServerOptions opt) => Results.Ok(new ServerInfoResponse
|
|
||||||
{
|
|
||||||
ServerName = opt.ServerName,
|
|
||||||
Version = "1.0.0",
|
|
||||||
RegistrationMode = opt.RegistrationMode,
|
|
||||||
AllowDmE2ee = opt.AllowDmE2ee,
|
|
||||||
MaxGroupChatUsers = opt.MaxGroupChatUsers,
|
|
||||||
EnableVoiceCalls = opt.EnableVoiceCalls,
|
|
||||||
AllowVoiceRelayFallback = opt.AllowVoiceRelayFallback,
|
|
||||||
MaxVoiceCallUsers = opt.MaxVoiceCallUsers,
|
|
||||||
IceServers = opt.GetIceServers()
|
|
||||||
}));
|
|
||||||
|
|
||||||
_app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth) =>
|
|
||||||
{
|
|
||||||
var res = await auth.RegisterAsync(req);
|
|
||||||
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
|
||||||
});
|
|
||||||
|
|
||||||
_app.MapPost("/api/auth/login", async (LoginRequest req, IAuthService auth) =>
|
|
||||||
{
|
|
||||||
var res = await auth.LoginAsync(req);
|
|
||||||
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
|
||||||
});
|
|
||||||
|
|
||||||
_app.MapGet("/ws", async (HttpContext context, ChatWebSocketManager wsManager, IAuthService auth, ServerOptions options) =>
|
|
||||||
{
|
|
||||||
if (!context.WebSockets.IsWebSocketRequest)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 400;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
string? token = null;
|
|
||||||
if (context.Request.Headers.TryGetValue("Authorization", out var h) && h.ToString().StartsWith("Bearer "))
|
|
||||||
token = h.ToString().Substring(7).Trim();
|
|
||||||
else if (context.Request.Query.TryGetValue("token", out var q))
|
|
||||||
token = q.ToString();
|
|
||||||
|
|
||||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
|
||||||
if (user == null)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = 401;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
using var ws = await context.WebSockets.AcceptWebSocketAsync();
|
|
||||||
await wsManager.HandleClientAsync(ws, user, context.RequestAborted, options.MaxWebSocketMessageSizeBytes);
|
|
||||||
});
|
|
||||||
|
|
||||||
await _app.StartAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task DisposeAsync()
|
|
||||||
{
|
|
||||||
if (_app != null)
|
|
||||||
{
|
|
||||||
await _app.StopAsync();
|
|
||||||
await _app.DisposeAsync();
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (Directory.Exists(_testDir))
|
|
||||||
{
|
|
||||||
Directory.Delete(_testDir, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch { }
|
|
||||||
}
|
|
||||||
|
|
||||||
private ClientState CreateClientState(string name)
|
|
||||||
{
|
|
||||||
return new ClientState(Path.Combine(_testDir, $"e2ee_{name}.json"))
|
|
||||||
{
|
|
||||||
ServerUrl = _serverUrl
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<bool> WaitUntilAsync(Func<bool> condition, int timeoutMs = 4000)
|
|
||||||
{
|
|
||||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
|
||||||
while (sw.ElapsedMilliseconds < timeoutMs)
|
|
||||||
{
|
|
||||||
if (condition()) return true;
|
|
||||||
await Task.Delay(25);
|
|
||||||
}
|
|
||||||
return condition();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void G711AudioCodec_MuLawRoundTrip_ShouldPreserveSineWaveAndComputeRms()
|
|
||||||
{
|
|
||||||
const int sampleCount = 640; // 40ms @ 16kHz
|
|
||||||
byte[] pcm16 = new byte[sampleCount * 2];
|
|
||||||
|
|
||||||
for (int i = 0; i < sampleCount; i++)
|
|
||||||
{
|
|
||||||
short sample = (short)(Math.Sin(2.0 * Math.PI * 440.0 * i / 16000.0) * 4000);
|
|
||||||
pcm16[i * 2] = (byte)(sample & 0xFF);
|
|
||||||
pcm16[i * 2 + 1] = (byte)((sample >> 8) & 0xFF);
|
|
||||||
}
|
|
||||||
|
|
||||||
Assert.Equal(0f, G711AudioCodec.ComputeRmsLevelFromPcm16(new byte[128]));
|
|
||||||
|
|
||||||
double rmsPcm = G711AudioCodec.ComputeRmsLevelFromPcm16(pcm16);
|
|
||||||
Assert.InRange(rmsPcm, 0.20, 0.35);
|
|
||||||
|
|
||||||
byte[] muLaw = G711AudioCodec.EncodePcm16ToMuLaw(pcm16);
|
|
||||||
Assert.Equal(sampleCount, muLaw.Length);
|
|
||||||
|
|
||||||
double rmsMuLaw = G711AudioCodec.ComputeRmsLevelFromMuLaw(muLaw);
|
|
||||||
Assert.InRange(rmsMuLaw, 0.20, 0.35);
|
|
||||||
|
|
||||||
byte[] decodedPcm16 = G711AudioCodec.DecodeMuLawToPcm16(muLaw);
|
|
||||||
Assert.Equal(pcm16.Length, decodedPcm16.Length);
|
|
||||||
|
|
||||||
// Verify G.711 logarithmic quantization stays close to original signal
|
|
||||||
for (int i = 0; i < sampleCount; i++)
|
|
||||||
{
|
|
||||||
short orig = (short)(pcm16[i * 2] | (pcm16[i * 2 + 1] << 8));
|
|
||||||
short dec = (short)(decodedPcm16[i * 2] | (decodedPcm16[i * 2 + 1] << 8));
|
|
||||||
Assert.True(Math.Abs(orig - dec) <= 750, $"Sample {i} delta too large: orig={orig}, dec={dec}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void E2eeCrypto_VoiceAudioFrameEncryption_ShouldRoundTripAndRejectTampering()
|
|
||||||
{
|
|
||||||
var (alicePub, alicePriv) = E2eeCrypto.GenerateKeyPair();
|
|
||||||
var (bobPub, bobPriv) = E2eeCrypto.GenerateKeyPair();
|
|
||||||
|
|
||||||
byte[] originalAudio = new byte[640];
|
|
||||||
RandomNumberGenerator.Fill(originalAudio);
|
|
||||||
|
|
||||||
string encryptedFrame = E2eeCrypto.EncryptAudioFrame(originalAudio, alicePriv, bobPub);
|
|
||||||
Assert.True(E2eeCrypto.IsVoiceEncryptedPayload(encryptedFrame));
|
|
||||||
Assert.StartsWith("VENC:v1:", encryptedFrame);
|
|
||||||
|
|
||||||
byte[]? decryptedByBob = E2eeCrypto.DecryptAudioFrame(encryptedFrame, bobPriv, alicePub);
|
|
||||||
Assert.NotNull(decryptedByBob);
|
|
||||||
Assert.Equal(originalAudio, decryptedByBob);
|
|
||||||
|
|
||||||
// Tamper with a third party's keypair -> should fail authentication tag verification
|
|
||||||
var (_, malloryPriv) = E2eeCrypto.GenerateKeyPair();
|
|
||||||
byte[]? decryptedByMallory = E2eeCrypto.DecryptAudioFrame(encryptedFrame, malloryPriv, alicePub);
|
|
||||||
Assert.Null(decryptedByMallory);
|
|
||||||
|
|
||||||
// Also test ephemeral UDP P2P session key encryption
|
|
||||||
byte[] sessionKey = RandomNumberGenerator.GetBytes(32);
|
|
||||||
string encryptedUdpPayload = E2eeCrypto.EncryptWithSessionKey(originalAudio, sessionKey);
|
|
||||||
Assert.True(E2eeCrypto.IsVoiceEncryptedPayload(encryptedUdpPayload));
|
|
||||||
|
|
||||||
byte[]? decryptedUdpPacket = E2eeCrypto.DecryptWithSessionKey(encryptedUdpPayload, sessionKey);
|
|
||||||
Assert.NotNull(decryptedUdpPacket);
|
|
||||||
Assert.Equal(originalAudio, decryptedUdpPacket);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task StunClient_BindingRequestAndResponse_ShouldDiscoverXorMappedEndpoint()
|
|
||||||
{
|
|
||||||
var (host, port) = StunClient.ParseStunUri("stun:stun.l.google.com:19302");
|
|
||||||
Assert.Equal("stun.l.google.com", host);
|
|
||||||
Assert.Equal(19302, port);
|
|
||||||
|
|
||||||
// Spin up a local loopback RFC 5389 STUN responder
|
|
||||||
using var stunServerSocket = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));
|
|
||||||
int stunPort = ((IPEndPoint)stunServerSocket.Client.LocalEndPoint!).Port;
|
|
||||||
|
|
||||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
|
||||||
var responderTask = Task.Run(async () =>
|
|
||||||
{
|
|
||||||
var received = await stunServerSocket.ReceiveAsync(cts.Token);
|
|
||||||
Assert.True(received.Buffer.Length >= 20);
|
|
||||||
ReadOnlySpan<byte> txId = received.Buffer.AsSpan(8, 12);
|
|
||||||
byte[] response = StunClient.CreateBindingSuccessResponse(txId, received.RemoteEndPoint);
|
|
||||||
await stunServerSocket.SendAsync(response, response.Length, received.RemoteEndPoint);
|
|
||||||
}, cts.Token);
|
|
||||||
|
|
||||||
using var clientSocket = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0));
|
|
||||||
int expectedLocalPort = ((IPEndPoint)clientSocket.Client.LocalEndPoint!).Port;
|
|
||||||
|
|
||||||
IPEndPoint? discovered = await StunClient.QueryPublicEndpointAsync(
|
|
||||||
clientSocket,
|
|
||||||
$"stun:127.0.0.1:{stunPort}",
|
|
||||||
cts.Token);
|
|
||||||
|
|
||||||
await responderTask;
|
|
||||||
|
|
||||||
Assert.NotNull(discovered);
|
|
||||||
Assert.Equal(IPAddress.Loopback, discovered!.Address);
|
|
||||||
Assert.Equal(expectedLocalPort, discovered.Port);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ServerOptions_GetIceServers_ShouldIncludeStunAndTurnCredentials()
|
|
||||||
{
|
|
||||||
var opts = new ServerOptions
|
|
||||||
{
|
|
||||||
StunServers = new List<string> { "stun:stun.l.google.com:19302" },
|
|
||||||
TurnServers = new List<IceServerConfig>
|
|
||||||
{
|
|
||||||
new IceServerConfig
|
|
||||||
{
|
|
||||||
Urls = new List<string> { "turns:turn.example.com:443?transport=tcp" },
|
|
||||||
Username = "alice",
|
|
||||||
Credential = "secret123"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
var ice = opts.GetIceServers();
|
|
||||||
Assert.Equal(2, ice.Count);
|
|
||||||
Assert.Contains("stun:stun.l.google.com:19302", ice[0].Urls);
|
|
||||||
Assert.Null(ice[0].Username);
|
|
||||||
|
|
||||||
Assert.Contains("turns:turn.example.com:443?transport=tcp", ice[1].Urls);
|
|
||||||
Assert.Equal("alice", ice[1].Username);
|
|
||||||
Assert.Equal("secret123", ice[1].Credential);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task DirectMessageVoiceCall_RingingAcceptAndEncryptedSinglePortRelay_ShouldSucceed()
|
|
||||||
{
|
|
||||||
var aliceState = CreateClientState("alice");
|
|
||||||
var bobState = CreateClientState("bob");
|
|
||||||
|
|
||||||
using var alice = new ChatClientConnection(aliceState, allowInsecure: true);
|
|
||||||
using var bob = new ChatClientConnection(bobState, allowInsecure: true);
|
|
||||||
|
|
||||||
var aliceReg = await alice.RegisterAsync("voice_alice", "Pass123!", null, null);
|
|
||||||
var bobReg = await bob.RegisterAsync("voice_bob", "Pass123!", null, null);
|
|
||||||
Assert.True(aliceReg.Success);
|
|
||||||
Assert.True(bobReg.Success);
|
|
||||||
|
|
||||||
await alice.StartWebSocketAsync();
|
|
||||||
await bob.StartWebSocketAsync();
|
|
||||||
|
|
||||||
await alice.UnlockOrInitializeE2eeWithPinAsync("1111");
|
|
||||||
await bob.UnlockOrInitializeE2eeWithPinAsync("2222");
|
|
||||||
|
|
||||||
Assert.True(await WaitUntilAsync(() => aliceState.Channels.Count > 0 && bobState.Channels.Count > 0));
|
|
||||||
|
|
||||||
// Start a DM between Alice and Bob
|
|
||||||
await alice.StartDmAsync("voice_bob");
|
|
||||||
Assert.True(await WaitUntilAsync(() => aliceState.DirectMessages.Count == 1 && bobState.DirectMessages.Count == 1));
|
|
||||||
string dmChannelId = aliceState.DirectMessages[0].Id;
|
|
||||||
|
|
||||||
// 1. Alice starts a DM voice call -> state becomes 'Ringing'
|
|
||||||
await alice.StartVoiceCallAsync(dmChannelId);
|
|
||||||
|
|
||||||
Assert.True(await WaitUntilAsync(() =>
|
|
||||||
bobState.ActiveVoiceCalls.TryGetValue(dmChannelId, out var s) &&
|
|
||||||
s.Status == VoiceCallStatus.Ringing));
|
|
||||||
|
|
||||||
// 2. Bob accepts the DM voice call -> state becomes 'Active' with both participants
|
|
||||||
await bob.AcceptVoiceCallAsync(dmChannelId);
|
|
||||||
|
|
||||||
Assert.True(await WaitUntilAsync(() =>
|
|
||||||
aliceState.ActiveVoiceCalls.TryGetValue(dmChannelId, out var s) &&
|
|
||||||
s.Status == VoiceCallStatus.Active &&
|
|
||||||
s.Participants.Count == 2));
|
|
||||||
|
|
||||||
// 3. Test Single-Port WebSocket Audio Relay with E2EE encrypted voice frame
|
|
||||||
int prevFrames = bobState.VoiceFramesReceivedCount;
|
|
||||||
byte[] samplePcm16 = new byte[1280]; // 640 samples (40ms @ 16kHz)
|
|
||||||
for (int i = 0; i < 640; i++)
|
|
||||||
{
|
|
||||||
short val = (short)(Math.Sin(2.0 * Math.PI * 440.0 * i / 16000.0) * 12000);
|
|
||||||
samplePcm16[i * 2] = (byte)(val & 0xFF);
|
|
||||||
samplePcm16[i * 2 + 1] = (byte)((val >> 8) & 0xFF);
|
|
||||||
}
|
|
||||||
|
|
||||||
byte[] sampleMuLaw = G711AudioCodec.EncodePcm16ToMuLaw(samplePcm16);
|
|
||||||
string encryptedPayload = E2eeCrypto.EncryptAudioFrame(
|
|
||||||
sampleMuLaw,
|
|
||||||
aliceState.PrivateKeyBase64,
|
|
||||||
bobState.PublicKeyBase64);
|
|
||||||
|
|
||||||
await alice.SendVoiceAudioFrameAsync(new VoiceAudioFramePacket
|
|
||||||
{
|
|
||||||
ChannelId = dmChannelId,
|
|
||||||
Sequence = 42,
|
|
||||||
Codec = "ulaw-16k",
|
|
||||||
DataBase64 = encryptedPayload,
|
|
||||||
IsEncrypted = true,
|
|
||||||
SenderPublicKey = aliceState.PublicKeyBase64,
|
|
||||||
SpeakingLevel = 0.25f
|
|
||||||
});
|
|
||||||
|
|
||||||
Assert.True(await WaitUntilAsync(() => bobState.VoiceFramesReceivedCount > prevFrames));
|
|
||||||
Assert.Equal(aliceReg.UserId, bobState.LastVoiceFrameSenderId);
|
|
||||||
Assert.NotNull(bobState.LastReceivedVoiceMuLaw);
|
|
||||||
Assert.Equal(sampleMuLaw, bobState.LastReceivedVoiceMuLaw);
|
|
||||||
Assert.NotNull(bobState.LastReceivedVoicePcm16);
|
|
||||||
Assert.Equal(1280, bobState.LastReceivedVoicePcm16!.Length);
|
|
||||||
|
|
||||||
// 4. Alice hangs up -> DM call ends
|
|
||||||
await alice.LeaveVoiceCallAsync(dmChannelId);
|
|
||||||
Assert.True(await WaitUntilAsync(() => !bobState.ActiveVoiceCalls.ContainsKey(dmChannelId)));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task DirectMessageVoiceCall_DeclineRingingCall_ShouldEndCallSession()
|
|
||||||
{
|
|
||||||
var aliceState = CreateClientState("decline_alice");
|
|
||||||
var bobState = CreateClientState("decline_bob");
|
|
||||||
|
|
||||||
using var alice = new ChatClientConnection(aliceState, allowInsecure: true);
|
|
||||||
using var bob = new ChatClientConnection(bobState, allowInsecure: true);
|
|
||||||
|
|
||||||
var aliceReg = await alice.RegisterAsync("decline_alice", "Pass123!", null, null);
|
|
||||||
var bobReg = await bob.RegisterAsync("decline_bob", "Pass123!", null, null);
|
|
||||||
Assert.True(aliceReg.Success);
|
|
||||||
Assert.True(bobReg.Success);
|
|
||||||
|
|
||||||
await alice.StartWebSocketAsync();
|
|
||||||
await bob.StartWebSocketAsync();
|
|
||||||
|
|
||||||
Assert.True(await WaitUntilAsync(() => aliceState.Channels.Count > 0 && bobState.Channels.Count > 0));
|
|
||||||
|
|
||||||
await alice.StartDmAsync("decline_bob");
|
|
||||||
Assert.True(await WaitUntilAsync(() => aliceState.DirectMessages.Count == 1 && bobState.DirectMessages.Count == 1));
|
|
||||||
string dmChannelId = aliceState.DirectMessages[0].Id;
|
|
||||||
|
|
||||||
await alice.StartVoiceCallAsync(dmChannelId);
|
|
||||||
Assert.True(await WaitUntilAsync(() =>
|
|
||||||
bobState.ActiveVoiceCalls.TryGetValue(dmChannelId, out var s) &&
|
|
||||||
s.Status == VoiceCallStatus.Ringing));
|
|
||||||
|
|
||||||
await bob.DeclineVoiceCallAsync(dmChannelId);
|
|
||||||
Assert.True(await WaitUntilAsync(() =>
|
|
||||||
!aliceState.ActiveVoiceCalls.ContainsKey(dmChannelId) &&
|
|
||||||
!bobState.ActiveVoiceCalls.ContainsKey(dmChannelId)));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task ChannelVoiceRoom_MultiPeerJoinStateUpdateAndRelay_ShouldSucceed()
|
|
||||||
{
|
|
||||||
var s1 = CreateClientState("room_u1");
|
|
||||||
var s2 = CreateClientState("room_u2");
|
|
||||||
var s3 = CreateClientState("room_u3");
|
|
||||||
|
|
||||||
using var user1 = new ChatClientConnection(s1, allowInsecure: true);
|
|
||||||
using var user2 = new ChatClientConnection(s2, allowInsecure: true);
|
|
||||||
using var user3 = new ChatClientConnection(s3, allowInsecure: true);
|
|
||||||
|
|
||||||
var r1 = await user1.RegisterAsync("room_u1", "Pass123!", null, null);
|
|
||||||
var r2 = await user2.RegisterAsync("room_u2", "Pass123!", null, null);
|
|
||||||
var r3 = await user3.RegisterAsync("room_u3", "Pass123!", null, null);
|
|
||||||
Assert.True(r1.Success);
|
|
||||||
Assert.True(r2.Success);
|
|
||||||
Assert.True(r3.Success);
|
|
||||||
|
|
||||||
await user1.StartWebSocketAsync();
|
|
||||||
await user2.StartWebSocketAsync();
|
|
||||||
await user3.StartWebSocketAsync();
|
|
||||||
|
|
||||||
Assert.True(await WaitUntilAsync(() =>
|
|
||||||
s1.Channels.Count > 0 &&
|
|
||||||
s2.Channels.Count > 0 &&
|
|
||||||
s3.Channels.Count > 0));
|
|
||||||
|
|
||||||
string generalChannelId = s1.Channels[0].Id;
|
|
||||||
|
|
||||||
// User 1 starts voice room in #general -> immediately Active
|
|
||||||
await user1.StartVoiceCallAsync(generalChannelId);
|
|
||||||
|
|
||||||
Assert.True(await WaitUntilAsync(() =>
|
|
||||||
s2.ActiveVoiceCalls.TryGetValue(generalChannelId, out var s) &&
|
|
||||||
s.Status == VoiceCallStatus.Active &&
|
|
||||||
s.Participants.Count == 1));
|
|
||||||
|
|
||||||
// User 2 and User 3 join the voice room
|
|
||||||
await user2.StartVoiceCallAsync(generalChannelId);
|
|
||||||
await user3.StartVoiceCallAsync(generalChannelId);
|
|
||||||
|
|
||||||
Assert.True(await WaitUntilAsync(() =>
|
|
||||||
s1.ActiveVoiceCalls.TryGetValue(generalChannelId, out var s) &&
|
|
||||||
s.Participants.Count == 3));
|
|
||||||
|
|
||||||
// User 2 mutes microphone and switches to relay mode -> broadcast to room
|
|
||||||
await user2.ToggleVoiceMuteAsync(true);
|
|
||||||
await user2.ToggleVoiceRelayModeAsync(true);
|
|
||||||
|
|
||||||
Assert.True(await WaitUntilAsync(() =>
|
|
||||||
{
|
|
||||||
if (!s1.ActiveVoiceCalls.TryGetValue(generalChannelId, out var s)) return false;
|
|
||||||
var p2 = s.Participants.FirstOrDefault(p => p.UserId == r2.UserId);
|
|
||||||
return p2 != null && p2.IsMuted && p2.TransportMode == VoiceTransportModes.Relay;
|
|
||||||
}));
|
|
||||||
|
|
||||||
// User 1 sends a relayed audio frame -> both User 2 and User 3 receive it, but User 1 does not echo to self
|
|
||||||
byte[] testMuLaw = new byte[640];
|
|
||||||
Array.Fill(testMuLaw, (byte)0x7F);
|
|
||||||
|
|
||||||
await user1.SendVoiceAudioFrameAsync(new VoiceAudioFramePacket
|
|
||||||
{
|
|
||||||
ChannelId = generalChannelId,
|
|
||||||
Sequence = 7,
|
|
||||||
Codec = "ulaw-16k",
|
|
||||||
DataBase64 = Convert.ToBase64String(testMuLaw),
|
|
||||||
SpeakingLevel = 0.2f
|
|
||||||
});
|
|
||||||
|
|
||||||
Assert.True(await WaitUntilAsync(() =>
|
|
||||||
s2.VoiceFramesReceivedCount > 0 &&
|
|
||||||
s3.VoiceFramesReceivedCount > 0));
|
|
||||||
|
|
||||||
Assert.Equal(0, s1.VoiceFramesReceivedCount);
|
|
||||||
Assert.Equal(testMuLaw, s2.LastReceivedVoiceMuLaw);
|
|
||||||
Assert.Equal(testMuLaw, s3.LastReceivedVoiceMuLaw);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -109,16 +109,10 @@ public class WebClientStaticTests : IAsyncLifetime
|
||||||
Assert.Contains("id=\"navTabInbox\"", html);
|
Assert.Contains("id=\"navTabInbox\"", html);
|
||||||
Assert.Contains("id=\"inboxUnreadBadge\"", html);
|
Assert.Contains("id=\"inboxUnreadBadge\"", html);
|
||||||
Assert.Contains("id=\"toggleWebPushBtn\"", html);
|
Assert.Contains("id=\"toggleWebPushBtn\"", html);
|
||||||
Assert.Contains("id=\"navTabInbox\"", html);
|
|
||||||
Assert.Contains("id=\"inboxUnreadBadge\"", html);
|
|
||||||
Assert.Contains("id=\"toggleWebPushBtn\"", html);
|
|
||||||
Assert.Contains("id=\"desktopNotifBanner\"", html);
|
Assert.Contains("id=\"desktopNotifBanner\"", html);
|
||||||
Assert.Contains("id=\"bannerEnablePushBtn\"", html);
|
Assert.Contains("id=\"bannerEnablePushBtn\"", html);
|
||||||
Assert.Contains("id=\"headerPushBtn\"", html);
|
Assert.Contains("id=\"headerPushBtn\"", html);
|
||||||
Assert.Contains("rel=\"icon\"", html);
|
Assert.Contains("rel=\"icon\"", html);
|
||||||
Assert.Contains("id=\"voiceCallBtn\"", html);
|
|
||||||
Assert.Contains("id=\"voiceCallBar\"", html);
|
|
||||||
Assert.Contains("id=\"incomingCallModal\"", html);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|
@ -136,9 +130,6 @@ public class WebClientStaticTests : IAsyncLifetime
|
||||||
Assert.Contains(".inbox-item", css);
|
Assert.Contains(".inbox-item", css);
|
||||||
Assert.Contains(".inbox-badge", css);
|
Assert.Contains(".inbox-badge", css);
|
||||||
Assert.Contains(".notif-banner", css);
|
Assert.Contains(".notif-banner", css);
|
||||||
Assert.Contains(".voice-call-bar", css);
|
|
||||||
Assert.Contains(".voice-participant-chip", css);
|
|
||||||
Assert.Contains(".incoming-call-card", css);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|
@ -164,12 +155,6 @@ public class WebClientStaticTests : IAsyncLifetime
|
||||||
Assert.Contains("initServiceWorkerAndPush", js);
|
Assert.Contains("initServiceWorkerAndPush", js);
|
||||||
Assert.Contains("markActiveChannelInboxRead", js);
|
Assert.Contains("markActiveChannelInboxRead", js);
|
||||||
Assert.Contains("deleteFile", js);
|
Assert.Contains("deleteFile", js);
|
||||||
Assert.Contains("VOICE_CALL_START", js);
|
|
||||||
Assert.Contains("VOICE_CALL_STATE", js);
|
|
||||||
Assert.Contains("VOICE_SIGNAL", js);
|
|
||||||
Assert.Contains("VOICE_AUDIO_FRAME", js);
|
|
||||||
Assert.Contains("encryptVoiceFrame", js);
|
|
||||||
Assert.Contains("decryptVoiceFrame", js);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue