diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ee921d5e..41b544604 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ ### Added +* [PostIt] Remember detected podcast cameras/microphones, selected devices (including no microphone) and the default title in user settings; restore them when reopening the page and report persistence failures. +* [Podcasts] Reuse persisted LiveFlow entities to prepare, edit and delete emissions from PostIt with a title, scheduled start and estimated duration. Keep start/stop manual and plans private; optionally publish presentation-only announcements on Yavsc.Org without opening anonymous playback. Preserve broadcast identifiers, legacy recordings and authenticated HLS/MP4 access; add a scheduling migration and lifecycle/privacy regressions. * [PostIt/API/Yavsc.Org] Expose the private PayPal recipient setting in PostIt's performer editor and authenticated profile API; validate addresses, allow disabling with an empty value and preserve the setting for older clients. Make Web donation settings discoverable from the performer profile and podcast catalogue. * [API] Initialize the required address field when creating a performer profile so a first configuration can be saved. * [Yavsc.Org] Add an authenticated Razor podcast catalogue with same-origin API-backed HLS/MP4 playback and replay byte-range support. Reuse Site.ApiUrl and the authority's signing credentials to issue short-lived user tokens, without a separate OAuth client or PodcastWeb configuration. Distinguish an empty catalogue from API/configuration failures. diff --git a/doc/Architecture.md b/doc/Architecture.md index d8f1406d7..17df96891 100644 --- a/doc/Architecture.md +++ b/doc/Architecture.md @@ -84,6 +84,54 @@ connecté (`sub`, audience `api`, scope `api` attendu par Yavsc.Api). Ce jeton reste côté serveur. Une adresse API manquante renvoie 503 ; une panne de l'API renvoie une erreur explicite, pas un catalogue vide. +### Emissions preparees + +PostIt memorise dans ses parametres utilisateur les cameras et microphones +detectes, leurs identifiants selectionnes et le titre par defaut. La page +les restaure sans redetection automatique ; le bouton de detection actualise +le materiel disponible en conservant les choix encore presents. Le choix +« sans microphone » est memorise lui aussi. Charger le titre d'une emission +preparee ne remplace pas le titre par defaut ; une saisie explicite le modifie. +Les erreurs de sauvegarde sont affichees dans la page. + +PostIt permet de preparer, modifier et supprimer une emission avant son +demarrage : titre, date/heure locale, duree entiere positive en minutes et +annonce publique optionnelle. Les horaires sont previsionnels : la camera, +le demarrage et l'arret restent manuels. Les heures locales inexistantes ou +ambigues au changement d'heure sont refusees. + +La table existante `LiveFlow` conserve la preparation et son proprietaire ; +`PodcastId` (GUID unique) relie cette emission au manifeste media sur disque. +`PodcastResponse` reste un DTO, enrichi de `FlowId`, `ScheduledStartAt`, +`PlannedDurationMinutes` et `PublicAnnouncement`. Un etat `Planned` +precede le direct ; la date previsionnelle n'est jamais confondue avec +`CreatedAt` du direct ni la duree previsionnelle avec les secondes enregistrees. +Les anciens manifestes sans `LiveFlow` restent lisibles ; aucune copie ou +migration de leurs medias n'est requise. Le demarrage immediat historique +reste disponible sans preparation. + +L'API propose `POST /api/v1/podcasts/planned`, +`PUT /api/v1/podcasts/{id}/planned` et `POST /api/v1/podcasts/{id}/start`. +La preparation n'est visible que du proprietaire, meme avec une annonce ; +les nouvelles routes de mutation exigent le scope `api`. Le demarrage +conserve le GUID et les tentatives concurrentes reutilisent le meme direct. +Une emission demarree ne peut plus etre reprogrammee ou redemarree apres +sa fin. Les medias restent geres par `ILiveProcessor`, avec ses quotas, +expiration, reprise et preparation MP4. Une suppression conserve un +marqueur en base pour ne pas ressusciter une emission deja supprimee. +Le verrou de coordination suit le deploiement mono-processus du stockage +media actuel ; un deploiement multi-instance necessiterait un stockage et +une coordination distribues. + +Seul `GET /api/v1/podcasts/announcements` est anonyme : titre, nom d'auteur, +horaire UTC, duree et texte public, sans URL de flux ni metadonnees privees. +`/Podcast/Announcements` affiche ces annonces avec encodage Razor et sans +jeton utilisateur. Retirer le texte public avant le debut retire l'annonce. +Les annonces restent disponibles apres le direct jusqu'a suppression du +podcast. Les pages et toutes les routes de lecture restent authentifiees. +Appliquer la migration `PodcastScheduling` au deploiement, apres celle des +dons ; aucune migration de production n'est appliquee automatiquement ici. + ### Dons PayPal aux performers Les dons sont gérés par Yavsc.Org, pas par un lien de paiement externe diff --git a/doc/testing.md b/doc/testing.md index 7444d3273..5b41ddba3 100644 --- a/doc/testing.md +++ b/doc/testing.md @@ -82,13 +82,16 @@ dotnet test --project src/test/Yavsc.Org.Tests/Yavsc.Org.Tests.csproj \ --filter-class '*PodcastWebTests' --filter-class '*PerformerDonationTests' dotnet test --project src/test/Yavsc.Api.Tests/Yavsc.Api.Tests.csproj \ --filter-class '*LiveProcessorTests' --filter-class '*PodcastControllerTests' \ - --filter-class '*PodcastReplayTests' --filter-class '*PerformerDonationSettingsTests' + --filter-class '*PodcastReplayTests' --filter-class '*PodcastScheduleTests' \ + --filter-class '*PerformerDonationSettingsTests' dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \ --filter-class '*PodcastTests' --filter-class '*PodcastReplayTests' \ --filter-class '*YavscApiClientTests' --filter-class '*PodcastNativeCaptureTests' \ --filter-class '*PerformerDonationSettingsTests' dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \ --filter-method '*Shared_page_exposes_running_capture_preview_and_clears_it_before_disposal' +dotnet test --project src/PostIt/PostIt.Tests/PostIt.Tests.csproj \ + --filter-class '*PodcastScheduleTests' ``` Les tests serveur couvrent HTTP/authentification, proprietaire, sequences, @@ -97,6 +100,12 @@ apres interruption/redemarrage, dans des dossiers temporaires isoles. Les tests de configuration PayPal couvrent la lecture privee, la creation, la validation avant toute sauvegarde, l'effacement, la compatibilite des anciens clients, ainsi que le chargement, la liaison du champ et l'enregistrement PostIt. +Les tests `PodcastScheduleTests` couvrent la preparation persistante dans +`LiveFlow`, la confidentialite, l'annonce/unpublication, les controles +proprietaire, la validation et le demarrage manuel idempotent. +La preparation PostIt et les tests de capture headless ont ete verifies +separement : leur selection groupee peut rester bloquee alors que chaque +test cible reussit isole. Installer FFmpeg 5+ et ffprobe pour ces tests serveur : ils generent une source H.264/AAC synthetique de quatre secondes, verifient le remuxage reel (pistes, duree, faststart, decodage et seek a deux secondes), puis les reponses diff --git a/src/PostIt/PostIt.Tests/PodcastBroadcasterTests.cs b/src/PostIt/PostIt.Tests/PodcastBroadcasterTests.cs index fe766335f..36bf33d4e 100644 --- a/src/PostIt/PostIt.Tests/PodcastBroadcasterTests.cs +++ b/src/PostIt/PostIt.Tests/PodcastBroadcasterTests.cs @@ -22,7 +22,7 @@ public sealed class PodcastBroadcasterTests var factory = Platform.CreatePodcastCaptureAsync; var store = new TokenStore(tokenPath); store.Save(new RefreshTokenRecord("test-access-token", "test-refresh-token", DateTimeOffset.UtcNow.AddHours(1), null)); - await using var api = new YavscApiClient(new Settings(), store); + await using var api = new YavscApiClient(new Settings(tokenPath + ".settings"), store); await using var transport = new Transport(); FakeCapture? capture = null; PodcastsPageViewModel? vm = null; @@ -72,6 +72,7 @@ public sealed class PodcastBroadcasterTests Platform.RequestPodcastPermissionsAsync = permissions; Platform.CreatePodcastCaptureAsync = factory; File.Delete(tokenPath); + File.Delete(tokenPath + ".settings"); } }, TestContext.Current.CancellationToken); @@ -84,7 +85,7 @@ public sealed class PodcastBroadcasterTests var factory = Platform.CreatePodcastCaptureAsync; var store = new TokenStore(tokenPath); store.Save(new RefreshTokenRecord("test-access-token", "test-refresh-token", DateTimeOffset.UtcNow.AddHours(1), null)); - await using var api = new YavscApiClient(new Settings(), store); + await using var api = new YavscApiClient(new Settings(tokenPath + ".settings"), store); await using var transport = new Transport(); try { @@ -119,9 +120,26 @@ public sealed class PodcastBroadcasterTests Platform.RequestPodcastPermissionsAsync = permissions; Platform.CreatePodcastCaptureAsync = factory; File.Delete(tokenPath); + File.Delete(tokenPath + ".settings"); } } + [Fact] + public async Task Prepared_broadcast_starts_the_existing_emission_instead_of_creating_another() + { + await using var transport = new Transport(); + var client = new PodcastApiClient(transport, () => "https://api.example/"); + FakeCapture? capture = null; + await using var broadcaster = await PodcastBroadcaster.StartAsync(client, "Prepared", + (directory, _) => Task.FromResult(capture = new FakeCapture(directory)), + TestContext.Current.CancellationToken, transport.PodcastId); + Assert.Equal(transport.PodcastId, broadcaster.Podcast.Id); + Assert.Equal(transport.PodcastId, transport.StartedId); + Assert.Equal(0, transport.CreateCount); + await capture!.StopAsync(); + await broadcaster.Completion.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + [Fact] public async Task Native_stop_flushes_final_segment_before_completing_server_replay() { @@ -217,10 +235,14 @@ public sealed class PodcastBroadcasterTests public List Events { get; } = []; public bool FailUpload { get; init; } public int CreateCount { get; private set; } + public Guid PodcastId => _podcast.Id; + public Guid? StartedId { get; private set; } public TaskCompletionSource FirstUpload { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) { if (path.EndsWith("/complete", StringComparison.Ordinal)) Events.Add("complete"); + else if (path.EndsWith("/start", StringComparison.Ordinal)) + StartedId = Guid.Parse(new Uri(path).Segments[^2].TrimEnd('/')); else CreateCount++; return Task.FromResult((T)(object)_podcast); } diff --git a/src/PostIt/PostIt.Tests/PodcastPreferencesTests.cs b/src/PostIt/PostIt.Tests/PodcastPreferencesTests.cs new file mode 100644 index 000000000..ff822e492 --- /dev/null +++ b/src/PostIt/PostIt.Tests/PodcastPreferencesTests.cs @@ -0,0 +1,79 @@ +using Avalonia.Headless.XUnit; +using PostIt.Services; +using PostIt.ViewModels; +using Yavsc.Api.Client; + +namespace PostIt.Tests; + +public sealed class PodcastPreferencesTests +{ + [AvaloniaFact] + public async Task Detection_selection_and_title_survive_settings_reload_without_detecting_again() + { + var path = Path.Combine(Path.GetTempPath(), $"postit-preferences-{Guid.NewGuid():N}.json"); + var previous = Platform.GetPodcastCaptureDevices; + try + { + Platform.GetPodcastCaptureDevices = () => new( + [new("Front", "front"), new("Rear", "rear")], + [new("None", ""), new("USB", "usb")]); + var settings = new Settings(path); + await using var api = new YavscApiClient(settings, new TokenStore(path + ".tokens")); + var session = new SessionStatusViewModel(); + var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => settings.ApiUrl), api, session); + vm.DetectDevicesCommand.Execute(null); + vm.SelectedCamera = vm.Cameras[1]; + vm.SelectedMicrophone = vm.Microphones[0]; + vm.Title = "Mon emission habituelle"; + vm.DetectDevicesCommand.Execute(null); + Assert.Equal("rear", vm.SelectedCamera?.Value); + Assert.Equal("", vm.SelectedMicrophone?.Value); + + var restored = new Settings(path); + restored.Authentication.Authority = ""; + restored.Load(); + Assert.False(restored.IsDirty); + Assert.Equal("Mon emission habituelle", restored.PodcastDefaultTitle); + Assert.Equal("rear", restored.PodcastCameraId); + Assert.Equal("", restored.PodcastMicrophoneId); + Platform.GetPodcastCaptureDevices = () => throw new InvalidOperationException("Must use saved devices."); + await using var otherApi = new YavscApiClient(restored, new TokenStore(path + ".tokens")); + var other = new PodcastsPageViewModel(new PodcastApiClient(otherApi, () => restored.ApiUrl), otherApi, session); + Assert.Equal(2, other.Cameras.Count); + Assert.Equal(2, other.Microphones.Count); + Assert.Equal("rear", other.SelectedCamera?.Value); + Assert.Equal("", other.SelectedMicrophone?.Value); + Assert.Equal(vm.Title, other.Title); + + Platform.GetPodcastCaptureDevices = () => new([], []); + other.DetectDevicesCommand.Execute(null); + Assert.Null(other.SelectedCamera); + Assert.Null(other.SelectedMicrophone); + Assert.Contains("Aucune camera", other.Status); + } + finally + { + Platform.GetPodcastCaptureDevices = previous; + File.Delete(path); + File.Delete(path + ".tokens"); + } + } + + [AvaloniaFact] + public async Task Failed_save_is_reported_without_losing_the_title() + { + var path = Path.Combine(Path.GetTempPath(), $"postit-preferences-{Guid.NewGuid():N}"); + Directory.CreateDirectory(path); + try + { + var settings = new Settings(path); + await using var api = new YavscApiClient(settings, new TokenStore(path + ".tokens")); + var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => settings.ApiUrl), api, new()); + vm.Title = "Titre conserve"; + Assert.Equal("Titre conserve", vm.Title); + Assert.Contains("sauvegarde impossible", vm.Status); + Assert.True(settings.IsDirty); + } + finally { Directory.Delete(path); File.Delete(path + ".tokens"); } + } +} diff --git a/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs b/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs new file mode 100644 index 000000000..16101c420 --- /dev/null +++ b/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs @@ -0,0 +1,93 @@ +using Avalonia.Headless.XUnit; +using PostIt.Services; +using PostIt.ViewModels; +using Yavsc.Abstract.Identity; +using Yavsc.Abstract.Streaming; +using Yavsc.Api.Client; + +namespace PostIt.Tests; + +public sealed class PodcastScheduleTests +{ + [AvaloniaFact] + public async Task Preparation_and_editing_send_schedule_and_optional_announcement_without_capture() + { + var tokenPath = Path.Combine(Path.GetTempPath(), $"postit-plan-{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", ScheduledDate = DateTimeOffset.Now.AddDays(7), + ScheduledTime = new TimeSpan(14, 15, 0), PlannedDurationMinutes = 90 + }; + Assert.True(vm.PrepareCommand.CanExecute(null)); + await vm.PrepareCommand.ExecuteAsync(null); + Assert.Equal(HttpMethod.Post, api.SavedMethod); + Assert.EndsWith("/podcasts/planned", api.SavedPath); + Assert.Equal(90, api.Saved?.PlannedDurationMinutes); + Assert.Null(api.Saved?.PublicAnnouncement); + Assert.Equal(14, api.Saved?.ScheduledStartAt.Hour); + Assert.Equal(PodcastState.Planned, vm.SelectedPodcast?.State); + Assert.False(vm.FinishCommand.CanExecute(null)); + Assert.True(vm.DeleteCommand.CanExecute(null)); + Assert.True(vm.UpdatePlanCommand.CanExecute(null)); + vm.Title = "Nouveau titre"; + vm.PublishAnnouncement = true; + vm.Announcement = "Venez au concert"; + await vm.UpdatePlanCommand.ExecuteAsync(null); + Assert.Equal(HttpMethod.Put, api.SavedMethod); + Assert.EndsWith($"/podcasts/{api.Plan.Id}/planned", api.SavedPath); + Assert.Equal("Venez au concert", api.Saved?.PublicAnnouncement); + Assert.Equal("Nouveau titre", vm.SelectedPodcast?.Title); + vm.PublishAnnouncement = false; + await vm.UpdatePlanCommand.ExecuteAsync(null); + Assert.Null(api.Saved?.PublicAnnouncement); + vm.PlannedDurationMinutes = 0; + api.Saved = null; + await vm.UpdatePlanCommand.ExecuteAsync(null); + Assert.Null(api.Saved); + Assert.Contains("Preparation impossible", vm.Status); + Assert.False(vm.IsBroadcasting); + vm.SelectedPodcast = api.Plan with { Title = "Titre programme distinct" }; + Assert.Equal("Titre programme distinct", vm.Title); + Assert.Equal("Nouveau titre", api.Settings.PodcastDefaultTitle); + vm.NewPlanCommand.Execute(null); + Assert.Equal("Nouveau titre", vm.Title); + } + finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); } + } + + private sealed class ScheduleApi(TokenStore store, string settingsPath) : YavscApiClient(new Settings(settingsPath), store) + { + public PodcastResponse Plan { get; private set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner", + DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0); + public PreparePodcastRequest? Saved { get; set; } + public string? SavedPath { get; private set; } + public HttpMethod? SavedMethod { get; private set; } + + public override Task CallAsync(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 (method == HttpMethod.Get) response = new List { Plan }; + else + { + Saved = Assert.IsType(body); + SavedPath = path; + SavedMethod = method; + Plan = Plan with + { + Title = Saved.Title, ScheduledStartAt = Saved.ScheduledStartAt, + PlannedDurationMinutes = Saved.PlannedDurationMinutes, PublicAnnouncement = Saved.PublicAnnouncement + }; + response = Plan; + } + return Task.FromResult((T)response); + } + } +} diff --git a/src/PostIt/PostIt/Services/PodcastBroadcaster.cs b/src/PostIt/PostIt/Services/PodcastBroadcaster.cs index 0b931b6b0..2094abc99 100644 --- a/src/PostIt/PostIt/Services/PodcastBroadcaster.cs +++ b/src/PostIt/PostIt/Services/PodcastBroadcaster.cs @@ -52,10 +52,10 @@ public sealed class PodcastBroadcaster : IAsyncDisposable } public static async Task StartAsync(PodcastApiClient api, string title, - string camera, string? microphone, CancellationToken ct) + string camera, string? microphone, CancellationToken ct, Guid? plannedId = null) => await StartAsync(api, title, (directory, _) => Task.FromResult(new LibVlcPodcastCapture( - vlc => new CameraStreamer(vlc).CreateCaptureMedia(camera, microphone), directory, preview: true)), ct); + vlc => new CameraStreamer(vlc).CreateCaptureMedia(camera, microphone), directory, preview: true)), ct, plannedId); internal static async Task StartAsync(PodcastApiClient api, string title, Func createMedia, CancellationToken ct) @@ -63,7 +63,7 @@ public sealed class PodcastBroadcaster : IAsyncDisposable (directory, _) => Task.FromResult(new LibVlcPodcastCapture(createMedia, directory)), ct); public static async Task StartAsync(PodcastApiClient api, string title, - Func> createCapture, CancellationToken ct) + Func> createCapture, CancellationToken ct, Guid? plannedId = null) { IPodcastCapture? capture = null; PodcastBroadcaster? broadcaster = null; @@ -73,7 +73,9 @@ public sealed class PodcastBroadcaster : IAsyncDisposable try { Directory.CreateDirectory(directory); - podcast = await api.CreateAsync(title, ct); + podcast = plannedId.HasValue ? await api.StartAsync(plannedId.Value, ct) : await api.CreateAsync(title, 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); ct.ThrowIfCancellationRequested(); capture = await createCapture(directory, ct); diff --git a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs index 420024342..109fcb242 100644 --- a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs @@ -1,5 +1,6 @@ using System; using System.Collections.ObjectModel; +using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -32,6 +33,7 @@ public partial class PodcastsPageViewModel : ViewModelBase private CaptureDevice? _microphone; private PodcastResponse? _selected; private Control? _capturePreview; + private bool _restoringPreferences; public Control? CapturePreview { get => _capturePreview; private set => SetProperty(ref _capturePreview, value); } public ObservableCollection Podcasts { get; } = new(); @@ -41,8 +43,31 @@ public partial class PodcastsPageViewModel : ViewModelBase || (!OperatingSystem.IsAndroid() && (OperatingSystem.IsWindows() || OperatingSystem.IsLinux())); - public string Title { get => _title; set { if (SetProperty(ref _title, value)) UpdateCommands(); } } + public string Title + { + get => _title; + set + { + if (!SetProperty(ref _title, value)) return; + UpdateCommands(); + if (!_restoringPreferences) + { + _api.Settings.PodcastDefaultTitle = value; + SavePreferences(); + } + } + } + [ObservableProperty] + public partial DateTimeOffset? ScheduledDate { get; set; } = DateTimeOffset.Now.AddDays(1); + [ObservableProperty] + public partial TimeSpan? ScheduledTime { get; set; } = new TimeSpan(20, 0, 0); + [ObservableProperty] + public partial decimal PlannedDurationMinutes { get; set; } = 60; + [ObservableProperty] + public partial bool PublishAnnouncement { get; set; } + [ObservableProperty] + public partial string Announcement { get; set; } = ""; public string Status { get => _status; private set => SetProperty(ref _status, value); } public bool IsBroadcasting @@ -60,24 +85,59 @@ public partial class PodcastsPageViewModel : ViewModelBase public CaptureDevice? SelectedCamera { get => _camera; - set { if (SetProperty(ref _camera, value)) UpdateCommands(); } + set + { + if (!SetProperty(ref _camera, value)) return; + UpdateCommands(); + if (!_restoringPreferences && value != null) + { + _api.Settings.PodcastCameraId = value.Value; + SavePreferences(); + } + } } public CaptureDevice? SelectedMicrophone { get => _microphone; - set { if (SetProperty(ref _microphone, value)) UpdateCommands(); } + set + { + if (!SetProperty(ref _microphone, value)) return; + UpdateCommands(); + if (!_restoringPreferences && value != null) + { + _api.Settings.PodcastMicrophoneId = value.Value; + SavePreferences(); + } + } } public PodcastResponse? SelectedPodcast { get => _selected; - set { if (SetProperty(ref _selected, value)) UpdateCommands(); } + set + { + if (!SetProperty(ref _selected, value)) return; + if (value is { State: PodcastState.Planned } && value.OwnerId == _ownerId) + { + _title = value.Title; + OnPropertyChanged(nameof(Title)); + ScheduledDate = value.ScheduledStartAt?.ToLocalTime(); + ScheduledTime = value.ScheduledStartAt?.ToLocalTime().TimeOfDay; + PlannedDurationMinutes = value.PlannedDurationMinutes ?? 60; + Announcement = value.PublicAnnouncement ?? ""; + PublishAnnouncement = !string.IsNullOrEmpty(Announcement); + } + UpdateCommands(); + } } public IAsyncRelayCommand RefreshCommand { get; } public IRelayCommand DetectDevicesCommand { get; } public IAsyncRelayCommand StartCommand { get; } + public IAsyncRelayCommand PrepareCommand { get; } + public IAsyncRelayCommand UpdatePlanCommand { get; } + public IRelayCommand NewPlanCommand { get; } public IAsyncRelayCommand StopCommand { get; } public IAsyncRelayCommand PlayCommand { get; } public IAsyncRelayCommand FinishCommand { get; } @@ -95,11 +155,21 @@ public partial class PodcastsPageViewModel : ViewModelBase DetectDevicesCommand = new RelayCommand(DetectDevices, () => CanBroadcast && !IsBroadcasting && !IsBusy); StartCommand = new AsyncRelayCommand(StartAsync, () => CanBroadcast && !IsBroadcasting && !IsBusy && _session.IsLoggedIn - && SelectedCamera is not null && !string.IsNullOrWhiteSpace(Title)); + && SelectedCamera is not null && !string.IsNullOrWhiteSpace(Title) + && (SelectedPodcast == null || SelectedPodcast is { State: PodcastState.Planned } p && p.OwnerId == _ownerId)); + PrepareCommand = new AsyncRelayCommand(() => SavePlanAsync(false), + () => !IsBusy && !IsBroadcasting && _session.IsLoggedIn && !string.IsNullOrWhiteSpace(Title)); + UpdatePlanCommand = new AsyncRelayCommand(() => SavePlanAsync(true), + () => !IsBusy && !IsBroadcasting && SelectedPodcast is { State: PodcastState.Planned } p && p.OwnerId == _ownerId); + NewPlanCommand = new RelayCommand(() => + { + SelectedPodcast = null; + Title = _api.Settings.PodcastDefaultTitle; + }, () => !IsBusy && !IsBroadcasting); StopCommand = new AsyncRelayCommand(StopAsync, () => IsBroadcasting && !IsBusy); PlayCommand = new AsyncRelayCommand(PlayAsync, () => SelectedPodcast is { SegmentCount: > 0 } && !IsBroadcasting && !IsBusy); FinishCommand = new AsyncRelayCommand(FinishAsync, - () => SelectedPodcast is { State: not PodcastState.Completed } p + () => SelectedPodcast is { State: PodcastState.Live or PodcastState.Interrupted } p && p.OwnerId == _ownerId && !IsBroadcasting && !IsBusy); DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => SelectedPodcast is { State: not PodcastState.Live } p @@ -107,6 +177,32 @@ public partial class PodcastsPageViewModel : ViewModelBase RetryReplayCommand = new AsyncRelayCommand(RetryReplayAsync, () => SelectedPodcast is { State: PodcastState.Completed, Replay.State: PodcastReplayState.Failed } p && p.OwnerId == _ownerId && !IsBroadcasting && !IsBusy); + _title = _api.Settings.PodcastDefaultTitle; + _restoringPreferences = true; + try + { + foreach (var device in _api.Settings.PodcastCameras) Cameras.Add(device); + foreach (var device in _api.Settings.PodcastMicrophones) Microphones.Add(device); + RestoreDeviceSelection(); + } + finally { _restoringPreferences = false; } + } + + private void RestoreDeviceSelection() + { + SelectedCamera = Cameras.FirstOrDefault(d => d.Value == _api.Settings.PodcastCameraId) + ?? Cameras.FirstOrDefault(); + SelectedMicrophone = Microphones.FirstOrDefault(d => d.Value == _api.Settings.PodcastMicrophoneId) + ?? (Microphones.Count > 1 ? Microphones[1] : Microphones.FirstOrDefault()); + } + + private void SavePreferences() + { + try { _api.Settings.Save(); } + catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException) + { + Status = $"Preferences podcast appliquees, mais sauvegarde impossible : {ex.Message}"; + } } private void UpdateCommands() @@ -114,6 +210,9 @@ public partial class PodcastsPageViewModel : ViewModelBase RefreshCommand.NotifyCanExecuteChanged(); DetectDevicesCommand.NotifyCanExecuteChanged(); StartCommand.NotifyCanExecuteChanged(); + PrepareCommand.NotifyCanExecuteChanged(); + UpdatePlanCommand.NotifyCanExecuteChanged(); + NewPlanCommand.NotifyCanExecuteChanged(); StopCommand.NotifyCanExecuteChanged(); PlayCommand.NotifyCanExecuteChanged(); FinishCommand.NotifyCanExecuteChanged(); @@ -138,6 +237,34 @@ public partial class PodcastsPageViewModel : ViewModelBase finally { IsBusy = false; } } + private async Task SavePlanAsync(bool update) + { + IsBusy = true; + try + { + 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."); + 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); + if (TimeZoneInfo.Local.IsInvalidTime(local) || TimeZoneInfo.Local.IsAmbiguousTime(local)) + throw new InvalidOperationException("Cette heure est inexistante ou ambigue lors du changement d'heure. Choisissez une autre heure."); + var start = new DateTimeOffset(local, TimeZoneInfo.Local.GetUtcOffset(local)); + var plan = await _client.PrepareAsync(new PreparePodcastRequest + { + Title = Title, ScheduledStartAt = start, + PlannedDurationMinutes = (int)PlannedDurationMinutes, + PublicAnnouncement = PublishAnnouncement ? Announcement : null + }, update ? SelectedPodcast?.Id : null, _pageCancellation.Token); + await RefreshAsync(); + SelectedPodcast = plan; + Status = "Emission preparee. Debut et duree previsionnels : demarrage et arret manuels."; + } + catch (Exception ex) { Status = $"Preparation impossible : {ex.Message}"; } + finally { IsBusy = false; } + } + public async Task ActivateAsync() { if (_pageCancellation.IsCancellationRequested) @@ -156,6 +283,7 @@ public partial class PodcastsPageViewModel : ViewModelBase private void DetectDevices() { + _restoringPreferences = true; try { Cameras.Clear(); @@ -175,11 +303,16 @@ public partial class PodcastsPageViewModel : ViewModelBase Microphones.Add(new("Sans microphone", "")); foreach (var item in capture.GetAudioCaptureDevices()) Microphones.Add(new(item.Key, item.Value)); } - SelectedCamera = Cameras.Count == 0 ? null : Cameras[0]; - SelectedMicrophone = Microphones.Count > 1 ? Microphones[1] : Microphones[0]; + RestoreDeviceSelection(); + _api.Settings.PodcastCameras = Cameras.ToArray(); + _api.Settings.PodcastMicrophones = Microphones.ToArray(); + if (SelectedCamera != null) _api.Settings.PodcastCameraId = SelectedCamera.Value; + if (SelectedMicrophone != null) _api.Settings.PodcastMicrophoneId = SelectedMicrophone.Value; Status = Cameras.Count == 0 ? "Aucune camera detectee." : "Choisissez camera et microphone avant de demarrer."; + SavePreferences(); } catch (Exception ex) { Status = $"Detection impossible : {ex.Message}. Verifiez l'installation de LibVLC."; } + finally { _restoringPreferences = false; } } private async Task StartAsync() @@ -194,8 +327,8 @@ public partial class PodcastsPageViewModel : ViewModelBase await requestPermissions(microphone, _pageCancellation.Token); _broadcaster = Platform.CreatePodcastCaptureAsync is { } createCapture ? await PodcastBroadcaster.StartAsync(_client, Title, - (directory, ct) => createCapture(camera, microphone, directory, ct), _pageCancellation.Token) - : await PodcastBroadcaster.StartAsync(_client, Title, camera, microphone, _pageCancellation.Token); + (directory, ct) => createCapture(camera, microphone, directory, ct), _pageCancellation.Token, SelectedPodcast?.Id) + : await PodcastBroadcaster.StartAsync(_client, Title, camera, microphone, _pageCancellation.Token, SelectedPodcast?.Id); _broadcaster.Progress += OnProgress; CapturePreview = _broadcaster.Preview; _session.LogoutCompleted += OnLogout; diff --git a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs index 72eea5d35..49707c036 100644 --- a/src/PostIt/PostIt/ViewModels/Settings/Settings.cs +++ b/src/PostIt/PostIt/ViewModels/Settings/Settings.cs @@ -10,6 +10,7 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Globalization; using PostIt.Models; +using PostIt.Services; [assembly: InternalsVisibleTo("PostIt.Tests")] @@ -17,6 +18,10 @@ namespace PostIt.ViewModels; public partial class Settings : ViewModelBase { + public Settings() { } + + internal Settings(string settingsFileFullName) => SettingsFileFullName = settingsFileFullName; + [JsonIgnore] public string? SettingsFileFullName { get; private set; } @@ -41,6 +46,17 @@ public partial class Settings : ViewModelBase [ObservableProperty] public partial string ProviderOngoingRequestsSortOption { get; set; } = string.Empty; + [ObservableProperty] + public partial string PodcastDefaultTitle { get; set; } = string.Empty; + [ObservableProperty] + public partial CaptureDevice[] PodcastCameras { get; set; } = []; + [ObservableProperty] + public partial CaptureDevice[] PodcastMicrophones { get; set; } = []; + [ObservableProperty] + public partial string? PodcastCameraId { get; set; } + [ObservableProperty] + public partial string? PodcastMicrophoneId { get; set; } + [ObservableProperty] [JsonIgnore] public partial StatusNotice ActionStatus { get; set; } = StatusNotice.Info("Pret."); @@ -135,6 +151,11 @@ public partial class Settings : ViewModelBase partial void OnApiUrlChanged(string value) => MarkDirty(); partial void OnSearchTextChanged(string value) => MarkDirty(); partial void OnProviderOngoingRequestsSortOptionChanged(string value) => MarkDirty(); + partial void OnPodcastDefaultTitleChanged(string value) => MarkDirty(); + partial void OnPodcastCamerasChanged(CaptureDevice[] value) => MarkDirty(); + partial void OnPodcastMicrophonesChanged(CaptureDevice[] value) => MarkDirty(); + partial void OnPodcastCameraIdChanged(string? value) => MarkDirty(); + partial void OnPodcastMicrophoneIdChanged(string? value) => MarkDirty(); /// /// Authentication can be reassigned wholesale by @@ -392,6 +413,11 @@ public partial class Settings : ViewModelBase : this.ApiUrl; this.SearchText = settings.SearchText ?? string.Empty; this.ProviderOngoingRequestsSortOption = settings.ProviderOngoingRequestsSortOption ?? string.Empty; + PodcastDefaultTitle = settings.PodcastDefaultTitle ?? string.Empty; + PodcastCameras = settings.PodcastCameras ?? []; + PodcastMicrophones = settings.PodcastMicrophones ?? []; + PodcastCameraId = settings.PodcastCameraId; + PodcastMicrophoneId = settings.PodcastMicrophoneId; if (!(settings.Authentication is null)) { this.Authentication = new AuthenticationSettings(); diff --git a/src/PostIt/PostIt/Views/Video/PodcastsPage.axaml b/src/PostIt/PostIt/Views/Video/PodcastsPage.axaml index 0456e3718..9af54d2cc 100644 --- a/src/PostIt/PostIt/Views/Video/PodcastsPage.axaml +++ b/src/PostIt/PostIt/Views/Video/PodcastsPage.axaml @@ -50,6 +50,26 @@ + + + + + + + + + + + + +