Add contact preferences announcement

Persist contact options and announce them on chat connection and reconnection. Prepare the audio-only call contract; enforcement and audio-only media remain unimplemented.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-16 01:10:47 +00:00
commit 9c4cce6840
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
11 changed files with 150 additions and 5 deletions

View file

@ -14,6 +14,7 @@ using PostIt.Services;
using PostIt.ViewModels;
using PostIt.ViewModels.Chat;
using PostIt.Views;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
@ -308,6 +309,8 @@ public sealed class MessagingSessionTests
await chat.JoinRoomCommand();
Assert.Equal(new[] { "first", "second" }, chat.JoinedRooms);
var counter = server.Services.GetRequiredService<ConnectionCounter>();
settings.AllowVideoCalls = false;
counter.ContactPreferences = null;
counter.Context!.Abort();
var deadline = DateTime.UtcNow.AddSeconds(40);
while (!counter.RoomsRejoined.Task.IsCompleted && DateTime.UtcNow < deadline)
@ -319,6 +322,7 @@ public sealed class MessagingSessionTests
$"Connections={counter.Count}, transport={transport.Connection.State}, chat={chat.Status.Message}");
Assert.Equal(2, await transport.Connection.InvokeAsync<int>("ConnectionCount"));
Assert.Equal(new[] { "first", "second" }, counter.RejoinedRooms);
Assert.Equal(new ContactPreferences(true, false, true), counter.ContactPreferences);
Platform.SuspendPlayback();
Assert.True(chat.IsConnected);
@ -366,7 +370,13 @@ public sealed class MessagingSessionTests
var path = Path.Combine(Path.GetTempPath(), $"postit-chat-rooms-{Guid.NewGuid():N}");
try
{
var settings = new Settings(path + ".settings") { ApiUrl = server.Urls.Single() + "/api/v1/" };
var settings = new Settings(path + ".settings")
{
ApiUrl = server.Urls.Single() + "/api/v1/",
AllowAudioCalls = true,
AllowVideoCalls = false,
AllowPrivateMessages = false
};
settings.Authentication.Authority = "https://login.example.test";
var store = CreateStore(path);
var jwt = "e30." + Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"sub\":\"alice\"}")).TrimEnd('=')
@ -376,6 +386,8 @@ public sealed class MessagingSessionTests
await using (var transport = new ChatHubConnection(api))
{
await transport.StartAsync(TestContext.Current.CancellationToken);
Assert.Equal(new ContactPreferences(true, false, false),
server.Services.GetRequiredService<ConnectionCounter>().ContactPreferences);
await transport.JoinAsync("SavedRoom", TestContext.Current.CancellationToken);
Assert.Single(settings.ChatRoomsByAccount);
}
@ -385,6 +397,8 @@ public sealed class MessagingSessionTests
await using var resumedApi = new YavscApiClient(restored, store);
await using var resumed = new ChatHubConnection(resumedApi);
await resumed.StartAsync(TestContext.Current.CancellationToken);
Assert.Equal(new ContactPreferences(true, false, false),
server.Services.GetRequiredService<ConnectionCounter>().ContactPreferences);
Assert.Equal(2, await resumed.Connection.InvokeAsync<int>("ConnectionCount"));
Assert.Equal("SavedRoom", Assert.Single(resumed.JoinedRooms).Name);
Assert.Equal(new[] { "SavedRoom" }, server.Services.GetRequiredService<ConnectionCounter>().RejoinedRooms);
@ -437,12 +451,14 @@ public sealed class MessagingSessionTests
{
public int Count;
public HubCallerContext? Context;
public ContactPreferences? ContactPreferences;
public List<string> RejoinedRooms { get; } = [];
public TaskCompletionSource RoomsRejoined { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
public sealed class TestChatHub(ConnectionCounter counter) : Hub
{
public void SetContactPreferences(ContactPreferences preferences) => counter.ContactPreferences = preferences;
public int ConnectionCount() => counter.Count;
public ChatRoomInfo Join(string room)
{

View file

@ -5,6 +5,34 @@ namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public class SettingsLoadTests
{
[Fact]
public void Contact_options_survive_save_and_load_and_legacy_settings_keep_defaults()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-contact-{Guid.NewGuid():N}.json");
try
{
File.WriteAllText(path, "{}");
var settings = new PostIt.ViewModels.Settings(path);
settings.Load();
Assert.True(settings.AllowAudioCalls);
Assert.True(settings.AllowVideoCalls);
Assert.True(settings.AllowPrivateMessages);
settings.AllowAudioCalls = false;
settings.AllowPrivateMessages = false;
Assert.True(settings.IsDirty);
settings.Save();
var restored = new PostIt.ViewModels.Settings(path);
restored.Load();
Assert.False(restored.AllowAudioCalls);
Assert.True(restored.AllowVideoCalls);
Assert.False(restored.AllowPrivateMessages);
Assert.False(restored.IsDirty);
}
finally { File.Delete(path); }
}
/// <summary>
/// On the dev machine, the user-level settings file
/// (~/.config/PostIt/postit-settings.json) does not exist, so Load()

View file

@ -9,6 +9,7 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using PostIt.ViewModels.Chat;
using PostIt.Models;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Services;
@ -76,8 +77,20 @@ public sealed class ChatHubConnection : IAsyncDisposable
RememberMessage(connection, message.Room, message.Name ?? "", message.Message ?? ""));
connection.On<string, string>("addPV", (sender, message) =>
RememberMessage(connection, null, sender, message));
connection.Reconnected += _ => ReferenceEquals(Connection, connection) && IsCurrentConfiguration
? RestoreRoomsAsync(connection, CancellationToken.None) : Task.CompletedTask;
connection.Reconnected += async _ =>
{
if (!ReferenceEquals(Connection, connection) || !IsCurrentConfiguration) return;
try
{
await AnnounceContactPreferencesAsync(connection, CancellationToken.None);
await RestoreRoomsAsync(connection, CancellationToken.None);
}
catch (Exception ex)
{
ReportError($"Impossible d'annoncer les preferences de contact : {ex.Message}");
await connection.StopAsync();
}
};
return connection;
}
@ -112,12 +125,26 @@ public sealed class ChatHubConnection : IAsyncDisposable
if (Connection.State == HubConnectionState.Disconnected)
{
await Connection.StartAsync(ct);
await RestoreRoomsAsync(Connection, ct);
try
{
await AnnounceContactPreferencesAsync(Connection, ct);
await RestoreRoomsAsync(Connection, ct);
}
catch
{
await Connection.StopAsync(CancellationToken.None);
throw;
}
}
}
finally { _gate.Release(); }
}
private Task AnnounceContactPreferencesAsync(HubConnection connection, CancellationToken ct) =>
connection.InvokeAsync(CallHubMethods.SetContactPreferences,
new ContactPreferences(_api.Settings.AllowAudioCalls, _api.Settings.AllowVideoCalls,
_api.Settings.AllowPrivateMessages), ct);
public async Task StopAsync(CancellationToken ct = default)
{
await _gate.WaitAsync(ct);

View file

@ -67,6 +67,12 @@ public partial class Settings : ViewModelBase
[ObservableProperty]
public partial string? LanCallAddress { get; set; }
[ObservableProperty]
public partial bool AllowAudioCalls { get; set; } = true;
[ObservableProperty]
public partial bool AllowVideoCalls { get; set; } = true;
[ObservableProperty]
public partial bool AllowPrivateMessages { get; set; } = true;
[ObservableProperty]
public partial bool AndroidKeepChatConnected { get; set; }
[ObservableProperty]
public partial bool ShareExceptionReports { get; set; }
@ -177,6 +183,9 @@ public partial class Settings : ViewModelBase
partial void OnPodcastKeepScreenOnChanged(bool value) => MarkDirty();
partial void OnPodcastBlurBackgroundChanged(bool value) => MarkDirty();
partial void OnLanCallAddressChanged(string? value) => MarkDirty();
partial void OnAllowAudioCallsChanged(bool value) => MarkDirty();
partial void OnAllowVideoCallsChanged(bool value) => MarkDirty();
partial void OnAllowPrivateMessagesChanged(bool value) => MarkDirty();
partial void OnAndroidKeepChatConnectedChanged(bool value) => MarkDirty();
partial void OnShareExceptionReportsChanged(bool value) => MarkDirty();
partial void OnChatRoomsByAccountChanged(Dictionary<string, string[]> value) => MarkDirty();
@ -445,6 +454,9 @@ public partial class Settings : ViewModelBase
PodcastKeepScreenOn = settings.PodcastKeepScreenOn;
PodcastBlurBackground = settings.PodcastBlurBackground;
LanCallAddress = settings.LanCallAddress;
AllowAudioCalls = settings.AllowAudioCalls;
AllowVideoCalls = settings.AllowVideoCalls;
AllowPrivateMessages = settings.AllowPrivateMessages;
AndroidKeepChatConnected = settings.AndroidKeepChatConnected;
ShareExceptionReports = settings.ShareExceptionReports;
ChatRoomsByAccount = settings.ChatRoomsByAccount ?? new();

View file

@ -49,6 +49,15 @@
<CheckBox Grid.Row="11" x:Name="DarkModeCheckBox" IsChecked="{Binding DarkMode, Mode=TwoWay}"/>
<StackPanel Grid.Row="12" Spacing="8">
<TextBlock Text="Moyens de contact" FontWeight="SemiBold" />
<CheckBox Content="Autoriser les appels audio"
IsChecked="{Binding AllowAudioCalls, Mode=TwoWay}" />
<CheckBox Content="Autoriser les appels audio-video"
IsChecked="{Binding AllowVideoCalls, Mode=TwoWay}" />
<CheckBox Content="Autoriser les messages prives"
IsChecked="{Binding AllowPrivateMessages, Mode=TwoWay}" />
<TextBlock Text="Ces preferences sont annoncees au serveur a la connexion et a la reconnexion. Leur application aux appels et aux messages n'est pas encore implementee ; elles ne bloquent donc pas les contacts."
TextWrapping="Wrap" />
<StackPanel IsVisible="{Binding SupportsBackgroundChatService}" Spacing="6">
<CheckBox x:Name="BackgroundChatCheckBox"
Content="Garder la connexion au serveur active et la reprendre au demarrage du telephone"

View file

@ -4,6 +4,7 @@ namespace Yavsc.Abstract.Chat.Calls;
public static class CallHubMethods
{
public const string SetContactPreferences = "SetContactPreferences";
public const string Invite = "InviteCall";
public const string InviteLan = "InviteLanCall";
public const string Accept = "AcceptCall";
@ -15,9 +16,18 @@ public static class CallHubMethods
public const string SignalReceived = "CallSignal";
}
public sealed record ContactPreferences(bool AllowAudioCalls, bool AllowVideoCalls, bool AllowPrivateMessages);
public enum CallDisplayMode
{
AudioVideo,
AudioOnly
}
public sealed record CallSession(
Guid Id, string RoomName, string Caller, string Callee, bool RelayOnly,
DateTimeOffset ExpiresAt, string Transport = CallTransports.WebRtc);
DateTimeOffset ExpiresAt, string Transport = CallTransports.WebRtc,
CallDisplayMode DisplayMode = CallDisplayMode.AudioVideo);
public static class CallTransports
{

View file

@ -9,6 +9,14 @@ namespace Yavsc.Server.Hubs;
public partial class ChatHub
{
public void SetContactPreferences(ContactPreferences preferences)
{
CallUser();
if (preferences is null)
throw new HubException("Contact preferences are required.");
_calls.SetContactPreferences(Context.ConnectionId, preferences);
}
public Task<CallSession> InviteCall(string roomName, string callee) =>
InviteCoreAsync(roomName, callee, CallTransports.WebRtc);

View file

@ -2,6 +2,7 @@
using System.Security.Cryptography;
using System.Text;
using System.Collections.Concurrent;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
@ -33,8 +34,15 @@ public sealed class CallSignalingService(
private readonly SemaphoreSlim _gate = new(1);
private readonly Dictionary<Guid, PendingCall> _calls = [];
private readonly ConcurrentDictionary<string, ContactPreferences> _contactPreferences = new();
private readonly AudioVideoCallOptions _options = options.Value;
public void SetContactPreferences(string connection, ContactPreferences preferences) =>
_contactPreferences[connection] = preferences;
public ContactPreferences? GetContactPreferences(string connection) =>
_contactPreferences.TryGetValue(connection, out var preferences) ? preferences : null;
public async Task<CallSession> InviteAsync(
string room, string caller, string callee, string callerConnection,
string[] calleeConnections, bool relayOnly, string transport = CallTransports.WebRtc)
@ -207,6 +215,7 @@ public sealed class CallSignalingService(
public async Task DisconnectAsync(string connection)
{
_contactPreferences.TryRemove(connection, out _);
await _gate.WaitAsync();
try
{

View file

@ -59,6 +59,24 @@ public sealed class CallHubTests
}
}
[Fact]
public async Task Contact_preferences_are_scoped_to_the_authenticated_connection_and_removed_on_disconnect()
{
using var f = new Fixture();
using var alice = f.Hub("alice", "alice-1");
using var spoof = f.Hub("bob", "alice-1");
var preferences = new ContactPreferences(true, false, false);
Assert.Throws<HubException>(() => spoof.SetContactPreferences(preferences));
Assert.Throws<HubException>(() => alice.SetContactPreferences(null!));
alice.SetContactPreferences(preferences);
Assert.Equal(preferences, f.Calls.GetContactPreferences("alice-1"));
Assert.Null(f.Calls.GetContactPreferences("bob-1"));
await f.Calls.DisconnectAsync("alice-1");
Assert.Null(f.Calls.GetContactPreferences("alice-1"));
}
[Fact]
public async Task Lan_requires_https_at_invitation_acceptance_and_key_exchange()
{