Add OBS podcast ingestion and account withdrawal privacy controls

Support scoped RTMPS publishing through MediaMTX, authenticated replay, resource accounting and PostIt activation/revocation. Close withdrawn accounts, erase managed files and purge eligible payment residues after one year. Include migrations, documentation and regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-08 07:43:15 +00:00
commit b157dce4e4
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
54 changed files with 12996 additions and 50 deletions

View file

@ -15,6 +15,31 @@ namespace PostIt.Tests;
public class AdministrationToolsTests
{
[Fact]
public async Task Payment_purge_requires_confirmation_reports_counts_and_clears_on_logout()
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
await session.RefreshAsync();
await using var transport = new AdminTransport();
var vm = new AdministrationPageViewModel(null, session: session,
administrationClient: new AdministrationApiClient(transport, () => "https://example.invalid/api/v1"));
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
Assert.Empty(transport.Paths);
vm.ConfirmDestructiveAction = true;
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
Assert.Contains("POST https://example.invalid/api/v1/administration/payment-residues/purge", transport.Paths);
Assert.Contains("2 compte(s)", vm.PaymentPurgeReport);
Assert.False(vm.ConfirmDestructiveAction);
session.Api = null;
session.Refresh();
transport.Paths.Clear();
vm.ConfirmDestructiveAction = true;
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
Assert.Empty(transport.Paths);
Assert.Empty(vm.PaymentPurgeReport);
}
[AvaloniaTheory]
[InlineData(400, 800)]
[InlineData(800, 400)]
@ -207,6 +232,8 @@ public class AdministrationToolsTests
: await PendingSecret.Task;
else if (typeof(T) == typeof(ImportResult))
result = new ImportResult(0, 0, 0);
else if (typeof(T) == typeof(PaymentResiduePurgeResult))
result = new PaymentResiduePurgeResult(2, 3, 4, 1, 1);
else
throw new NotSupportedException(typeof(T).Name);
return JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(result))!;

View file

