From b157dce4e46a40f90e7cd377b8c5620704876a7a Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 8 Nov 2026 07:43:15 +0000 Subject: [PATCH] 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> --- CHANGELOG.md | 4 + INSTALL.md | 138 +- contrib/mediamtx-podcasts.yml | 26 + .../PostIt.Tests/AdministrationToolsTests.cs | 27 + .../PostIt.Tests/PodcastScheduleTests.cs | 104 +- .../AdministrationPageViewModel.Tools.cs | 11 + .../ViewModels/AdministrationPageViewModel.cs | 1 + .../ViewModels/PodcastsPageViewModel.cs | 86 +- .../Views/Layout/AdministrationPage.axaml | 3 + .../PostIt/Views/Video/PodcastsPage.axaml | 16 + .../PaymentResiduePurgeResult.cs | 5 + src/Yavsc.Abstract/Streaming/Podcast.cs | 21 + .../AdministrationApiClient.cs | 2 + src/Yavsc.Api.Client/PodcastApiClient.cs | 9 + src/Yavsc.Api/Administration.http | 6 + .../SiteAdministrationApiController.cs | 7 + .../Controllers/Musical/PodcastController.cs | 6 +- .../Musical/PodcastObsController.cs | 57 + src/Yavsc.Api/Podcast.http | 15 + src/Yavsc.Api/Program.cs | 1 + ...ministrationServiceCollectionExtensions.cs | 3 + src/Yavsc.Api/Services/PodcastObsOptions.cs | 33 + src/Yavsc.Api/Services/PodcastObsRelay.cs | 62 + src/Yavsc.Api/Services/PodcastObsService.cs | 158 + src/Yavsc.Api/Services/PodcastObsWorker.cs | 267 + .../Services/PodcastScheduleService.cs | 52 +- .../PodcastServiceCollectionExtensions.cs | 5 + src/Yavsc.Blogs/Program.cs | 1 + .../Accounting/AccountController.cs | 40 +- src/Yavsc.Org/Extensions/HostingExtensions.cs | 5 + ...261108061011_AccountWithdrawal.Designer.cs | 5228 ++++++++++++++++ .../20261108061011_AccountWithdrawal.cs | 43 + ...1108073234_PodcastObsIngestion.Designer.cs | 5242 +++++++++++++++++ .../20261108073234_PodcastObsIngestion.cs | 61 + .../ApplicationDbContextModelSnapshot.cs | 23 +- .../Services/AccountWithdrawalService.cs | 208 + .../Services/PaymentResiduePurgeWorker.cs | 38 + .../Services/ResourceSubscriptionService.cs | 10 + src/Yavsc.Org/Views/Account/Delete.cshtml | 9 +- src/Yavsc.Org/Views/Home/Privacy.cshtml | 122 +- .../Helpers/PaymentResidueService.cs | 72 + .../Helpers/ResourceUsageTracker.cs | 36 +- .../Helpers/WithdrawnAccountMiddleware.cs | 24 + .../Models/ApplicationDbContext.cs | 3 +- src/Yavsc.Server/Models/ApplicationUser.cs | 4 + src/Yavsc.Server/Models/Messaging/LiveFlow.cs | 8 + src/Yavsc.Server/Services/ProfileService.cs | 4 +- src/test/Yavsc.Api.Tests/PodcastObsTests.cs | 348 ++ .../Yavsc.Api.Tests/PodcastScheduleTests.cs | 9 + .../SiteAdministrationApiTests.cs | 20 +- .../ResourceSubscriptionControllerTests.cs | 15 + .../Controllers/ResourceUsageTermsTests.cs | 19 + .../AccountWithdrawalTests.cs | 298 + .../Yavsc.Server.Tests/ResourceUsageTests.cs | 31 + 54 files changed, 12996 insertions(+), 50 deletions(-) create mode 100644 contrib/mediamtx-podcasts.yml create mode 100644 src/Yavsc.Abstract/Administration/PaymentResiduePurgeResult.cs create mode 100644 src/Yavsc.Api/Controllers/Musical/PodcastObsController.cs create mode 100644 src/Yavsc.Api/Services/PodcastObsOptions.cs create mode 100644 src/Yavsc.Api/Services/PodcastObsRelay.cs create mode 100644 src/Yavsc.Api/Services/PodcastObsService.cs create mode 100644 src/Yavsc.Api/Services/PodcastObsWorker.cs create mode 100644 src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.Designer.cs create mode 100644 src/Yavsc.Org/Migrations/20261108061011_AccountWithdrawal.cs create mode 100644 src/Yavsc.Org/Migrations/20261108073234_PodcastObsIngestion.Designer.cs create mode 100644 src/Yavsc.Org/Migrations/20261108073234_PodcastObsIngestion.cs create mode 100644 src/Yavsc.Org/Services/AccountWithdrawalService.cs create mode 100644 src/Yavsc.Org/Services/PaymentResiduePurgeWorker.cs create mode 100644 src/Yavsc.Server/Helpers/PaymentResidueService.cs create mode 100644 src/Yavsc.Server/Helpers/WithdrawnAccountMiddleware.cs create mode 100644 src/test/Yavsc.Api.Tests/PodcastObsTests.cs create mode 100644 src/test/Yavsc.Server.Tests/AccountWithdrawalTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d06395a7..2f6e2084a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ### Added +* [Podcasts/OBS/PostIt] Add opt-in MediaMTX RTMPS ingestion for programmed emissions, activated explicitly from PostIt with one-time scoped, expiring and revocable keys. Start on publisher connection, remux H.264/AAC into the existing authenticated segments and MP4 replay workflow, bound concurrency/duration/buffering, enforce consumption and effective disk quotas, account storage with deletion refunds, and report owner-only ingest errors. Add relay configuration, installation instructions and real synthetic RTMP/RTMPS-to-replay regressions, including active revocation. + +* [Yavsc/PostIt/Privacy] Close and pseudonymize withdrawn accounts, cancel PayPal subscriptions before confirming withdrawal, erase managed personal files, avatars and podcasts, and reject old sessions across hosts. Purge eligible technical payment residues one year after effective withdrawal automatically and through a confirmed administrator-only PostIt action; preserve accounting records separately. Clarify the privacy policy, recipients, third-party integrations, withdrawal failures and deployment responsibilities. Make the unique email constraint mutable to support pseudonymization without deleting accounting identities. + * [Yavsc/API/Blogs/PostIt] Refund tracked storage points when personal files are deleted or replaced, and when generated PDFs are replaced. Persist per-file accounting receipts, preserve them on rename, reject refunds for untracked legacy files, and allow deletion at the consumption limit without refunding API/CPU/transfer costs. Update CGU and installation instructions. * [Yavsc/PostIt/PayPal] Add monthly Découverte (EUR 1 excluding VAT) and Premium (EUR 2 excluding VAT) resource subscriptions, charged at EUR 1.20 / EUR 2.40 including 20% VAT. Confirmed monthly PayPal payments erase up to one / three default quotas, carry two thirds of unused monthly credit without expiry, and preserve historical counters. Add persistent idempotent payment credits, refund reconciliation, authenticated Web subscription/cancellation pages, verified REST webhooks, PostIt links and balances, migration and updated CGU. diff --git a/INSTALL.md b/INSTALL.md index b143e7226..4987ef501 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -78,6 +78,42 @@ these Windows runtime behaviours. ## Resource consumption and CGU +### Account withdrawal and payment retention + +Apply the `AccountWithdrawal` migration before deploying all three hosts. It adds +withdrawal timestamps and replaces the immutable alternate email key with a +required unique email index, preserving uniqueness while allowing pseudonymization. +Do not run the withdrawal flow until every host uses the matching backend. + +Yavsc.Org must have write/delete access to the same managed volumes as API/Blogs: +`Site:UserFilesRoot`, `Site:Avatars` and `Podcast:RootPath`. +Use absolute paths shared across processes; defaults relative to application +directories are not shared automatically. Accounting files under `Site:Bills` +are not erased by withdrawal. Symbolic links in managed user directories are +refused rather than followed. + +The account is blocked before cancellation/erasure, and withdrawal is only +confirmed when these operations and pseudonymization succeed. On an explicit +failure, an administrator must fix the cause and retry the existing administrative +withdrawal action. Ensure no live upload/encoding operation is still writing to +the user's volumes during withdrawal; drain such operations before retrying. + +The Org hosted worker purges eligible technical payment records at startup and +checks at most every minute, with an earlier wake-up for a known anniversary. +Monitor errors and service availability: scheduled processing +cannot ensure an exact wall-clock deletion while the host is stopped. At least +one Org instance must run, and an external operations process must enforce the +one-year retention deadline during prolonged downtime. PostIt administrators can +also confirm and run `POST /api/v1/administration/payment-residues/purge`. +The report counts accounts, subscriptions, monthly payments, donations and legacy +PayPal payments. Active accounts and unfinished withdrawals are never purged. +No new subscription credits may be granted after withdrawal begins. + +Invoice payments, invoices and other legal accounting records are excluded. +Define and publish the actual accounting, logs and backup retention policy for +the deployment, verify configured providers and international-transfer safeguards, +and prevent withdrawn data from being reactivated by backup restoration. + Configure the **same** `ResourceUsage` section on Yavsc.Api, Yavsc.Blogs and Yavsc.Org. API and Blogs must also use the same application database. All three hosts and configuration templates inherit the backend defaults @@ -252,6 +288,100 @@ or PayPal account eligibility. ## Podcast live broadcasts and replays +### OBS Studio for planned emissions + +Deploy MediaMTX **v1.21.3** beside the **single Yavsc.Api media instance** and +FFmpeg on that API host. The generated configuration in +[`contrib/mediamtx-podcasts.yml`](contrib/mediamtx-podcasts.yml) enables only the +OBS publishing paths, RTMPS for publishers and private RTMP/control listeners. +Adjust its `authHTTPAddress` to the API's internal HTTP listener; this listener +must accept the local authentication callback without redirecting it to HTTPS. +Alternatively, use an internal HTTPS URL with a valid certificate. +Install the RTMPS TLS certificate and key at the configured paths. Keep the +control API and internal RTMP ports on loopback (or an isolated authenticated network), +never on the public Internet. Do not enable anonymous HLS/RTMP reads on the relay. +MediaMTX must not record independent copies: Yavsc owns storage and retention. + +Apply the `PodcastObsIngestion` migration on the shared database. Configure +`Podcast:Obs` on **Yavsc.Api only**, for example: + +```json +{ + "Podcast": { + "Obs": { + "Enabled": true, + "ServerUrl": "rtmps://obs.example.org:1936", + "RelayApiUrl": "http://127.0.0.1:9997/", + "RelayReadUrl": "rtmp://127.0.0.1:1935/", + "RelayUser": "yavsc", + "ActivationMinutes": 30, + "MaxDurationMinutes": 120, + "MaxConcurrentBroadcasts": 2 + } + } +} +``` + +Set `Podcast__Obs__RelayPassword` through the deployment's secret mechanism to +a random password of at least 32 characters. It authenticates Yavsc's private +reader/control client, not OBS users. Keep process arguments and credentials +accessible only to the service administrator. The public RTMPS URL must have +no `/live` suffix: the stream key includes the full `obs/` path. +Plain RTMP for the public OBS URL requires the explicit `AllowUnencryptedRtmp: true` option and should +only be used for local testing or inside a VPN. Limit publisher network bitrate +at the relay/network level as well as configuring OBS; application quotas are +checked on completed media segments, not on every incoming RTMP packet. + +In PostIt: + +1. Prepare an emission and select it. +2. Choose **Activer OBS / renouveler la cle**. +3. In OBS, select **Parametres > Stream > Service : Personnalise**, then copy + the displayed server and stream key. Use **H.264 video**, **AAC audio**, + a **2-second keyframe interval** and a bitrate producing segments below 8 MiB. +4. Start streaming in OBS before the activation expires. The actual emission + starts when the publisher connects, even if the scheduled date is later. + No camera capture in PostIt is required; PostIt may be closed afterwards. +5. Stop OBS or choose **Revoquer OBS et arreter le diffuseur** in PostIt. + Committed segments remain available and the normal MP4 worker prepares replay. + +Keys are scoped to one emission, stored only as SHA-256 hashes, displayed once, +rotated on each activation and erased after completion. PostIt never persists +them; navigation/logout clears the displayed key but does not revoke a running +external emission. Revocation is available at the consumption limit. +After disconnect, restart or timeout, the emission ends rather than silently +resuming under a new publisher: prepare a new emission for another broadcast. + +The worker polls the authenticated relay once a second and starts bounded FFmpeg +remuxing tasks. It rejects ended, deleted, revoked or withdrawn accounts and caps +concurrent captures and duration (the lower of planned duration and configured +maximum). MediaMTX also receives a session expiry from authentication, so the +publisher is disconnected at that maximum lifetime even if the API stops. +Committed segments are charged as transferred and stored MiB under the same +consumption rule; their storage receipts are refunded on podcast deletion. +OBS storage counts towards the user's effective disk quota and the existing +podcast media limits. Pending capture files are monitored and bounded; enforcement +can overshoot by one polling interval of incoming data. Processing errors are +reported in the owner-only OBS status endpoint, without exposing keys or FFmpeg +diagnostics. Monitor scan/cleanup failures and do not restore old activation keys +from backups. A prolonged relay/API outage requires operational intervention. + +The normal API listens/authenticates playback; OBS stream credentials never grant +listener access. If the relay is separately hosted, include it in the deployment's +privacy/provider information. + +For the real media regression, set `YAVSC_TEST_MEDIAMTX` to the installed MediaMTX +v1.21.3 executable and run: + +```bash +dotnet test --project src/test/Yavsc.Api.Tests/Yavsc.Api.Tests.csproj --filter-class '*PodcastObsTests' +``` + +The test launches loopback-only listeners, generates synthetic H.264/AAC media +with FFmpeg, verifies RTMP/RTMPS authentication, revocation during streaming, +AAC audio, HLS segments, MP4 replay and refund, +then stops its own processes and removes its temporary files. + PostIt Desktop's home page provides **Podcasts : directs et replays**. Install LibVLC 3 with the `livehttp`, MPEG-TS, x264 and AAC plugins on the Desktop machine. Windows capture uses DirectShow; Linux uses V4L2 and the @@ -274,7 +404,8 @@ replays; only the broadcaster can upload, complete or delete their podcast. Media is not anonymous and no access token is included in a playback URL. Configure Yavsc.Api's `Podcast` section (or environment variables such as -`Podcast__RootPath`). No database migration is needed. Install **FFmpeg 5+ +`Podcast__RootPath`). The base media store needs no database migration; +planned emissions and OBS require their migrations documented above. Install **FFmpeg 5+ on the API server** (with `concatf`, MPEG-TS, MP4 and AAC bitstream-filter support; for Debian/Ubuntu: `apt-get install ffmpeg`). The API runtime stage in the main Dockerfile includes it. Only stream-copy remuxing is performed, @@ -305,7 +436,10 @@ Defaults allow 8 MiB per segment (also the HTTP endpoint's hard limit), 1 GiB retained per owner, 7,200 segments per episode and 100 episodes per owner. At the target two-second segment duration, this is roughly four hours per episode; the byte quota can be reached earlier. Podcast quotas are -separate from the legacy user-files `DiskQuota`. Deleting an ended podcast +separate from the legacy user-files `DiskQuota` for native HTTP capture. +OBS source segments also count towards the user's effective disk quota and +instrumented consumption; the additional MP4 is counted only by `MaxOwnerBytes`. +Deleting an ended podcast releases its podcast quota. Reverse proxies must allow an 8 MiB PUT body and forward Authorization, Range and Content-Range on every API request/response. The retained MPEG-TS **and** the additional MP4 count toward `MaxOwnerBytes`. diff --git a/contrib/mediamtx-podcasts.yml b/contrib/mediamtx-podcasts.yml new file mode 100644 index 000000000..cc7aa2740 --- /dev/null +++ b/contrib/mediamtx-podcasts.yml @@ -0,0 +1,26 @@ +# MediaMTX v1.21.3. Run beside the single Yavsc.Api media host. +# Replace the auth URL port and TLS certificate paths for the deployment. +logLevel: warn +authMethod: http +authHTTPAddress: http://127.0.0.1:5103/api/v1/podcasts/relay/auth +authHTTPExclude: [] +api: true +apiAddress: 127.0.0.1:9997 +rtsp: false +rtmp: true +rtmpEncryption: optional +rtmpAddress: 127.0.0.1:1935 +rtmpsAddress: :1936 +rtmpServerKey: /etc/yavsc/obs/server.key +rtmpServerCert: /etc/yavsc/obs/server.crt +hls: false +webrtc: false +srt: false +playback: false +pathDefaults: + source: publisher + overridePublisher: false + maxReaders: 1 + record: false +paths: + "~^obs/[0-9a-f]{32}$": diff --git a/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs b/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs index 8b03dda89..4c9501a3f 100644 --- a/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs +++ b/src/PostIt/PostIt.Tests/AdministrationToolsTests.cs @@ -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(JsonSerializer.Serialize(result))!; diff --git a/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs b/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs index 16101c420..9a55ff3fc 100644 --- a/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs +++ b/src/PostIt/PostIt.Tests/PodcastScheduleTests.cs @@ -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? PendingActivation { get; set; } - public override Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) + public override async 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 (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 { 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; } } } diff --git a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.Tools.cs b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.Tools.cs index b87cbeccc..78486904c 100644 --- a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.Tools.cs +++ b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.Tools.cs @@ -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()); diff --git a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs index 9aef20641..9f9d5c9c8 100644 --- a/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/AdministrationPageViewModel.cs @@ -156,6 +156,7 @@ public partial class AdministrationPageViewModel : ViewModelBase private void ClearAdministrationData() { + PaymentPurgeReport = ""; Users.Clear(); UsageOverview.Clear(); SelectedUser = null; diff --git a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs index 62f297563..26307ed10 100644 --- a/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs +++ b/src/PostIt/PostIt/ViewModels/PodcastsPageViewModel.cs @@ -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(HttpMethod.Get, profileUrl.AbsoluteUri)).UserId; + var ownerId = (await _api.CallAsync(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; diff --git a/src/PostIt/PostIt/Views/Layout/AdministrationPage.axaml b/src/PostIt/PostIt/Views/Layout/AdministrationPage.axaml index a7f4a0c5a..08d367d17 100644 --- a/src/PostIt/PostIt/Views/Layout/AdministrationPage.axaml +++ b/src/PostIt/PostIt/Views/Layout/AdministrationPage.axaml @@ -77,6 +77,9 @@ TextWrapping="Wrap"/> +