feat/calls #62
26 changed files with 384 additions and 94 deletions
Add audio-only WebRTC calls
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
commit
97e197996f
|
|
@ -6,6 +6,8 @@
|
|||
|
||||
### Added
|
||||
|
||||
* [PostIt/Chat] Add audio-only WebRTC calls on Linux and Android with the user's avatar as a static image, microphone-only capture, dedicated navigation and capability-aware invitations. Keep direct SRTP audio-video only; add signaling, UI and Linux native-media regressions.
|
||||
|
||||
* [PostIt/Chat] Filter video invitations and private messages by announced per-connection preferences, stop affected calls when preferences change, and prepare mode-aware audio signaling. Audio-only calls and static images are not implemented yet; legacy clients without preferences remain reachable.
|
||||
|
||||
* [PostIt/Chat] Persist audio, audio-video and private-message contact preferences and announce them to ChatHub on connection and reconnection. Add the audio-only call display contract; filtering contacts and audio-only media are not implemented yet.
|
||||
|
|
|
|||
|
|
@ -8,10 +8,11 @@ La préférence de confidentialité est persistée et éditable dans le profil.
|
|||
PostIt conserve aussi trois activations de contact locales (audio, audio-video,
|
||||
messages prives) et les annonce pour chaque connexion ChatHub, y compris apres
|
||||
reconnexion. Les modifications prennent effet a la prochaine connexion. Le
|
||||
serveur filtre les invitations video et les messages prives par appareil ;
|
||||
serveur filtre les invitations et les messages prives par appareil ;
|
||||
une autre connexion peut avoir des preferences differentes et les anciens
|
||||
clients sans annonce restent autorises. Le mode audio seul n'est pas encore
|
||||
implemente.
|
||||
clients sans annonce restent autorises pour la video et les messages. Les
|
||||
invitations audio seules exigent en outre une annonce explicite de compatibilite
|
||||
audio seul sur chaque appareil, pour ne pas solliciter les anciens clients.
|
||||
La signalisation est intégrée au chat, désactivée par défaut. Une page d'appel
|
||||
separee propose **WebRTC natif** et le transport direct VLC/SRTP sur Android et
|
||||
Desktop Linux. WebRTC utilise ICE/STUN/TURN et le masquage IP impose par la
|
||||
|
|
@ -19,7 +20,9 @@ politique serveur. Le mode SRTP direct ne masque pas les adresses IP et exige
|
|||
que cette preference soit desactivee pour les deux participants. Les groupes
|
||||
et les clients navigateur ne sont pas implementes.
|
||||
Depuis le chat textuel, selectionner un membre present puis « Ouvrir l'appel »
|
||||
prepare le pair sans demarrer les medias. Les invitations entrantes disposent
|
||||
ou « Ouvrir l'appel audio » prepare le pair sans demarrer les medias. La page
|
||||
WebRTC propose les deux modes : un utilisateur autorisant l'audio et la video
|
||||
peut appeler en audio seul. Les invitations entrantes disposent
|
||||
d'un bouton pour ouvrir cette meme page sans selection de membre. Passer du
|
||||
chat a la page d'appel ne raccroche pas ; quitter la page d'appel termine les
|
||||
medias. Un salon commun reste requis ; les capacites distantes et les appels
|
||||
|
|
@ -38,7 +41,11 @@ La cible couvre :
|
|||
|
||||
- [WebRtcCallViewModel](../../src/PostIt/PostIt/ViewModels/Chat/WebRtcCallViewModel.cs)
|
||||
conserve invitation/acceptation/fin via SignalR, sans demarrer la capture
|
||||
avant consentement. Les SDP et candidats ICE utilisent les contrats existants.
|
||||
avant consentement. En audio seul, seul le microphone est requis et ouvert :
|
||||
aucune piste video ni permission camera n'est demandee. L'avatar du
|
||||
correspondant, choisi dans les parametres PostIt, sert d'image fixe ; une
|
||||
icone de remplacement est affichee si l'avatar est indisponible.
|
||||
Les SDP et candidats ICE utilisent les contrats existants.
|
||||
- [AndroidWebRtcMedia](../../src/PostIt/PostIt.Android/Services/AndroidWebRtcMedia.cs)
|
||||
heberge deux surfaces natives. Le pont Java
|
||||
[WebRtcPeer](../../src/PostIt/PostIt.Android/Services/WebRtcPeer.java) utilise
|
||||
|
|
@ -62,12 +69,12 @@ La cible couvre :
|
|||
Un SDP qui expose une adresse non relayee est refuse, pas corrige.
|
||||
- Raccrocher, sortir de la page/salle, se deconnecter ou passer l'application
|
||||
en arriere-plan annule aussi un demarrage natif en cours et libere les medias.
|
||||
Un echec natif, une perte ICE ou 30 secondes sans progression audio/video
|
||||
Un echec natif, une perte ICE ou 30 secondes sans progression des medias requis
|
||||
terminent l'appel explicitement. Il n'y a pas d'ICE restart/renegociation
|
||||
automatique ni de migration transparente d'un appel existant.
|
||||
|
||||
Le panneau WebRTC ne demande pas d'adresse ni de port RTP manuel. Le panneau
|
||||
SRTP direct demande une adresse locale, un port UDP pair et le consentement au
|
||||
SRTP direct ne prend en charge que l'audio-video. Il demande une adresse locale, un port UDP pair et le consentement au
|
||||
partage d'adresse ; il requiert HTTPS pour proteger les cles de signalisation.
|
||||
Les invitations sont dirigees vers le panneau correspondant, sans bascule
|
||||
automatique entre transports. Sans masquage,
|
||||
|
|
@ -84,7 +91,8 @@ les Podcasts conservent leur chemin existant.
|
|||
|
||||
Tests Linux reels, sans compte ni camera, avec sources video/audio synthetiques,
|
||||
decodage bidirectionnel, selection effective d'un relais coturn, controle des
|
||||
adresses signalees et panne TURN sans repli :
|
||||
adresses signalees et panne TURN sans repli. Les tests audio seuls verifient
|
||||
egalement l'absence de piste et de trames video, en direct et via TURN :
|
||||
|
||||
```bash
|
||||
python3 src/PostIt/PostIt.Tests/Native/webrtc_media_test.py -v
|
||||
|
|
|
|||
|
|
@ -37,10 +37,12 @@ internal sealed class AndroidWebRtcMedia : WebRtcNativeMedia
|
|||
protected override async Task StartCoreAsync(WebRtcMediaConfiguration configuration, CancellationToken ct)
|
||||
{
|
||||
var activity = MainActivity.Current ?? throw new InvalidOperationException("Activité Android indisponible.");
|
||||
await PodcastPermissions.EnsureAsync(activity, microphone: true, ct, notifications: false);
|
||||
await PodcastPermissions.EnsureAsync(activity, microphone: true, ct, notifications: false,
|
||||
camera: !configuration.AudioOnly);
|
||||
if (!MainActivity.IsForeground)
|
||||
throw new InvalidOperationException("Revenez dans PostIt pour demarrer l'appel.");
|
||||
await Task.WhenAll(_local.Ready, _remote.Ready).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
if (!configuration.AudioOnly)
|
||||
await Task.WhenAll(_local.Ready, _remote.Ready).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
await SendCommandAsync(StartCommand(configuration), ct);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -17,9 +17,11 @@ internal static class PodcastPermissions
|
|||
private static TaskCompletionSource<bool>? _pending;
|
||||
private static string[] _requested = [];
|
||||
|
||||
public static async Task EnsureAsync(Activity activity, bool microphone, CancellationToken ct, bool notifications = true)
|
||||
public static async Task EnsureAsync(Activity activity, bool microphone, CancellationToken ct,
|
||||
bool notifications = true, bool camera = true)
|
||||
{
|
||||
var requested = new List<string> { Manifest.Permission.Camera };
|
||||
var requested = new List<string>();
|
||||
if (camera) requested.Add(Manifest.Permission.Camera);
|
||||
if (microphone) requested.Add(Manifest.Permission.RecordAudio);
|
||||
if (notifications && OperatingSystem.IsAndroidVersionAtLeast(33)) requested.Add(Manifest.Permission.PostNotifications);
|
||||
var permissions = requested.ToArray();
|
||||
|
|
@ -32,6 +34,7 @@ internal static class PodcastPermissions
|
|||
if (!await pending.Task.WaitAsync(ct))
|
||||
throw new UnauthorizedAccessException(notifications
|
||||
? "Autorisez la camera, les notifications et, si selectionne, le microphone pour diffuser."
|
||||
: microphone && !camera ? "Autorisez le microphone pour l'appel."
|
||||
: microphone ? "Autorisez la camera et le microphone pour l'appel."
|
||||
: "Autorisez la camera pour la previsualisation.");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -123,27 +123,32 @@ public final class WebRtcPeer {
|
|||
rtc.iceTransportsType = relay ? PeerConnection.IceTransportsType.RELAY : PeerConnection.IceTransportsType.ALL;
|
||||
peer = factory.createPeerConnection(rtc, new Observer());
|
||||
if (peer == null) throw new IllegalStateException("Cannot create native WebRTC peer");
|
||||
Camera2Enumerator cameras = new Camera2Enumerator(context);
|
||||
String camera = configuration.getString("camera");
|
||||
capturer = cameras.createCapturer(camera, new CameraVideoCapturer.CameraEventsHandler() {
|
||||
public void onCameraError(String message) { error("Camera: " + message); }
|
||||
public void onCameraDisconnected() { if (!closed) error("Camera disconnected"); }
|
||||
public void onCameraFreezed(String message) { error("Camera frozen: " + message); }
|
||||
public void onCameraOpening(String name) {}
|
||||
public void onFirstFrameAvailable() {}
|
||||
public void onCameraClosed() { if (!closed) error("Camera closed unexpectedly"); }
|
||||
});
|
||||
if (capturer == null) throw new IllegalArgumentException("Camera unavailable");
|
||||
texture = SurfaceTextureHelper.create("PostIt-WebRTC-camera", egl.getEglBaseContext());
|
||||
videoSource = factory.createVideoSource(false);
|
||||
capturer.initialize(texture, context, videoSource.getCapturerObserver());
|
||||
videoTrack = factory.createVideoTrack("postit-video", videoSource);
|
||||
videoTrack.addSink(local);
|
||||
boolean audioOnly = configuration.optBoolean("audioOnly", false);
|
||||
if (!audioOnly) {
|
||||
Camera2Enumerator cameras = new Camera2Enumerator(context);
|
||||
String camera = configuration.getString("camera");
|
||||
capturer = cameras.createCapturer(camera, new CameraVideoCapturer.CameraEventsHandler() {
|
||||
public void onCameraError(String message) { error("Camera: " + message); }
|
||||
public void onCameraDisconnected() { if (!closed) error("Camera disconnected"); }
|
||||
public void onCameraFreezed(String message) { error("Camera frozen: " + message); }
|
||||
public void onCameraOpening(String name) {}
|
||||
public void onFirstFrameAvailable() {}
|
||||
public void onCameraClosed() { if (!closed) error("Camera closed unexpectedly"); }
|
||||
});
|
||||
if (capturer == null) throw new IllegalArgumentException("Camera unavailable");
|
||||
texture = SurfaceTextureHelper.create("PostIt-WebRTC-camera", egl.getEglBaseContext());
|
||||
videoSource = factory.createVideoSource(false);
|
||||
capturer.initialize(texture, context, videoSource.getCapturerObserver());
|
||||
videoTrack = factory.createVideoTrack("postit-video", videoSource);
|
||||
videoTrack.addSink(local);
|
||||
}
|
||||
audioSource = factory.createAudioSource(new MediaConstraints());
|
||||
audioTrack = factory.createAudioTrack("postit-audio", audioSource);
|
||||
peer.addTrack(audioTrack, Collections.singletonList("postit"));
|
||||
peer.addTrack(videoTrack, Collections.singletonList("postit"));
|
||||
capturer.startCapture(640, 480, 24);
|
||||
if (!audioOnly) {
|
||||
peer.addTrack(videoTrack, Collections.singletonList("postit"));
|
||||
capturer.startCapture(640, 480, 24);
|
||||
}
|
||||
if (configuration.getBoolean("caller")) peer.createOffer(new CreateDescription("offer"), new MediaConstraints());
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Media.Imaging;
|
||||
using PostIt.Views.Chat;
|
||||
using PostIt.Services;
|
||||
using PostIt.ViewModels;
|
||||
|
|
@ -36,6 +37,34 @@ public sealed class CallTransportRoutingTests
|
|||
Assert.False(webRtc.Busy);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Audio_page_shows_static_image_and_hides_video_and_srtp_controls()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
await using var webRtc = new WebRtcCallViewModel(signaling);
|
||||
var chat = new ChatViewModel(settings: new Settings()) { VideoCall = webRtc, IsConnected = true };
|
||||
signaling.Invite(new CallSession(Guid.NewGuid(), "General", "alice", "bob", false,
|
||||
DateTimeOffset.UtcNow.AddMinutes(1), DisplayMode: CallDisplayMode.AudioOnly));
|
||||
await WaitAsync(() => webRtc.Incoming);
|
||||
var page = new CallPage { DataContext = new AudioCallPageViewModel(chat) };
|
||||
var window = new Window { Content = page };
|
||||
try
|
||||
{
|
||||
window.Show();
|
||||
Assert.False(page.FindControl<ComboBox>("WebRtcCamera")!.IsVisible);
|
||||
Assert.False(page.FindControl<Button>("WebRtcVideoInvite")!.IsVisible);
|
||||
Assert.False(page.FindControl<StackPanel>("LanCallPanel")!.IsVisible);
|
||||
var fallback = page.FindControl<Image>("AudioFallbackImage")!;
|
||||
Assert.True(fallback.IsEffectivelyVisible);
|
||||
Assert.NotNull(fallback.Source);
|
||||
var displayedAvatar = page.FindControl<Image>("AudioAvatarImage")!;
|
||||
Assert.Null(displayedAvatar.Source);
|
||||
webRtc.RemoteAvatar = Assert.IsType<Bitmap>(fallback.Source);
|
||||
Assert.Same(webRtc.RemoteAvatar, displayedAvatar.Source);
|
||||
}
|
||||
finally { window.Close(); }
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Unknown_transport_is_rejected_once_without_starting_either_call()
|
||||
{
|
||||
|
|
@ -104,8 +133,10 @@ public sealed class CallTransportRoutingTests
|
|||
};
|
||||
chat.FocusedUsers.Add("bob");
|
||||
Assert.False(chat.OpenCallCommand.CanExecute(null));
|
||||
Assert.False(chat.OpenAudioCallCommand.CanExecute(null));
|
||||
chat.SelectedUser = "bob";
|
||||
Assert.True(chat.OpenCallCommand.CanExecute(null));
|
||||
Assert.True(chat.OpenAudioCallCommand.CanExecute(null));
|
||||
var page = chat.PrepareCallPage();
|
||||
Assert.Same(chat, page.Chat);
|
||||
Assert.Equal("bob", lan.Target);
|
||||
|
|
@ -115,6 +146,7 @@ public sealed class CallTransportRoutingTests
|
|||
chat.FocusedUsers.Remove("bob");
|
||||
Assert.Null(chat.SelectedUser);
|
||||
Assert.False(chat.OpenCallCommand.CanExecute(null));
|
||||
Assert.False(chat.OpenAudioCallCommand.CanExecute(null));
|
||||
chat.FocusedUsers.Add("bob");
|
||||
chat.SelectedUser = "bob";
|
||||
chat.SelectedRoom = "Other";
|
||||
|
|
@ -168,6 +200,8 @@ public sealed class CallTransportRoutingTests
|
|||
public void Invite(CallSession call) => Invitation?.Invoke(call);
|
||||
public Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default) =>
|
||||
throw new NotSupportedException();
|
||||
public Task<CallSession> InviteAudioAsync(string room, string user, CancellationToken ct = default) =>
|
||||
throw new NotSupportedException();
|
||||
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default) =>
|
||||
throw new NotSupportedException();
|
||||
public Task AcceptAsync(Guid callId, CancellationToken ct = default) => throw new NotSupportedException();
|
||||
|
|
|
|||
|
|
@ -115,6 +115,23 @@ public sealed class LanCallViewModelTests
|
|||
return vm;
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Audio_only_invitation_on_srtp_is_rejected_without_opening_media()
|
||||
{
|
||||
var signaling = new Signaling();
|
||||
var created = false;
|
||||
await using var vm = Configure(signaling, (_, _) =>
|
||||
{
|
||||
created = true;
|
||||
return new FakeMedia();
|
||||
});
|
||||
signaling.Invite(vm, signaling.Call with { DisplayMode = CallDisplayMode.AudioOnly });
|
||||
await WaitAsync(() => signaling.EndedCalls.Count != 0);
|
||||
Assert.False(created);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Contains("audio seul", vm.Status);
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData("8.8.8.8")]
|
||||
[InlineData("2001:db8::1")]
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ class AndroidPeer:
|
|||
|
||||
|
||||
class NativeWebRtcTests(unittest.TestCase):
|
||||
def run_pair(self, relay, unavailable=False, android=False, android_caller=False):
|
||||
def run_pair(self, relay, unavailable=False, android=False, android_caller=False, audio_only=False):
|
||||
processes = []
|
||||
events = queue.Queue()
|
||||
errors = []
|
||||
|
|
@ -156,7 +156,8 @@ class NativeWebRtcTests(unittest.TestCase):
|
|||
self.send(process, {"command": "start", "configuration": {
|
||||
"iceServers": servers, "relayOnly": relay,
|
||||
"caller": index == (1 if android_caller else 0),
|
||||
"camera": "test", "microphone": "test"}})
|
||||
"camera": "" if audio_only else "test", "microphone": "test",
|
||||
"audioOnly": audio_only}})
|
||||
stats = {}
|
||||
rendered = set()
|
||||
candidates = 0
|
||||
|
|
@ -176,6 +177,8 @@ class NativeWebRtcTests(unittest.TestCase):
|
|||
self.fail(message["message"] + "\n" + str(errors[-10:]))
|
||||
if kind == "signal":
|
||||
signal = message["signal"]
|
||||
if audio_only and signal.get("sdp"):
|
||||
self.assertNotIn("m=video", signal["sdp"])
|
||||
if relay:
|
||||
candidate = signal.get("candidate")
|
||||
if candidate:
|
||||
|
|
@ -195,15 +198,17 @@ class NativeWebRtcTests(unittest.TestCase):
|
|||
self.send(processes[1 - index], {"command": "signal", "signal": signal})
|
||||
if kind == "rendered" and message["size"] > 100:
|
||||
rendered.add((index, message["target"]))
|
||||
self.assertFalse(audio_only, "Audio-only call produced a video frame")
|
||||
if kind == "status":
|
||||
stats[index] = message["status"]
|
||||
if unavailable:
|
||||
self.assertNotEqual("connected", message["status"]["connectionState"])
|
||||
self.assertEqual(0, message["status"]["audioPackets"])
|
||||
self.assertEqual(0, message["status"]["videoFrames"])
|
||||
elif time.monotonic() - started >= 10 and len(stats) == 2 and len(rendered) == 4 and all(
|
||||
elif time.monotonic() - started >= 10 and len(stats) == 2 and (audio_only or len(rendered) == 4) and all(
|
||||
s["connectionState"] == "connected" and s["audioPackets"] > 100
|
||||
and s["videoFrames"] >= 100 for s in stats.values()
|
||||
and (s["videoFrames"] == 0 if audio_only else s["videoFrames"] >= 100)
|
||||
for s in stats.values()
|
||||
):
|
||||
if relay:
|
||||
self.assertTrue(all(s["localCandidateType"] == "relay" for s in stats.values()))
|
||||
|
|
@ -246,6 +251,12 @@ class NativeWebRtcTests(unittest.TestCase):
|
|||
def test_direct_bidirectional_media(self):
|
||||
self.run_pair(False)
|
||||
|
||||
def test_audio_only_bidirectional_media(self):
|
||||
self.run_pair(False, audio_only=True)
|
||||
|
||||
def test_audio_only_relay_bidirectional_media(self):
|
||||
self.run_pair(True, audio_only=True)
|
||||
|
||||
def test_relay_bidirectional_media_and_no_address_disclosure(self):
|
||||
self.run_pair(True)
|
||||
|
||||
|
|
|
|||
|
|
@ -44,6 +44,73 @@ public sealed class WebRtcCallViewModelTests
|
|||
Assert.Contains(signaling.Call.Id, signaling.EndedCalls);
|
||||
}
|
||||
|
||||
[AvaloniaTheory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task Audio_call_uses_only_microphone_and_monitors_audio(bool outgoing)
|
||||
{
|
||||
var signaling = new Signaling(true);
|
||||
var media = new Media();
|
||||
await using var vm = Configure(signaling, media);
|
||||
vm.Camera = null;
|
||||
if (outgoing)
|
||||
await vm.InviteAudioCommand.ExecuteAsync(null);
|
||||
else
|
||||
{
|
||||
signaling.InviteAudio();
|
||||
await WaitAsync(() => vm.Incoming);
|
||||
await vm.AcceptCommand.ExecuteAsync(null);
|
||||
}
|
||||
Assert.True(vm.AudioOnly);
|
||||
if (outgoing) signaling.Ready();
|
||||
await WaitAsync(() => media.Configuration is not null);
|
||||
Assert.True(media.Configuration!.AudioOnly);
|
||||
Assert.Equal("", media.Configuration.Camera);
|
||||
Assert.Equal("default", media.Configuration.Microphone);
|
||||
Assert.Null(vm.LocalVideo);
|
||||
Assert.Null(vm.RemoteVideo);
|
||||
media.Report(new("connected", "relay", 20, 0));
|
||||
await WaitAsync(() => vm.Status.Contains("Audio WebRTC etabli"));
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Accepted_mode_mismatch_ends_call_without_opening_media()
|
||||
{
|
||||
var signaling = new Signaling(true);
|
||||
var media = new Media();
|
||||
await using var vm = Configure(signaling, media);
|
||||
await vm.InviteAudioCommand.ExecuteAsync(null);
|
||||
signaling.Ready(signaling.Call with { DisplayMode = CallDisplayMode.AudioVideo });
|
||||
await WaitAsync(() => !vm.Busy);
|
||||
Assert.Null(media.Configuration);
|
||||
Assert.Single(signaling.EndedCalls);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Audio_call_loads_the_remote_avatar_without_blocking_hangup()
|
||||
{
|
||||
var signaling = new Signaling(true);
|
||||
var media = new Media();
|
||||
var avatar = new TaskCompletionSource<Bitmap?>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
string? requestedUser = null;
|
||||
await using var vm = new WebRtcCallViewModel(signaling, () => media, loadAvatar: user =>
|
||||
{
|
||||
requestedUser = user;
|
||||
return avatar.Task;
|
||||
})
|
||||
{ Microphone = new("Mic", "default"), Target = " bob ", Room = "General" };
|
||||
await vm.InviteAudioCommand.ExecuteAsync(null);
|
||||
signaling.Ready();
|
||||
await WaitAsync(() => requestedUser is not null);
|
||||
Assert.Equal("bob", requestedUser);
|
||||
await vm.HangupAsync();
|
||||
avatar.SetResult(null);
|
||||
await Task.Delay(20, TestContext.Current.CancellationToken);
|
||||
Assert.False(vm.Busy);
|
||||
Assert.Null(vm.RemoteAvatar);
|
||||
Assert.Equal("", vm.AvatarStatus);
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task Incoming_relay_needs_acceptance_but_never_requires_IP_disclosure()
|
||||
{
|
||||
|
|
@ -275,11 +342,16 @@ public sealed class WebRtcCallViewModelTests
|
|||
public event Action<CallEnded>? Ended;
|
||||
public event Action<Guid, CallSignal>? Signal;
|
||||
public event Action? Interrupted;
|
||||
public CallSession Call { get; } = new(Guid.NewGuid(), "General", "alice", "bob", relay,
|
||||
public CallSession Call { get; private set; } = new(Guid.NewGuid(), "General", "alice", "bob", relay,
|
||||
DateTimeOffset.UtcNow.AddMinutes(1));
|
||||
public List<CallSignal> Sent { get; } = [];
|
||||
public List<Guid> EndedCalls { get; } = [];
|
||||
public Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default) => Task.FromResult(Call);
|
||||
public Task<CallSession> InviteAudioAsync(string room, string user, CancellationToken ct = default)
|
||||
{
|
||||
Call = Call with { DisplayMode = CallDisplayMode.AudioOnly };
|
||||
return Task.FromResult(Call);
|
||||
}
|
||||
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default) =>
|
||||
throw new InvalidOperationException("Legacy LAN transport must not be used");
|
||||
public Task AcceptAsync(Guid callId, CancellationToken ct = default) { Ready(); return Task.CompletedTask; }
|
||||
|
|
@ -288,6 +360,11 @@ public sealed class WebRtcCallViewModelTests
|
|||
public Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default)
|
||||
{ Sent.Add(signal); return Task.CompletedTask; }
|
||||
public void Invite() => Invitation?.Invoke(Call);
|
||||
public void InviteAudio()
|
||||
{
|
||||
Call = Call with { DisplayMode = CallDisplayMode.AudioOnly };
|
||||
Invitation?.Invoke(Call);
|
||||
}
|
||||
public void Ready(CallSession? session = null, CallIceServer[]? servers = null) =>
|
||||
Accepted?.Invoke(new(session ?? Call, servers ?? Turn));
|
||||
public void Receive(CallSignal signal) => Signal?.Invoke(Call.Id, signal);
|
||||
|
|
|
|||
|
|
@ -45,6 +45,12 @@ public sealed class CallSignalingClient : IWebRtcCallSignaling, IDisposable
|
|||
return _connection.InvokeAsync<CallSession>(CallHubMethods.InviteLan, room, user, ct);
|
||||
}
|
||||
|
||||
public Task<CallSession> InviteAudioAsync(string room, string user, CancellationToken ct = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
return _connection.InvokeAsync<CallSession>(CallHubMethods.InviteAudio, room, user, ct);
|
||||
}
|
||||
|
||||
public Task AcceptAsync(Guid callId, CancellationToken ct = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
|
|
|
|||
|
|
@ -143,7 +143,8 @@ public sealed class ChatHubConnection : IAsyncDisposable
|
|||
private Task AnnounceContactPreferencesAsync(HubConnection connection, CancellationToken ct) =>
|
||||
connection.InvokeAsync(CallHubMethods.SetContactPreferences,
|
||||
new ContactPreferences(_api.Settings.AllowAudioCalls, _api.Settings.AllowVideoCalls,
|
||||
_api.Settings.AllowPrivateMessages), ct);
|
||||
_api.Settings.AllowPrivateMessages, Platform.CreateWebRtcMedia != null ||
|
||||
(OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid())), ct);
|
||||
|
||||
public async Task StopAsync(CancellationToken ct = default)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ using Yavsc.Abstract.Chat.Calls;
|
|||
namespace PostIt.Services;
|
||||
|
||||
public sealed record WebRtcMediaConfiguration(CallIceServer[] IceServers, bool RelayOnly,
|
||||
bool Caller, string Camera, string Microphone);
|
||||
bool Caller, string Camera, string Microphone, bool AudioOnly = false);
|
||||
|
||||
public sealed record WebRtcMediaStatus(string ConnectionState, string? LocalCandidateType,
|
||||
long AudioPackets, long VideoFrames, bool LocalVideoRendered = false, bool RemoteVideoRendered = false)
|
||||
|
|
@ -29,4 +29,5 @@ public interface IWebRtcMedia : IAsyncDisposable
|
|||
public interface IWebRtcCallSignaling : ILanCallSignaling
|
||||
{
|
||||
Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default);
|
||||
Task<CallSession> InviteAudioAsync(string room, string user, CancellationToken ct = default);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -71,27 +71,33 @@ class Peer:
|
|||
def start(self, configuration):
|
||||
if self.pipeline is not None:
|
||||
raise RuntimeError("WebRTC already started")
|
||||
for plugin in ("webrtcbin", "nicesrc", "vp8enc", "opusenc", "jpegenc"):
|
||||
audio_only = configuration.get("audioOnly", False)
|
||||
plugins = ("webrtcbin", "nicesrc", "opusenc") if audio_only else (
|
||||
"webrtcbin", "nicesrc", "vp8enc", "opusenc", "jpegenc")
|
||||
for plugin in plugins:
|
||||
if not Gst.ElementFactory.find(plugin):
|
||||
raise RuntimeError("Missing GStreamer plugin: " + plugin)
|
||||
synthetic = configuration["camera"] == "test"
|
||||
synthetic = (configuration["microphone"] == "test" if audio_only
|
||||
else configuration["camera"] == "test")
|
||||
camera = "videotestsrc is-live=true" if synthetic else "v4l2src name=camera"
|
||||
microphone = "audiotestsrc is-live=true" if synthetic else "pulsesrc name=microphone"
|
||||
self.pipeline = Gst.parse_launch(
|
||||
"webrtcbin name=rtc bundle-policy=max-bundle latency=100 "
|
||||
+ camera + " ! videoconvert ! videoscale ! videorate ! "
|
||||
video = "" if audio_only else (
|
||||
camera + " ! videoconvert ! videoscale ! videorate ! "
|
||||
"video/x-raw,width=640,height=360,framerate=15/1 ! tee name=local "
|
||||
"local. ! queue leaky=downstream max-size-buffers=2 ! "
|
||||
"vp8enc deadline=1 target-bitrate=900000 keyframe-max-dist=30 ! "
|
||||
"rtpvp8pay pt=96 ! application/x-rtp,media=video,encoding-name=VP8,payload=96 ! rtc. "
|
||||
"local. ! queue leaky=downstream max-size-buffers=1 ! videorate ! "
|
||||
"video/x-raw,framerate=10/1 ! jpegenc ! appsink name=local_frames "
|
||||
"emit-signals=true sync=false max-buffers=1 drop=true "
|
||||
+ microphone + " ! audioconvert ! audioresample ! audio/x-raw,rate=48000,channels=1 ! "
|
||||
"emit-signals=true sync=false max-buffers=1 drop=true ")
|
||||
self.pipeline = Gst.parse_launch(
|
||||
"webrtcbin name=rtc bundle-policy=max-bundle latency=100 "
|
||||
+ video + microphone + " ! audioconvert ! audioresample ! audio/x-raw,rate=48000,channels=1 ! "
|
||||
"opusenc ! rtpopuspay pt=111 ! application/x-rtp,media=audio,encoding-name=OPUS,payload=111 ! rtc."
|
||||
)
|
||||
if not synthetic:
|
||||
self.pipeline.get_by_name("camera").set_property("device", configuration["camera"])
|
||||
if not audio_only:
|
||||
self.pipeline.get_by_name("camera").set_property("device", configuration["camera"])
|
||||
if configuration["microphone"] != "default":
|
||||
self.pipeline.get_by_name("microphone").set_property("device", configuration["microphone"])
|
||||
self.synthetic = synthetic
|
||||
|
|
@ -117,7 +123,8 @@ class Peer:
|
|||
self.rtc.set_property("stun-server", url.replace(":", "://", 1))
|
||||
elif not configuration["relayOnly"] and url.startswith("stuns:"):
|
||||
raise RuntimeError("GStreamer does not support STUN/TLS; configure STUN or TURN/TLS")
|
||||
self.pipeline.get_by_name("local_frames").connect("new-sample", self.frame, "local")
|
||||
if not audio_only:
|
||||
self.pipeline.get_by_name("local_frames").connect("new-sample", self.frame, "local")
|
||||
self.rtc.connect("on-ice-candidate", self.candidate)
|
||||
self.rtc.connect("pad-added", self.incoming)
|
||||
bus = self.pipeline.get_bus()
|
||||
|
|
|
|||
|
|
@ -71,6 +71,7 @@ public class ViewLocator : IDataTemplate
|
|||
AdministrationPageViewModel => services.GetRequiredService<AdministrationPage>(),
|
||||
ResourceUsageReliefPageViewModel => services.GetRequiredService<ResourceUsageReliefPage>(),
|
||||
ChatViewModel => services.GetRequiredService<ChatPage>(),
|
||||
AudioCallPageViewModel => services.GetRequiredService<CallPage>(),
|
||||
CallPageViewModel => services.GetRequiredService<CallPage>(),
|
||||
null => new TextBlock { Text = "No view for <null>" },
|
||||
_ => new TextBlock { Text = $"No view for {data.GetType().Name}" }
|
||||
|
|
|
|||
|
|
@ -0,0 +1,8 @@
|
|||
namespace PostIt.ViewModels.Chat;
|
||||
|
||||
public sealed class AudioCallPageViewModel(ChatViewModel chat) : CallPageViewModel(chat)
|
||||
{
|
||||
public override string Header => "Appel audio";
|
||||
public override bool IsAudioPage => true;
|
||||
public override string Description => "Appel audio WebRTC. Les deux participants doivent etre presents dans le meme salon. Quitter cette page termine l'appel.";
|
||||
}
|
||||
|
|
@ -2,8 +2,12 @@ using System.Threading.Tasks;
|
|||
|
||||
namespace PostIt.ViewModels.Chat;
|
||||
|
||||
public sealed class CallPageViewModel(ChatViewModel chat) : ViewModelBase
|
||||
public class CallPageViewModel(ChatViewModel chat) : ViewModelBase
|
||||
{
|
||||
public virtual string Header => "Appel audio-video";
|
||||
public virtual bool IsAudioPage => false;
|
||||
public bool ShowLanCalls => !IsAudioPage && Chat.SupportsLanCalls;
|
||||
public virtual string Description => "Choisissez WebRTC ou SRTP direct. Les deux participants doivent etre presents dans le meme salon. Quitter cette page termine l'appel.";
|
||||
public ChatViewModel Chat { get; } = chat;
|
||||
public override bool CanNavigateNext { get; protected set; } = false;
|
||||
public override bool CanNavigatePrevious { get; protected set; } = true;
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ using Microsoft.AspNetCore.SignalR.Client;
|
|||
using Microsoft.Extensions.DependencyInjection;
|
||||
using PostIt.Models;
|
||||
using PostIt.Services;
|
||||
using PostIt.Helpers;
|
||||
using Yavsc.Api.Client;
|
||||
using Yavsc;
|
||||
|
||||
namespace PostIt.ViewModels.Chat
|
||||
|
|
@ -64,7 +66,7 @@ namespace PostIt.ViewModels.Chat
|
|||
(OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid());
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(ShowCallCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(OpenAudioCallCommand), nameof(ShowCallCommand))]
|
||||
public partial WebRtcCallViewModel? VideoCall { get; set; }
|
||||
|
||||
[ObservableProperty]
|
||||
|
|
@ -72,7 +74,7 @@ namespace PostIt.ViewModels.Chat
|
|||
public partial LanCallViewModel? LanCall { get; set; }
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(OpenAudioCallCommand))]
|
||||
public partial string? SelectedUser { get; set; }
|
||||
|
||||
[ObservableProperty]
|
||||
|
|
@ -89,7 +91,7 @@ namespace PostIt.ViewModels.Chat
|
|||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(SendMessageCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(ShowCallCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(OpenAudioCallCommand), nameof(ShowCallCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(IsConnectedAndInARoom))]
|
||||
public partial bool IsConnected { get; set; } = false;
|
||||
|
||||
|
|
@ -104,7 +106,7 @@ namespace PostIt.ViewModels.Chat
|
|||
// alors les notifications système.
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(SendMessageCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(OpenAudioCallCommand))]
|
||||
public partial string? SelectedRoom { get; set; }
|
||||
|
||||
// Notifications globales (connexion, erreurs de join, ...)
|
||||
|
|
@ -130,12 +132,14 @@ namespace PostIt.ViewModels.Chat
|
|||
{
|
||||
value.CollectionChanged += OnFocusedUsersCollectionChanged;
|
||||
OpenCallCommand.NotifyCanExecuteChanged();
|
||||
OpenAudioCallCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
private void OnFocusedUsersCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args)
|
||||
{
|
||||
if (SelectedUser != null && !FocusedUsers.Contains(SelectedUser)) SelectedUser = null;
|
||||
OpenCallCommand.NotifyCanExecuteChanged();
|
||||
OpenAudioCallCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
private void UpdateRoomUsers(string type, string room, string user)
|
||||
|
|
@ -184,15 +188,22 @@ namespace PostIt.ViewModels.Chat
|
|||
[RelayCommand(CanExecute = nameof(CanOpenCall))]
|
||||
private Task OpenCallAsync() => NavigateToCallAsync(configureTarget: true);
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanOpenAudioCall))]
|
||||
private Task OpenAudioCallAsync() => NavigateToCallAsync(configureTarget: true, audio: true);
|
||||
|
||||
private bool CanOpenAudioCall() => CanOpenCall() && VideoCall != null;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanShowCall))]
|
||||
private Task ShowCallAsync() => NavigateToCallAsync(configureTarget: false);
|
||||
|
||||
private async Task NavigateToCallAsync(bool configureTarget)
|
||||
private async Task NavigateToCallAsync(bool configureTarget, bool audio = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
var app = App.Current as App ?? throw new InvalidOperationException("Application indisponible.");
|
||||
var page = configureTarget ? PrepareCallPage() : new CallPageViewModel(this);
|
||||
if (VideoCall?.Busy == true ? VideoCall.AudioOnly : audio && LanCall?.Busy != true)
|
||||
page = new AudioCallPageViewModel(this);
|
||||
await app.PushPageAsync(page);
|
||||
}
|
||||
catch (Exception error) { Log($"Impossible d'ouvrir l'appel : {error.Message}"); }
|
||||
|
|
@ -401,7 +412,13 @@ namespace PostIt.ViewModels.Chat
|
|||
|
||||
Calls = new CallSignalingClient(_connection);
|
||||
if (SupportsVideoCalls)
|
||||
VideoCall = new WebRtcCallViewModel(Calls, settings: _settings) { Room = SelectedRoom ?? "" };
|
||||
{
|
||||
var avatars = new ActivityApiClient(_api, () => _settings.ApiUrl,
|
||||
() => _settings.Authentication.Authority);
|
||||
VideoCall = new WebRtcCallViewModel(Calls, settings: _settings,
|
||||
loadAvatar: user => ImageHelper.LoadFromWeb(new Uri(avatars.BuildAvatarXsUrl(user))))
|
||||
{ Room = SelectedRoom ?? "" };
|
||||
}
|
||||
if (SupportsLanCalls)
|
||||
LanCall = new LanCallViewModel(Calls, settings: _settings) { Room = SelectedRoom ?? "" };
|
||||
Calls.Invitation += call =>
|
||||
|
|
|
|||
|
|
@ -221,6 +221,8 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
throw new InvalidOperationException("Selectionnez une salle jointe et un autre utilisateur.");
|
||||
Busy = true;
|
||||
_call = await _signaling.InviteLanAsync(Room, Target.Trim(), _lifetime.Token);
|
||||
if (_call.Transport != CallTransports.LanSrtp || _call.DisplayMode != CallDisplayMode.AudioVideo)
|
||||
throw new InvalidOperationException("Mode d'appel SRTP incompatible.");
|
||||
Status = $"Invitation envoyee a {_call.Callee} ; attente du consentement.";
|
||||
});
|
||||
|
||||
|
|
@ -248,6 +250,12 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
if (call.Transport != CallTransports.LanSrtp) return;
|
||||
Queue(async () =>
|
||||
{
|
||||
if (call.DisplayMode != CallDisplayMode.AudioVideo)
|
||||
{
|
||||
await _signaling.EndAsync(call.Id, _lifetime.Token);
|
||||
Status = "Le mode audio seul n'est pas disponible en SRTP.";
|
||||
return;
|
||||
}
|
||||
if (_call != null) throw new InvalidOperationException("Invitation concurrente inattendue.");
|
||||
if (call.RelayOnly) throw new InvalidOperationException("Le mode LAN ne peut pas masquer les adresses IP.");
|
||||
_call = call;
|
||||
|
|
@ -265,6 +273,7 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
|
|||
if (_call?.Id != accepted.Session.Id) return;
|
||||
if (_media != null) throw new InvalidOperationException("Acceptation repetee.");
|
||||
if (accepted.Session.Transport != CallTransports.LanSrtp || accepted.Session.RelayOnly ||
|
||||
accepted.Session.DisplayMode != CallDisplayMode.AudioVideo ||
|
||||
(Incoming && !_accepting))
|
||||
throw new InvalidOperationException("Acceptation ou politique de transport inattendue.");
|
||||
_call = accepted.Session;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ using System.Linq;
|
|||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
|
@ -18,6 +19,7 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
|
|||
private readonly IWebRtcCallSignaling _signaling;
|
||||
private readonly Func<IWebRtcMedia> _createMedia;
|
||||
private readonly Settings? _settings;
|
||||
private readonly Func<string, Task<Bitmap?>>? _loadAvatar;
|
||||
private readonly SemaphoreSlim _events = new(1);
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private CancellationTokenSource? _callLifetime;
|
||||
|
|
@ -40,20 +42,26 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
|
|||
[ObservableProperty] public partial string Target { get; set; } = "";
|
||||
[ObservableProperty] public partial string Room { get; set; } = "";
|
||||
[ObservableProperty] public partial string Status { get; set; } = "Appel WebRTC : aucun appel.";
|
||||
[ObservableProperty, NotifyPropertyChangedFor(nameof(CanConfigure))]
|
||||
[ObservableProperty, NotifyPropertyChangedFor(nameof(CanConfigure)), NotifyPropertyChangedFor(nameof(IsAudioCall))]
|
||||
public partial bool Busy { get; set; }
|
||||
[ObservableProperty, NotifyPropertyChangedFor(nameof(CanConfigure))]
|
||||
public partial bool Incoming { get; set; }
|
||||
[ObservableProperty] public partial bool Preparing { get; set; }
|
||||
[ObservableProperty] public partial Control? LocalVideo { get; set; }
|
||||
[ObservableProperty] public partial Control? RemoteVideo { get; set; }
|
||||
[ObservableProperty, NotifyPropertyChangedFor(nameof(IsAudioCall))]
|
||||
public partial bool AudioOnly { get; set; }
|
||||
[ObservableProperty] public partial Bitmap? RemoteAvatar { get; set; }
|
||||
[ObservableProperty] public partial string AvatarStatus { get; set; } = "";
|
||||
public bool IsAudioCall => Busy && AudioOnly;
|
||||
public bool CanConfigure => !Busy || Incoming;
|
||||
|
||||
public WebRtcCallViewModel(IWebRtcCallSignaling signaling, Func<IWebRtcMedia>? createMedia = null,
|
||||
Settings? settings = null)
|
||||
Settings? settings = null, Func<string, Task<Bitmap?>>? loadAvatar = null)
|
||||
{
|
||||
_signaling = signaling;
|
||||
_settings = settings;
|
||||
_loadAvatar = loadAvatar;
|
||||
_createMedia = createMedia ?? Platform.CreateWebRtcMedia ?? (() => new LinuxWebRtcMedia());
|
||||
signaling.Invitation += OnInvitation;
|
||||
signaling.Accepted += OnAccepted;
|
||||
|
|
@ -89,21 +97,22 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
|
|||
foreach (var device in devices.Cameras) Cameras.Add(device);
|
||||
foreach (var device in devices.Microphones.Where(d => !string.IsNullOrEmpty(d.Value))) Microphones.Add(device);
|
||||
RestoreSelection();
|
||||
Status = Cameras.Count == 0 ? "Aucune camera detectee."
|
||||
Status = Cameras.Count == 0 ? "Aucune camera detectee ; les appels audio restent possibles."
|
||||
: "Peripheriques actualises. Le profil de masquage IP sera applique par le serveur.";
|
||||
}
|
||||
catch (Exception error) { Status = "Peripheriques indisponibles : " + error.Message; }
|
||||
}
|
||||
|
||||
private void SelectDevices()
|
||||
private void SelectDevices(bool audioOnly)
|
||||
{
|
||||
if (Camera is null || Microphone is null)
|
||||
throw new InvalidOperationException("Une camera et un microphone sont requis.");
|
||||
_camera = Camera.Value;
|
||||
if (Microphone is null || (!audioOnly && Camera is null))
|
||||
throw new InvalidOperationException(audioOnly ? "Un microphone est requis."
|
||||
: "Une camera et un microphone sont requis.");
|
||||
_camera = audioOnly ? "" : Camera!.Value;
|
||||
_microphone = Microphone.Value;
|
||||
if (_settings is not null)
|
||||
{
|
||||
_settings.PodcastCameraId = _camera;
|
||||
if (!audioOnly) _settings.PodcastCameraId = _camera;
|
||||
_settings.PodcastMicrophoneId = _microphone;
|
||||
try { _settings.Save(); }
|
||||
catch (Exception error) when (error is System.IO.IOException or UnauthorizedAccessException)
|
||||
|
|
@ -123,16 +132,26 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
|
|||
}
|
||||
|
||||
[RelayCommand]
|
||||
private Task InviteAsync() => RunAsync(async () =>
|
||||
private Task InviteAsync() => InviteCoreAsync(false);
|
||||
|
||||
[RelayCommand]
|
||||
private Task InviteAudioAsync() => InviteCoreAsync(true);
|
||||
|
||||
private Task InviteCoreAsync(bool audioOnly) => RunAsync(async () =>
|
||||
{
|
||||
if (Busy) throw new InvalidOperationException("Un appel est deja en cours.");
|
||||
SelectDevices();
|
||||
SelectDevices(audioOnly);
|
||||
if (string.IsNullOrWhiteSpace(Target) || string.IsNullOrWhiteSpace(Room))
|
||||
throw new InvalidOperationException("Selectionnez une salle jointe et un autre utilisateur.");
|
||||
_callLifetime = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
|
||||
_caller = true;
|
||||
AudioOnly = audioOnly;
|
||||
Busy = true;
|
||||
_call = await _signaling.InviteAsync(Room, Target.Trim(), _callLifetime.Token);
|
||||
_call = audioOnly
|
||||
? await _signaling.InviteAudioAsync(Room, Target.Trim(), _callLifetime.Token)
|
||||
: await _signaling.InviteAsync(Room, Target.Trim(), _callLifetime.Token);
|
||||
if (_call.DisplayMode != (audioOnly ? CallDisplayMode.AudioOnly : CallDisplayMode.AudioVideo))
|
||||
throw new InvalidOperationException("Mode d'appel inattendu.");
|
||||
CheckPolicy(_call);
|
||||
Status = $"Invitation envoyee a {_call.Callee} ; attente du consentement.";
|
||||
});
|
||||
|
|
@ -142,7 +161,7 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
|
|||
{
|
||||
if (_call is null || !Incoming) throw new InvalidOperationException("Aucune invitation a accepter.");
|
||||
CheckPolicy(_call);
|
||||
SelectDevices();
|
||||
SelectDevices(_call.DisplayMode == CallDisplayMode.AudioOnly);
|
||||
Incoming = false;
|
||||
_accepted = true;
|
||||
await _signaling.AcceptAsync(_call.Id, _callLifetime!.Token);
|
||||
|
|
@ -161,19 +180,21 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
|
|||
if (call.Transport == CallTransports.LanSrtp) return;
|
||||
Queue(async () =>
|
||||
{
|
||||
if (call.Transport != CallTransports.WebRtc || _call is not null)
|
||||
if (call.Transport != CallTransports.WebRtc || _call is not null ||
|
||||
call.DisplayMode is not (CallDisplayMode.AudioOnly or CallDisplayMode.AudioVideo))
|
||||
{
|
||||
await _signaling.EndAsync(call.Id, _lifetime.Token);
|
||||
Status = "Invitation refusee : transport incompatible ou appel deja en cours.";
|
||||
return;
|
||||
}
|
||||
_call = call;
|
||||
AudioOnly = call.DisplayMode == CallDisplayMode.AudioOnly;
|
||||
Room = call.RoomName;
|
||||
Target = call.Caller;
|
||||
_caller = false;
|
||||
_callLifetime = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
|
||||
Busy = Incoming = true;
|
||||
Status = $"{call.Caller} propose un appel dans {call.RoomName}. "
|
||||
Status = $"{call.Caller} propose un appel {(AudioOnly ? "audio" : "audio-video")} dans {call.RoomName}. "
|
||||
+ (call.RelayOnly ? "Masquage IP : relais TURN obligatoire. " : "Mode direct : consentement au partage IP requis. ")
|
||||
+ "Acceptez ou refusez.";
|
||||
});
|
||||
|
|
@ -183,13 +204,14 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
|
|||
{
|
||||
if (_call?.Id != accepted.Session.Id) return;
|
||||
if (_media is not null || (!_caller && !_accepted) ||
|
||||
(_call.RelayOnly && !accepted.Session.RelayOnly))
|
||||
(_call.RelayOnly && !accepted.Session.RelayOnly) ||
|
||||
_call.DisplayMode != accepted.Session.DisplayMode)
|
||||
throw new InvalidOperationException("Acceptation ou politique WebRTC inattendue.");
|
||||
CheckPolicy(accepted.Session);
|
||||
_call = accepted.Session;
|
||||
Incoming = false;
|
||||
var configuration = new WebRtcMediaConfiguration(accepted.IceServers, _call.RelayOnly,
|
||||
_caller, _camera!, _microphone!);
|
||||
_caller, _camera!, _microphone!, AudioOnly);
|
||||
WebRtcPrivacy.ValidateConfiguration(configuration);
|
||||
_media = _createMedia();
|
||||
var id = _call.Id;
|
||||
|
|
@ -211,14 +233,38 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
|
|||
});
|
||||
media.Signal += _sendSignal;
|
||||
media.StatusChanged += _receiveStatus;
|
||||
LocalVideo = media.LocalVideo;
|
||||
RemoteVideo = media.RemoteVideo;
|
||||
if (!AudioOnly)
|
||||
{
|
||||
LocalVideo = media.LocalVideo;
|
||||
RemoteVideo = media.RemoteVideo;
|
||||
}
|
||||
Status = _call.RelayOnly ? "Connexion WebRTC via TURN uniquement ; aucun repli direct."
|
||||
: "Connexion WebRTC ICE/STUN/TURN.";
|
||||
await media.StartAsync(configuration, _callLifetime!.Token);
|
||||
_ = MonitorAsync(id, media, _callLifetime.Token);
|
||||
if (AudioOnly && _loadAvatar is not null)
|
||||
_ = LoadAvatarAsync(id, _caller ? _call.Callee : _call.Caller);
|
||||
});
|
||||
|
||||
private async Task LoadAvatarAsync(Guid id, string user)
|
||||
{
|
||||
try
|
||||
{
|
||||
var avatar = await _loadAvatar!(user);
|
||||
if (_disposed || _call?.Id != id) avatar?.Dispose();
|
||||
else
|
||||
{
|
||||
RemoteAvatar = avatar;
|
||||
AvatarStatus = avatar is null ? "Avatar indisponible." : "";
|
||||
}
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
if (!_disposed && _call?.Id == id)
|
||||
AvatarStatus = "Avatar indisponible : " + error.Message;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSignal(Guid id, CallSignal signal) => Queue(async () =>
|
||||
{
|
||||
if (_call?.Id != id) return;
|
||||
|
|
@ -261,19 +307,20 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
|
|||
if (_call?.Id != id || _mediaStatus is not { } status) return;
|
||||
if (status.ConnectionState is "failed" or "closed" or "disconnected")
|
||||
throw new InvalidOperationException("Connexion ICE interrompue ; aucun repli automatique.");
|
||||
if (!status.HasRemoteMedia) return;
|
||||
if (status.AudioPackets > audio && status.VideoFrames > video)
|
||||
if (status.ConnectionState != "connected" || status.AudioPackets <= 0 ||
|
||||
(!AudioOnly && status.VideoFrames <= 0)) return;
|
||||
if (status.AudioPackets > audio && (AudioOnly || status.VideoFrames > video))
|
||||
{
|
||||
audio = status.AudioPackets;
|
||||
video = status.VideoFrames;
|
||||
progress.Restart();
|
||||
}
|
||||
received = true;
|
||||
Status = _call.RelayOnly ? "Audio-video WebRTC etabli via TURN (IP masquee)."
|
||||
: "Audio-video WebRTC etabli.";
|
||||
Status = (AudioOnly ? "Audio" : "Audio-video") +
|
||||
(_call.RelayOnly ? " WebRTC etabli via TURN (IP masquee)." : " WebRTC etabli.");
|
||||
});
|
||||
if (progress.Elapsed > TimeSpan.FromSeconds(30))
|
||||
throw new TimeoutException(received ? "Reception audio-video interrompue."
|
||||
throw new TimeoutException(received ? "Reception des medias interrompue."
|
||||
: "Aucun media distant. Verifiez ICE, TURN et les pare-feu ; aucun repli hors politique.");
|
||||
await Task.Delay(500, ct);
|
||||
}
|
||||
|
|
@ -333,6 +380,10 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
|
|||
finally
|
||||
{
|
||||
LocalVideo = RemoteVideo = null;
|
||||
RemoteAvatar?.Dispose();
|
||||
RemoteAvatar = null;
|
||||
AvatarStatus = "";
|
||||
AudioOnly = false;
|
||||
_sendSignal = null;
|
||||
_receiveStatus = null;
|
||||
_callLifetime?.Dispose();
|
||||
|
|
|
|||
|
|
@ -5,21 +5,22 @@
|
|||
xmlns:vm="using:PostIt.ViewModels.Chat"
|
||||
xmlns:services="using:PostIt.Services"
|
||||
x:DataType="vm:CallPageViewModel"
|
||||
Header="Appel audio-video">
|
||||
Header="{Binding Header}">
|
||||
<ScrollViewer HorizontalScrollBarVisibility="Disabled">
|
||||
<StackPanel Margin="16" Spacing="16">
|
||||
<TextBlock Text="Choisissez WebRTC ou SRTP direct. Les deux participants doivent etre presents dans le meme salon. Quitter cette page termine l'appel."
|
||||
<TextBlock Text="{Binding Description}"
|
||||
TextWrapping="Wrap" />
|
||||
<StackPanel IsVisible="{Binding Chat.SupportsVideoCalls}">
|
||||
<TextBlock Text="Appel video WebRTC" FontSize="20" FontWeight="SemiBold" Margin="0,0,0,8" />
|
||||
<TextBlock Text="Appel WebRTC" FontSize="20" FontWeight="SemiBold" Margin="0,0,0,8" />
|
||||
<StackPanel DataContext="{Binding Chat.VideoCall}" x:DataType="vm:WebRtcCallViewModel"
|
||||
IsEnabled="{Binding $parent[ContentPage].((vm:CallPageViewModel)DataContext).Chat.IsConnected}" Spacing="8">
|
||||
<TextBlock Text="Android et Linux : medias chiffres par WebRTC (DTLS-SRTP), ICE/STUN/TURN. Activez le masquage IP dans votre profil pour imposer un relais TURN aux deux participants, sans repli direct. La camera et le microphone ne demarrent qu'apres acceptation."
|
||||
<TextBlock Text="Android et Linux : medias chiffres par WebRTC (DTLS-SRTP), ICE/STUN/TURN. Activez le masquage IP dans votre profil pour imposer un relais TURN aux deux participants, sans repli direct. Les medias ne demarrent qu'apres acceptation ; l'appel audio ne demande pas de camera."
|
||||
TextWrapping="Wrap" />
|
||||
<WrapPanel IsEnabled="{Binding CanConfigure}" IsVisible="{Binding !RemoteVideo}">
|
||||
<Button Content="Actualiser les peripheriques" Command="{Binding RefreshDevicesCommand}" Margin="0,0,8,4" />
|
||||
<ComboBox Width="190" ItemsSource="{Binding Cameras}" SelectedItem="{Binding Camera}"
|
||||
PlaceholderText="Camera" Margin="0,0,8,4">
|
||||
<ComboBox x:Name="WebRtcCamera" Width="190" ItemsSource="{Binding Cameras}" SelectedItem="{Binding Camera}"
|
||||
PlaceholderText="Camera" Margin="0,0,8,4"
|
||||
IsVisible="{Binding !$parent[ContentPage].((vm:CallPageViewModel)DataContext).IsAudioPage}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="services:CaptureDevice">
|
||||
<TextBlock Text="{Binding Name}" />
|
||||
|
|
@ -40,19 +41,29 @@
|
|||
IsChecked="{Binding AllowAddressDisclosure}" IsEnabled="{Binding CanConfigure}"
|
||||
IsVisible="{Binding !RemoteVideo}" />
|
||||
<WrapPanel>
|
||||
<Button Content="Appeler dans la salle active" Command="{Binding InviteCommand}" IsEnabled="{Binding !Busy}" Margin="0,0,8,4" />
|
||||
<Button x:Name="WebRtcVideoInvite" Content="Appeler en audio-video" Command="{Binding InviteCommand}" IsEnabled="{Binding !Busy}"
|
||||
IsVisible="{Binding !$parent[ContentPage].((vm:CallPageViewModel)DataContext).IsAudioPage}" Margin="0,0,8,4" />
|
||||
<Button Content="Appeler en audio" Command="{Binding InviteAudioCommand}" IsEnabled="{Binding !Busy}" Margin="0,0,8,4" />
|
||||
<Button Content="Accepter" Command="{Binding AcceptCommand}" IsEnabled="{Binding Incoming}" Margin="0,0,8,4" />
|
||||
<Button Content="Refuser / Raccrocher" Command="{Binding HangupCommand}" IsEnabled="{Binding Busy}" Margin="0,0,8,4" />
|
||||
</WrapPanel>
|
||||
<TextBlock Text="{Binding Status}" TextWrapping="Wrap" />
|
||||
<StackPanel IsVisible="{Binding IsAudioCall}" HorizontalAlignment="Center" Spacing="8">
|
||||
<Grid Width="160" Height="160">
|
||||
<Image x:Name="AudioFallbackImage" Source="avares://PostIt/Assets/Icon.png" Stretch="Uniform" />
|
||||
<Image x:Name="AudioAvatarImage" Source="{Binding RemoteAvatar}" Stretch="Uniform" />
|
||||
</Grid>
|
||||
<TextBlock Text="{Binding Target}" HorizontalAlignment="Center" />
|
||||
<TextBlock Text="{Binding AvatarStatus}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<Grid ColumnDefinitions="*,2*" Height="280" IsVisible="{Binding !!RemoteVideo}">
|
||||
<ContentControl Content="{Binding LocalVideo}" Margin="0,0,8,0" />
|
||||
<ContentControl Grid.Column="1" Content="{Binding RemoteVideo}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
<StackPanel IsVisible="{Binding Chat.SupportsLanCalls}">
|
||||
<TextBlock Text="Appel direct IPv4/IPv6 SRTP (LAN/VPN ou IP publique)"
|
||||
<StackPanel x:Name="LanCallPanel" IsVisible="{Binding ShowLanCalls}">
|
||||
<TextBlock Text="Appel audio-video direct IPv4/IPv6 SRTP (LAN/VPN ou IP publique)"
|
||||
FontSize="20" FontWeight="SemiBold" TextWrapping="Wrap" Margin="0,0,0,8" />
|
||||
<StackPanel DataContext="{Binding Chat.LanCall}" x:DataType="vm:LanCallViewModel"
|
||||
IsEnabled="{Binding $parent[ContentPage].((vm:CallPageViewModel)DataContext).Chat.IsConnected}" Spacing="8">
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@
|
|||
Margin="10,0,0,0"
|
||||
BorderBrush="#E0E0E0"
|
||||
BorderThickness="1">
|
||||
<Grid RowDefinitions="Auto, *, Auto">
|
||||
<Grid RowDefinitions="Auto, *, Auto, Auto">
|
||||
<TextBlock
|
||||
Grid.Row="0"
|
||||
Margin="5"
|
||||
|
|
@ -73,6 +73,8 @@
|
|||
SelectedItem="{Binding SelectedUser}" />
|
||||
<Button Grid.Row="2" Margin="5" Content="Ouvrir l'appel"
|
||||
Command="{Binding OpenCallCommand}" />
|
||||
<Button Grid.Row="3" Margin="5" Content="Ouvrir l'appel audio"
|
||||
Command="{Binding OpenAudioCallCommand}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@
|
|||
IsChecked="{Binding AllowVideoCalls, Mode=TwoWay}" />
|
||||
<CheckBox Content="Autoriser les messages prives"
|
||||
IsChecked="{Binding AllowPrivateMessages, Mode=TwoWay}" />
|
||||
<TextBlock Text="Les changements prennent effet a la prochaine connexion au chat. Les autres appareils conservent leurs propres preferences ; les anciens clients sans preferences restent joignables. Les appels audio seuls ne sont pas encore disponibles."
|
||||
<TextBlock Text="Les changements prennent effet a la prochaine connexion au chat. Les autres appareils conservent leurs propres preferences ; les appels audio seuls necessitent un client compatible."
|
||||
TextWrapping="Wrap" />
|
||||
<StackPanel IsVisible="{Binding SupportsBackgroundChatService}" Spacing="6">
|
||||
<CheckBox x:Name="BackgroundChatCheckBox"
|
||||
|
|
@ -69,7 +69,7 @@
|
|||
IsChecked="{Binding ShareExceptionReports, Mode=TwoWay}" />
|
||||
<TextBlock Text="Desactive par defaut. Si vous activez cette option, PostIt transmet le type, le message et la trace technique des exceptions signalees pour aider au diagnostic. Ces details peuvent contenir des informations issues de l'environnement de l'application."
|
||||
TextWrapping="Wrap" />
|
||||
<TextBlock Text="Avatar: PNG, JPG/JPEG, WEBP, GIF. Taille max 2 MB."
|
||||
<TextBlock Text="Avatar affiche notamment pendant les appels audio : PNG, JPG/JPEG, WEBP, GIF. Taille max 2 MB."
|
||||
Opacity="0.8"
|
||||
TextWrapping="Wrap" />
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ public static class CallHubMethods
|
|||
{
|
||||
public const string SetContactPreferences = "SetContactPreferences";
|
||||
public const string Invite = "InviteCall";
|
||||
public const string InviteAudio = "InviteAudioCall";
|
||||
public const string InviteLan = "InviteLanCall";
|
||||
public const string Accept = "AcceptCall";
|
||||
public const string End = "EndCall";
|
||||
|
|
@ -16,7 +17,8 @@ public static class CallHubMethods
|
|||
public const string SignalReceived = "CallSignal";
|
||||
}
|
||||
|
||||
public sealed record ContactPreferences(bool AllowAudioCalls, bool AllowVideoCalls, bool AllowPrivateMessages);
|
||||
public sealed record ContactPreferences(bool AllowAudioCalls, bool AllowVideoCalls, bool AllowPrivateMessages,
|
||||
bool SupportsAudioOnly = false);
|
||||
|
||||
public enum CallDisplayMode
|
||||
{
|
||||
|
|
|
|||
|
|
@ -20,10 +20,14 @@ public partial class ChatHub
|
|||
public Task<CallSession> InviteCall(string roomName, string callee) =>
|
||||
InviteCoreAsync(roomName, callee, CallTransports.WebRtc);
|
||||
|
||||
public Task<CallSession> InviteAudioCall(string roomName, string callee) =>
|
||||
InviteCoreAsync(roomName, callee, CallTransports.WebRtc, CallDisplayMode.AudioOnly);
|
||||
|
||||
public Task<CallSession> InviteLanCall(string roomName, string callee) =>
|
||||
InviteCoreAsync(roomName, callee, CallTransports.LanSrtp);
|
||||
|
||||
private async Task<CallSession> InviteCoreAsync(string roomName, string callee, string transport)
|
||||
private async Task<CallSession> InviteCoreAsync(string roomName, string callee, string transport,
|
||||
CallDisplayMode mode = CallDisplayMode.AudioVideo)
|
||||
{
|
||||
var caller = CallUser();
|
||||
RequireSecureLanControl(transport);
|
||||
|
|
@ -33,7 +37,7 @@ public partial class ChatHub
|
|||
RequireCallPresence(roomName, caller, callee);
|
||||
var relayOnly = await RequiresRelayAsync(caller, callee);
|
||||
return await _calls.InviteAsync(roomName, caller, callee, Context.ConnectionId,
|
||||
_cxManager.GetConnexionIds(callee)?.Distinct().ToArray() ?? [], relayOnly, transport);
|
||||
_cxManager.GetConnexionIds(callee)?.Distinct().ToArray() ?? [], relayOnly, transport, mode);
|
||||
}
|
||||
|
||||
public async Task AcceptCall(Guid callId)
|
||||
|
|
|
|||
|
|
@ -65,7 +65,8 @@ public sealed class CallSignalingService(
|
|||
private bool AllowsCallMode(string connection, CallDisplayMode mode) => mode switch
|
||||
{
|
||||
CallDisplayMode.AudioVideo => GetContactPreferences(connection)?.AllowVideoCalls != false,
|
||||
CallDisplayMode.AudioOnly => GetContactPreferences(connection)?.AllowAudioCalls == true,
|
||||
CallDisplayMode.AudioOnly => GetContactPreferences(connection) is
|
||||
{ AllowAudioCalls: true, SupportsAudioOnly: true },
|
||||
_ => false
|
||||
};
|
||||
|
||||
|
|
@ -98,6 +99,8 @@ public sealed class CallSignalingService(
|
|||
ValidateTransport(transport, relayOnly);
|
||||
if (displayMode is not (CallDisplayMode.AudioVideo or CallDisplayMode.AudioOnly))
|
||||
throw new HubException("Unknown call mode.");
|
||||
if (transport == CallTransports.LanSrtp && displayMode == CallDisplayMode.AudioOnly)
|
||||
throw new HubException("Audio-only calls require WebRTC.");
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
|
|
|
|||
|
|
@ -59,8 +59,12 @@ public sealed class CallSignalingTests
|
|||
public async Task Audio_mode_reaches_only_devices_that_announced_audio_and_is_preserved_on_acceptance()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
await f.Service.SetContactPreferencesAsync("alice-device", new(true, true, true));
|
||||
await f.Service.SetContactPreferencesAsync("bob-1", new(true, false, true));
|
||||
await f.Service.SetContactPreferencesAsync("alice-device", new(true, true, true, true));
|
||||
await f.Service.SetContactPreferencesAsync("bob-1", new(true, false, true, true));
|
||||
await f.Service.SetContactPreferencesAsync("bob-2", new(true, true, true));
|
||||
await Assert.ThrowsAsync<HubException>(() => f.Service.InviteAsync(
|
||||
"General", "alice", "bob", "alice-device", ["bob-1"], false,
|
||||
transport: CallTransports.LanSrtp, displayMode: CallDisplayMode.AudioOnly));
|
||||
await Assert.ThrowsAsync<HubException>(() => f.Service.InviteAsync(
|
||||
"General", "alice", "bob", "alice-device", ["bob-2"], false,
|
||||
displayMode: CallDisplayMode.AudioOnly));
|
||||
|
|
|
|||
Loading…
Reference in a new issue