@ -9,6 +9,78 @@ namespace PostIt.Tests;
public sealed class PodcastScheduleTests
{
[AvaloniaFact]
public async Task Late_obs_credentials_are_not_displayed_after_selection_changes_or_navigation()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-obs-late-{Guid.NewGuid():N}.json");
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("test-access", "test-refresh", DateTimeOffset.UtcNow.AddHours(1), null));
try
{
await using var api = new ScheduleApi(store, path + ".settings");
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session);
await vm.ActivateAsync();
vm.SelectedPodcast = api.Plan;
api.PendingActivation = new(TaskCreationOptions.RunContinuationsAsynchronously);
var activation = vm.ActivateObsCommand.ExecuteAsync(null);
vm.SelectedPodcast = api.Plan with { Id = Guid.NewGuid() };
vm.SelectedPodcast = api.Plan;
api.PendingActivation.SetResult(new("rtmps://obs.example:1936", "secret", DateTimeOffset.UtcNow.AddMinutes(30)));
await activation;
Assert.Empty(vm.ObsStreamKey);
api.PendingActivation = new(TaskCreationOptions.RunContinuationsAsynchronously);
activation = vm.ActivateObsCommand.ExecuteAsync(null);
await vm.DeactivateAsync();
api.PendingActivation.SetResult(new("rtmps://obs.example:1936", "secret", DateTimeOffset.UtcNow.AddMinutes(30)));
await activation;
Assert.Empty(vm.ObsStreamKey);
}
finally { File.Delete(path); File.Delete(path + ".settings"); }
}
[AvaloniaFact]
public async Task Obs_activation_is_owned_displays_credentials_and_clears_them_on_navigation_and_revocation()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-obs-{Guid.NewGuid():N}.json");
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("test-access", "test-refresh", DateTimeOffset.UtcNow.AddHours(1), null));
try
{
await using var api = new ScheduleApi(store, path + ".settings");
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session);
await vm.ActivateAsync();
vm.SelectedPodcast = api.Plan;
Assert.True(vm.ActivateObsCommand.CanExecute(null));
await vm.ActivateObsCommand.ExecuteAsync(null);
Assert.Equal("rtmps://obs.example:1936", vm.ObsServerUrl);
Assert.Equal("obs/stream-secret", vm.ObsStreamKey);
Assert.False(vm.IsBroadcasting);
api.Settings.Save();
Assert.DoesNotContain("stream-secret", await File.ReadAllTextAsync(path + ".settings"));
vm.SelectedPodcast = api.Plan with { Id = Guid.NewGuid(), OwnerId = "other" };
Assert.Empty(vm.ObsStreamKey);
Assert.False(vm.ActivateObsCommand.CanExecute(null));
vm.SelectedPodcast = api.Plan;
await vm.ActivateObsCommand.ExecuteAsync(null);
await vm.DeactivateAsync();
Assert.Empty(vm.ObsStreamKey);
Assert.True(api.ObsEnabled);
await vm.ActivateAsync();
vm.SelectedPodcast = api.Plan;
await vm.ActivateObsCommand.ExecuteAsync(null);
await vm.DeactivateObsCommand.ExecuteAsync(null);
Assert.False(api.ObsEnabled);
Assert.Empty(vm.ObsStreamKey);
Assert.EndsWith("/obs", api.RevokedPath);
await vm.DeactivateAsync();
}
finally { File.Delete(path); File.Delete(path + ".settings"); }
}
[AvaloniaFact]
public async Task Preparation_and_editing_send_schedule_and_optional_announcement_without_capture()
{
@ -62,18 +134,33 @@ public sealed class PodcastScheduleTests
finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); }
}
private sealed class ScheduleApi(TokenStore store, string settingsPath) : YavscApiClient(new Settings(settingsPath), store)
private sealed class ScheduleApi(TokenStore store, string settingsPath)
: YavscApiClient(new Settings(settingsPath), store), IYavscApiClient
{
public PodcastResponse Plan { get; private set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner",
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0);
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0) { FlowId = 1 };
public bool ObsEnabled { get; private set; }
public string? RevokedPath { get; private set; }
public PreparePodcastRequest? Saved { get; set; }
public string? SavedPath { get; private set; }
public HttpMethod? SavedMethod { get; private set; }
public TaskCompletionSource<PodcastObsCredentials>? PendingActivation { get; set; }
public override Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
public override async Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
object response;
if (path.EndsWith("/account/me", StringComparison.Ordinal)) response = new Me { UserId = "owner" };
else if (path.EndsWith("/obs", StringComparison.Ordinal))
{
if (method == HttpMethod.Post)
{
ObsEnabled = true;
response = PendingActivation is null
? new PodcastObsCredentials("rtmps://obs.example:1936", "obs/stream-secret", DateTimeOffset.UtcNow.AddMinutes(30))
: await PendingActivation.Task;
}
else response = new PodcastObsStatus(ObsEnabled, DateTimeOffset.UtcNow.AddMinutes(30), null);
}
else if (method == HttpMethod.Get) response = new List<PodcastResponse> { Plan };
else
{
@ -87,7 +174,16 @@ public sealed class PodcastScheduleTests
};
response = Plan;
}
return Task.FromResult((T)response);
return (T)response;
}
Task IYavscApiClient.CallAsync(HttpMethod method, string path, object? body, CancellationToken ct)
{
Assert.Equal(HttpMethod.Delete, method);
Assert.EndsWith("/obs", path);
ObsEnabled = false;
RevokedPath = path;
return Task.CompletedTask;
}
}
}

View file

