From 377afc711a093ed7ad8aa7d943fdafeec2b7d013 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Mon, 2 Nov 2026 15:17:23 +0000 Subject: [PATCH 1/6] Share podcast devices with calls and persist network selection Reuse camera and microphone preferences across podcast and chat-room pages. Restore available LAN/VPN addresses without persisting disclosure consent, and cover shared preferences and save failures with regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + doc/Architecture.md | 8 ++ .../PostIt.Tests/LanCallViewModelTests.cs | 91 ++++++++++++++ .../PostIt.Tests/PodcastPreferencesTests.cs | 20 +++- .../PostIt/ViewModels/Chat/ChatViewModel.cs | 2 +- .../ViewModels/Chat/LanCallViewModel.cs | 113 ++++++++++++++++-- .../ViewModels/PodcastsPageViewModel.cs | 10 ++ .../PostIt/ViewModels/Settings/Settings.cs | 4 + 8 files changed, 236 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41b544604..8efc50e9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Added +* [PostIt] Share podcast camera/microphone preferences with chat-room calls and persist the selected LAN/VPN address. Restore only currently available network addresses without remembering address-disclosure consent; require an explicit microphone choice for calls when podcasts use no microphone. * [PostIt] Remember detected podcast cameras/microphones, selected devices (including no microphone) and the default title in user settings; restore them when reopening the page and report persistence failures. * [Podcasts] Reuse persisted LiveFlow entities to prepare, edit and delete emissions from PostIt with a title, scheduled start and estimated duration. Keep start/stop manual and plans private; optionally publish presentation-only announcements on Yavsc.Org without opening anonymous playback. Preserve broadcast identifiers, legacy recordings and authenticated HLS/MP4 access; add a scheduling migration and lifecycle/privacy regressions. * [PostIt/API/Yavsc.Org] Expose the private PayPal recipient setting in PostIt's performer editor and authenticated profile API; validate addresses, allow disabling with an empty value and preserve the setting for older clients. Make Web donation settings discoverable from the performer profile and podcast catalogue. diff --git a/doc/Architecture.md b/doc/Architecture.md index 17df96891..8fb43ee2b 100644 --- a/doc/Architecture.md +++ b/doc/Architecture.md @@ -93,6 +93,14 @@ le materiel disponible en conservant les choix encore presents. Le choix « sans microphone » est memorise lui aussi. Charger le titre d'une emission preparee ne remplace pas le titre par defaut ; une saisie explicite le modifie. Les erreurs de sauvegarde sont affichees dans la page. +Les appels des salons de discussion reutilisent ces memes choix camera/micro +et enregistrent leurs changements dans les memes parametres. La page Podcasts +les recharge a son activation. Les appels exigent toujours un microphone : +le choix podcast « sans microphone » laisse donc le micro d'appel non selectionne. +L'adresse LAN/VPN choisie pour les appels est aussi memorisee, mais restauree +uniquement si elle est encore presente sur une interface locale active. +Sinon, une nouvelle selection est requise. Le consentement au partage +d'adresse avec le pair n'est jamais memorise. PostIt permet de preparer, modifier et supprimer une emission avant son demarrage : titre, date/heure locale, duree entiere positive en minutes et diff --git a/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs b/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs index 6afe892a2..316997292 100644 --- a/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs +++ b/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs @@ -2,12 +2,103 @@ using Avalonia.Controls; using Avalonia.Headless.XUnit; using PostIt.Services; using PostIt.ViewModels.Chat; +using PostIt.ViewModels; using Yavsc.Abstract.Chat.Calls; namespace PostIt.Tests; public sealed class LanCallViewModelTests { + [AvaloniaFact] + public async Task Calls_restore_shared_devices_and_persist_choices_and_network_address() + { + var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}.json"); + var previousDevices = Platform.GetLanCallDevices; + try + { + var settings = new Settings(path) + { + PodcastCameras = [new("Front", "front"), new("Rear", "rear")], + PodcastMicrophones = [new("None", ""), new("USB", "usb"), new("Built-in", "built-in")], + PodcastCameraId = "rear", PodcastMicrophoneId = "usb" + }; + await using (var vm = new LanCallViewModel(new Signaling(), settings: settings)) + { + Assert.Equal("rear", vm.Camera?.Value); + Assert.Equal("usb", vm.Microphone?.Value); + Assert.False(vm.AllowAddressDisclosure); + vm.Camera = vm.Cameras[0]; + vm.Microphone = vm.Microphones[1]; + Assert.Equal("front", settings.PodcastCameraId); + Assert.Equal("built-in", settings.PodcastMicrophoneId); + Assert.NotEmpty(vm.Addresses); + vm.Address = vm.Addresses.Last(); + settings.Save(); + var preferred = vm.Address; + Platform.GetLanCallDevices = () => new( + [new("Rear", "rear"), new("Front", "front")], + [new("Built-in", "built-in"), new("USB", "usb")]); + vm.RefreshDevicesCommand.Execute(null); + Assert.Equal("front", vm.Camera?.Value); + Assert.Equal("built-in", vm.Microphone?.Value); + Assert.Equal(preferred, vm.Address); + Assert.Contains(settings.PodcastMicrophones, d => d.Value == ""); + + var reloaded = new Settings(path); + reloaded.Authentication.Authority = ""; + reloaded.Load(); + await using var restored = new LanCallViewModel(new Signaling(), settings: reloaded); + Assert.Equal(preferred, restored.Address); + Assert.Equal("front", restored.Camera?.Value); + Assert.Equal("built-in", restored.Microphone?.Value); + Assert.False(restored.AllowAddressDisclosure); + settings.PodcastCameraId = "rear"; + Assert.Equal("rear", vm.Camera?.Value); + settings.PodcastMicrophoneId = ""; + Assert.Null(vm.Microphone); + vm.AllowAddressDisclosure = true; + vm.Room = "General"; + vm.Target = "bob"; + await vm.InviteCommand.ExecuteAsync(null); + Assert.Contains("microphone", vm.Status); + } + } + finally { Platform.GetLanCallDevices = previousDevices; File.Delete(path); } + } + + [AvaloniaFact] + public async Task Call_preference_save_failures_are_reported_without_losing_the_choice() + { + var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}"); + Directory.CreateDirectory(path); + try + { + var settings = new Settings(path); + await using var vm = new LanCallViewModel(new Signaling(), settings: settings); + vm.Address = null; + vm.Address = "127.0.0.1"; + Assert.Equal("127.0.0.1", settings.LanCallAddress); + Assert.Contains("sauvegarde impossible", vm.Status); + Assert.True(settings.IsDirty); + } + finally { Directory.Delete(path); } + } + + [AvaloniaFact] + public async Task Missing_saved_network_address_requires_a_new_selection_and_does_not_restore_consent() + { + var path = Path.Combine(Path.GetTempPath(), $"postit-call-preferences-{Guid.NewGuid():N}.json"); + try + { + var settings = new Settings(path) { LanCallAddress = "not-a-local-address" }; + await using var vm = new LanCallViewModel(new Signaling(), settings: settings); + Assert.Null(vm.Address); + Assert.False(vm.AllowAddressDisclosure); + Assert.Equal("not-a-local-address", settings.LanCallAddress); + } + finally { File.Delete(path); } + } + private static CallSession Session() => new(Guid.NewGuid(), "General", "alice", "bob", false, DateTimeOffset.UtcNow.AddMinutes(1), CallTransports.LanSrtp); diff --git a/src/PostIt/PostIt.Tests/PodcastPreferencesTests.cs b/src/PostIt/PostIt.Tests/PodcastPreferencesTests.cs index ff822e492..cd7acbb53 100644 --- a/src/PostIt/PostIt.Tests/PodcastPreferencesTests.cs +++ b/src/PostIt/PostIt.Tests/PodcastPreferencesTests.cs @@ -2,6 +2,8 @@ using Avalonia.Headless.XUnit; using PostIt.Services; using PostIt.ViewModels; using Yavsc.Api.Client; +using Yavsc.Abstract.Identity; +using Yavsc.Abstract.Streaming; namespace PostIt.Tests; @@ -37,13 +39,18 @@ public sealed class PodcastPreferencesTests Assert.Equal("rear", restored.PodcastCameraId); Assert.Equal("", restored.PodcastMicrophoneId); Platform.GetPodcastCaptureDevices = () => throw new InvalidOperationException("Must use saved devices."); - await using var otherApi = new YavscApiClient(restored, new TokenStore(path + ".tokens")); + await using var otherApi = new PreferencesApi(restored, new TokenStore(path + ".tokens")); var other = new PodcastsPageViewModel(new PodcastApiClient(otherApi, () => restored.ApiUrl), otherApi, session); Assert.Equal(2, other.Cameras.Count); Assert.Equal(2, other.Microphones.Count); Assert.Equal("rear", other.SelectedCamera?.Value); Assert.Equal("", other.SelectedMicrophone?.Value); Assert.Equal(vm.Title, other.Title); + restored.PodcastCameraId = "front"; + restored.PodcastMicrophoneId = "usb"; + await other.ActivateAsync(); + Assert.Equal("front", other.SelectedCamera?.Value); + Assert.Equal("usb", other.SelectedMicrophone?.Value); Platform.GetPodcastCaptureDevices = () => new([], []); other.DetectDevicesCommand.Execute(null); @@ -57,6 +64,17 @@ public sealed class PodcastPreferencesTests File.Delete(path); File.Delete(path + ".tokens"); } + + } + + private sealed class PreferencesApi(Settings settings, TokenStore store) : YavscApiClient(settings, store) + { + public override Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + { + object response = path.EndsWith("/account/me", StringComparison.Ordinal) + ? new Me { UserId = "owner" } : new List(); + return Task.FromResult((T)response); + } } [AvaloniaFact] diff --git a/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs b/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs index 50dacd192..d44ebcd65 100644 --- a/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs @@ -222,7 +222,7 @@ namespace PostIt.ViewModels.Chat Calls = new CallSignalingClient(_connection); if (SupportsLanCalls) - LanCall = new LanCallViewModel(Calls) { Room = SelectedRoom ?? "" }; + LanCall = new LanCallViewModel(Calls, settings: _settings) { Room = SelectedRoom ?? "" }; else Calls.Invitation += call => Avalonia.Threading.Dispatcher.UIThread.Post(() => Log($"Invitation audio-vidéo de {call.Caller} dans {call.RoomName} ; transport non disponible sur cette plateforme.")); diff --git a/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs b/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs index 5753e7b36..a2055f913 100644 --- a/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs @@ -31,6 +31,8 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable private string? _activeMicrophone; private string? _activeAddress; private int _activePort; + private readonly Settings? _settings; + private bool _restoringPreferences; public ObservableCollection Addresses { get; } = []; public ObservableCollection Cameras { get; } = []; @@ -53,9 +55,11 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable [ObservableProperty] public partial Control? RemoteVideo { get; set; } public bool CanConfigure => !Busy || Incoming; - public LanCallViewModel(ILanCallSignaling signaling, Func? createMedia = null) + public LanCallViewModel(ILanCallSignaling signaling, Func? createMedia = null, + Settings? settings = null) { _signaling = signaling; + _settings = settings; _createMedia = createMedia ?? Platform.CreateLanCallMedia ?? ((address, port) => new LinuxLanCallVideo(address, port)); signaling.Invitation += OnInvitation; @@ -64,22 +68,98 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable signaling.Ended += OnEnded; signaling.Interrupted += OnInterrupted; Platform.PlaybackSuspending += OnSuspending; + if (settings != null) + { + _restoringPreferences = true; + try + { + foreach (var device in settings.PodcastCameras) Cameras.Add(device); + foreach (var device in settings.PodcastMicrophones.Where(d => !string.IsNullOrEmpty(d.Value))) + Microphones.Add(device); + RestoreDevices(); + RefreshAddresses(); + } + catch (NetworkInformationException ex) { Status = $"Adresses reseau indisponibles : {ex.Message}"; } + finally { _restoringPreferences = false; } + settings.PropertyChanged += OnSettingsChanged; + } + } + + private void OnSettingsChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs args) + { + if (_restoringPreferences || !CanConfigure) return; + if (args.PropertyName is not (nameof(Settings.PodcastCameraId) or nameof(Settings.PodcastMicrophoneId) + or nameof(Settings.PodcastCameras) or nameof(Settings.PodcastMicrophones))) return; + _restoringPreferences = true; + try + { + Cameras.Clear(); + Microphones.Clear(); + foreach (var device in _settings!.PodcastCameras) Cameras.Add(device); + foreach (var device in _settings.PodcastMicrophones.Where(d => !string.IsNullOrEmpty(d.Value))) Microphones.Add(device); + RestoreDevices(); + } + finally { _restoringPreferences = false; } + } + + private void RestoreDevices() + { + Camera = Cameras.FirstOrDefault(d => d.Value == _settings?.PodcastCameraId) ?? Cameras.FirstOrDefault(); + Microphone = _settings?.PodcastMicrophoneId == "" ? null + : Microphones.FirstOrDefault(d => d.Value == _settings?.PodcastMicrophoneId) ?? Microphones.FirstOrDefault(); + } + + private void RefreshAddresses() + { + var preferred = _settings?.LanCallAddress ?? Address; + Addresses.Clear(); + foreach (var address in NetworkInterface.GetAllNetworkInterfaces() + .Where(n => n.OperationalStatus == OperationalStatus.Up) + .SelectMany(n => n.GetIPProperties().UnicastAddresses) + .Select(a => a.Address.ToString()).Where(LanCallNetwork.IsPrivateIPv4) + .Distinct().OrderBy(a => IPAddress.IsLoopback(IPAddress.Parse(a)))) + Addresses.Add(address); + Address = preferred == null ? Addresses.FirstOrDefault() : Addresses.FirstOrDefault(a => a == preferred); + } + + partial void OnCameraChanged(CaptureDevice? value) + { + if (_restoringPreferences || _settings == null || value == null) return; + _settings.PodcastCameraId = value.Value; + SavePreferences(); + } + + partial void OnMicrophoneChanged(CaptureDevice? value) + { + if (_restoringPreferences || _settings == null || value == null) return; + _settings.PodcastMicrophoneId = value.Value; + SavePreferences(); + } + + partial void OnAddressChanged(string? value) + { + if (_restoringPreferences || _settings == null || value == null) return; + _settings.LanCallAddress = value; + SavePreferences(); + } + + private void SavePreferences() + { + try { _settings?.Save(); } + catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException) + { + Status = $"Preferences d'appel appliquees, mais sauvegarde impossible : {ex.Message}"; + } } [RelayCommand] private void RefreshDevices() { + _restoringPreferences = true; try { if (!CanConfigure) throw new InvalidOperationException("Terminez l'appel avant de changer les peripheriques."); - Addresses.Clear(); - foreach (var address in NetworkInterface.GetAllNetworkInterfaces() - .Where(n => n.OperationalStatus == OperationalStatus.Up) - .SelectMany(n => n.GetIPProperties().UnicastAddresses) - .Select(a => a.Address.ToString()).Where(LanCallNetwork.IsPrivateIPv4) - .Distinct().OrderBy(a => IPAddress.IsLoopback(IPAddress.Parse(a)))) - Addresses.Add(address); - Address = Addresses.FirstOrDefault(); + RefreshAddresses(); Cameras.Clear(); Microphones.Clear(); if (Platform.GetLanCallDevices is { } getDevices) @@ -97,14 +177,24 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable foreach (var device in streamer.GetCaptureDevices()) Cameras.Add(new(device.Key, device.Value)); foreach (var device in streamer.GetAudioCaptureDevices()) Microphones.Add(new(device.Key, device.Value)); } - Camera = Cameras.FirstOrDefault(); - Microphone = Microphones.FirstOrDefault(); + RestoreDevices(); Status = Cameras.Count == 0 ? "Aucune camera detectee. Verifiez les peripheriques puis actualisez." : Incoming && _call != null ? $"{_call.Caller} propose un appel dans {_call.RoomName}. Selectionnez vos peripheriques puis acceptez ou refusez." : "Selectionnez le pair, l'adresse LAN/VPN et les peripheriques. Utilisez un casque."; + if (_settings != null) + { + _settings.PodcastCameras = Cameras.ToArray(); + var noMicrophone = _settings.PodcastMicrophones.Where(d => string.IsNullOrEmpty(d.Value)); + _settings.PodcastMicrophones = noMicrophone.Concat(Microphones).ToArray(); + if (Camera != null) _settings.PodcastCameraId = Camera.Value; + if (Microphone != null) _settings.PodcastMicrophoneId = Microphone.Value; + if (Address != null) _settings.LanCallAddress = Address; + SavePreferences(); + } } catch (Exception error) { Status = "Peripheriques indisponibles : " + error.Message; } + finally { _restoringPreferences = false; } } private void ValidateSelection() @@ -324,6 +414,7 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable _signaling.Ended -= OnEnded; _signaling.Interrupted -= OnInterrupted; Platform.PlaybackSuspending -= OnSuspending; + if (_settings != null) _settings.PropertyChanged -= OnSettingsChanged; try { await StopAsync("Appel arrete.", true); } finally { _lifetime.Dispose(); } } diff --git a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs index 109fcb242..06ba92e1a 100644 --- a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs @@ -267,6 +267,16 @@ public partial class PodcastsPageViewModel : ViewModelBase public async Task ActivateAsync() { + _restoringPreferences = true; + try + { + Cameras.Clear(); + Microphones.Clear(); + foreach (var device in _api.Settings.PodcastCameras) Cameras.Add(device); + foreach (var device in _api.Settings.PodcastMicrophones) Microphones.Add(device); + RestoreDeviceSelection(); + } + finally { _restoringPreferences = false; } if (_pageCancellation.IsCancellationRequested) { _pageCancellation.Dispose(); diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 49707c036..b8bbb2702 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -56,6 +56,8 @@ public partial class Settings : ViewModelBase public partial string? PodcastCameraId { get; set; } [ObservableProperty] public partial string? PodcastMicrophoneId { get; set; } + [ObservableProperty] + public partial string? LanCallAddress { get; set; } [ObservableProperty] [JsonIgnore] @@ -156,6 +158,7 @@ public partial class Settings : ViewModelBase partial void OnPodcastMicrophonesChanged(CaptureDevice[] value) => MarkDirty(); partial void OnPodcastCameraIdChanged(string? value) => MarkDirty(); partial void OnPodcastMicrophoneIdChanged(string? value) => MarkDirty(); + partial void OnLanCallAddressChanged(string? value) => MarkDirty(); /// /// Authentication can be reassigned wholesale by @@ -418,6 +421,7 @@ public partial class Settings : ViewModelBase PodcastMicrophones = settings.PodcastMicrophones ?? []; PodcastCameraId = settings.PodcastCameraId; PodcastMicrophoneId = settings.PodcastMicrophoneId; + LanCallAddress = settings.LanCallAddress; if (!(settings.Authentication is null)) { this.Authentication = new AuthenticationSettings(); From 7f0e868a3249ab14944416c517fac7c2ef412404 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Mon, 2 Nov 2026 15:20:43 +0000 Subject: [PATCH 2/6] Update bundled settings with the default podcast title, camera/microphone preferences and French language selection. --- CHANGELOG.md | 6 ++++++ src/PostIt/PostIt/postit-settings.json | 26 ++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8efc50e9b..85ec69c16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ # Changelog +## [1.0.8-rc35] - unstable + +### Added + +* [PostIt] Update bundled settings with the default podcast title, camera/microphone preferences and French language selection. + ## [1.0.8-rc34] - unstable ### Added diff --git a/src/PostIt/PostIt/postit-settings.json b/src/PostIt/PostIt/postit-settings.json index f46edd808..20746ede7 100644 --- a/src/PostIt/PostIt/postit-settings.json +++ b/src/PostIt/PostIt/postit-settings.json @@ -12,5 +12,27 @@ "BlogsApiUrl": "https://blogs.pschneider.fr/api/v1/", "ApiUrl": "https://api.pschneider.fr/api/v1/", "SearchText": "", - "ProviderOngoingRequestsSortOption": "" -} + "IsMarkdownViewerVisible": false, + "ProviderOngoingRequestsSortOption": "", + "PodcastDefaultTitle": "Le chant des marais", + "PodcastCameras": [ + { + "Name": "Cam\u00E9ra (/dev/video0)", + "Value": "/dev/video0" + } + ], + "PodcastMicrophones": [ + { + "Name": "Sans microphone", + "Value": "" + }, + { + "Name": "Microphone par defaut (PulseAudio)", + "Value": "default" + } + ], + "PodcastCameraId": "/dev/video0", + "PodcastMicrophoneId": "default", + "SelectedLanguage": "fr-FR", + "SaveCommand": {} +} \ No newline at end of file From 73411f2f7e273e9fed50da907762a3bfb7863ad8 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Mon, 2 Nov 2026 15:25:54 +0000 Subject: [PATCH 3/6] Allow public IPv4 addresses for direct SRTP calls Use shared unicast IPv4 validation for interface discovery, media endpoints and server signaling. Preserve disclosure consent and privacy constraints, and document direct connectivity requirements. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + doc/architecture/audio-video-calls.md | 21 +++++++++++++---- .../PostIt.Tests/LanCallViewModelTests.cs | 12 ++++++++++ .../PostIt/Services/LibVlcLanCallMedia.cs | 2 +- .../ViewModels/Chat/LanCallViewModel.cs | 8 +++---- src/PostIt/PostIt/Views/Chat/ChatPage.axaml | 8 +++---- .../Chat/Calls/CallContracts.cs | 12 +++++++++- .../CallLanSignalingTests.cs | 23 +++++++++++++------ 8 files changed, 65 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 85ec69c16..0c33380c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Added +* [PostIt/Calls] Allow directly assigned public IPv4 addresses for direct SRTP calls, alongside LAN/VPN and loopback addresses. Share unicast validation between interface discovery, media and server signaling; continue rejecting unspecified, link-local, multicast, reserved and IPv6 addresses. Keep explicit address-disclosure consent and no automatic NAT traversal. * [PostIt] Update bundled settings with the default podcast title, camera/microphone preferences and French language selection. ## [1.0.8-rc34] - unstable diff --git a/doc/architecture/audio-video-calls.md b/doc/architecture/audio-video-calls.md index 4c4ee0f26..789c587ac 100644 --- a/doc/architecture/audio-video-calls.md +++ b/doc/architecture/audio-video-calls.md @@ -5,7 +5,7 @@ Ce document décrit l'architecture cible et l'implémentation commencée. La préférence de confidentialité est persistée et éditable dans le profil. La signalisation est intégrée au chat, désactivée par défaut. Un premier -transport natif **Android et Desktop Linux sur LAN/VPN** est raccordé : +transport natif **Android et Desktop Linux en IPv4 directe (LAN/VPN ou IP publique)** est raccordé : captures Podcast existantes et SRTP direct, sans libwebrtc ni nouvelle couche JNI WebRTC. Il ne réalise pas encore la cible Internet, TURN ou groupe. Il complète la [topologie de PostIt](postit.md) et les @@ -18,7 +18,17 @@ La cible couvre : - les appels de groupe ; - les clients Browser, Android et Desktop. -## Première implémentation Android et Desktop Linux : SRTP sur LAN/VPN +## Première implémentation Android et Desktop Linux : SRTP direct IPv4 + +Les adresses IPv4 publiques directement assignees a une interface locale active +sont egalement disponibles, avec la meme validation unicast cote client, +media et signalisation serveur. Les adresses non specifiees, link-local, +multicast, reservees (240/4), IPv6 et les formes non canoniques sont refusees. +Il faut autoriser en entree les deux ports UDP consecutifs choisis et assurer +la joignabilite entre les pairs. Ce support n'ajoute ni ICE/TURN ni traversee +NAT automatique : l'adresse publique d'un routeur ne remplace pas une adresse +assignee a la machine. Le consentement explicite au partage d'IP et le refus +du mode direct pour les comptes masquant leur IP restent inchanges. Cette tranche réutilise la capture caméra/microphone et les encodeurs des Podcasts, mais **pas leur segmentation HLS ni leurs envois de fichiers** : @@ -67,7 +77,7 @@ de fichier média temporaire ou de moteur WebRTC Android ajouté. H.264/AAC. La version Debian 13 a été utilisée pour les essais Linux. Les deux comptes doivent être présents dans la même salle existante et ne pas se bloquer mutuellement. -3. Dans « Appel direct (LAN/VPN) », actualiser les périphériques, +3. Dans « Appel direct IPv4 (LAN/VPN ou IP publique) », actualiser les périphériques, sélectionner la caméra, le microphone et une IPv4 privée locale accessible depuis le pair. Les adresses RFC1918 et de bouclage sont acceptées ; pas de DNS, IPv6 ou adresse publique. Le bouclage sert aux @@ -79,7 +89,7 @@ de fichier média temporaire ou de moteur WebRTC Android ajouté. adresse doivent utiliser des paires distinctes. Aucun pare-feu n'est modifié automatiquement. 5. Saisir le pseudo exact du destinataire, confirmer la divulgation de - l'adresse LAN/VPN, puis appeler. Le destinataire choisit ses propres + l'adresse IPv4 locale (LAN/VPN ou publique), puis appeler. Le destinataire choisit ses propres périphériques et son adresse, confirme et accepte explicitement. Aucun accès à la caméra/microphone ne commence avant l'acceptation ; l'émission attend également la destination validée du pair. @@ -140,7 +150,8 @@ l'ajout d'un moteur WebRTC ou d'une cryptographie propre au projet. Il n'y a aucun repli direct contournant cette préférence. - Pas d'ICE, de STUN, de TURN, de traversée NAT automatique, de groupe, d'interopérabilité Browser, de négociation de codecs ni - d'adaptation de débit. Ce mode exige un LAN/VPN routable entre les pairs. + d'adaptation de débit. Ce mode exige une connectivite IPv4 directe entre les pairs + (LAN/VPN ou adresse publique assignee), avec les ports UDP ouverts. - H.264 à 30 images/s, cible 1 200 kbit/s ; AAC mono 48 kHz, 96 kbit/s. Ces réglages ne constituent pas une garantie de latence ni de débit. Le retour local n'émet pas le son du microphone. diff --git a/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs b/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs index 316997292..9de24bbcb 100644 --- a/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs +++ b/src/PostIt/PostIt.Tests/LanCallViewModelTests.cs @@ -114,6 +114,18 @@ public sealed class LanCallViewModelTests return vm; } + [AvaloniaFact] + public async Task Public_ipv4_can_be_selected_for_an_explicitly_consented_direct_call() + { + var signaling = new Signaling(); + await using var vm = Configure(signaling, (_, _) => throw new Exception("No media before acceptance")); + vm.Addresses.Add("8.8.8.8"); + vm.Address = "8.8.8.8"; + await vm.InviteCommand.ExecuteAsync(null); + Assert.Equal(1, signaling.Invites); + Assert.True(vm.Busy); + } + [AvaloniaFact] public async Task No_capture_starts_before_explicit_acceptance_and_endpoint_exchange() { diff --git a/src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs b/src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs index da7488a46..785838c02 100644 --- a/src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs +++ b/src/PostIt/PostIt/Services/LibVlcLanCallMedia.cs @@ -35,7 +35,7 @@ public sealed class LibVlcLanCallMedia : IAsyncDisposable Endpoint = new(localAddress, port, Convert.ToHexString(RandomNumberGenerator.GetBytes(16)), Convert.ToHexString(RandomNumberGenerator.GetBytes(14))); if (!Endpoint.IsValid()) - throw new ArgumentException("Adresse IPv4 privee et port UDP pair (1024-65534) requis."); + throw new ArgumentException("Adresse IPv4 unicast et port UDP pair (1024-65534) requis."); using (var reservation = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var rtcp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { diff --git a/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs b/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs index a2055f913..88340b853 100644 --- a/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Chat/LanCallViewModel.cs @@ -116,7 +116,7 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable foreach (var address in NetworkInterface.GetAllNetworkInterfaces() .Where(n => n.OperationalStatus == OperationalStatus.Up) .SelectMany(n => n.GetIPProperties().UnicastAddresses) - .Select(a => a.Address.ToString()).Where(LanCallNetwork.IsPrivateIPv4) + .Select(a => a.Address.ToString()).Where(LanCallNetwork.IsUnicastIPv4) .Distinct().OrderBy(a => IPAddress.IsLoopback(IPAddress.Parse(a)))) Addresses.Add(address); Address = preferred == null ? Addresses.FirstOrDefault() : Addresses.FirstOrDefault(a => a == preferred); @@ -181,7 +181,7 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable Status = Cameras.Count == 0 ? "Aucune camera detectee. Verifiez les peripheriques puis actualisez." : Incoming && _call != null ? $"{_call.Caller} propose un appel dans {_call.RoomName}. Selectionnez vos peripheriques puis acceptez ou refusez." - : "Selectionnez le pair, l'adresse LAN/VPN et les peripheriques. Utilisez un casque."; + : "Selectionnez le pair, l'adresse IPv4 locale ou publique et les peripheriques. Utilisez un casque."; if (_settings != null) { _settings.PodcastCameras = Cameras.ToArray(); @@ -200,10 +200,10 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable private void ValidateSelection() { if (!AllowAddressDisclosure) - throw new InvalidOperationException("Confirmez le partage de votre adresse LAN/VPN avec le pair."); + throw new InvalidOperationException("Confirmez le partage de votre adresse IPv4 avec le pair."); if (Camera == null || Microphone == null) throw new InvalidOperationException("Une camera et un microphone sont requis."); - if (Address == null || !Addresses.Contains(Address) || !LanCallNetwork.IsPrivateIPv4(Address) || + if (Address == null || !Addresses.Contains(Address) || !LanCallNetwork.IsUnicastIPv4(Address) || !int.TryParse(Port, out var port) || port is < 1024 or > 65534 || port % 2 != 0) throw new InvalidOperationException("Selectionnez une adresse locale et un port UDP pair (1024-65534)."); _activeCamera = Camera.Value; diff --git a/src/PostIt/PostIt/Views/Chat/ChatPage.axaml b/src/PostIt/PostIt/Views/Chat/ChatPage.axaml index d9e513f97..92a7ed7e7 100644 --- a/src/PostIt/PostIt/Views/Chat/ChatPage.axaml +++ b/src/PostIt/PostIt/Views/Chat/ChatPage.axaml @@ -103,16 +103,16 @@ Content="Envoyer" /> - - public class YavscApiClient : IYavscApiClient, IAsyncDisposable { + public event Func? SigningOut; + private int _signingOut; + public bool IsSigningOut => Volatile.Read(ref _signingOut) != 0; // 60s of slack before the access_token's nominal expiry. Covers // network latency + JWT validation on the server side. private static readonly TimeSpan RefreshSkew = TimeSpan.FromSeconds(60); @@ -562,8 +565,27 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable public async Task LogoutAsync() { - _store.Clear(); - _tokens = null; + Interlocked.Exchange(ref _signingOut, 1); + try + { + if (SigningOut is { } handlers) + foreach (Func handler in handlers.GetInvocationList()) + await handler(); + } + finally + { + await _refreshGate.WaitAsync(); + try + { + try { _store.Clear(); } + finally { _tokens = null; } + } + finally + { + _refreshGate.Release(); + Interlocked.Exchange(ref _signingOut, 0); + } + } // Optional: clear the IdP session in the browser too. // await _oidc.LogoutAsync(new LogoutRequest()); await Task.CompletedTask; diff --git a/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs b/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs index d44ebcd65..144ab7e57 100644 --- a/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Chat/ChatViewModel.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; +using System.Threading; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Microsoft.AspNetCore.SignalR.Client; @@ -22,14 +23,30 @@ namespace PostIt.ViewModels.Chat { private readonly Settings _settings; private readonly YavscApiClient? _api; + private readonly ChatHubConnection? _transport; + private bool _handlersRegistered; + private readonly SemaphoreSlim _connectionGate = new(1); + private int _sessionVersion; + private readonly object _connectOperationGate = new(); + private CancellationTokenSource? _connectOperation; + private long _lastDeliverySequence; + public bool ConnectionRequested { get; private set; } + public event Action? ConnectionRequestedChanged; // Le paramètre optionnel permet l'instanciation design-time // (Design.DataContext dans ChatPage.axaml) sans conteneur DI. - public ChatViewModel(YavscApiClient? api = null) + public ChatViewModel(YavscApiClient? api = null, Settings? settings = null, ChatHubConnection? transport = null) { var app = App.Current as App; - _settings = app!.ServiceProvider!.GetRequiredService(); // Assurez-vous que _settings est initialisé avant utilisation. + _settings = settings ?? app!.ServiceProvider!.GetRequiredService(); _api = api; + _transport = transport; + if (_transport != null) + { + _transport.RoomJoined += room => PostForCurrentSession(() => OnRoomJoined(room)); + _transport.Error += message => PostForCurrentSession(() => Log(message)); + _transport.MessageReceived += delivery => PostForCurrentSession(() => OnMessageReceived(delivery)); + } Status = new StatusNotice("Déconnecté", StatusSeverity.Info, new RelayCheckCommand("Connecter", async () => await ConnectAsync())); FocusedMessages = _systemMessages; @@ -46,7 +63,7 @@ namespace PostIt.ViewModels.Chat public partial LanCallViewModel? LanCall { get; set; } [ObservableProperty] - public partial string CurrentRoom { get; set; } = "General"; + public partial string CurrentRoom { get; set; } = "General"; [ObservableProperty] public partial string NickName { get; set; } = ""; @@ -105,6 +122,30 @@ namespace PostIt.ViewModels.Chat FocusedMessages.Add(line); } + private void PostForCurrentSession(Action callback) + { + var version = Volatile.Read(ref _sessionVersion); + Avalonia.Threading.Dispatcher.UIThread.Post(() => + { + if (ConnectionRequested && version == Volatile.Read(ref _sessionVersion)) + callback(); + }); + } + + private void OnMessageReceived(ChatHubConnection.ChatDelivery delivery) + { + if (delivery.Sequence <= _lastDeliverySequence) return; + _lastDeliverySequence = delivery.Sequence; + if (delivery.Room == null) + { + Log($"[Prive] {delivery.Sender} : {delivery.Text}"); + return; + } + if (!_messagesByRoom.TryGetValue(delivery.Room, out var messages)) + messages = _messagesByRoom[delivery.Room] = new(); + messages.Add($"{delivery.Sender} : {delivery.Text}"); + } + // Commandes pour les boutons [RelayCommand] public async Task ConnectCommand() => await ConnectAsync(); @@ -112,6 +153,24 @@ namespace PostIt.ViewModels.Chat [RelayCommand] public async Task JoinRoomCommand() => await JoinRoomAsync(); + [RelayCommand] + public async Task LeaveRoom() + { + var room = SelectedRoom; + if (_transport == null || room == null) return; + try + { + if (LanCall != null) await LanCall.HangupAsync(); + await _transport.LeaveAsync(room); + JoinedRooms.Remove(room); + _messagesByRoom.Remove(room); + _usersByRoom.Remove(room); + SelectedRoom = JoinedRooms.Count > 0 ? JoinedRooms[0] : null; + Log($"Salon quitte : {room}"); + } + catch (Exception ex) { Log($"Impossible de quitter le salon : {ex.Message}"); } + } + // Le serveur (ChatHub.Send) refuse tout message d'un utilisateur // qui n'a pas joint le salon ("NoJoinNoSend") : on garde la // commande inactive tant qu'aucune salle n'est en focus. @@ -137,7 +196,18 @@ namespace PostIt.ViewModels.Chat public override bool CanNavigateNext { get; protected set; } = false; public override bool CanNavigatePrevious { get; protected set; } = true; - private async Task DisconnectAsync() + public async Task DisconnectAsync() + { + ConnectionRequested = false; + ConnectionRequestedChanged?.Invoke(); + lock (_connectOperationGate) _connectOperation?.Cancel(); + Interlocked.Increment(ref _sessionVersion); + await _connectionGate.WaitAsync(); + try { await DisconnectCoreAsync(); } + finally { _connectionGate.Release(); } + } + + private async Task DisconnectCoreAsync() { Exception? callError = null; if (LanCall != null) @@ -148,28 +218,55 @@ namespace PostIt.ViewModels.Chat } Calls?.Dispose(); Calls = null; - if (_connection != null) + try { - await _connection.StopAsync(); - await _connection.DisposeAsync(); - _connection = null; + if (_connection != null) + await _transport!.StopAsync(); + } + catch (Exception error) { callError = error; throw; } + finally + { + IsConnected = false; + SelectedRoom = null; + JoinedRooms.Clear(); + _messagesByRoom.Clear(); + _usersByRoom.Clear(); + _systemMessages.Clear(); + Status = new StatusNotice(callError == null ? "Déconnecté" : + "Déconnecté ; erreur de fermeture : " + callError.Message, + callError == null ? StatusSeverity.Info : StatusSeverity.Error, + new RelayCheckCommand("Connecter", async () => await ConnectAsync())); } - IsConnected = false; - SelectedRoom = null; - JoinedRooms.Clear(); - _messagesByRoom.Clear(); - _usersByRoom.Clear(); - _systemMessages.Clear(); - Status = new StatusNotice(callError == null ? "Déconnecté" : - "Déconnecté ; erreur de fermeture de l'appel : " + callError.Message, - callError == null ? StatusSeverity.Info : StatusSeverity.Error, - new RelayCheckCommand("Connecter", async () => await ConnectAsync())); } - private async Task ConnectAsync() + public async Task ConnectAsync() + { + if (_api?.IsSigningOut == true) + { + Status = StatusNotice.Info("La deconnexion du compte est en cours."); + return; + } + ConnectionRequested = true; + ConnectionRequestedChanged?.Invoke(); + await _connectionGate.WaitAsync(); + try + { + if (!ConnectionRequested) return; + using var operation = new CancellationTokenSource(); + lock (_connectOperationGate) _connectOperation = operation; + try { await ConnectCoreAsync(operation.Token); } + finally { lock (_connectOperationGate) _connectOperation = null; } + } + finally { _connectionGate.Release(); } + } + + private async Task ConnectCoreAsync(CancellationToken ct) { try { + if (_transport?.IsCurrentConfiguration == true && + _connection?.State is HubConnectionState.Connected or HubConnectionState.Reconnecting) + return; if (_connection != null) { if (LanCall != null) @@ -179,8 +276,6 @@ namespace PostIt.ViewModels.Chat } Calls?.Dispose(); Calls = null; - await _connection.DisposeAsync(); - _connection = null; } Status = new StatusNotice("Connexion en cours...", StatusSeverity.Info, new RelayCheckCommand("Vérifier la connexion", async () => await CheckConnectionAsync())); @@ -192,125 +287,92 @@ namespace PostIt.ViewModels.Chat return; } - // Le hub est mappé à la racine du service ("/chathub"), - // pas sous le préfixe versionné "/api/v1" : on le retire. - var hubBase = _settings.ApiUrl.TrimEnd('/'); - if (hubBase.EndsWith("/api/v1", StringComparison.OrdinalIgnoreCase)) - hubBase = hubBase[..^"/api/v1".Length]; - var hubUrl = hubBase + "/" + Constants.ChatHubPath; - - _connection = new HubConnectionBuilder() - .WithUrl(hubUrl, - - options => - { - // Le hub est [Authorize] : on attache le Bearer OIDC. - // AccessTokenProvider est rappelé à chaque reconnexion, - // donc on tente un refresh silencieux à chaque appel. - // Un refresh mort (invalid_grant) ne doit pas faire - // échouer StartAsync avec une exception interne : on - // renvoie le token courant (éventuellement expiré) et - // le serveur répondra un 401 propre, surfacé à l'UI. - options.AccessTokenProvider = async () => - { - await _api.TrySilentLoginAsync(); - return _api.CurrentAccessToken; - }; - }) - .WithAutomaticReconnect() - .Build(); + if (_transport == null) + throw new InvalidOperationException("Transport de messagerie indisponible."); + var connection = await _transport.GetConnectionAsync(ct); + if (!ReferenceEquals(_connection, connection)) + _handlersRegistered = false; + _connection = connection; + // Le hub est [Authorize] : on attache le Bearer OIDC. Calls = new CallSignalingClient(_connection); if (SupportsLanCalls) LanCall = new LanCallViewModel(Calls, settings: _settings) { Room = SelectedRoom ?? "" }; else - Calls.Invitation += call => Avalonia.Threading.Dispatcher.UIThread.Post(() => + Calls.Invitation += call => PostForCurrentSession(() => Log($"Invitation audio-vidéo de {call.Caller} dans {call.RoomName} ; transport non disponible sur cette plateforme.")); - Calls.Ended += call => Avalonia.Threading.Dispatcher.UIThread.Post(() => + Calls.Ended += call => PostForCurrentSession(() => Log($"Appel terminé : {call.Reason}.")); - // 1. Ecoute des notifications globales (notifyUser) - _connection.On("notifyUser", (type, user, msg) => + if (!_handlersRegistered) { - Avalonia.Threading.Dispatcher.UIThread.Post(() => - Log($"[{type}] {user}: {msg}")); - }); - - // 2. Ecoute des notifications de salon (notifyRoom) - _connection.On("notifyRoom", (type, room, user) => - { - Avalonia.Threading.Dispatcher.UIThread.Post(() => + // 1. Ecoute des notifications globales (notifyUser) + _connection.On("notifyUser", (type, user, msg) => { - if (_messagesByRoom.TryGetValue(room, out var roomLog)) - roomLog.Add($"*{user} a interagi avec le salon {room} (Action: {type})"); - else - Log($"*{user} a interagi avec le salon {room} (Action: {type})"); - if (type == "UserJoin" && _usersByRoom.TryGetValue(room, out var users) - && !users.Contains(user)) - users.Add(user); + PostForCurrentSession(() => + { + Log($"[{type}] {user}: {msg}"); + }); }); - }); - // 3. Réception de l'état complet suite au Join réussi (joint) - _connection.On("joint", (roomInfo) => - { - Avalonia.Threading.Dispatcher.UIThread.Post(() => OnRoomJoined(roomInfo)); - }); - - // 4. Réception des messages de salon (diffusés par ChatHub.Send) - _connection.On("ReceiveMessage", (msg) => - { - Avalonia.Threading.Dispatcher.UIThread.Post(() => + // 2. Ecoute des notifications de salon (notifyRoom) + _connection.On("notifyRoom", (type, room, user) => { - var room = msg.Room ?? "?"; - if (!_messagesByRoom.TryGetValue(room, out var roomLog)) - roomLog = _messagesByRoom[room] = new(); - roomLog.Add($"{msg.Name} : {msg.Message}"); + PostForCurrentSession(() => + { + if (_messagesByRoom.TryGetValue(room, out var roomLog)) + roomLog.Add($"*{user} a interagi avec le salon {room} (Action: {type})"); + else + Log($"*{user} a interagi avec le salon {room} (Action: {type})"); + if (type == "UserJoin" && _usersByRoom.TryGetValue(room, out var users) + && !users.Contains(user)) + users.Add(user); + }); }); - }); - await _connection.StartAsync(); + // WithAutomaticReconnect ne lève pas d'exception en cas de + // perte réseau : l'état passe par Reconnecting/Closed. Sans + // ces handlers, IsConnected resterait optimiste et Join() + // échouerait avec "connection is not active". + _connection.Reconnecting += error => + { + PostForCurrentSession(() => + { + IsConnected = false; + Status = new StatusNotice($"Connexion perdue ({error?.Message ?? "réseau"}), reconnexion...", StatusSeverity.Error, + new RelayCheckCommand("Déconnecter", async () => await DisconnectAsync())); + }); + return Task.CompletedTask; + }; + _connection.Reconnected += _ => + { + PostForCurrentSession(() => + { + IsConnected = true; + Status = new StatusNotice("Reconnecté au Hub SignalR", StatusSeverity.Info, + new RelayCheckCommand("Déconnecter", async () => await DisconnectAsync())); + }); + return Task.CompletedTask; + }; + _connection.Closed += error => + { + PostForCurrentSession(() => + { + IsConnected = false; + Status = new StatusNotice($"Déconnecté ({error?.Message ?? "fin de connexion"})", StatusSeverity.Info, + new RelayCheckCommand("Connecter", async () => await ConnectAsync())); + }); + return Task.CompletedTask; + }; + _handlersRegistered = true; + } + await _transport.StartAsync(ct); + foreach (var room in _transport.JoinedRooms) + OnRoomJoined(room); + foreach (var delivery in _transport.RecentMessages) + OnMessageReceived(delivery); IsConnected = true; Status = new StatusNotice("Connecté au Hub SignalR", StatusSeverity.Info, new RelayCheckCommand("Déconnecter", async () => await DisconnectAsync())); - - // WithAutomaticReconnect ne lève pas d'exception en cas de - // perte réseau : l'état passe par Reconnecting/Closed. Sans - // ces handlers, IsConnected resterait optimiste et Join() - // échouerait avec "connection is not active". - _connection.Reconnecting += error => - { - Avalonia.Threading.Dispatcher.UIThread.Post(() => - { - IsConnected = false; - Status = new StatusNotice($"Connexion perdue ({error?.Message ?? "réseau"}), reconnexion...", StatusSeverity.Error, - new RelayCheckCommand("Déconnecter", async () => await DisconnectAsync())); - }); - return Task.CompletedTask; - }; - _connection.Reconnected += async _ => - { - Avalonia.Threading.Dispatcher.UIThread.Post(() => - { - IsConnected = true; - Status = new StatusNotice("Reconnecté au Hub SignalR", StatusSeverity.Info, - new RelayCheckCommand("Déconnecter", async () => await DisconnectAsync())); - }); - // La reconnexion crée une nouvelle ConnectionId côté - // serveur : l'appartenance aux salons est perdue, il - // faut rejoindre à nouveau le salon courant. - if (!string.IsNullOrWhiteSpace(CurrentRoom)) - await JoinRoomAsync(); - }; - _connection.Closed += error => - { - Avalonia.Threading.Dispatcher.UIThread.Post(() => - { - IsConnected = false; - Status = new StatusNotice($"Déconnecté ({error?.Message ?? "fin de connexion"})", StatusSeverity.Info, - new RelayCheckCommand("Connecter", async () => await ConnectAsync())); - }); - return Task.CompletedTask; - }; } catch (Exception ex) { @@ -365,7 +427,7 @@ namespace PostIt.ViewModels.Chat Log($"Connexion non active ({_connection.State}), tentative de reconnexion..."); try { - await _connection.StartAsync(); + await _transport!.StartAsync(); } catch (Exception ex) { @@ -377,7 +439,7 @@ namespace PostIt.ViewModels.Chat try { // Appel de la méthode publique 'Join' du Hub (renvoie un ChatRoomInfo) - var info = await _connection.InvokeAsync("Join", CurrentRoom); + var info = await _transport!.JoinAsync(CurrentRoom); if (info == null) { Log("Erreur lors de la validation du salon par le serveur."); diff --git a/src/PostIt/PostIt/ViewModels/Layout/SessionStatusViewModel.cs b/src/PostIt/PostIt/ViewModels/Layout/SessionStatusViewModel.cs index f6bf2282a..dedf210f2 100644 --- a/src/PostIt/PostIt/ViewModels/Layout/SessionStatusViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/Layout/SessionStatusViewModel.cs @@ -166,7 +166,14 @@ public partial class SessionStatusViewModel : ViewModelBase public async System.Threading.Tasks.Task LogoutAsync() { if (Api is null) return; - await Api.LogoutAsync().ConfigureAwait(false); + try { await Api.LogoutAsync().ConfigureAwait(true); } + catch (Exception ex) + { + Refresh(); + SessionLabel = $"Deconnecte ; nettoyage de la messagerie incomplet : {ex.Message}"; + LogoutCompleted?.Invoke(); + return; + } Refresh(); LogoutCompleted?.Invoke(); } diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index b8bbb2702..6b10f982b 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -18,6 +18,7 @@ namespace PostIt.ViewModels; public partial class Settings : ViewModelBase { + public event EventHandler? Saved; public Settings() { } internal Settings(string settingsFileFullName) => SettingsFileFullName = settingsFileFullName; @@ -58,6 +59,12 @@ public partial class Settings : ViewModelBase public partial string? PodcastMicrophoneId { get; set; } [ObservableProperty] public partial string? LanCallAddress { get; set; } + [ObservableProperty] + public partial bool AndroidKeepChatConnected { get; set; } + [ObservableProperty] + public partial Dictionary ChatRoomsByAccount { get; set; } = new(); + [JsonIgnore] + public bool SupportsBackgroundChatService => OperatingSystem.IsAndroid(); [ObservableProperty] [JsonIgnore] @@ -159,6 +166,8 @@ public partial class Settings : ViewModelBase partial void OnPodcastCameraIdChanged(string? value) => MarkDirty(); partial void OnPodcastMicrophoneIdChanged(string? value) => MarkDirty(); partial void OnLanCallAddressChanged(string? value) => MarkDirty(); + partial void OnAndroidKeepChatConnectedChanged(bool value) => MarkDirty(); + partial void OnChatRoomsByAccountChanged(Dictionary value) => MarkDirty(); /// /// Authentication can be reassigned wholesale by @@ -422,6 +431,8 @@ public partial class Settings : ViewModelBase PodcastCameraId = settings.PodcastCameraId; PodcastMicrophoneId = settings.PodcastMicrophoneId; LanCallAddress = settings.LanCallAddress; + AndroidKeepChatConnected = settings.AndroidKeepChatConnected; + ChatRoomsByAccount = settings.ChatRoomsByAccount ?? new(); if (!(settings.Authentication is null)) { this.Authentication = new AuthenticationSettings(); @@ -559,6 +570,7 @@ public partial class Settings : ViewModelBase throw; } } + Saved?.Invoke(this, EventArgs.Empty); } private bool CanSave() => IsDirty; diff --git a/src/PostIt/PostIt/Views/Chat/ChatPage.axaml b/src/PostIt/PostIt/Views/Chat/ChatPage.axaml index d2da099bb..6dd8ab95a 100644 --- a/src/PostIt/PostIt/Views/Chat/ChatPage.axaml +++ b/src/PostIt/PostIt/Views/Chat/ChatPage.axaml @@ -37,6 +37,7 @@ Text="{Binding CurrentRoom}" PlaceholderText="Nom du salon" /> public class YavscApiClientTests { + [Theory] + [InlineData(600, true, false, 540)] + [InlineData(3600, false, true, 3540)] + [InlineData(40, true, false, 0)] + [InlineData(-5, true, false, 0)] + [InlineData(600, false, false, -1)] + public async Task Maintenance_delay_is_derived_from_the_persisted_access_token_expiry( + int lifetimeSeconds, bool active, bool keepConnected, int expectedDelaySeconds) + { + var path = TokensPath(); + var now = DateTimeOffset.UtcNow; + try + { + var store = new TokenStore(path); + store.Save(new RefreshTokenRecord("access", "refresh", now.AddSeconds(lifetimeSeconds))); + var settings = new Settings(); + await using var client = new YavscApiClient(settings, store); + settings.AndroidKeepChatConnected = keepConnected; + Assert.Equal(expectedDelaySeconds < 0 ? Timeout.InfiniteTimeSpan + : TimeSpan.FromSeconds(expectedDelaySeconds), client.GetSessionRefreshDelay(now, active)); + } + finally { File.Delete(path); } + } + + [Theory] + [InlineData(true, false, 40, 1)] + [InlineData(false, true, 40, 1)] + [InlineData(false, false, 40, 0)] + [InlineData(true, true, 180, 0)] + public async Task Session_maintenance_refreshes_before_expiry_only_while_active_or_opted_in( + bool active, bool keepConnected, int secondsUntilExpiry, int expectedRefreshes) + { + using var authority = await OIDCStubAuthority.StartAsync(); + using var apiServer = new StubApiServer(); + await apiServer.StartAsync(); + var settings = BuildSettings(authority, apiServer.BaseUrl); + settings.AndroidKeepChatConnected = keepConnected; + var tokensPath = TokensPath(); + try + { + await using var original = await LoginAndPersistAsync(settings, authority, tokensPath); + var store = new TokenStore(tokensPath); + var previous = store.Load()!; + var expiry = DateTimeOffset.UtcNow.AddSeconds(secondsUntilExpiry); + store.Save(previous with { AccessTokenExpiresAt = expiry }); + await using var client = new YavscApiClient(settings, store); + await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => + client.RefreshSessionIfNeededAsync(active, TestContext.Current.CancellationToken))); + Assert.Equal(expectedRefreshes, authority.RefreshRequestCount); + Assert.Equal(0, apiServer.RequestCount); + Assert.True(expiry > DateTimeOffset.UtcNow, "Refresh must occur before expiry, not after a 401."); + var persisted = store.Load()!; + if (expectedRefreshes > 0) + { + Assert.NotEqual(previous.RefreshToken, persisted.RefreshToken); + Assert.True(persisted.AccessTokenExpiresAt > expiry); + } + else Assert.Equal(previous.RefreshToken, persisted.RefreshToken); + } + finally { File.Delete(tokensPath); } + } + + [Fact] + public async Task Scheduled_maintenance_runs_without_an_API_call_and_starts_only_once() + { + using var authority = await OIDCStubAuthority.StartAsync(); + using var apiServer = new StubApiServer(); + await apiServer.StartAsync(); + var settings = BuildSettings(authority, apiServer.BaseUrl); + settings.AndroidKeepChatConnected = true; + var tokensPath = TokensPath(); + try + { + await using var original = await LoginAndPersistAsync(settings, authority, tokensPath); + var store = new TokenStore(tokensPath); + store.Save(store.Load()! with { AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(62) }); + await using var client = new YavscApiClient(settings, store); + var scheduledDelay = client.GetSessionRefreshDelay(DateTimeOffset.UtcNow, true); + Assert.InRange(scheduledDelay.TotalSeconds, 1, 2); + client.StartSessionMaintenance(); + client.StartSessionMaintenance(); + await Task.Delay(250, TestContext.Current.CancellationToken); + Assert.Equal(0, authority.RefreshRequestCount); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + while (store.Load()!.AccessTokenExpiresAt - DateTimeOffset.UtcNow < TimeSpan.FromMinutes(2)) + await Task.Delay(20, timeout.Token); + Assert.Equal(1, authority.RefreshRequestCount); + Assert.Equal(0, apiServer.RequestCount); + Assert.InRange(client.GetSessionRefreshDelay(DateTimeOffset.UtcNow, true).TotalSeconds, 500, 600); + } + finally { File.Delete(tokensPath); } + } + + [Fact] + public async Task Session_maintenance_rejects_revoked_tokens_and_does_not_retry_after_logout() + { + using var authority = await OIDCStubAuthority.StartAsync(); + using var apiServer = new StubApiServer(); + await apiServer.StartAsync(); + var settings = BuildSettings(authority, apiServer.BaseUrl); + var tokensPath = TokensPath(); + try + { + await using var original = await LoginAndPersistAsync(settings, authority, tokensPath); + var store = new TokenStore(tokensPath); + store.Save(store.Load()! with + { + RefreshToken = "revoked-refresh-token", + AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(40) + }); + await using var client = new YavscApiClient(settings, store); + var ct = TestContext.Current.CancellationToken; + client.SigningOut += () => client.RefreshSessionIfNeededAsync(true, ct); + var error = await Assert.ThrowsAsync(() => + client.RefreshSessionIfNeededAsync(true, ct)); + Assert.True(error.IsPermanent); + Assert.Null(store.Load()); + Assert.False(client.HasValidSession); + await client.LogoutAsync(); + await client.RefreshSessionIfNeededAsync(true, ct); + Assert.Equal(1, authority.RefreshRequestCount); + } + finally { File.Delete(tokensPath); } + } + + [Fact] + public async Task Session_maintenance_does_not_refresh_a_due_token_during_logout() + { + using var authority = await OIDCStubAuthority.StartAsync(); + using var apiServer = new StubApiServer(); + await apiServer.StartAsync(); + var settings = BuildSettings(authority, apiServer.BaseUrl); + var tokensPath = TokensPath(); + try + { + await using var original = await LoginAndPersistAsync(settings, authority, tokensPath); + var store = new TokenStore(tokensPath); + store.Save(store.Load()! with { AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(40) }); + await using var client = new YavscApiClient(settings, store); + client.SigningOut += () => + { + Assert.True(client.HasValidSession); + return client.RefreshSessionIfNeededAsync(true, TestContext.Current.CancellationToken); + }; + await client.LogoutAsync(); + Assert.Equal(0, authority.RefreshRequestCount); + Assert.Null(store.Load()); + Assert.False(client.HasValidSession); + } + finally { File.Delete(tokensPath); } + } + [Theory] [InlineData(false)] [InlineData(true)] @@ -474,7 +627,9 @@ public class YavscApiClientTests .Select(_ => client.TrySilentLoginAsync(null, ct)).ToArray(); var calls = Enumerable.Range(0, 8) .Select(_ => client.CallAsync>(HttpMethod.Get, "posts", ct)).ToArray(); - await Task.WhenAll(silentLogins.Cast().Concat(calls)); + var maintenance = Enumerable.Range(0, 8) + .Select(_ => client.RefreshSessionIfNeededAsync(true, ct)); + await Task.WhenAll(silentLogins.Cast().Concat(calls).Concat(maintenance)); Assert.All(silentLogins, login => Assert.True(login.Result)); Assert.All(calls, call => Assert.NotEmpty(call.Result)); diff --git a/src/PostIt/PostIt/App.axaml.cs b/src/PostIt/PostIt/App.axaml.cs index 82ada85a2..7b9106703 100644 --- a/src/PostIt/PostIt/App.axaml.cs +++ b/src/PostIt/PostIt/App.axaml.cs @@ -52,6 +52,7 @@ public partial class App : Application, ILiveView, IVMPusherApp this.ServiceProvider = Platform.CreateServiceProvider?.Invoke() ?? new ServiceCollection().BuildPostItServices(); var settings = ServiceProvider.GetRequiredService(); + ServiceProvider.GetRequiredService().StartSessionMaintenance(); if (!LiveMode) { diff --git a/src/PostIt/PostIt/Services/Platform.cs b/src/PostIt/PostIt/Services/Platform.cs index a13446447..a2cae74d7 100644 --- a/src/PostIt/PostIt/Services/Platform.cs +++ b/src/PostIt/PostIt/Services/Platform.cs @@ -12,6 +12,18 @@ namespace PostIt.Services; /// public static class Platform { + private static bool _isApplicationActive = !OperatingSystem.IsAndroid(); + public static event Action? ApplicationActivityChanged; + public static bool IsApplicationActive + { + get => Volatile.Read(ref _isApplicationActive); + set + { + if (value == _isApplicationActive) return; + Volatile.Write(ref _isApplicationActive, value); + ApplicationActivityChanged?.Invoke(); + } + } public static IBackgroundChatService? BackgroundChatService { get; set; } public static Func? CreateServiceProvider { get; set; } public static Func? GetLanCallDevices { get; set; } diff --git a/src/PostIt/PostIt/Services/YavscApiClient.cs b/src/PostIt/PostIt/Services/YavscApiClient.cs index e00441b1e..7cd1ee210 100644 --- a/src/PostIt/PostIt/Services/YavscApiClient.cs +++ b/src/PostIt/PostIt/Services/YavscApiClient.cs @@ -40,6 +40,11 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable public HttpClient Http { get; } private readonly BearerTokenHandler _bearer; private readonly SemaphoreSlim _refreshGate = new(1, 1); + private readonly CancellationTokenSource _maintenanceLifetime = new(); + private readonly object _maintenanceGate = new(); + private readonly SemaphoreSlim _maintenanceChanged = new(0, 1); + private Task? _maintenance; + private bool _maintenanceStopped; private RefreshTokenRecord? _tokens; private static readonly HttpRequestOptionsKey AnonymousRequest = new("PostIt.AnonymousRequest"); @@ -103,6 +108,81 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable /// The current OIDC id_token, or null. public string? CurrentIdToken => _tokens?.IdToken; + public void StartSessionMaintenance() + { + lock (_maintenanceGate) + { + _maintenanceLifetime.Token.ThrowIfCancellationRequested(); + if (_maintenance is not null) return; + Platform.ApplicationActivityChanged += WakeSessionMaintenance; + Settings.PropertyChanged += OnMaintenanceSettingsChanged; + _maintenance = Task.Run(() => MaintainSessionAsync(_maintenanceLifetime.Token)); + } + } + + private void OnMaintenanceSettingsChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs args) + { + if (args.PropertyName == nameof(Settings.AndroidKeepChatConnected)) WakeSessionMaintenance(); + } + + private void WakeSessionMaintenance() + { + lock (_maintenanceGate) + { + if (!_maintenanceStopped && _maintenanceChanged.CurrentCount == 0) + _maintenanceChanged.Release(); + } + } + + internal TimeSpan GetSessionRefreshDelay(DateTimeOffset now, bool applicationActive) + { + var tokens = _tokens; + if ((!applicationActive && !Settings.AndroidKeepChatConnected) + || IsSigningOut || string.IsNullOrEmpty(tokens?.RefreshToken)) + return Timeout.InfiniteTimeSpan; + var delay = tokens.AccessTokenExpiresAt - RefreshSkew - now; + return delay > TimeSpan.Zero ? delay : TimeSpan.Zero; + } + + internal async Task RefreshSessionIfNeededAsync(bool applicationActive, CancellationToken ct) + { + if ((!applicationActive && !Settings.AndroidKeepChatConnected) + || IsSigningOut || string.IsNullOrEmpty(_tokens?.RefreshToken)) return; + await ForceRefreshAsync(ct).ConfigureAwait(false); + } + + private async Task MaintainSessionAsync(CancellationToken ct) + { + try + { + while (!ct.IsCancellationRequested) + { + var delay = GetSessionRefreshDelay(DateTimeOffset.UtcNow, Platform.IsApplicationActive); + // SemaphoreSlim's timed wait accepts at most Int32.MaxValue milliseconds. + if (delay > TimeSpan.FromMilliseconds(int.MaxValue)) + delay = TimeSpan.FromMilliseconds(int.MaxValue); + if (delay != TimeSpan.Zero + && await _maintenanceChanged.WaitAsync(delay, ct).ConfigureAwait(false)) + continue; + try + { + using var attempt = CancellationTokenSource.CreateLinkedTokenSource(ct); + attempt.CancelAfter(TimeSpan.FromSeconds(20)); + await RefreshSessionIfNeededAsync(Platform.IsApplicationActive, attempt.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception ex) + { + Console.Error.WriteLine($"Session maintenance failed: {ex}"); + Settings.SetActionStatus($"Renouvellement automatique de la session impossible : {ex.Message}", + PostIt.Models.StatusSeverity.Error); + await _maintenanceChanged.WaitAsync(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false); + } + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { } + } + /// Force a new interactive login (PKCE). Throws on failure. /// Optional sink for the discrete phases of /// the flow; the UI uses this to render a debug-friendly status @@ -157,6 +237,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable IdToken: result.IdentityToken); _store.Save(_tokens); + WakeSessionMaintenance(); progress?.Report(OIDCLoginPhase.Success); } @@ -400,6 +481,8 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable await _refreshGate.WaitAsync(ct).ConfigureAwait(false); try { + if (IsSigningOut) + throw new InvalidOperationException("Deconnexion en cours."); var tokens = _tokens; if (tokens is null || string.IsNullOrEmpty(tokens.RefreshToken)) throw new InvalidOperationException("Session expirée. Veuillez vous reconnecter."); @@ -417,6 +500,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable { _store.Clear(); _tokens = null; + WakeSessionMaintenance(); } throw new RefreshFailedException( isPermanent @@ -432,6 +516,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable IdToken: result.IdentityToken ?? tokens.IdToken); _store.Save(_tokens); + WakeSessionMaintenance(); } finally { @@ -566,6 +651,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable public async Task LogoutAsync() { Interlocked.Exchange(ref _signingOut, 1); + WakeSessionMaintenance(); try { if (SigningOut is { } handlers) @@ -584,6 +670,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable { _refreshGate.Release(); Interlocked.Exchange(ref _signingOut, 0); + WakeSessionMaintenance(); } } // Optional: clear the IdP session in the browser too. @@ -591,11 +678,22 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable await Task.CompletedTask; } - public ValueTask DisposeAsync() + public async ValueTask DisposeAsync() { + Task? maintenance; + lock (_maintenanceGate) + { + _maintenanceStopped = true; + _maintenanceLifetime.Cancel(); + Platform.ApplicationActivityChanged -= WakeSessionMaintenance; + Settings.PropertyChanged -= OnMaintenanceSettingsChanged; + maintenance = _maintenance; + } + if (maintenance is not null) await maintenance.ConfigureAwait(false); + _maintenanceChanged.Dispose(); + _maintenanceLifetime.Dispose(); Http.Dispose(); _refreshGate.Dispose(); - return ValueTask.CompletedTask; } /// diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 6b10f982b..9c77ff2d5 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -19,6 +19,7 @@ namespace PostIt.ViewModels; public partial class Settings : ViewModelBase { public event EventHandler? Saved; + public event EventHandler? Applied; public Settings() { } internal Settings(string settingsFileFullName) => SettingsFileFullName = settingsFileFullName; @@ -575,6 +576,13 @@ public partial class Settings : ViewModelBase private bool CanSave() => IsDirty; + [RelayCommand(CanExecute = nameof(CanSave))] + public void Apply() + { + Save(); + Applied?.Invoke(this, EventArgs.Empty); + } + /// /// Re-notify the SaveCommand (generated by /// [RelayCommand] on ) so XAML @@ -582,6 +590,10 @@ public partial class Settings : ViewModelBase /// outside the scope of a direct save (e.g. on /// / ). /// - partial void OnIsDirtyChanged(bool value) => SaveCommand.NotifyCanExecuteChanged(); + partial void OnIsDirtyChanged(bool value) + { + SaveCommand.NotifyCanExecuteChanged(); + ApplyCommand.NotifyCanExecuteChanged(); + } } diff --git a/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml b/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml index e86573cf6..f0865fd70 100644 --- a/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml +++ b/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml @@ -52,7 +52,7 @@ - -