From de08edaaf968f0fef8e757968e66461152a7fdef Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Mon, 16 Nov 2026 16:07:14 +0000 Subject: [PATCH] =?UTF-8?q?PostIt:=20options=20et=20contr=C3=B4les=20du=20?= =?UTF-8?q?raffinage=20du=20replay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ajoute à la page podcasts le choix du raffinage et de la conservation des originaux (émission préparée et direct immédiat), l'état du brouillon et l'échéance pour l'auteur, la publication du brouillon tel quel et la suppression confirmée des originaux après publication. La lecture choisit le MP4 publié, sinon les originaux pour l'auteur, et informe les autres utilisateurs que le replay est en cours de finalisation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 + doc/video-edition.md | 12 +- .../PostIt.Tests/PodcastScheduleTests.cs | 124 +++++++++++++++++- .../PostIt/Services/PodcastBroadcaster.cs | 13 +- src/PostIt/PostIt/Services/PodcastPlayback.cs | 29 ++++ .../ViewModels/PodcastsPageViewModel.cs | 100 +++++++++++++- .../PostIt/Views/Video/PodcastsPage.axaml | 18 +++ .../PostIt/Views/Video/VideoPage.axaml.cs | 15 +-- 8 files changed, 293 insertions(+), 20 deletions(-) create mode 100644 src/PostIt/PostIt/Services/PodcastPlayback.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index d559bf251..66596b7ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ ### Added +* [PostIt/Podcasts] Add the refined replay options and owner controls to the podcasts page: opt into refinement and choose the originals retention (0–365 days) for planned and immediate lives, see the draft state and originals deadline, publish the draft unchanged, and delete the originals after publication with confirmation. Playback now prefers the published MP4, lets the owner play unpublished originals, and tells other viewers the replay is being finalized instead of failing. + * [Yavsc.Api.Client/Podcasts] Add the refined replay client: create a live with `RefineReplay` and `RetentionDays`, save and publish drafts, delete published originals, and read the owner-only draft source by bounded, verified byte ranges. `PodcastReplayMediaInput` can stream the draft source for the upcoming PostIt editor. * [Yavsc.Server/Podcasts] Apply the retention of refined replays: `RetentionDays` (0–365, default 7; migration `PodcastReplayRetention` adds `LiveFlow.RetentionDays`) sets `OriginalsExpireAt` from the end of the live, or from publication with 0 days. The replay worker then deletes the segments, source and draft of published emissions (`OriginalsDeleted`, the MP4 stays playable but no longer re-editable) and deletes emissions never published by the deadline, marking their flow deleted. The owner can purge published originals early with `DELETE podcasts/{id}/originals`. The web catalogue keeps showing the published MP4 after the purge. diff --git a/doc/video-edition.md b/doc/video-edition.md index 8392c5bd0..924ce9c5c 100644 --- a/doc/video-edition.md +++ b/doc/video-edition.md @@ -277,8 +277,16 @@ Le brouillon privé est implémenté côté serveur ; l'éditeur PostIt reste à authentifiée par plages de 256 Kio au plus de la source du brouillon, avec les mêmes contrôles que le MP4 publié. `PodcastReplayMediaInput` lit cette source avec `draftSource: true` pour l'éditeur. -- **Reste à faire** : chapitres, interface et éditeur PostIt (réglage de - conservation, échéance affichée, proposition de suppression après publication). +- **Interface PostIt** : la page podcasts propose « Raffiner le replay avant + publication » et la durée de conservation (0 à 365 jours) pour une émission + préparée comme pour un direct immédiat. Pour l'auteur, elle affiche l'état du + brouillon, l'échéance des originaux (avec l'avertissement de suppression d'une + émission jamais publiée), puis permet de publier le brouillon tel quel et, + après publication et confirmation, de supprimer les originaux. La lecture + choisit le MP4 publié dès qu'il existe ; sinon l'auteur lit les originaux et + les autres utilisateurs voient « Le replay est en cours de finalisation par + son auteur. ». +- **Reste à faire** : chapitres et éditeur PostIt des marques et plages. Une émission interrompue doit rester récupérable par son auteur. Lorsqu'un direct programmé s'arrête après le délai « Direct interrompu », ou qu'un diff --git a/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs b/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs index 177b74567..1830bbf26 100644 --- a/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs +++ b/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs @@ -143,10 +143,120 @@ public sealed class PodcastScheduleTests(AvaloniaUiFixture ui) finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); } }, TestContext.Current.CancellationToken); + [Fact] + public Task Refinement_options_are_sent_with_the_plan_and_reloaded_on_selection() + => ui.RunAsync(async () => + { + var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-refine-{Guid.NewGuid():N}.json"); + var store = new TokenStore(tokenPath); + store.Save(new RefreshTokenRecord("test-access-token", "test-refresh-token", DateTimeOffset.UtcNow.AddHours(1), null)); + try + { + await using var api = new ScheduleApi(store, tokenPath + ".settings"); + var session = new SessionStatusViewModel { Api = api }; + session.Refresh(); + var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session) + { + Title = "Concert", RefineReplay = true, RetentionDays = 30 + }; + await vm.PrepareCommand.ExecuteAsync(null); + Assert.True(api.Saved?.RefineReplay); + Assert.Equal(30, api.Saved?.RetentionDays); + vm.RefineReplay = false; + vm.RetentionDays = 0; + vm.SelectedPodcast = null; + vm.SelectedPodcast = api.Plan; + Assert.True(vm.RefineReplay); + Assert.Equal(30, vm.RetentionDays); + vm.RetentionDays = 366; + api.Saved = null; + await vm.UpdatePlanCommand.ExecuteAsync(null); + Assert.Null(api.Saved); + Assert.Contains("conservation des originaux", vm.Status); + } + finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); } + }, TestContext.Current.CancellationToken); + + [Fact] + public Task Owner_publishes_an_unchanged_draft_then_deletes_the_originals() + => ui.RunAsync(async () => + { + var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-draft-{Guid.NewGuid():N}.json"); + var store = new TokenStore(tokenPath); + store.Save(new RefreshTokenRecord("test-access-token", "test-refresh-token", DateTimeOffset.UtcNow.AddHours(1), null)); + try + { + await using var api = new ScheduleApi(store, tokenPath + ".settings"); + api.Plan = api.Plan with + { + State = PodcastState.Completed, SegmentCount = 3, RefineReplay = true, FlowId = null, + Replay = new(PodcastReplayState.Pending), Draft = new(PodcastDraftState.Ready, 2, [], []), + OriginalsExpireAt = DateTimeOffset.UtcNow.AddDays(7) + }; + 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.Contains("non publie", vm.DraftSummary); + Assert.Contains("sera supprimee", vm.DraftSummary); + Assert.False(vm.DeleteOriginalsCommand.CanExecute(null)); + await vm.PublishDraftCommand.ExecuteAsync(null); + var publish = Assert.Single(api.DraftCalls); + Assert.Equal(2, Assert.IsType(publish.Body).Revision); + Assert.Equal(PodcastDraftState.Publishing, vm.SelectedPodcast?.Draft?.State); + Assert.False(vm.PublishDraftCommand.CanExecute(null)); + + api.Plan = api.Plan with + { + Replay = new(PodcastReplayState.Ready, 100), + Draft = api.Plan.Draft! with { State = PodcastDraftState.Ready, PublishedRevision = 2 } + }; + await vm.RefreshCommand.ExecuteAsync(null); + vm.SelectedPodcast = api.Plan; + Assert.Contains("Revision 2 publiee", vm.DraftSummary); + Assert.False(vm.PublishDraftCommand.CanExecute(null)); + await vm.DeleteOriginalsCommand.ExecuteAsync(null); + Assert.Equal(HttpMethod.Delete, api.DraftCalls[^1].Method); + Assert.EndsWith($"/podcasts/{api.Plan.Id}/originals", api.DraftCalls[^1].Path); + Assert.True(vm.SelectedPodcast?.OriginalsDeleted); + Assert.Contains("Originaux supprimes", vm.DraftSummary); + Assert.False(vm.DeleteOriginalsCommand.CanExecute(null)); + Assert.Equal(PodcastPlaybackSource.PublishedReplay, PodcastPlayback.Choose(vm.SelectedPodcast!).Source); + + vm.SelectedPodcast = api.Plan with { OwnerId = "other" }; + Assert.Empty(vm.DraftSummary); + await vm.DeactivateAsync(); + } + finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); } + }, TestContext.Current.CancellationToken); + + [Theory] + [InlineData(PodcastState.Live, true, false, false, PodcastPlaybackSource.Originals)] + [InlineData(PodcastState.Completed, false, false, false, PodcastPlaybackSource.Pending)] + [InlineData(PodcastState.Completed, false, false, true, PodcastPlaybackSource.PublishedReplay)] + [InlineData(PodcastState.Completed, true, true, false, PodcastPlaybackSource.Originals)] + [InlineData(PodcastState.Completed, true, false, false, PodcastPlaybackSource.Unavailable)] + [InlineData(PodcastState.Interrupted, true, false, false, PodcastPlaybackSource.Unavailable)] + [InlineData(PodcastState.Interrupted, true, false, true, PodcastPlaybackSource.PublishedReplay)] + [InlineData(PodcastState.Interrupted, false, false, false, PodcastPlaybackSource.Originals)] + public void Playback_hides_unpublished_refined_originals_from_other_viewers( + PodcastState state, bool refine, bool owner, bool published, PodcastPlaybackSource expected) + { + var podcast = new PodcastResponse(Guid.NewGuid(), "Concert", "owner", "Owner", + DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, state, 3, 300, 6) + { + RefineReplay = refine, + Draft = owner ? new(PodcastDraftState.Ready, 0, [], []) : null, + Replay = published ? new(PodcastReplayState.Ready, 100) : new(PodcastReplayState.Pending) + }; + Assert.Equal(expected, PodcastPlayback.Choose(podcast).Source); + } + 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", + public PodcastResponse Plan { get; set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner", DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0) { FlowId = 1 }; public bool ObsEnabled { get; private set; } public string? RevokedPath { get; private set; } @@ -154,6 +264,7 @@ public sealed class PodcastScheduleTests(AvaloniaUiFixture ui) public string? SavedPath { get; private set; } public HttpMethod? SavedMethod { get; private set; } public TaskCompletionSource? PendingActivation { get; set; } + public List<(HttpMethod Method, string Path, object? Body)> DraftCalls { get; } = []; public override async Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) { @@ -170,6 +281,14 @@ public sealed class PodcastScheduleTests(AvaloniaUiFixture ui) } else response = new PodcastObsStatus(ObsEnabled, DateTimeOffset.UtcNow.AddMinutes(30), null); } + else if (path.EndsWith("/draft/publish", StringComparison.Ordinal) || path.EndsWith("/originals", StringComparison.Ordinal)) + { + DraftCalls.Add((method, path, body)); + Plan = method == HttpMethod.Delete + ? Plan with { OriginalsDeleted = true, OriginalsExpireAt = null, Draft = null } + : Plan with { Draft = Plan.Draft! with { State = PodcastDraftState.Publishing } }; + response = Plan; + } else if (method == HttpMethod.Get) response = new List { Plan }; else { @@ -179,7 +298,8 @@ public sealed class PodcastScheduleTests(AvaloniaUiFixture ui) Plan = Plan with { Title = Saved.Title, ScheduledStartAt = Saved.ScheduledStartAt, - PlannedDurationMinutes = Saved.PlannedDurationMinutes, PublicAnnouncement = Saved.PublicAnnouncement + PlannedDurationMinutes = Saved.PlannedDurationMinutes, PublicAnnouncement = Saved.PublicAnnouncement, + RefineReplay = Saved.RefineReplay, RetentionDays = Saved.RetentionDays }; response = Plan; } diff --git a/src/PostIt/PostIt/Services/PodcastBroadcaster.cs b/src/PostIt/PostIt/Services/PodcastBroadcaster.cs index 2094abc99..0b8bb69dc 100644 --- a/src/PostIt/PostIt/Services/PodcastBroadcaster.cs +++ b/src/PostIt/PostIt/Services/PodcastBroadcaster.cs @@ -51,9 +51,9 @@ public sealed class PodcastBroadcaster : IAsyncDisposable media.AddOption(":sout=#" + (preview ? $"duplicate{{dst=display{{noaudio}},dst=\"{destination}\"}}" : encoding)); } - public static async Task StartAsync(PodcastApiClient api, string title, + public static async Task StartAsync(PodcastApiClient api, CreatePodcastRequest request, string camera, string? microphone, CancellationToken ct, Guid? plannedId = null) - => await StartAsync(api, title, + => await StartAsync(api, request, (directory, _) => Task.FromResult(new LibVlcPodcastCapture( vlc => new CameraStreamer(vlc).CreateCaptureMedia(camera, microphone), directory, preview: true)), ct, plannedId); @@ -62,7 +62,12 @@ public sealed class PodcastBroadcaster : IAsyncDisposable => await StartAsync(api, title, (directory, _) => Task.FromResult(new LibVlcPodcastCapture(createMedia, directory)), ct); - public static async Task StartAsync(PodcastApiClient api, string title, + public static Task StartAsync(PodcastApiClient api, string title, + Func> createCapture, CancellationToken ct, Guid? plannedId = null) + => StartAsync(api, new CreatePodcastRequest { Title = title }, createCapture, ct, plannedId); + + /// Starts a planned emission, or creates an immediate live with the options of . + public static async Task StartAsync(PodcastApiClient api, CreatePodcastRequest request, Func> createCapture, CancellationToken ct, Guid? plannedId = null) { IPodcastCapture? capture = null; @@ -73,7 +78,7 @@ public sealed class PodcastBroadcaster : IAsyncDisposable try { Directory.CreateDirectory(directory); - podcast = plannedId.HasValue ? await api.StartAsync(plannedId.Value, ct) : await api.CreateAsync(title, ct); + podcast = plannedId.HasValue ? await api.StartAsync(plannedId.Value, ct) : await api.CreateAsync(request, ct); if (podcast.State != PodcastState.Live) throw new InvalidOperationException("Cette emission est deja terminee. Preparez une nouvelle emission."); await File.WriteAllTextAsync(Path.Combine(directory, "podcast.json"), JsonSerializer.Serialize(podcast), ct); diff --git a/src/PostIt/PostIt/Services/PodcastPlayback.cs b/src/PostIt/PostIt/Services/PodcastPlayback.cs new file mode 100644 index 000000000..c0db04a04 --- /dev/null +++ b/src/PostIt/PostIt/Services/PodcastPlayback.cs @@ -0,0 +1,29 @@ +using Yavsc.Abstract.Streaming; + +namespace PostIt.Services; + +public enum PodcastPlaybackSource { Originals, PublishedReplay, Pending, Unavailable } + +public readonly record struct PodcastPlaybackChoice(PodcastPlaybackSource Source, string? Message = null); + +/// Chooses what a viewer can play: the published MP4, the HLS originals, or nothing yet. +public static class PodcastPlayback +{ + public static PodcastPlaybackChoice Choose(PodcastResponse podcast) + { + if (podcast.State != PodcastState.Live && podcast.Replay is { State: PodcastReplayState.Ready, Bytes: > 0 }) + return new(PodcastPlaybackSource.PublishedReplay); + if (podcast.OriginalsDeleted) + return new(PodcastPlaybackSource.Unavailable, "Les originaux de cette emission ont ete supprimes."); + if (podcast.RefineReplay && podcast.State != PodcastState.Live) + // Only the owner receives the draft; other viewers wait for the publication. + return podcast.Draft is null + ? new(PodcastPlaybackSource.Unavailable, "Le replay est en cours de finalisation par son auteur.") + : new(PodcastPlaybackSource.Originals); + if (podcast.State == PodcastState.Completed) + return podcast.Replay is { State: PodcastReplayState.Failed } failed + ? new(PodcastPlaybackSource.Unavailable, failed.Error ?? "Preparation du MP4 en echec.") + : new(PodcastPlaybackSource.Pending, "Preparation du replay MP4..."); + return new(PodcastPlaybackSource.Originals); + } +} diff --git a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs index 2c409f660..4a72fb6f8 100644 --- a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; @@ -131,6 +132,39 @@ public partial class PodcastsPageViewModel : ViewModelBase public partial bool PublishAnnouncement { get; set; } [ObservableProperty] public partial string Announcement { get; set; } = ""; + /// Keeps the replay private until the owner refines and publishes it. + [ObservableProperty] + public partial bool RefineReplay { get; set; } + [ObservableProperty] + public partial decimal RetentionDays { get; set; } = PodcastRetention.DefaultDays; + public int MaxRetentionDays => PodcastRetention.MaxDays; + + public bool HasDraftSummary => DraftSummary.Length > 0; + /// Owner-only state of the refined replay of the selected emission. + public string DraftSummary + { + get + { + if (SelectedPodcast is not { RefineReplay: true } p || p.OwnerId != _ownerId || p.State is PodcastState.Planned or PodcastState.Live) + return ""; + var lines = new List(); + lines.Add(p.Draft switch + { + null => "Brouillon : non disponible.", + { State: PodcastDraftState.Preparing } => "Brouillon : preparation de la source en cours.", + { State: PodcastDraftState.Failed } d => $"Brouillon en echec : {d.Error}", + { State: PodcastDraftState.Publishing } d => $"Publication de la revision {d.Revision} en cours.", + { PublishedRevision: { } published } d when published == d.Revision => $"Revision {d.Revision} publiee.", + var d => $"Brouillon pret (revision {d.Revision}, {d.RemovedRanges.Count} plage(s) supprimee(s)), non publie." + }); + if (p.OriginalsDeleted) lines.Add("Originaux supprimes : seul le MP4 publie reste disponible."); + else if (p.OriginalsExpireAt is { } expiry) + lines.Add($"Originaux conserves jusqu'au {expiry.ToLocalTime():g}" + + (p.Replay?.State == PodcastReplayState.Ready ? "." : " ; sans publication d'ici la, l'emission sera supprimee.")); + else if (p.RetentionDays == 0) lines.Add("Originaux supprimes des la publication."); + return string.Join(Environment.NewLine, lines); + } + } public string Status { get => _status; private set => SetProperty(ref _status, value); } public bool IsBroadcasting @@ -203,7 +237,11 @@ public partial class PodcastsPageViewModel : ViewModelBase PlannedDurationMinutes = value.PlannedDurationMinutes ?? 60; Announcement = value.PublicAnnouncement ?? ""; PublishAnnouncement = !string.IsNullOrEmpty(Announcement); + RefineReplay = value.RefineReplay; + RetentionDays = value.RetentionDays; } + OnPropertyChanged(nameof(DraftSummary)); + OnPropertyChanged(nameof(HasDraftSummary)); UpdateCommands(); } } @@ -221,6 +259,8 @@ public partial class PodcastsPageViewModel : ViewModelBase public IAsyncRelayCommand FinishCommand { get; } public IAsyncRelayCommand DeleteCommand { get; } public IAsyncRelayCommand RetryReplayCommand { get; } + public IAsyncRelayCommand PublishDraftCommand { get; } + public IAsyncRelayCommand DeleteOriginalsCommand { get; } public IAsyncRelayCommand ActivateObsCommand { get; } public IAsyncRelayCommand DeactivateObsCommand { get; } public override bool CanNavigateNext { get => false; protected set { } } @@ -266,6 +306,12 @@ public partial class PodcastsPageViewModel : ViewModelBase RetryReplayCommand = new AsyncRelayCommand(RetryReplayAsync, () => SelectedPodcast is { State: PodcastState.Completed, Replay.State: PodcastReplayState.Failed } p && p.OwnerId == _ownerId && !IsBroadcasting && !IsBusy); + PublishDraftCommand = new AsyncRelayCommand(PublishDraftAsync, + () => SelectedPodcast is { RefineReplay: true, Draft: { State: PodcastDraftState.Ready } d } p + && d.PublishedRevision != d.Revision && p.OwnerId == _ownerId && !IsBroadcasting && !IsBusy); + DeleteOriginalsCommand = new AsyncRelayCommand(DeleteOriginalsAsync, + () => SelectedPodcast is { RefineReplay: true, OriginalsDeleted: false, Replay.State: PodcastReplayState.Ready } p + && p.OwnerId == _ownerId && !IsBroadcasting && !IsBusy); _title = _api.Settings.PodcastDefaultTitle; _keepScreenOnDuringCapture = _api.Settings.PodcastKeepScreenOn; _blurPodcastBackground = _api.Settings.PodcastBlurBackground; @@ -311,6 +357,8 @@ public partial class PodcastsPageViewModel : ViewModelBase FinishCommand.NotifyCanExecuteChanged(); DeleteCommand.NotifyCanExecuteChanged(); RetryReplayCommand.NotifyCanExecuteChanged(); + PublishDraftCommand.NotifyCanExecuteChanged(); + DeleteOriginalsCommand.NotifyCanExecuteChanged(); ActivateObsCommand.NotifyCanExecuteChanged(); DeactivateObsCommand.NotifyCanExecuteChanged(); OnPropertyChanged(nameof(CanNavigatePrevious)); @@ -348,6 +396,7 @@ public partial class PodcastsPageViewModel : ViewModelBase if (ScheduledDate == null || ScheduledTime == null || PlannedDurationMinutes != decimal.Truncate(PlannedDurationMinutes) || PlannedDurationMinutes is < 1 or > int.MaxValue) throw new InvalidOperationException("Choisissez un debut et une duree entiere positive en minutes."); + var retentionDays = ValidRetentionDays(); if (PublishAnnouncement && string.IsNullOrWhiteSpace(Announcement)) throw new InvalidOperationException("Saisissez le texte de l'annonce publique ou desactivez sa publication."); var local = DateTime.SpecifyKind(ScheduledDate.Value.Date + ScheduledTime.Value, DateTimeKind.Unspecified); @@ -358,7 +407,8 @@ public partial class PodcastsPageViewModel : ViewModelBase { Title = Title, ScheduledStartAt = start, PlannedDurationMinutes = (int)PlannedDurationMinutes, - PublicAnnouncement = PublishAnnouncement ? Announcement : null + PublicAnnouncement = PublishAnnouncement ? Announcement : null, + RefineReplay = RefineReplay, RetentionDays = retentionDays }, update ? SelectedPodcast?.Id : null, _pageCancellation.Token); await RefreshAsync(); SelectedPodcast = plan; @@ -368,6 +418,11 @@ public partial class PodcastsPageViewModel : ViewModelBase finally { IsBusy = false; } } + private int ValidRetentionDays() + => RetentionDays == decimal.Truncate(RetentionDays) && RetentionDays is >= 0 and <= PodcastRetention.MaxDays + ? (int)RetentionDays + : throw new InvalidOperationException($"Choisissez une conservation des originaux entiere, de 0 a {PodcastRetention.MaxDays} jours."); + public async Task ActivateAsync() { _session.LogoutCompleted -= ClearObsOnLogout; @@ -580,6 +635,7 @@ public partial class PodcastsPageViewModel : ViewModelBase _pageCancellation.Token.ThrowIfCancellationRequested(); if (SelectedCamera is null) throw new InvalidOperationException("Choisissez une camera."); var camera = SelectedCamera.Value; + var request = new CreatePodcastRequest { Title = Title, RefineReplay = RefineReplay, RetentionDays = ValidRetentionDays() }; var microphone = string.IsNullOrWhiteSpace(SelectedMicrophone?.Value) ? null : SelectedMicrophone.Value; if (Platform.RequestPodcastPermissionsAsync is { } requestPermissions) await requestPermissions(microphone, _pageCancellation.Token); @@ -588,9 +644,9 @@ public partial class PodcastsPageViewModel : ViewModelBase ?? throw new InvalidOperationException("Le flou d'arriere-plan n'est pas disponible sur cet appareil.") : Platform.CreatePodcastCaptureAsync; _broadcaster = captureFactory is { } createCapture - ? await PodcastBroadcaster.StartAsync(_client, Title, + ? await PodcastBroadcaster.StartAsync(_client, request, (directory, ct) => createCapture(camera, microphone, directory, ct), _pageCancellation.Token, SelectedPodcast?.Id) - : await PodcastBroadcaster.StartAsync(_client, Title, camera, microphone, _pageCancellation.Token, SelectedPodcast?.Id); + : await PodcastBroadcaster.StartAsync(_client, request, camera, microphone, _pageCancellation.Token, SelectedPodcast?.Id); _broadcaster.Progress += OnProgress; CapturePreview = _broadcaster.Preview; _session.LogoutCompleted += OnLogout; @@ -657,6 +713,8 @@ public partial class PodcastsPageViewModel : ViewModelBase try { var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez un podcast."); + if (PodcastPlayback.Choose(podcast) is { Source: PodcastPlaybackSource.Unavailable } unavailable) + throw new InvalidOperationException(unavailable.Message); var app = Application.Current as App ?? throw new InvalidOperationException("Application indisponible."); var manifestUrl = new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/"), $"podcasts/{podcast.Id}/index.m3u8"); var catalogueUrl = new Uri(new Uri(_api.Settings.Authentication.Authority.TrimEnd('/') + "/"), "Podcast"); @@ -707,4 +765,40 @@ public partial class PodcastsPageViewModel : ViewModelBase catch (Exception ex) { Status = $"Relance du MP4 impossible : {ex.Message}"; } finally { IsBusy = false; } } + + private async Task PublishDraftAsync() + { + IsBusy = true; + try + { + var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez un podcast."); + var draft = podcast.Draft ?? throw new InvalidOperationException("Aucun brouillon a publier."); + await _client.PublishDraftAsync(podcast.Id, draft.Revision, _pageCancellation.Token); + await RefreshSelectionAsync(podcast.Id); + Status = "Publication du replay demandee ; le MP4 sera visible une fois prepare."; + } + catch (Exception ex) { Status = $"Publication impossible : {ex.Message}"; } + finally { IsBusy = false; } + } + + private async Task DeleteOriginalsAsync() + { + IsBusy = true; + try + { + var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez un podcast."); + await _client.DeleteOriginalsAsync(podcast.Id, _pageCancellation.Token); + await RefreshSelectionAsync(podcast.Id); + Status = "Originaux et brouillon supprimes ; le MP4 publie reste disponible."; + } + catch (Exception ex) { Status = $"Suppression des originaux impossible : {ex.Message}"; } + finally { IsBusy = false; } + } + + private async Task RefreshSelectionAsync(Guid id) + { + await RefreshAsync(); + IsBusy = true; + SelectedPodcast = Podcasts.FirstOrDefault(p => p.Id == id); + } } diff --git a/src/PostIt/PostIt/Views/Video/PodcastsPage.axaml b/src/PostIt/PostIt/Views/Video/PodcastsPage.axaml index f2e31c580..18a878928 100644 --- a/src/PostIt/PostIt/Views/Video/PodcastsPage.axaml +++ b/src/PostIt/PostIt/Views/Video/PodcastsPage.axaml @@ -62,6 +62,15 @@ IsChecked="{Binding PublishAnnouncement, Mode=TwoWay}" /> + + + + + + @@ -146,6 +155,15 @@