@ -113,6 +113,17 @@ public partial class AdministrationPageViewModel
throw new InvalidOperationException("Cochez la confirmation avant cette opération destructive.");
}
[RelayCommand]
private Task PurgePaymentResiduesAsync() => RunOperationAsync(async client =>
{
RequireConfirmation();
var result = await client.PurgePaymentResiduesAsync();
RequireAccess();
PaymentPurgeReport = $"{result.Users} compte(s), {result.Subscriptions} abonnement(s), {result.Payments} mensualité(s), {result.Donations} don(s), {result.LegacyPayments} paiement(s) historique(s) purgés.";
});
[ObservableProperty] public partial string PaymentPurgeReport { get; set; } = "";
partial void OnSelectedClientChanged(AdministrationClient? value)
{
ClientFields = AdministrationFieldViewModel.From(value?.Settings ?? new ClientSettings());

View file

@ -156,6 +156,7 @@ public partial class AdministrationPageViewModel : ViewModelBase
private void ClearAdministrationData()
{
PaymentPurgeReport = "";
Users.Clear();
UsageOverview.Clear();
SelectedUser = null;

View file

@ -35,6 +35,11 @@ public partial class PodcastsPageViewModel : ViewModelBase
private Control? _capturePreview;
private bool _restoringPreferences;
private bool _keepScreenOnDuringCapture;
private Guid? _obsPodcastId;
private int _obsVersion;
[ObservableProperty] public partial string ObsServerUrl { get; set; } = "";
[ObservableProperty] public partial string ObsStreamKey { get; set; } = "";
[ObservableProperty] public partial string ObsStatus { get; set; } = "";
private IDisposable? _screenAwake;
public bool SupportsCaptureScreenAwake => OperatingSystem.IsAndroid();
public bool KeepScreenOnDuringCapture
@ -165,6 +170,7 @@ public partial class PodcastsPageViewModel : ViewModelBase
set
{
if (!SetProperty(ref _selected, value)) return;
if (_obsPodcastId != value?.Id) ClearObsCredentials();
if (value is { State: PodcastState.Planned } && value.OwnerId == _ownerId)
{
_title = value.Title;
@ -192,6 +198,8 @@ public partial class PodcastsPageViewModel : ViewModelBase
public IAsyncRelayCommand FinishCommand { get; }
public IAsyncRelayCommand DeleteCommand { get; }
public IAsyncRelayCommand RetryReplayCommand { get; }
public IAsyncRelayCommand ActivateObsCommand { get; }
public IAsyncRelayCommand DeactivateObsCommand { get; }
public override bool CanNavigateNext { get => false; protected set { } }
public override bool CanNavigatePrevious { get => !IsBroadcasting; protected set { } }
@ -201,6 +209,12 @@ public partial class PodcastsPageViewModel : ViewModelBase
_api = api;
_session = session;
RefreshCommand = new AsyncRelayCommand(RefreshAsync, () => !IsBusy);
ActivateObsCommand = new AsyncRelayCommand(ActivateObsAsync,
() => !IsBusy && !IsCapturing && _session.IsLoggedIn
&& SelectedPodcast is { State: PodcastState.Planned } p && p.OwnerId == _ownerId);
DeactivateObsCommand = new AsyncRelayCommand(DeactivateObsAsync,
() => !IsBusy && !IsBroadcasting && _session.IsLoggedIn
&& SelectedPodcast is { FlowId: not null } p && p.OwnerId == _ownerId);
DetectDevicesCommand = new RelayCommand(DetectDevices, () => CanBroadcast && !IsCapturing && !IsBusy);
PreviewCommand = new AsyncRelayCommand(StartPreviewAsync,
() => CanBroadcast && !IsCapturing && !IsBusy && _session.IsLoggedIn && SelectedCamera is not null);
@ -273,6 +287,8 @@ public partial class PodcastsPageViewModel : ViewModelBase
FinishCommand.NotifyCanExecuteChanged();
DeleteCommand.NotifyCanExecuteChanged();
RetryReplayCommand.NotifyCanExecuteChanged();
ActivateObsCommand.NotifyCanExecuteChanged();
DeactivateObsCommand.NotifyCanExecuteChanged();
OnPropertyChanged(nameof(CanNavigatePrevious));
}
@ -282,10 +298,18 @@ public partial class PodcastsPageViewModel : ViewModelBase
try
{
var profileUrl = new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/"), "account/me");
_ownerId = (await _api.CallAsync<Me>(HttpMethod.Get, profileUrl.AbsoluteUri)).UserId;
var ownerId = (await _api.CallAsync<Me>(HttpMethod.Get, profileUrl.AbsoluteUri)).UserId;
if (_ownerId != ownerId) ClearObsCredentials();
_ownerId = ownerId;
var podcasts = await _client.ListAsync();
Podcasts.Clear();
foreach (var podcast in podcasts) Podcasts.Add(podcast);
if (SelectedPodcast is { FlowId: not null } selected && selected.OwnerId == _ownerId)
{
var obs = await _client.ObsStatusAsync(selected.Id);
ObsStatus = obs.Error ?? (obs.Enabled ? "Entree OBS activee. Le direct commence a la connexion du diffuseur." : "Entree OBS desactivee.");
if (!obs.Enabled) ClearObsCredentials(clearStatus: false);
}
Status = "Directs et replays reserves aux utilisateurs connectes.";
}
catch (Exception ex) { Status = $"Chargement impossible : {ex.Message}"; }
@ -322,6 +346,8 @@ public partial class PodcastsPageViewModel : ViewModelBase
public async Task ActivateAsync()
{
_session.LogoutCompleted -= ClearObsOnLogout;
_session.LogoutCompleted += ClearObsOnLogout;
_restoringPreferences = true;
try
{
@ -343,11 +369,69 @@ public partial class PodcastsPageViewModel : ViewModelBase
public async Task DeactivateAsync()
{
_session.LogoutCompleted -= ClearObsOnLogout;
ClearObsCredentials();
_pageCancellation.Cancel();
await StopPreviewAsync();
if (_broadcaster is not null) await StopAsync();
}
private void ClearObsOnLogout()
{
ClearObsCredentials();
_ownerId = null;
SelectedPodcast = null;
UpdateCommands();
}
private void ClearObsCredentials(bool clearStatus = true)
{
ObsServerUrl = "";
ObsStreamKey = "";
_obsPodcastId = null;
_obsVersion++;
if (clearStatus) ObsStatus = "";
}
private async Task ActivateObsAsync()
{
IsBusy = true;
try
{
var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez une emission programmee.");
var owner = _ownerId;
ClearObsCredentials();
var version = _obsVersion;
var token = _pageCancellation.Token;
var credentials = await _client.ActivateObsAsync(podcast.Id, token);
token.ThrowIfCancellationRequested();
if (_obsVersion != version || !_session.IsLoggedIn || _ownerId != owner || SelectedPodcast?.Id != podcast.Id)
throw new InvalidOperationException("La session ou l'emission a change ; les identifiants OBS ne seront pas affiches.");
_obsPodcastId = podcast.Id;
ObsServerUrl = credentials.ServerUrl;
ObsStreamKey = credentials.StreamKey;
ObsStatus = $"Connectez OBS avant {credentials.ExpiresAt.ToLocalTime():g}. Cette cle remplace toute cle precedente.";
}
catch (Exception ex) { Status = $"Activation OBS impossible : {ex.Message}"; }
finally { IsBusy = false; }
}
private async Task DeactivateObsAsync()
{
IsBusy = true;
try
{
var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez une emission.");
await _client.DeactivateObsAsync(podcast.Id);
ClearObsCredentials();
ObsStatus = "Cle revoquee et diffuseur deconnecte. Le replay est finalise apres l'arret de la reception.";
await RefreshAsync();
}
catch (Exception ex) { Status = $"Desactivation OBS impossible : {ex.Message}"; }
finally { IsBusy = false; }
}
private void DetectDevices()
{
_restoringPreferences = true;

View file

@ -77,6 +77,9 @@
TextWrapping="Wrap"/>
<CheckBox Content="Je confirme la prochaine suppression, exclusion, régénération ou import."
IsChecked="{Binding ConfirmDestructiveAction, Mode=TwoWay}"/>
<Button Content="Purger les paiements résiduels des comptes retirés depuis un an"
Command="{Binding PurgePaymentResiduesCommand}" IsEnabled="{Binding !IsBusy}"/>
<TextBlock Text="{Binding PaymentPurgeReport}" TextWrapping="Wrap"/>
</StackPanel>
<TabControl Grid.Row="2" IsEnabled="{Binding !IsBusy}">

View file

@ -97,6 +97,22 @@
</WrapPanel>
</StackPanel>
<Button Content="Arreter et publier le replay" Command="{Binding StopCommand}" />
<StackPanel Spacing="8">
<TextBlock Text="Diffuser l'emission programmee avec OBS Studio" FontWeight="SemiBold" />
<TextBlock Text="Selectionnez votre emission puis activez OBS. Dans OBS : service Personnalise, video H.264, audio AAC, images cles toutes les 2 secondes. Le direct commence lorsque OBS se connecte, pas a l'heure prevue."
TextWrapping="Wrap" />
<WrapPanel>
<Button Content="Activer OBS / renouveler la cle" Command="{Binding ActivateObsCommand}" Margin="0,0,8,8" />
<Button Content="Revoquer OBS et arreter le diffuseur" Command="{Binding DeactivateObsCommand}" />
</WrapPanel>
<TextBlock Text="Serveur OBS" />
<TextBox Text="{Binding ObsServerUrl, Mode=OneWay}" IsReadOnly="True" />
<TextBlock Text="Cle de stream (secrete : ne pas partager)" />
<TextBox Text="{Binding ObsStreamKey, Mode=OneWay}" IsReadOnly="True" />
<TextBlock Text="{Binding ObsStatus}" TextWrapping="Wrap" />
<TextBlock Text="Les identifiants ne sont pas sauvegardes dans PostIt. Quitter la page masque la cle, mais n'arrete pas OBS : utilisez la revocation ou arretez OBS."
TextWrapping="Wrap" />
</StackPanel>
<CheckBox Content="Garder l'ecran allume pendant l'apercu camera et le direct"
IsVisible="{Binding SupportsCaptureScreenAwake}"
IsChecked="{Binding KeepScreenOnDuringCapture, Mode=TwoWay}" />