feat/calls #62

Open
notazof wants to merge 104 commits from feat/calls into main
42 changed files with 578 additions and 236 deletions
Showing only changes of commit 68a2364de2 - Show all commits

refacto App.Name and settings cleanup

Paul Schneider 2026-11-20 12:56:27 +00:00
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12

View file

@ -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ù

View file

@ -20,6 +20,7 @@
<PackageVersion Include="DirectShowLib" Version="1.0.0" />
<PackageVersion Include="LibVLCSharp.Avalonia" Version="3.10.2" />
<PackageVersion Include="LibVLCSharp" Version="3.10.2" />
<PackageVersion Include="Tmds.DBus.Protocol" Version="0.95.2" />
<PackageVersion Include="VideoLAN.LibVLC.Android" Version="3.7.0-beta" />
<PackageVersion Include="Live.Avalonia" Version="1.4.2" />
<PackageVersion Include="Mapsui" Version="5.1.0" />
@ -42,4 +43,4 @@
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.13" />
<PackageVersion Include="Microsoft.ML.OnnxRuntime" Version="1.31.1" />
</ItemGroup>
</Project>
</Project>

View file

@ -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.");
});
}

View file

@ -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;
}

View file

@ -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);
}
});
}

View file

@ -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;
};

View file

@ -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()); }
}
}
}

View file

@ -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(); }

View file

@ -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)

View file

@ -20,6 +20,7 @@
<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
</PackageReference>
<PackageReference Include="Material.Avalonia" />
<PackageReference Include="Tmds.DBus.Protocol" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PostIt\PostIt.csproj" />

View file

@ -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);

View file

@ -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<TimeSpan>? 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<VariantValue>();
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<string, VariantValue>
{
["handle_token"] = VariantValue.String(handleToken)
});
return _dbusConnection.CallMethodAsync(writer.CreateMessage());
}
public async Task StopRecordingAsync()
{
if (!IsRecording) return;
IsRecording = false;
}
private async Task<Dictionary<string, VariantValue>> SendPortalRequestAsync(
string expectedRequestPath,
Func<Task> dbusCall,
CancellationToken ct)
{
var tcs = new TaskCompletionSource<Dictionary<string, VariantValue>>(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<string, VariantValue> 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<string, VariantValue>
{
["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<string, VariantValue>
{
["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<SafeFileHandle> 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<string, VariantValue>());
return _dbusConnection.CallMethodAsync(
writer.CreateMessage(),
static (Message reply, object? state) => reply.GetBodyReader().ReadHandle<SafeFileHandle>()!
);
}
public void Dispose()
{
_timerCts?.Cancel();
_gstProcess?.Kill();
_gstProcess?.Dispose();
_pipewireFd?.Dispose();
_dbusConnection?.Dispose();
}
}

View file

@ -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);

View file

@ -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<Grid>("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<Grid>("PostEditor"));
Assert.True(editor.IsVisible);
Assert.False(page.FindControl<Grid>("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()

View file

@ -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;

View file

@ -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<MainView>(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()

View file

@ -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))
{

View file

@ -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<YavscApiClient>()
?.QueueExceptionReport(exception, "PostIt");
?.QueueExceptionReport(exception, AppName);
}
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs args)
{
if (Current is App app)
app.ServiceProvider?.GetService<YavscApiClient>()
?.QueueExceptionReport(args.Exception, "PostIt");
?.QueueExceptionReport(args.Exception, AppName);
}
private bool IsProduction()

View file

@ -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);

View file

@ -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<TimeSpan>? RecordingDurationUpdated;
Task StartRecordingAsync(CaptureOptions options, CancellationToken cancellationToken = default);
Task StopRecordingAsync();
}

View file

@ -2,7 +2,7 @@ using System.Threading.Tasks;
using PostIt.ViewModels;
using Avalonia.Controls;
namespace PostIt;
namespace PostIt.Interfaces;
internal interface IVMPusherApp
{

View file

@ -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;
}
}

View file

@ -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);
}

View file

@ -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(); }

View file

@ -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);
}
}
}

View file

@ -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));

View file

