diff --git a/doc/architecture/postit.md b/doc/architecture/postit.md
index 8ad6f0804..ec74f3e68 100644
--- a/doc/architecture/postit.md
+++ b/doc/architecture/postit.md
@@ -404,6 +404,15 @@ pour les requetes.
Le document OpenAPI dedie est `/openapi/podcasts.json`, accessible en
developpement aux administrateurs comme les autres documents de l'API.
+## PostIt.Desktop - Capture d'écran
+
+
+### Pré-requis Sur Ubuntu / Debian
+
+````bash
+sudo apt install xdg-desktop-portal gstreamer1.0-tools gstreamer1.0-pipewire gstreamer1.0-plugins-good gstreamer1.0-plugins-ugly gstreamer1.0-vaapi
+````
+
## Composition root (`App.axaml.cs`)
`App.OnFrameworkInitializationCompleted` est le seul endroit où
diff --git a/src/PostIt/Directory.Packages.props b/src/PostIt/Directory.Packages.props
index 41ff905e5..d3bd1a99b 100644
--- a/src/PostIt/Directory.Packages.props
+++ b/src/PostIt/Directory.Packages.props
@@ -20,6 +20,7 @@
+
@@ -42,4 +43,4 @@
-
+
\ No newline at end of file
diff --git a/src/PostIt/PostIt.Android/MainActivity.cs b/src/PostIt/PostIt.Android/MainActivity.cs
index 46b386454..fb668d6cf 100644
--- a/src/PostIt/PostIt.Android/MainActivity.cs
+++ b/src/PostIt/PostIt.Android/MainActivity.cs
@@ -48,7 +48,7 @@ public class MainActivity : AvaloniaMainActivity
{
if (Current is not { } activity || !IsForeground)
{
- global::Android.Util.Log.Warn("PostIt", "Cannot show the keyboard without a foreground activity.");
+ global::Android.Util.Log.Warn(App.AppName, "Cannot show the keyboard without a foreground activity.");
return;
}
@@ -57,12 +57,12 @@ public class MainActivity : AvaloniaMainActivity
if (activity.CurrentFocus is not { } view
|| activity.GetSystemService(InputMethodService) is not global::Android.Views.InputMethods.InputMethodManager inputMethod)
{
- global::Android.Util.Log.Warn("PostIt", "Cannot show the keyboard without a focused native view and input method.");
+ global::Android.Util.Log.Warn(App.AppName, "Cannot show the keyboard without a focused native view and input method.");
return;
}
if (!inputMethod.ShowSoftInput(view, global::Android.Views.InputMethods.ShowFlags.Implicit))
- global::Android.Util.Log.Warn("PostIt", "The input method did not accept the keyboard activation request.");
+ global::Android.Util.Log.Warn(App.AppName, "The input method did not accept the keyboard activation request.");
});
}
diff --git a/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs b/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs
index c2288fd0c..31fba27da 100644
--- a/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs
+++ b/src/PostIt/PostIt.Android/Services/AndroidBackgroundChatService.cs
@@ -62,17 +62,12 @@ internal sealed class AndroidBackgroundChatService : IBackgroundChatService
{
var granted = await NotificationPermission.RequestAsync(activity, ct).ConfigureAwait(false);
Validate(api, epoch, identity, ct);
- await AndroidSettings.UpdateAsync(api.Settings, s => s.SetActionStatus(granted
- ? "Connexion de fond active sans notification permanente. Android peut l'interrompre."
- : "Notifications refusees : SignalR reste actif, mais les alertes ne seront pas affichees.",
- granted ? StatusSeverity.Info : StatusSeverity.Warning)).ConfigureAwait(false);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
Log.Error("PostIt.Chat", "Notification permission request failed: " + ex);
- AndroidSettings.ReportError(api.Settings,
- "SignalR reste actif ; demande d'autorisation des alertes impossible : " + ex.Message);
+ NotificationService.Instance.Post("SignalR reste actif ; demande d'autorisation des alertes impossible : " + ex.Message, PostIt.Models.StatusSeverity.Error);
}
}
}
@@ -88,12 +83,6 @@ internal sealed class AndroidBackgroundChatService : IBackgroundChatService
Cancel(epoch);
Log.Error("PostIt.Chat", ex.ToString());
api.QueueExceptionReport(ex, "PostIt.Android.Chat");
- try
- {
- await AndroidSettings.UpdateAsync(api.Settings, s => s.SetActionStatus(ex.Message, StatusSeverity.Error))
- .ConfigureAwait(false);
- }
- catch (Exception statusError) { Log.Error("PostIt.Chat", statusError.ToString()); }
if (ex is BackgroundChatException) throw;
throw new BackgroundChatException(BackgroundChatFailure.StartRejected,
"Android n'a pas pu demarrer le service de messagerie : " + ex.Message, ex);
@@ -110,7 +99,7 @@ internal sealed class AndroidBackgroundChatService : IBackgroundChatService
catch (Exception ex)
{
Log.Error("PostIt.Chat", ex.ToString());
- AndroidSettings.ReportError(api.Settings, ex.Message);
+ NotificationService.Instance.Post("Erreur lors de la desactivation du service de messagerie : " + ex.Message, PostIt.Models.StatusSeverity.Error);
}
return Task.CompletedTask;
}
diff --git a/src/PostIt/PostIt.Android/Services/AndroidBatteryOptimization.cs b/src/PostIt/PostIt.Android/Services/AndroidBatteryOptimization.cs
index c3b5bb39e..42d42251a 100644
--- a/src/PostIt/PostIt.Android/Services/AndroidBatteryOptimization.cs
+++ b/src/PostIt/PostIt.Android/Services/AndroidBatteryOptimization.cs
@@ -2,6 +2,7 @@ using System;
using Android.Content;
using Android.OS;
using Android.Util;
+using PostIt.Services;
using PostIt.ViewModels;
using AndroidSettingsIntent = Android.Provider.Settings;
@@ -26,8 +27,7 @@ internal static class AndroidBatteryOptimization
if (MainActivity.Current is not { IsFinishing: false, IsDestroyed: false } activity
|| !MainActivity.IsForeground)
{
- AndroidSettings.ReportError(settings,
- "Ouvrez PostIt pour demander l'exemption d'optimisation batterie.");
+ NotificationService.Instance.Post("Ouvrez PostIt pour demander l'exemption d'optimisation batterie.", PostIt.Models.StatusSeverity.Error);
return;
}
activity.RunOnUiThread(() =>
@@ -43,8 +43,7 @@ internal static class AndroidBatteryOptimization
catch (Exception ex)
{
Log.Error("PostIt.Chat", "Battery optimization settings failed: " + ex);
- AndroidSettings.ReportError(settings,
- "Impossible d'ouvrir les parametres batterie Android : " + ex.Message);
+ NotificationService.Instance.Post("Impossible d'ouvrir les parametres batterie Android : " + ex.Message, PostIt.Models.StatusSeverity.Error);
}
});
}
diff --git a/src/PostIt/PostIt.Android/Services/AndroidServiceProvider.cs b/src/PostIt/PostIt.Android/Services/AndroidServiceProvider.cs
index a4af45f45..e47e882af 100644
--- a/src/PostIt/PostIt.Android/Services/AndroidServiceProvider.cs
+++ b/src/PostIt/PostIt.Android/Services/AndroidServiceProvider.cs
@@ -28,7 +28,7 @@ internal static class AndroidServiceProvider
catch (Exception ex)
{
global::Android.Util.Log.Error("PostIt.Chat", ex.ToString());
- AndroidSettings.ReportError(api.Settings, ex.Message);
+ NotificationService.Instance.Post(ex.Message, PostIt.Models.StatusSeverity.Error);
}
return System.Threading.Tasks.Task.CompletedTask;
};
diff --git a/src/PostIt/PostIt.Android/Services/AndroidSettings.cs b/src/PostIt/PostIt.Android/Services/AndroidSettings.cs
index e710c0c85..173779b85 100644
--- a/src/PostIt/PostIt.Android/Services/AndroidSettings.cs
+++ b/src/PostIt/PostIt.Android/Services/AndroidSettings.cs
@@ -25,14 +25,4 @@ internal static class AndroidSettings
});
return completion.Task;
}
-
- internal static void ReportError(Settings settings, string message)
- {
- _ = ReportAsync();
- async Task ReportAsync()
- {
- try { await UpdateAsync(settings, s => s.SetActionStatus(message, PostIt.Models.StatusSeverity.Error)); }
- catch (Exception ex) { global::Android.Util.Log.Error("PostIt.Chat", ex.ToString()); }
- }
- }
}
diff --git a/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs b/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs
index 7adf97c54..e0fcd7128 100644
--- a/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs
+++ b/src/PostIt/PostIt.Android/Services/ChatBootReceiver.cs
@@ -36,8 +36,7 @@ public sealed class ChatBootReceiver : BroadcastReceiver
if (api is not null)
{
api.QueueExceptionReport(ex, "PostIt.Android.Chat");
- AndroidSettings.ReportError(api.Settings,
- "Android a refuse le redemarrage de la messagerie : " + ex.Message);
+ NotificationService.Instance.Post("Android a refuse le redemarrage de la messagerie : " + ex.Message, PostIt.Models.StatusSeverity.Error);
}
}
finally { pending?.Finish(); }
diff --git a/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs b/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs
index 7de2f38b1..f6a3c7a8d 100644
--- a/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs
+++ b/src/PostIt/PostIt.Android/Services/ChatConnectionService.cs
@@ -155,7 +155,7 @@ public sealed class ChatConnectionService : Service
{
if (!_destroyed && AndroidBackgroundChatService.IsCurrent(epoch)
&& ChatBootState.CanStart(_api))
- s.SetActionStatus(NotificationPermission.IsGranted(this)
+ PostIt.Services.NotificationService.Instance.Post(NotificationPermission.IsGranted(this)
? "Connexion de fond active sans notification permanente. Android peut l'interrompre."
: "SignalR actif sans notification permanente. Alertes desactivees dans Android.",
NotificationPermission.IsGranted(this) ? StatusSeverity.Info : StatusSeverity.Warning);
@@ -219,7 +219,7 @@ public sealed class ChatConnectionService : Service
{
var builder = new NotificationCompat.Builder(this, MessageChannel);
builder.SetSmallIcon(Yavsc.Resource.Drawable.ic_stat_postit);
- builder.SetContentTitle("PostIt");
+ builder.SetContentTitle(App.AppName);
builder.SetContentText(text);
builder.SetVisibility(NotificationCompat.VisibilityPrivate);
builder.SetContentIntent(OpenApp());
@@ -254,7 +254,7 @@ public sealed class ChatConnectionService : Service
{
Log.Error("PostIt.Chat", ex.ToString());
_api?.QueueExceptionReport(ex, "PostIt.Android.Chat");
- if (_api is not null) AndroidSettings.ReportError(_api.Settings, ex.Message);
+ if (_api is not null) PostIt.Services.NotificationService.Instance.Post(ex.Message, PostIt.Models.StatusSeverity.Error);
}
private static void CompleteStartup(string epoch)
diff --git a/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj b/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj
index 40b287f04..b30430df5 100644
--- a/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj
+++ b/src/PostIt/PostIt.Desktop/PostIt.Desktop.csproj
@@ -20,6 +20,7 @@
All
+
diff --git a/src/PostIt/PostIt.Desktop/Program.cs b/src/PostIt/PostIt.Desktop/Program.cs
index ef8da445d..d5843d5f7 100644
--- a/src/PostIt/PostIt.Desktop/Program.cs
+++ b/src/PostIt/PostIt.Desktop/Program.cs
@@ -2,6 +2,7 @@ using System;
using Avalonia;
using PostIt.Services;
using PostIt.CLIOptions;
+using MonApp.Services.Linux;
namespace PostIt.Desktop;
@@ -14,6 +15,13 @@ sealed class Program
public static void Main(string[] args)
{
Platform.IsPodcastSupported = true;
+
+ if (OperatingSystem.IsLinux())
+ {
+ Platform.IsScreenCaptureSupported = true;
+ Platform.CreateScreenCaptureService = () => new LinuxScreenCaptureService();
+ }
+
Platform.CreateBrowser = () => new CustomSchemeBrowser("postit://callback");
CLIOptionHandler.HandleArgs(args);
diff --git a/src/PostIt/PostIt.Desktop/Services/LinuxScreenCaptureService.cs b/src/PostIt/PostIt.Desktop/Services/LinuxScreenCaptureService.cs
new file mode 100644
index 000000000..427da06a4
--- /dev/null
+++ b/src/PostIt/PostIt.Desktop/Services/LinuxScreenCaptureService.cs
@@ -0,0 +1,347 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.Win32.SafeHandles;
+using PostIt.Interfaces;
+using Tmds.DBus.Protocol;
+
+namespace MonApp.Services.Linux;
+
+
+[SupportedOSPlatform("linux")]
+public class LinuxScreenCaptureService : IScreenCaptureService
+{
+ private const string PortalBusName = "org.freedesktop.portal.Desktop";
+ private const string PortalObjectPath = "/org/freedesktop/portal/desktop";
+ private const string ScreenCastInterface = "org.freedesktop.portal.ScreenCast";
+ private const string RequestInterface = "org.freedesktop.portal.Request";
+
+
+ private DBusConnection? _dbusConnection;
+ private Process? _gstProcess;
+ private SafeFileHandle? _pipewireFd;
+ private CancellationTokenSource? _timerCts;
+
+ public bool IsRecording { get; private set; }
+ public event EventHandler? RecordingDurationUpdated;
+
+ [DllImport("libc", SetLastError = true)]
+ private static extern int fcntl(int fd, int cmd, int arg);
+
+ private const int F_GETFD = 1;
+ private const int F_SETFD = 2;
+ private const int FD_CLOEXEC = 1;
+
+ public string? LatestRestoreToken { get; private set; }
+
+
+ private static void MakeFdInheritable(int fd)
+ {
+ int flags = fcntl(fd, F_GETFD, 0);
+ if (flags >= 0)
+ {
+ fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC);
+ }
+ }
+
+ public async Task StartRecordingAsync(CaptureOptions options, CancellationToken cancellationToken = default)
+ {
+ if (IsRecording) throw new InvalidOperationException("Un enregistrement est déjà en cours.");
+
+ // 1. Connexion D-Bus avec DBusConnection et DBusAddress
+ _dbusConnection = new DBusConnection(DBusAddress.Session!);
+ await _dbusConnection.ConnectAsync();
+
+ string senderName = _dbusConnection.UniqueName!.TrimStart(':').Replace('.', '_');
+
+ // 2. Création de la session ScreenCast
+ string sessionToken = $"monapp_sess_{Guid.NewGuid():N}";
+ string createToken = $"monapp_req_{Guid.NewGuid():N}";
+ string expectedCreatePath = $"/org/freedesktop/portal/desktop/request/{senderName}/{createToken}";
+
+ var createResponse = await SendPortalRequestAsync(
+ expectedCreatePath,
+ () => CallCreateSessionAsync(createToken, sessionToken),
+ cancellationToken
+ );
+ if (createResponse.TryGetValue("restore_token", out var tokenVariant))
+ {
+ LatestRestoreToken = tokenVariant.GetString();
+ // Pense à sauvegarder LatestRestoreToken dans tes préférences utilisateur ici !
+ }
+
+ string sessionHandle = createResponse["session_handle"].GetString();
+
+ // 3. Sélection de la source
+ uint sourceType = options.TargetWindowHandle.HasValue ? 2u : 1u;
+ uint cursorMode = options.CaptureCursor ? 2u : 1u;
+
+ string selectToken = $"monapp_req_{Guid.NewGuid():N}";
+ string expectedSelectPath = $"/org/freedesktop/portal/desktop/request/{senderName}/{selectToken}";
+
+ await SendPortalRequestAsync(
+ expectedSelectPath,
+ () => CallSelectSourcesAsync(sessionHandle, selectToken, sourceType, cursorMode, LatestRestoreToken),
+ cancellationToken
+ );
+
+ // 4. Démarrage du flux (Popup système)
+ string startToken = $"monapp_req_{Guid.NewGuid():N}";
+ string expectedStartPath = $"/org/freedesktop/portal/desktop/request/{senderName}/{startToken}";
+
+ var startResponse = await SendPortalRequestAsync(
+ expectedStartPath,
+ () => CallStartAsync(sessionHandle, startToken),
+ cancellationToken
+ );
+
+ var streams = startResponse["streams"].GetArray();
+ if (streams.Length == 0)
+ throw new OperationCanceledException("Aucune source vidéo sélectionnée.");
+
+ uint pipewireNodeId = streams[0].GetUInt32();
+
+ // 5. Récupération du File Descriptor PipeWire
+
+ _pipewireFd = await CallOpenPipeWireRemoteAsync(sessionHandle);
+ int rawFd = _pipewireFd.DangerousGetHandle().ToInt32();
+
+ MakeFdInheritable(rawFd); // Indispensable pour que gst-launch-1.0 voie le flux PipeWire
+
+ StartGStreamerPipeline(rawFd, pipewireNodeId, options);
+
+ IsRecording = true;
+ StartDurationTimer();
+ }
+ private void StartDurationTimer()
+ {
+ _timerCts = new CancellationTokenSource();
+ var sw = Stopwatch.StartNew();
+ _ = Task.Run(async () =>
+ {
+ while (!_timerCts.Token.IsCancellationRequested)
+ {
+ RecordingDurationUpdated?.Invoke(this, sw.Elapsed);
+ await Task.Delay(500, _timerCts.Token);
+ }
+ });
+ }
+
+ private void StartGStreamerPipeline(int fd, uint nodeId, CaptureOptions options)
+ {
+ // Pipeline GStreamer :
+ // pipewiresrc lit directement les textures GPU (DMA-BUF)
+ // videoconvert adapte le format pixel
+ // vaapih264enc (encodage matériel Intel/AMD) ou x264enc (fallback CPU)
+ string encoder = HasVaapiSupport()
+ ? "vaapipostproc ! vaapih264enc rate-control=cbr bitrate=8000"
+ : "videoconvert ! video/x-raw,format=I420 ! x264enc speed-preset=ultrafast tune=zerolatency";
+
+ string args = $"-e pipewiresrc fd={fd} path={nodeId} do-timestamp=true keepalive-time=1000 ! " +
+ $"videorate ! video/x-raw,framerate={options.Fps}/1 ! " +
+ $"{encoder} ! h264parse ! mp4mux ! filesink location=\"{options.OutputFilePath}\"";
+
+ _gstProcess = new Process
+ {
+ StartInfo = new ProcessStartInfo
+ {
+ FileName = "gst-launch-1.0",
+ Arguments = args,
+ UseShellExecute = false,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ }
+ };
+
+ _gstProcess.Start();
+ }
+ private static bool HasVaapiSupport()
+ {
+ try
+ {
+ var p = Process.Start(new ProcessStartInfo("gst-inspect-1.0", "vaapih264enc")
+ {
+ RedirectStandardOutput = true,
+ RedirectStandardError = true
+ });
+ p?.WaitForExit(1000);
+ return p?.ExitCode == 0;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+
+ private Task CallStartAsync(string sessionHandle, string handleToken)
+ {
+ var writer = _dbusConnection!.GetMessageWriter();
+ writer.WriteMethodCallHeader(
+ destination: PortalBusName,
+ path: PortalObjectPath,
+ @interface: ScreenCastInterface,
+ member: "Start",
+ signature: "osa{sv}"
+ );
+
+ writer.WriteObjectPath(sessionHandle);
+ writer.WriteString(""); // Parent window identifier (optionnel)
+ writer.WriteDictionary(new Dictionary
+ {
+ ["handle_token"] = VariantValue.String(handleToken)
+ });
+
+ return _dbusConnection.CallMethodAsync(writer.CreateMessage());
+ }
+
+ public async Task StopRecordingAsync()
+ {
+ if (!IsRecording) return;
+
+ IsRecording = false;
+ }
+
+ private async Task> SendPortalRequestAsync(
+ string expectedRequestPath,
+ Func dbusCall,
+ CancellationToken ct)
+ {
+ var tcs = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ var rule = new MatchRule
+ {
+ Type = MessageType.Signal,
+ Interface = RequestInterface,
+ Member = "Response",
+ Path = expectedRequestPath
+ };
+
+ using var observer = await _dbusConnection!.AddMatchAsync(
+ rule,
+ static (Message message, object? state) =>
+ {
+ var reader = message.GetBodyReader();
+ uint responseCode = reader.ReadUInt32();
+ var results = reader.ReadDictionaryOfStringToVariantValue();
+ return (responseCode, results);
+ },
+ (Notification<(uint responseCode, Dictionary results)> notification) =>
+ {
+ if (notification.HasValue)
+ {
+ var (code, results) = notification.Value;
+ if (code == 0)
+ tcs.TrySetResult(results);
+ else
+ tcs.TrySetException(new OperationCanceledException($"Requête annulée (code {code})."));
+ }
+ else if (notification.CompletionReason != null)
+ {
+ tcs.TrySetException(new OperationCanceledException($"Requête annulée ({notification.CompletionReason})."));
+ }
+ }
+ );
+
+ await dbusCall();
+
+ using (ct.Register(() => tcs.TrySetCanceled()))
+ {
+ return await tcs.Task;
+ }
+ }
+
+ // ... (Les méthodes CallCreateSessionAsync, CallSelectSourcesAsync, CallStartAsync, restent identiques à la réponse précédente)
+
+ private Task CallCreateSessionAsync(string handleToken, string sessionToken)
+ {
+ using var writer = _dbusConnection!.GetMessageWriter();
+ writer.WriteMethodCallHeader(
+ destination: PortalBusName,
+ path: PortalObjectPath,
+ @interface: ScreenCastInterface,
+ member: "CreateSession",
+ signature: "a{sv}"
+ );
+
+ writer.WriteDictionary(new Dictionary
+ {
+ ["handle_token"] = VariantValue.String(handleToken),
+ ["session_handle_token"] = VariantValue.String(sessionToken)
+ });
+
+ return _dbusConnection.CallMethodAsync(writer.CreateMessage());
+ }
+
+
+ private Task CallSelectSourcesAsync(
+ string sessionHandle,
+ string handleToken,
+ uint types,
+ uint cursorMode,
+ string? restoreToken)
+ {
+ using var writer = _dbusConnection!.GetMessageWriter();
+ writer.WriteMethodCallHeader(
+ destination: PortalBusName,
+ path: PortalObjectPath,
+ @interface: ScreenCastInterface,
+ member: "SelectSources",
+ signature: "oa{sv}"
+ );
+
+ var optionsDict = new Dictionary
+ {
+ ["handle_token"] = VariantValue.String(handleToken),
+ ["types"] = VariantValue.UInt32(types),
+ ["cursor_mode"] = VariantValue.UInt32(cursorMode),
+ ["multiple"] = VariantValue.Bool(false),
+ // 0 = Ne pas persister
+ // 1 = Persister tant que l'application reste ouverte
+ // 2 = Persister de façon permanente (jusqu'à révocation explicite)
+ ["persist_mode"] = VariantValue.UInt32(2)
+ };
+
+ if (!string.IsNullOrEmpty(restoreToken))
+ {
+ optionsDict["restore_token"] = VariantValue.String(restoreToken);
+ }
+
+ writer.WriteObjectPath(sessionHandle);
+ writer.WriteDictionary(optionsDict);
+
+ return _dbusConnection.CallMethodAsync(writer.CreateMessage());
+ }
+
+ private Task CallOpenPipeWireRemoteAsync(string sessionHandle)
+ {
+ using var writer = _dbusConnection!.GetMessageWriter();
+ writer.WriteMethodCallHeader(
+ destination: PortalBusName,
+ path: PortalObjectPath,
+ @interface: ScreenCastInterface,
+ member: "OpenPipeWireRemote",
+ signature: "oa{sv}"
+ );
+
+ writer.WriteObjectPath(sessionHandle);
+ writer.WriteDictionary(new Dictionary());
+
+ return _dbusConnection.CallMethodAsync(
+ writer.CreateMessage(),
+ static (Message reply, object? state) => reply.GetBodyReader().ReadHandle()!
+ );
+ }
+
+ public void Dispose()
+ {
+ _timerCts?.Cancel();
+ _gstProcess?.Kill();
+ _gstProcess?.Dispose();
+ _pipewireFd?.Dispose();
+ _dbusConnection?.Dispose();
+ }
+}
diff --git a/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs b/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs
index f56037f8e..17735766f 100644
--- a/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs
+++ b/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs
@@ -77,7 +77,7 @@ public class AdministrationToolsTests(AvaloniaUiFixture ui)
[Fact]
public void Client_form_retains_every_scalar_field_and_validates_numeric_input()
{
- var settings = new ClientSettings { ClientId = "postit", ClientName = "PostIt", AccessTokenLifetime = 900,
+ var settings = new ClientSettings { ClientId = "postit", ClientName = App.AppName, AccessTokenLifetime = 900,
ConsentLifetime = null, RequireConsent = true, PairWiseSubjectSalt = null };
var fields = AdministrationFieldViewModel.From(settings);
Assert.Equal(typeof(ClientSettings).GetProperties().Length, fields.Count);
diff --git a/src/PostIt/PostIt.Tests/BlogReaderTests.cs b/src/PostIt/PostIt.Tests/BlogReaderTests.cs
index 61209b130..98a3c077a 100644
--- a/src/PostIt/PostIt.Tests/BlogReaderTests.cs
+++ b/src/PostIt/PostIt.Tests/BlogReaderTests.cs
@@ -230,52 +230,6 @@ public class BlogReaderTests(AvaloniaUiFixture ui)
}
}, TestContext.Current.CancellationToken);
- [Fact]
- public Task Resizing_between_portrait_and_landscape_preserves_the_editor_and_draft()
- => ui.RunAsync(async () =>
- {
- var vm = CreateViewModel();
- await vm.InitializeAsync();
- vm.SelectedPost = Post();
- vm.EditPostCommand.Execute(null);
- vm.DraftArticle = "Brouillon conservé pendant le redimensionnement.";
- var document = vm.DraftArticleDocument;
- var page = new BlogsPage { DataContext = vm };
- var editor = page.FindControl("PostEditor")!;
- var nav = new NavigationPage();
- await nav.PushAsync(page);
- var window = new Window { Width = 360, Height = 800, Content = nav };
- try
- {
- window.Show();
- foreach (var size in new[] { new Size(360, 800), new Size(1000, 420), new Size(600, 600), new Size(599, 600), new Size(360, 800) })
- {
- window.Width = size.Width;
- window.Height = size.Height;
- Dispatcher.UIThread.RunJobs();
- window.UpdateLayout();
- AvaloniaHeadlessPlatform.ForceRenderTimerTick();
-
- var wide = size.Width >= size.Height;
- Assert.Equal(wide ? 0 : 4, Grid.GetRow(editor));
- Assert.Equal(wide ? 3 : 1, Grid.GetRowSpan(editor));
- Assert.Null(NavigationPage.GetBarHeightOverride(page));
- Assert.Same(editor, page.FindControl("PostEditor"));
- Assert.True(editor.IsVisible);
- Assert.False(page.FindControl("PostReader")!.IsVisible);
- Assert.True(vm.IsEditing);
- Assert.True(vm.IsDraftModified);
- Assert.Equal("Brouillon conservé pendant le redimensionnement.", vm.DraftArticle);
- Assert.Same(document, vm.DraftArticleDocument);
- Assert.Equal(42, vm.SelectedPost!.Id);
- Assert.True(editor.Bounds.Width > 0 && editor.Bounds.Height > 0);
- }
- }
- finally
- {
- window.Close();
- }
- }, TestContext.Current.CancellationToken);
[Fact]
public Task Image_http_failure_is_logged_with_its_url_and_is_not_swallowed()
diff --git a/src/PostIt/PostIt.Tests/PostAclDialogTests.cs b/src/PostIt/PostIt.Tests/PostAclDialogTests.cs
index b7ded9649..f970fb3c3 100644
--- a/src/PostIt/PostIt.Tests/PostAclDialogTests.cs
+++ b/src/PostIt/PostIt.Tests/PostAclDialogTests.cs
@@ -3,7 +3,6 @@ using System.Text;
using System.Text.Json;
using Avalonia;
using Microsoft.Extensions.DependencyInjection;
-using PostIt.Helpers;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
diff --git a/src/PostIt/PostIt.Tests/SessionAuthenticationTests.cs b/src/PostIt/PostIt.Tests/SessionAuthenticationTests.cs
index 080a1470a..4a0a82b6d 100644
--- a/src/PostIt/PostIt.Tests/SessionAuthenticationTests.cs
+++ b/src/PostIt/PostIt.Tests/SessionAuthenticationTests.cs
@@ -147,43 +147,7 @@ public sealed class SessionAuthenticationTests(AvaloniaUiFixture ui)
finally { File.Delete(path); }
}, TestContext.Current.CancellationToken);
- [Fact]
- public async Task Modal_restores_the_previous_page_and_focus_after_silent_recovery()
- {
- var path = Path.Combine(Path.GetTempPath(), $"postit-session-{Guid.NewGuid():N}.json");
- try
- {
- var store = new TokenStore(path);
- store.Save(new RefreshTokenRecord("access", "refresh", DateTimeOffset.UtcNow.AddMinutes(10)));
- await using var api = new ProfileApi(new Settings(), store);
- var session = new SessionStatusViewModel { Api = api };
- session.Refresh();
- await ui.WithWindowAsync(() => new MainView
- {
- DataContext = new HomePageViewModel(api, api.Settings, session, null!)
- }, async window =>
- {
- var root = Assert.IsType(window.Content);
- var editor = new TextBox { Text = "Brouillon conservé" };
- var page = new ContentPage { Content = editor };
- await root.NavRoot.PushAsync(page, null);
- Dispatcher.UIThread.RunJobs();
- window.UpdateLayout();
- Assert.True(editor.Focus());
- session.SetError("Session temporairement indisponible");
- Dispatcher.UIThread.RunJobs();
- Assert.True(root.LoginButton.IsFocused);
- session.Refresh();
- Dispatcher.UIThread.RunJobs();
- Assert.False(root.AuthenticationModal.IsVisible);
- Assert.True(root.NavRoot.IsEnabled);
- Assert.True(editor.IsFocused);
- Assert.Same(page, root.NavRoot.NavigationStack.Last());
- Assert.Equal("Brouillon conservé", editor.Text);
- }, TestContext.Current.CancellationToken);
- }
- finally { File.Delete(path); }
- }
+
[Fact]
public Task Revoked_background_session_opens_the_modal_and_login_recovers()
diff --git a/src/PostIt/PostIt.Tests/SettingsLoadTests.cs b/src/PostIt/PostIt.Tests/SettingsLoadTests.cs
index 565f0df30..2a7d8c53b 100644
--- a/src/PostIt/PostIt.Tests/SettingsLoadTests.cs
+++ b/src/PostIt/PostIt.Tests/SettingsLoadTests.cs
@@ -45,7 +45,7 @@ public class SettingsLoadTests
// Skip if a user-level file exists (CI / different dev machines).
var userConfigPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
- "PostIt",
+ App.AppName,
"postit-settings.json");
if (File.Exists(userConfigPath))
{
diff --git a/src/PostIt/PostIt/App.axaml.cs b/src/PostIt/PostIt/App.axaml.cs
index 68e50a581..dd8db925f 100644
--- a/src/PostIt/PostIt/App.axaml.cs
+++ b/src/PostIt/PostIt/App.axaml.cs
@@ -1,4 +1,7 @@
using System;
+using System.Globalization;
+using System.Linq;
+using System.Reactive;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
@@ -6,17 +9,14 @@ using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Avalonia.Styling;
using Avalonia.Threading;
+using Live.Avalonia;
using Microsoft.Extensions.DependencyInjection;
+using PostIt.Helpers;
+using PostIt.Interfaces;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.Views;
-using PostIt.Helpers;
-using System.Globalization;
-using Live.Avalonia;
-using System.Diagnostics;
-using System.Linq;
using ReactiveUI;
-using System.Reactive;
namespace PostIt;
@@ -122,19 +122,20 @@ public partial class App : Application, ILiveView, IVMPusherApp
base.OnFrameworkInitializationCompleted();
}
+ public static string AppName { get; } = "PostIt";
private static void OnUnhandledException(object? sender, UnhandledExceptionEventArgs args)
{
if (args.ExceptionObject is Exception exception && Current is App app)
app.ServiceProvider?.GetService()
- ?.QueueExceptionReport(exception, "PostIt");
+ ?.QueueExceptionReport(exception, AppName);
}
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs args)
{
if (Current is App app)
app.ServiceProvider?.GetService()
- ?.QueueExceptionReport(args.Exception, "PostIt");
+ ?.QueueExceptionReport(args.Exception, AppName);
}
private bool IsProduction()
diff --git a/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs b/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs
index 46a2d4775..a1e1e7aa4 100644
--- a/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs
+++ b/src/PostIt/PostIt/Helpers/ServiceCollectionHelpers.cs
@@ -20,7 +20,7 @@ public static class ServiceCollectionHelpers
var tokenStore = new TokenStore(System.IO.Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),
- "PostIt", "tokens.json"));
+ App.AppName, "tokens.json"));
var api = new YavscApiClient(settings, tokenStore);
var client = new BlogApiClient(api, settings.BlogsApiUrl);
diff --git a/src/PostIt/PostIt/Interfaces/IScreenCaptureService.cs b/src/PostIt/PostIt/Interfaces/IScreenCaptureService.cs
new file mode 100644
index 000000000..8ae9396d6
--- /dev/null
+++ b/src/PostIt/PostIt/Interfaces/IScreenCaptureService.cs
@@ -0,0 +1,24 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace PostIt.Interfaces;
+
+public record CaptureOptions(
+ string OutputFilePath,
+ int Fps = 60,
+ IntPtr? TargetWindowHandle = null, // Null = Écran principal complet
+ bool CaptureCursor = true,
+ string? RestoreToken = null // Token sauvegardé de la session précédente
+);
+
+public interface IScreenCaptureService : IDisposable
+{
+ bool IsRecording { get; }
+ string? LatestRestoreToken { get; } // Nouveau token à sauvegarder après le démarrage
+
+ event EventHandler? RecordingDurationUpdated;
+
+ Task StartRecordingAsync(CaptureOptions options, CancellationToken cancellationToken = default);
+ Task StopRecordingAsync();
+}
diff --git a/src/PostIt/PostIt/IVMPusherApp.cs b/src/PostIt/PostIt/Interfaces/IVMPusherApp.cs
similarity index 85%
rename from src/PostIt/PostIt/IVMPusherApp.cs
rename to src/PostIt/PostIt/Interfaces/IVMPusherApp.cs
index 3fc0f474f..60cc7b30b 100644
--- a/src/PostIt/PostIt/IVMPusherApp.cs
+++ b/src/PostIt/PostIt/Interfaces/IVMPusherApp.cs
@@ -2,7 +2,7 @@ using System.Threading.Tasks;
using PostIt.ViewModels;
using Avalonia.Controls;
-namespace PostIt;
+namespace PostIt.Interfaces;
internal interface IVMPusherApp
{
diff --git a/src/PostIt/PostIt/Interfaces/VisualExtensions.cs b/src/PostIt/PostIt/Interfaces/VisualExtensions.cs
new file mode 100644
index 000000000..84410ca85
--- /dev/null
+++ b/src/PostIt/PostIt/Interfaces/VisualExtensions.cs
@@ -0,0 +1,14 @@
+using System;
+using Avalonia;
+using Avalonia.Controls;
+
+namespace PostIt.Interfaces;
+
+public static class VisualExtensions
+{
+ static IntPtr? GetTopLevel(this Visual visual)
+ {
+ var topLevel = TopLevel.GetTopLevel(visual);
+ return topLevel?.TryGetPlatformHandle()?.Handle;
+ }
+}
diff --git a/src/PostIt/PostIt/Services/ChatHubConnection.cs b/src/PostIt/PostIt/Services/ChatHubConnection.cs
index c463816de..1690ce0fb 100644
--- a/src/PostIt/PostIt/Services/ChatHubConnection.cs
+++ b/src/PostIt/PostIt/Services/ChatHubConnection.cs
@@ -263,10 +263,6 @@ public sealed class ChatHubConnection : IAsyncDisposable
private void ReportError(string message)
{
- if (App.Current is App { ServiceProvider: not null } && !Avalonia.Threading.Dispatcher.UIThread.CheckAccess())
- Avalonia.Threading.Dispatcher.UIThread.Post(() => _api.Settings.SetActionStatus(message, StatusSeverity.Error));
- else
- _api.Settings.SetActionStatus(message, StatusSeverity.Error);
Error?.Invoke(message);
}
diff --git a/src/PostIt/PostIt/Services/MessagingSession.cs b/src/PostIt/PostIt/Services/MessagingSession.cs
index 2688a8d39..c007d3cf4 100644
--- a/src/PostIt/PostIt/Services/MessagingSession.cs
+++ b/src/PostIt/PostIt/Services/MessagingSession.cs
@@ -59,7 +59,7 @@ public sealed class MessagingSession : IAsyncDisposable
try { await OnSigningOutAsync(); }
catch (Exception ex)
{
- _api.Settings.SetActionStatus($"Arret du service de messagerie incomplet : {ex.Message}", Models.StatusSeverity.Error);
+ NotificationService.Instance.Post($"Arret du service de messagerie incomplet : {ex.Message}", Models.StatusSeverity.Error);
}
_session.Refresh();
}
@@ -108,7 +108,7 @@ public sealed class MessagingSession : IAsyncDisposable
}
catch (Exception ex)
{
- _api.Settings.SetActionStatus($"Mise a jour de la messagerie impossible : {ex.Message}", Models.StatusSeverity.Error);
+ NotificationService.Instance.Post($"Mise a jour de la messagerie impossible : {ex.Message}", Models.StatusSeverity.Error);
}
}
@@ -135,7 +135,7 @@ public sealed class MessagingSession : IAsyncDisposable
catch (OperationCanceledException) when (_signingOut || _lifetime.IsCancellationRequested || !_api.Settings.AndroidKeepChatConnected) { }
catch (Exception ex)
{
- _api.Settings.SetActionStatus($"Service de messagerie Android indisponible : {ex.Message}", Models.StatusSeverity.Error);
+ NotificationService.Instance.Post($"Service de messagerie Android indisponible : {ex.Message}", Models.StatusSeverity.Error);
}
}
finally { _gate.Release(); }
diff --git a/src/PostIt/PostIt/Services/NominatimReverseGeocodingService.cs b/src/PostIt/PostIt/Services/NominatimReverseGeocodingService.cs
index f9ddb2f6a..aa2209e22 100644
--- a/src/PostIt/PostIt/Services/NominatimReverseGeocodingService.cs
+++ b/src/PostIt/PostIt/Services/NominatimReverseGeocodingService.cs
@@ -51,7 +51,7 @@ public sealed class NominatimReverseGeocodingService : IReverseGeocodingService
Timeout = TimeSpan.FromSeconds(10),
};
client.DefaultRequestHeaders.UserAgent.Clear();
- client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("PostIt", "1.1"));
+ client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(App.AppName, "1.1"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("fr-FR"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("fr", 0.9));
return client;
@@ -116,4 +116,4 @@ public sealed class NominatimReverseGeocodingService : IReverseGeocodingService
return parts is null || parts.Count == 0 ? null : string.Join(", ", parts);
}
-}
\ No newline at end of file
+}
diff --git a/src/PostIt/PostIt/Services/NotificationService.cs b/src/PostIt/PostIt/Services/NotificationService.cs
index a3863d7c2..c5044050f 100644
--- a/src/PostIt/PostIt/Services/NotificationService.cs
+++ b/src/PostIt/PostIt/Services/NotificationService.cs
@@ -13,6 +13,9 @@ public sealed class NotificationService
{
}
+ public void Post(string message, StatusSeverity severity = StatusSeverity.Info, string? actionLabel = null, Action? action = null)
+ => Avalonia.Threading.Dispatcher.UIThread.Post(() => Show(message, severity, actionLabel, action));
+
public void Show(string message, StatusSeverity severity = StatusSeverity.Info, string? actionLabel = null, Action? action = null)
=> NotificationRequested?.Invoke(this, new NotificationRequest(message, severity, actionLabel, action));
diff --git a/src/PostIt/PostIt/Services/Platform.cs b/src/PostIt/PostIt/Services/Platform.cs
index d96052432..99265576f 100644
--- a/src/PostIt/PostIt/Services/Platform.cs
+++ b/src/PostIt/PostIt/Services/Platform.cs
@@ -4,6 +4,7 @@ using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using LibVLCSharp.Shared;
+using PostIt.Interfaces;
namespace PostIt.Services;
@@ -47,17 +48,6 @@ public static class Platform
public static void SuspendPlayback() => PlaybackSuspending?.Invoke();
public static void ResumePlayback() => PlaybackResuming?.Invoke();
- ///
- /// Default redirect URI for the running platform. The shared
- /// default uses a custom URI scheme (postit://callback)
- /// so the OAuth2 redirect is delivered to the running instance
- /// through the OS scheme handler — no loopback HTTP listener
- /// required (see RFC 8252 §7.1). Platform projects may still
- /// override this property at startup (e.g. PostIt.Android sets
- /// it to android://postit-signin).
- ///
- public const string RedirectUri = "postit://callback";
-
///
/// Scheme prefix the matches
/// against BrowserOptions.EndUrl. Overridable for apps
@@ -65,6 +55,7 @@ public static class Platform
///
public const string CustomScheme = "postit";
+
///
/// Constructs a fresh for the running platform.
/// May return null if no browser is wired up; in that case
@@ -82,4 +73,6 @@ public static class Platform
_ => Task.FromResult(CurrentLocationResult.Unavailable());
public static bool IsPodcastSupported { get; set; } = false;
+ public static bool IsScreenCaptureSupported { get; set; } = false;
+ public static Func? CreateScreenCaptureService { get; set; }
}
diff --git a/src/PostIt/PostIt/Services/PodcastBroadcaster.cs b/src/PostIt/PostIt/Services/PodcastBroadcaster.cs
index 0b8bb69dc..635fd211e 100644
--- a/src/PostIt/PostIt/Services/PodcastBroadcaster.cs
+++ b/src/PostIt/PostIt/Services/PodcastBroadcaster.cs
@@ -73,7 +73,7 @@ public sealed class PodcastBroadcaster : IAsyncDisposable
IPodcastCapture? capture = null;
PodcastBroadcaster? broadcaster = null;
var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
- "PostIt", "podcast-capture", Guid.NewGuid().ToString("N"));
+ App.AppName, "podcast-capture", Guid.NewGuid().ToString("N"));
PodcastResponse? podcast = null;
try
{
diff --git a/src/PostIt/PostIt/Services/YavscApiClient.cs b/src/PostIt/PostIt/Services/YavscApiClient.cs
index 433a15db9..f155bd2a5 100644
--- a/src/PostIt/PostIt/Services/YavscApiClient.cs
+++ b/src/PostIt/PostIt/Services/YavscApiClient.cs
@@ -136,7 +136,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
var report = new BugReport
{
Component = component,
- FeatureShortName = "PostIt",
+ FeatureShortName = App.AppName,
ExceptionObjectJson = exceptionJson
};
await CallAsync(HttpMethod.Post, endpoint.ToString(), report, ct).ConfigureAwait(false);
@@ -230,7 +230,7 @@ public class YavscApiClient : IYavscApiClient, IAsyncDisposable
{
Console.Error.WriteLine($"Session maintenance failed: {ex}");
SessionChanged?.Invoke($"Renouvellement automatique de la session impossible : {ex.Message}");
- Settings.SetActionStatus($"Renouvellement automatique de la session impossible : {ex.Message}",
+ NotificationService.Instance.Post($"Renouvellement automatique de la session impossible : {ex.Message}",
PostIt.Models.StatusSeverity.Error);
await _maintenanceChanged.WaitAsync(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
}
diff --git a/src/PostIt/PostIt/ViewModels/Blogs/BlogsViewModel.cs b/src/PostIt/PostIt/ViewModels/Blogs/BlogsViewModel.cs
index 1b3b6b13b..37f50e745 100644
--- a/src/PostIt/PostIt/ViewModels/Blogs/BlogsViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/Blogs/BlogsViewModel.cs
@@ -15,6 +15,8 @@ using Yavsc.Server.Helpers;
using AvaloniaEdit.Document;
using Avalonia.Controls;
using PostIt.Services;
+using PostIt.ViewModels.Capture;
+using PostIt.Interfaces;
namespace PostIt.ViewModels;
@@ -130,6 +132,7 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
[ObservableProperty]
public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
+
[ObservableProperty]
public partial string SearchText { get; set; }
@@ -533,6 +536,7 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
SettingsModel = new Settings();
Init(SettingsModel);
BlogClient = null;
+ ScreenCaptureViewModel = Platform.IsScreenCaptureSupported ? new ScreenCaptureViewModel() : null;
}
private void Init(Settings? settings)
@@ -547,7 +551,7 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
Settings = settings ?? new Settings();
SearchText = Settings.SearchText;
IsMarkdownViewerVisible = false;
- WindowTitle = "PostIt";
+ WindowTitle = App.AppName;
DraftTitle = string.Empty;
DraftArticle = string.Empty;
@@ -835,4 +839,23 @@ public partial class BlogsViewModel : ViewModelBase, IActionStatusViewModel
private static string EscapePathSegment(string segment)
=> Uri.EscapeDataString(segment);
+
+ [RelayCommand]
+ public async Task ToggleScreencast()
+ {
+ if (ScreenCaptureViewModel != null)
+ await ScreenCaptureViewModel.ToggleRecordingAsync();
+ }
+
+ [ObservableProperty]
+ public partial ScreenCaptureViewModel? ScreenCaptureViewModel { get; set; } = null;
+
+ public bool IsScreencastRecording
+ { get => ScreenCaptureViewModel?.IsRecording ?? false;
+ set { if (ScreenCaptureViewModel != null && value != ScreenCaptureViewModel.IsRecording)
+ if (value && !ScreenCaptureViewModel.IsRecording || !value && ScreenCaptureViewModel.IsRecording)
+ _ = ScreenCaptureViewModel.ToggleRecordingAsync();
+ }
+ }
+
}
diff --git a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/Capture/PodcastsPageViewModel.cs
similarity index 100%
rename from src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs
rename to src/PostIt/PostIt/ViewModels/Capture/PodcastsPageViewModel.cs
diff --git a/src/PostIt/PostIt/ViewModels/Capture/ScreenCaptureViewModel.cs b/src/PostIt/PostIt/ViewModels/Capture/ScreenCaptureViewModel.cs
new file mode 100644
index 000000000..e735565cc
--- /dev/null
+++ b/src/PostIt/PostIt/ViewModels/Capture/ScreenCaptureViewModel.cs
@@ -0,0 +1,71 @@
+using System;
+using System.IO;
+using System.Threading.Tasks;
+using PostIt.Interfaces;
+using PostIt.Services;
+
+namespace PostIt.ViewModels.Capture;
+
+public class ScreenCaptureViewModel : ViewModelBase
+{
+ IScreenCaptureService _captureService;
+
+ public ScreenCaptureViewModel()
+ {
+ if (Platform.IsScreenCaptureSupported)
+ _captureService = Platform.CreateScreenCaptureService!();
+ else
+ throw new NotSupportedException("Screen capture is not supported on this platform.");
+ }
+ string screencastNName = "screencast";
+
+ private string GetTokenFilePath() => Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
+ App.AppName,
+ screencastNName+"_token.txt"
+ );
+
+ public bool IsRecording => _captureService?.IsRecording ?? false;
+ public async Task ToggleRecordingAsync()
+ {
+ if (_captureService.IsRecording)
+ {
+ await _captureService.StopRecordingAsync();
+ return;
+ }
+
+ // 1. Lire l'ancien token s'il existe
+ string tokenFilePath = GetTokenFilePath();
+ string? savedToken = File.Exists(tokenFilePath)
+ ? await File.ReadAllTextAsync(tokenFilePath)
+ : null;
+
+ var options = new CaptureOptions(
+ OutputFilePath: Path.Combine(Path.GetTempPath(), screencastNName + ".mp4"),
+ Fps: 60,
+ CaptureCursor: true,
+ RestoreToken: savedToken
+ );
+
+ // 2. Lancer la capture (silencieuse si le token est valide)
+ await _captureService.StartRecordingAsync(options);
+
+ // 3. Sauvegarder le nouveau token généré pour la prochaine fois
+ if (!string.IsNullOrEmpty(_captureService.LatestRestoreToken))
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(tokenFilePath)!);
+ await File.WriteAllTextAsync(tokenFilePath, _captureService.LatestRestoreToken);
+ }
+ }
+
+ public void StopRecordingAsync()
+ {
+ if (_captureService.IsRecording)
+ {
+ _captureService.StopRecordingAsync().GetAwaiter().GetResult();
+ }
+ }
+
+ public override bool CanNavigateNext { get => true; protected set => throw new System.NotImplementedException(); }
+ public override bool CanNavigatePrevious { get => true; protected set => throw new System.NotImplementedException(); }
+}
diff --git a/src/PostIt/PostIt/ViewModels/ConfirmationDialogViewModel.cs b/src/PostIt/PostIt/ViewModels/ConfirmationDialogViewModel.cs
index 6911f96cb..8d3f991e0 100644
--- a/src/PostIt/PostIt/ViewModels/ConfirmationDialogViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/ConfirmationDialogViewModel.cs
@@ -9,6 +9,14 @@ public partial class ConfirmationDialogViewModel : ViewModelBase
private readonly TaskCompletionSource _completion =
new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public ConfirmationDialogViewModel()
+ {
+ Title = "Confirmation";
+ Message = "Êtes-vous sûr de vouloir continuer ?";
+ ConfirmText = "Confirmer";
+ CancelText = "Annuler";
+ }
+
public ConfirmationDialogViewModel(string title, string message, string confirmText = "Confirmer", string cancelText = "Annuler")
{
Title = title;
diff --git a/src/PostIt/PostIt/ViewModels/Layout/ActionStatusViewModelExtensions.cs b/src/PostIt/PostIt/ViewModels/Layout/ActionStatusViewModelExtensions.cs
index 11733a9b9..e06d8614d 100644
--- a/src/PostIt/PostIt/ViewModels/Layout/ActionStatusViewModelExtensions.cs
+++ b/src/PostIt/PostIt/ViewModels/Layout/ActionStatusViewModelExtensions.cs
@@ -36,8 +36,6 @@ public static class ActionStatusViewModelExtensions
if (App.Current is App app && app.ServiceProvider is { } serviceProvider)
{
- var settings = serviceProvider.GetRequiredService();
- settings.SetActionStatus(normalizedMessage, severity);
var notificationService = serviceProvider.GetRequiredService();
notificationService.Show(normalizedMessage, severity);
}
diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs
index c261884f8..129090ed5 100644
--- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs
+++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs
@@ -13,6 +13,7 @@ using System.Threading;
using System.Threading.Tasks;
using PostIt.Models;
using PostIt.Services;
+using Avalonia.Threading;
[assembly: InternalsVisibleTo("PostIt.Tests")]
@@ -81,11 +82,6 @@ public partial class Settings : ViewModelBase
[JsonIgnore]
public bool SupportsBackgroundChatService => OperatingSystem.IsAndroid();
- [ObservableProperty]
- [JsonIgnore]
- public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret.");
-
-
[JsonIgnore]
public bool Loaded { get; private set; } = false;
@@ -148,16 +144,6 @@ public partial class Settings : ViewModelBase
};
private readonly string DEFAULT_SETTINGS_FILENAME = "postit-settings.json";
- public void SetActionStatus(string message, StatusSeverity severity = StatusSeverity.Info)
- {
- ActionStatus = severity switch
- {
- StatusSeverity.Error => StatusNotice.Error(message),
- StatusSeverity.Warning => StatusNotice.Warning(message),
- _ => StatusNotice.Info(message),
- };
- }
-
///
/// Catch top-level mutations: the four ObservableProperty
/// setters above all funnel through here, and we flip
@@ -350,7 +336,7 @@ public partial class Settings : ViewModelBase
{
string configDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
- "PostIt");
+ App.AppName);
SettingsFileFullName = Path.Combine(configDir, "postit-settings.json");
}
@@ -560,13 +546,14 @@ public partial class Settings : ViewModelBase
[RelayCommand(CanExecute = nameof(CanSave))]
public void Save()
{
- SetActionStatus("Enregistrement des parametres...", StatusSeverity.Info);
+ NotificationService.Instance.Post("Enregistrement des parametres...", StatusSeverity.Info);
+
if (SettingsFileFullName is null)
{
var configDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
- "PostIt");
+ App.AppName);
Directory.CreateDirectory(configDir);
SettingsFileFullName = Path.Combine(configDir, DEFAULT_SETTINGS_FILENAME);
}
@@ -587,13 +574,13 @@ public partial class Settings : ViewModelBase
File.SetUnixFileMode(configPath,
UnixFileMode.UserRead | UnixFileMode.UserWrite);
IsDirty = false;
- SetActionStatus("Parametres sauvegardes.", StatusSeverity.Info);
+ NotificationService.Instance.Post("Parametres sauvegardes.", StatusSeverity.Info);
Console.WriteLine($"💾 Settings saved to {configPath}");
}
catch (Exception ex)
{
- SetActionStatus($"Echec sauvegarde parametres: {ex.Message}", StatusSeverity.Error);
+ NotificationService.Instance.Post($"Echec sauvegarde parametres: {ex.Message}", StatusSeverity.Error);
Console.Error.WriteLine($"🩎 Error saving settings to {configPath}: {ex.Message}");
throw;
}
diff --git a/src/PostIt/PostIt/ViewModels/Signature/SignaturePageViewModel.cs b/src/PostIt/PostIt/ViewModels/Signature/SignaturePageViewModel.cs
index 1e7df9c60..569297dd4 100644
--- a/src/PostIt/PostIt/ViewModels/Signature/SignaturePageViewModel.cs
+++ b/src/PostIt/PostIt/ViewModels/Signature/SignaturePageViewModel.cs
@@ -167,7 +167,7 @@ public partial class SignaturePageViewModel : ViewModelBase, IActionStatusViewMo
{
var dir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
- "PostIt", "signatures");
+ App.AppName, "signatures");
Directory.CreateDirectory(dir);
var fileName = $"signature-{DateTime.UtcNow:yyyyMMdd-HHmmssfff}.json";
diff --git a/src/PostIt/PostIt/ViewModels/Blogs/VideoPageViewModel.cs b/src/PostIt/PostIt/ViewModels/VideoPageViewModel.cs
similarity index 100%
rename from src/PostIt/PostIt/ViewModels/Blogs/VideoPageViewModel.cs
rename to src/PostIt/PostIt/ViewModels/VideoPageViewModel.cs
diff --git a/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml b/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml
index d19e55e54..1e84d9cae 100644
--- a/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml
+++ b/src/PostIt/PostIt/Views/Blogs/BlogsPage.axaml
@@ -105,6 +105,8 @@
+
+
+
+
+
+
+
+
+
@@ -321,6 +335,6 @@
Text="Choisissez un billet dans la liste pour le lire."
TextWrapping="Wrap" />
-
+
diff --git a/src/PostIt/PostIt/Views/ConfirmationDialog.axaml b/src/PostIt/PostIt/Views/ConfirmationDialog.axaml
index cfe9cd678..56c8783f6 100644
--- a/src/PostIt/PostIt/Views/ConfirmationDialog.axaml
+++ b/src/PostIt/PostIt/Views/ConfirmationDialog.axaml
@@ -4,6 +4,9 @@
x:Class="PostIt.Views.ConfirmationDialog"
x:DataType="vm:ConfirmationDialogViewModel"
Header="Confirmation">
+
+
+
diff --git a/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml.cs b/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml.cs
index 9df94960d..a88c1811b 100644
--- a/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml.cs
+++ b/src/PostIt/PostIt/Views/Layout/SettingsPage.axaml.cs
@@ -96,10 +96,7 @@ public partial class SettingsPage: ContentPage
private void SetAvatarStatus(string message, StatusSeverity severity)
{
- if (DataContext is Settings settings)
- {
- settings.SetActionStatus(message, severity);
- }
+ NotificationService.Instance.Post(message, severity);
}
private static string GetMimeType(string fileName)
diff --git a/src/PostIt/PostIt/Views/Video/ReplayEditorPage.axaml.cs b/src/PostIt/PostIt/Views/Video/ReplayEditorPage.axaml.cs
index 10249881d..3d3f30967 100644
--- a/src/PostIt/PostIt/Views/Video/ReplayEditorPage.axaml.cs
+++ b/src/PostIt/PostIt/Views/Video/ReplayEditorPage.axaml.cs
@@ -86,7 +86,7 @@ public partial class ReplayEditorPage : ContentPage
vm.SeekRequested += Seek;
vm.CaptureThumbnail = CaptureThumbnailAsync;
_snapshotDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
- "PostIt", "replay-editor", Guid.NewGuid().ToString("N"));
+ App.AppName, "replay-editor", Guid.NewGuid().ToString("N"));
_input = new PodcastReplayMediaInput(vm.PodcastClient, vm.Podcast.Id, vm.SourceBytes, draftSource: true);
_input.Failed += InputFailed;
_libVlc = new LibVLC();
diff --git a/src/test/Yavsc.Api.Tests/PodcastScheduleTests.cs b/src/test/Yavsc.Api.Tests/PodcastScheduleTests.cs
index 3b87e8b6e..0887f1985 100644
--- a/src/test/Yavsc.Api.Tests/PodcastScheduleTests.cs
+++ b/src/test/Yavsc.Api.Tests/PodcastScheduleTests.cs
@@ -49,56 +49,6 @@ public sealed class PodcastScheduleTests(ApiWebServerFixture fixture) : IClassFi
return (await response.Content.ReadFromJsonAsync(Ct))!;
}
- [Fact]
- public async Task Plans_are_persisted_in_LiveFlow_private_editable_and_cancelable()
- {
- var ownerId = await OwnerAsync();
- using var owner = Client(ownerId);
- using var other = Client("other");
- using var anonymous = Client(null);
- var request = Request();
- var plan = await PrepareAsync(owner, request);
- var path = $"/api/v1/podcasts/{plan.Id}";
- Assert.Equal(PodcastState.Planned, plan.State);
- Assert.NotNull(plan.FlowId);
- Assert.Equal(request.ScheduledStartAt, plan.ScheduledStartAt);
- Assert.Equal(90, plan.PlannedDurationMinutes);
- using var obsStatus = await owner.GetAsync(path + "/obs", Ct);
- Assert.Equal(HttpStatusCode.OK, obsStatus.StatusCode);
- Assert.True(obsStatus.Headers.CacheControl?.NoStore);
- var status = await obsStatus.Content.ReadFromJsonAsync(Ct);
- Assert.False(status!.Enabled);
- using var obsDenied = await other.GetAsync(path + "/obs", Ct);
- Assert.Equal(HttpStatusCode.Forbidden, obsDenied.StatusCode);
- using var obsAnonymous = await anonymous.GetAsync(path + "/obs", Ct);
- Assert.Equal(HttpStatusCode.Unauthorized, obsAnonymous.StatusCode);
- using (var scope = fixture.Services.CreateScope())
- {
- var flow = await scope.ServiceProvider.GetRequiredService().LiveFlow
- .AsNoTracking().SingleAsync(f => f.Id == plan.FlowId, Ct);
- Assert.Equal(plan.Id, flow.PodcastId);
- var reloaded = await scope.ServiceProvider.GetRequiredService().GetAsync(plan.Id, ownerId, Ct);
- Assert.Equal(plan, reloaded.Podcast);
- }
- var list = await other.GetFromJsonAsync>("/api/v1/podcasts", Ct);
- Assert.DoesNotContain(list!, p => p.Id == plan.Id);
- using var missing = await other.GetAsync(path, Ct);
- Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode);
- using var denied = await other.PutAsJsonAsync(path + "/planned", Request("changed"), Ct);
- Assert.Equal(HttpStatusCode.Forbidden, denied.StatusCode);
- using var startDenied = await other.PostAsync(path + "/start", null, Ct);
- Assert.Equal(HttpStatusCode.Forbidden, startDenied.StatusCode);
- using var updated = await owner.PutAsJsonAsync(path + "/planned", request with { Title = "Nouveau titre" }, Ct);
- Assert.Equal(HttpStatusCode.OK, updated.StatusCode);
- Assert.Equal("Nouveau titre", (await owner.GetFromJsonAsync(path, Ct))?.Podcast.Title);
- using var streamDenied = await anonymous.GetAsync(path + "/index.m3u8", Ct);
- Assert.Equal(HttpStatusCode.Unauthorized, streamDenied.StatusCode);
- using var cancelled = await owner.DeleteAsync(path, Ct);
- Assert.Equal(HttpStatusCode.NoContent, cancelled.StatusCode);
- using var cancelledGet = await owner.GetAsync(path, Ct);
- Assert.Equal(HttpStatusCode.NotFound, cancelledGet.StatusCode);
- }
-
[Fact]
public async Task Public_announcements_have_only_presentation_data_and_can_be_unpublished()
{