@ -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();
/// <summary>
/// Default redirect URI for the running platform. The shared
/// default uses a custom URI scheme (<c>postit://callback</c>)
/// 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 <c>android://postit-signin</c>).
/// </summary>
public const string RedirectUri = "postit://callback";
/// <summary>
/// Scheme prefix the <see cref="CustomSchemeBrowser"/> matches
/// against <c>BrowserOptions.EndUrl</c>. Overridable for apps
@ -65,6 +55,7 @@ public static class Platform
/// </summary>
public const string CustomScheme = "postit";
/// <summary>
/// Constructs a fresh <see cref="IBrowser"/> for the running platform.
/// May return <c>null</c> 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<IScreenCaptureService>? CreateScreenCaptureService { get; set; }
}

View file

@ -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
{

View file

@ -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);
}

View file

@ -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();
}
}
}

View file

@ -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(); }
}

View file

@ -9,6 +9,14 @@ public partial class ConfirmationDialogViewModel : ViewModelBase
private readonly TaskCompletionSource<bool> _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;

View file

@ -36,8 +36,6 @@ public static class ActionStatusViewModelExtensions
if (App.Current is App app && app.ServiceProvider is { } serviceProvider)
{
var settings = serviceProvider.GetRequiredService<Settings>();
settings.SetActionStatus(normalizedMessage, severity);
var notificationService = serviceProvider.GetRequiredService<NotificationService>();
notificationService.Show(normalizedMessage, severity);
}

View file

@ -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),
};
}
/// <summary>
/// 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;
}

View file

@ -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";

View file

@ -105,6 +105,8 @@
<PathIcon Data="{StaticResource send_regular}" />
</CommandBarToggleButton.Icon>
</CommandBarToggleButton>
<CommandBarToggleButton
DataContext="{Binding #BlogsPageRoot.DataContext}"
IsChecked="{Binding IsMarkdownViewerVisible, Mode=TwoWay}"
@ -147,6 +149,18 @@
<PathIcon Data="{StaticResource form_new_regular}" />
</CommandBarButton.Icon>
</CommandBarButton>
<CommandBarToggleButton
x:Name="ToggleScreencastButton"
Command="{Binding ToggleScreencast}"
DataContext="{Binding #BlogsPageRoot.DataContext}"
IsChecked="{Binding IsScreencastRecording, Mode=TwoWay}"
Label="Caster votre écran">
<CommandBarToggleButton.Icon>
<PathIcon Data="{StaticResource preview_link_regular}" />
</CommandBarToggleButton.Icon>
</CommandBarToggleButton>
</CommandBar.SecondaryCommands>
</CommandBar>
</NavigationPage.TopCommandBar>
@ -321,6 +335,6 @@
Text="Choisissez un billet dans la liste pour le lire."
TextWrapping="Wrap" />
</Grid>
</Grid>
</ContentPage>

View file

@ -4,6 +4,9 @@
x:Class="PostIt.Views.ConfirmationDialog"
x:DataType="vm:ConfirmationDialogViewModel"
Header="Confirmation">
<Design.DataContext>
<vm:ConfirmationDialogViewModel />
</Design.DataContext>
<Border Margin="20" Padding="20" CornerRadius="10" BorderBrush="#D0D7DE" BorderThickness="1" VerticalAlignment="Center" HorizontalAlignment="Center">
<StackPanel Spacing="14" MaxWidth="420">
<TextBlock Text="{Binding Title}" FontSize="20" FontWeight="SemiBold" TextWrapping="Wrap" />

View file

@ -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)

View file

@ -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();

View file

@ -49,56 +49,6 @@ public sealed class PodcastScheduleTests(ApiWebServerFixture fixture) : IClassFi
return (await response.Content.ReadFromJsonAsync<PodcastResponse>(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<PodcastObsStatus>(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<ApplicationDbContext>().LiveFlow
.AsNoTracking().SingleAsync(f => f.Id == plan.FlowId, Ct);
Assert.Equal(plan.Id, flow.PodcastId);
var reloaded = await scope.ServiceProvider.GetRequiredService<IPodcastScheduleService>().GetAsync(plan.Id, ownerId, Ct);
Assert.Equal(plan, reloaded.Podcast);
}
var list = await other.GetFromJsonAsync<List<PodcastResponse>>("/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<PodcastManifestResponse>(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()
{