PostIt: éditeur desktop des marques et plages du replay
L'auteur édite le brouillon d'un replay raffiné depuis PostIt desktop : navigation image par image, marques au temps courant (Ctrl+M) avec miniatures locales, plages supprimées entre deux marques, rétablissement, enregistrement avec contrôle de révision (un conflit conserve les modifications locales) et publication après enregistrement. ReplayEditPlan passe dans Yavsc.Abstract pour que le client fusionne et valide les plages comme le serveur. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
de08edaaf9
commit
b0b81f3632
15 changed files with 886 additions and 5 deletions
|
|
@ -6,6 +6,8 @@
|
|||
|
||||
### Added
|
||||
|
||||
* [PostIt/Podcasts] Add the desktop replay draft editor: from the refinement panel, the owner plays the private draft source, steps frame by frame, adds marks at the current time (Ctrl+M) with local thumbnails, picks start and end marks to remove ranges, restores ranges, then saves with the read revision (a conflict keeps local edits and asks for a reload) or publishes after saving pending edits. `ReplayEditPlan` moves to `Yavsc.Abstract` so the editor merges and validates ranges like the server.
|
||||
|
||||
* [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.
|
||||
|
|
|
|||
|
|
@ -223,7 +223,7 @@ supprimer le brouillon et les originaux.
|
|||
|
||||
#### Implémentation serveur du brouillon
|
||||
|
||||
Le brouillon privé est implémenté côté serveur ; l'éditeur PostIt reste à faire.
|
||||
Le brouillon privé est implémenté côté serveur, et son éditeur sur PostIt desktop.
|
||||
|
||||
- **Option** : `RefineReplay` est accepté à la création d'un direct immédiat
|
||||
et à la préparation d'une émission programmée (colonne `LiveFlow.RefineReplay`).
|
||||
|
|
@ -286,7 +286,19 @@ Le brouillon privé est implémenté côté serveur ; l'éditeur PostIt reste à
|
|||
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.
|
||||
- **Éditeur desktop** : « Éditer les marques et plages » ouvre le brouillon
|
||||
dans un lecteur qui lit la source privée. L'auteur avance image par image,
|
||||
pose une marque au temps courant (Ctrl+M) avec une miniature locale, choisit
|
||||
une marque de début et une de fin, et ajoute la plage aux suppressions. Les
|
||||
plages sont fusionnées et bornées par `ReplayEditPlan` (désormais partagé
|
||||
dans `Yavsc.Abstract`), comme sur le serveur ; une suppression totale est
|
||||
refusée. Les marques contenues dans une plage sont signalées puis retirées
|
||||
par le serveur à l'enregistrement. L'enregistrement envoie la révision lue ;
|
||||
un conflit conserve les modifications locales et invite à recharger. La
|
||||
publication enregistre d'abord les modifications en attente.
|
||||
- **Reste à faire** : chapitres nommés, miniatures des marques rechargées
|
||||
depuis le serveur (elles ne sont créées qu'à la pose), éditeur Android et
|
||||
validation sur de vrais médias.
|
||||
|
||||
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
|
||||
|
|
@ -386,7 +398,7 @@ différent de celui annoncé à l'auteur.
|
|||
prototype serveur »).
|
||||
3. Ajouter le brouillon privé et ses états, les autorisations, les limites et
|
||||
la reprise après incident (fait côté serveur, voir « Implémentation serveur
|
||||
du brouillon »), puis l'éditeur de marques et plages desktop.
|
||||
du brouillon »), puis l'éditeur de marques et plages desktop (fait).
|
||||
4. Valider la finalisation sur de vrais médias synthétiques et conserver le
|
||||
comportement existant pour les émissions sans raffinage.
|
||||
5. Porter l'éditeur sur Android (surface native), en réutilisant l'API et le
|
||||
|
|
|
|||
193
src/PostIt/PostIt.Tests/ReplayEditorTests.cs
Normal file
193
src/PostIt/PostIt.Tests/ReplayEditorTests.cs
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
using System.Net;
|
||||
using PostIt.ViewModels;
|
||||
using Yavsc.Abstract.Streaming;
|
||||
using Yavsc.Api.Client;
|
||||
|
||||
namespace PostIt.Tests;
|
||||
|
||||
[Collection(AvaloniaUiCollection.Name)]
|
||||
public sealed class ReplayEditorTests(AvaloniaUiFixture ui)
|
||||
{
|
||||
[Fact]
|
||||
public Task Marks_are_added_at_the_current_time_once_and_ranges_flag_their_marks()
|
||||
=> ui.RunAsync(() =>
|
||||
{
|
||||
var vm = Editor(new DraftApi());
|
||||
long? seek = null;
|
||||
vm.SeekRequested += t => seek = t;
|
||||
|
||||
vm.CurrentTimeMs = 12_000;
|
||||
vm.AddMarkCommand.Execute(null);
|
||||
vm.AddMarkCommand.Execute(null);
|
||||
Assert.Single(vm.Marks);
|
||||
Assert.Contains("existe deja", vm.Status);
|
||||
vm.CurrentTimeMs = 4_000;
|
||||
vm.AddMarkCommand.Execute(null);
|
||||
vm.CurrentTimeMs = 20_000;
|
||||
vm.AddMarkCommand.Execute(null);
|
||||
Assert.Equal([4_000L, 12_000, 20_000], vm.Marks.Select(m => m.TimeMs));
|
||||
|
||||
vm.GoToMarkCommand.Execute(vm.Marks[1]);
|
||||
Assert.Equal(12_000, seek);
|
||||
// The end mark may be chosen first: the range is ordered.
|
||||
vm.SetRangeEndCommand.Execute(vm.Marks[0]);
|
||||
vm.SetRangeStartCommand.Execute(vm.Marks[2]);
|
||||
Assert.True(vm.Marks[0].IsSelected);
|
||||
vm.RemoveSelectionCommand.Execute(null);
|
||||
|
||||
var range = Assert.Single(vm.RemovedRanges);
|
||||
Assert.Equal((4_000L, 20_000L), (range.StartMs, range.EndMs));
|
||||
Assert.Equal([true, true, false], vm.Marks.Select(m => m.IsRemoved));
|
||||
Assert.All(vm.Marks, m => Assert.False(m.IsSelected));
|
||||
Assert.True(vm.IsDirty);
|
||||
|
||||
vm.RestoreRangeCommand.Execute(range);
|
||||
Assert.Empty(vm.RemovedRanges);
|
||||
Assert.All(vm.Marks, m => Assert.False(m.IsRemoved));
|
||||
return Task.CompletedTask;
|
||||
}, TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public Task Overlapping_ranges_are_merged_and_removing_everything_is_refused()
|
||||
=> ui.RunAsync(() =>
|
||||
{
|
||||
var vm = Editor(new DraftApi());
|
||||
foreach (var t in new long[] { 0, 10_000, 20_000, 30_000, 60_000 })
|
||||
{
|
||||
vm.CurrentTimeMs = t;
|
||||
vm.AddMarkCommand.Execute(null);
|
||||
}
|
||||
RemoveBetween(vm, 10_000, 30_000);
|
||||
RemoveBetween(vm, 20_000, 60_000);
|
||||
var merged = Assert.Single(vm.RemovedRanges);
|
||||
Assert.Equal((10_000L, 60_000L), (merged.StartMs, merged.EndMs));
|
||||
|
||||
RemoveBetween(vm, 0, 10_000);
|
||||
Assert.Contains("Plage refusee", vm.Status);
|
||||
Assert.Equal(merged, Assert.Single(vm.RemovedRanges));
|
||||
Assert.Equal(0, vm.RangeStart?.TimeMs);
|
||||
return Task.CompletedTask;
|
||||
}, TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public Task Saving_sends_the_read_revision_and_reloads_the_server_draft()
|
||||
=> ui.RunAsync(async () =>
|
||||
{
|
||||
var api = new DraftApi();
|
||||
var vm = Editor(api);
|
||||
foreach (var t in new long[] { 5_000, 15_000, 25_000 })
|
||||
{
|
||||
vm.CurrentTimeMs = t;
|
||||
await vm.AddMarkCommand.ExecuteAsync(null);
|
||||
}
|
||||
RemoveBetween(vm, 5_000, 15_000);
|
||||
|
||||
Assert.True(await vm.SaveAsync());
|
||||
|
||||
var request = Assert.IsType<SavePodcastDraftRequest>(api.Saved);
|
||||
Assert.Equal(3, request.Revision);
|
||||
Assert.Equal([5_000L, 15_000, 25_000], request.Marks);
|
||||
Assert.Equal([new PodcastDraftRange(5_000, 15_000)], request.RemovedRanges);
|
||||
// The server drops the marks inside removed ranges.
|
||||
Assert.Equal([15_000L, 25_000], vm.Marks.Select(m => m.TimeMs));
|
||||
Assert.Equal(4, vm.Podcast.Draft?.Revision);
|
||||
Assert.False(vm.IsDirty);
|
||||
Assert.False(vm.SaveCommand.CanExecute(null));
|
||||
}, TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public Task A_revision_conflict_keeps_local_changes_and_asks_for_a_reload()
|
||||
=> ui.RunAsync(async () =>
|
||||
{
|
||||
var api = new DraftApi { Conflict = true };
|
||||
var vm = Editor(api);
|
||||
vm.CurrentTimeMs = 5_000;
|
||||
await vm.AddMarkCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.False(await vm.SaveAsync());
|
||||
|
||||
Assert.Contains("Rechargez", vm.Status);
|
||||
Assert.True(vm.IsDirty);
|
||||
Assert.Single(vm.Marks);
|
||||
Assert.Equal(3, vm.Podcast.Draft?.Revision);
|
||||
}, TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public Task Publishing_saves_pending_changes_first_and_publishes_the_saved_revision()
|
||||
=> ui.RunAsync(async () =>
|
||||
{
|
||||
var api = new DraftApi();
|
||||
var vm = Editor(api);
|
||||
vm.CurrentTimeMs = 5_000;
|
||||
await vm.AddMarkCommand.ExecuteAsync(null);
|
||||
|
||||
await vm.PublishCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal([HttpMethod.Put, HttpMethod.Post], api.Calls.Select(c => c.Method));
|
||||
Assert.Equal(4, Assert.IsType<PublishPodcastDraftRequest>(api.Calls[1].Body).Revision);
|
||||
Assert.Equal(PodcastDraftState.Publishing, vm.Podcast.Draft?.State);
|
||||
Assert.False(vm.CanEdit);
|
||||
Assert.False(vm.AddMarkCommand.CanExecute(null));
|
||||
}, TestContext.Current.CancellationToken);
|
||||
|
||||
private static ReplayEditorPageViewModel Editor(DraftApi api)
|
||||
=> new(new PodcastApiClient(api, () => "https://api.example/"), api.Podcast);
|
||||
|
||||
private static void RemoveBetween(ReplayEditorPageViewModel vm, long start, long end)
|
||||
{
|
||||
vm.SetRangeStartCommand.Execute(vm.Marks.Single(m => m.TimeMs == start));
|
||||
vm.SetRangeEndCommand.Execute(vm.Marks.Single(m => m.TimeMs == end));
|
||||
vm.RemoveSelectionCommand.Execute(null);
|
||||
}
|
||||
|
||||
private sealed class DraftApi : IYavscApiClient
|
||||
{
|
||||
public PodcastResponse Podcast { get; private set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner",
|
||||
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Completed, 1, 1024, 60)
|
||||
{
|
||||
RefineReplay = true,
|
||||
Draft = new PodcastDraftResponse(PodcastDraftState.Ready, 3, [], [], 1024)
|
||||
};
|
||||
public bool Conflict { get; init; }
|
||||
public SavePodcastDraftRequest? Saved { get; private set; }
|
||||
public List<(HttpMethod Method, string Path, object? Body)> Calls { get; } = [];
|
||||
public HttpClient Http { get; } = new();
|
||||
|
||||
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
|
||||
{
|
||||
Calls.Add((method, path, body));
|
||||
if (Conflict) throw new HttpRequestException("conflict", null, HttpStatusCode.Conflict);
|
||||
var draft = Podcast.Draft!;
|
||||
if (path.EndsWith("/draft", StringComparison.Ordinal))
|
||||
{
|
||||
Saved = Assert.IsType<SavePodcastDraftRequest>(body);
|
||||
var ranges = Saved.RemovedRanges;
|
||||
Podcast = Podcast with
|
||||
{
|
||||
Draft = draft with
|
||||
{
|
||||
Revision = draft.Revision + 1,
|
||||
Marks = Saved.Marks.Where(m => !ranges.Any(r => m >= r.StartMs && m < r.EndMs)).ToArray(),
|
||||
RemovedRanges = ranges
|
||||
}
|
||||
};
|
||||
}
|
||||
else if (path.EndsWith("/draft/publish", StringComparison.Ordinal))
|
||||
Podcast = Podcast with { Draft = draft with { State = PodcastDraftState.Publishing } };
|
||||
else throw new InvalidOperationException(path);
|
||||
return Task.FromResult((T)(object)Podcast);
|
||||
}
|
||||
|
||||
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
|
||||
=> throw new NotSupportedException();
|
||||
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
|
||||
=> throw new NotSupportedException();
|
||||
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default)
|
||||
=> throw new NotSupportedException();
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
Http.Dispose();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -48,6 +48,7 @@ public static class ServiceCollectionHelpers
|
|||
services.AddTransient<MainView>();
|
||||
services.AddTransient<BlogsPage>();
|
||||
services.AddTransient<VideoPage>();
|
||||
services.AddTransient<ReplayEditorPage>();
|
||||
services.AddTransient<PodcastsPage>();
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -34,4 +34,12 @@ public sealed class ReplayControlsState(TimeProvider? clock = null)
|
|||
return time.TotalHours >= 1 ? $"{(int)time.TotalHours}:{time.Minutes:00}:{time.Seconds:00}"
|
||||
: $"{(int)time.TotalMinutes}:{time.Seconds:00}";
|
||||
}
|
||||
|
||||
/// <summary>Formats a source time to the millisecond, as used by edit marks.</summary>
|
||||
public static string FormatPreciseTime(long milliseconds)
|
||||
{
|
||||
var time = TimeSpan.FromMilliseconds(Math.Max(0, milliseconds));
|
||||
return time.TotalHours >= 1 ? $"{(int)time.TotalHours}:{time.Minutes:00}:{time.Seconds:00}.{time.Milliseconds:000}"
|
||||
: $"{(int)time.TotalMinutes}:{time.Seconds:00}.{time.Milliseconds:000}";
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ public class ViewLocator : IDataTemplate
|
|||
{
|
||||
BlogsViewModel => services.GetRequiredService<BlogsPage>(),
|
||||
VideoPageViewModel => services.GetRequiredService<VideoPage>(),
|
||||
ReplayEditorPageViewModel => services.GetRequiredService<ReplayEditorPage>(),
|
||||
PodcastsPageViewModel => services.GetRequiredService<PodcastsPage>(),
|
||||
Settings => services.GetRequiredService<SettingsPage>(),
|
||||
AboutPageViewModel => services.GetRequiredService<AboutPage>(),
|
||||
|
|
|
|||
|
|
@ -260,6 +260,7 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
public IAsyncRelayCommand DeleteCommand { get; }
|
||||
public IAsyncRelayCommand RetryReplayCommand { get; }
|
||||
public IAsyncRelayCommand PublishDraftCommand { get; }
|
||||
public IAsyncRelayCommand EditDraftCommand { get; }
|
||||
public IAsyncRelayCommand DeleteOriginalsCommand { get; }
|
||||
public IAsyncRelayCommand ActivateObsCommand { get; }
|
||||
public IAsyncRelayCommand DeactivateObsCommand { get; }
|
||||
|
|
@ -309,6 +310,9 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
PublishDraftCommand = new AsyncRelayCommand(PublishDraftAsync,
|
||||
() => SelectedPodcast is { RefineReplay: true, Draft: { State: PodcastDraftState.Ready } d } p
|
||||
&& d.PublishedRevision != d.Revision && p.OwnerId == _ownerId && !IsBroadcasting && !IsBusy);
|
||||
EditDraftCommand = new AsyncRelayCommand(EditDraftAsync,
|
||||
() => SelectedPodcast is { RefineReplay: true, OriginalsDeleted: false, Draft: { State: PodcastDraftState.Ready, SourceBytes: > 0 } } p
|
||||
&& 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);
|
||||
|
|
@ -358,6 +362,7 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
DeleteCommand.NotifyCanExecuteChanged();
|
||||
RetryReplayCommand.NotifyCanExecuteChanged();
|
||||
PublishDraftCommand.NotifyCanExecuteChanged();
|
||||
EditDraftCommand.NotifyCanExecuteChanged();
|
||||
DeleteOriginalsCommand.NotifyCanExecuteChanged();
|
||||
ActivateObsCommand.NotifyCanExecuteChanged();
|
||||
DeactivateObsCommand.NotifyCanExecuteChanged();
|
||||
|
|
@ -781,6 +786,17 @@ public partial class PodcastsPageViewModel : ViewModelBase
|
|||
finally { IsBusy = false; }
|
||||
}
|
||||
|
||||
private async Task EditDraftAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez un podcast.");
|
||||
var app = Application.Current as App ?? throw new InvalidOperationException("Application indisponible.");
|
||||
await app.PushPageAsync(new ReplayEditorPageViewModel(_client, podcast));
|
||||
}
|
||||
catch (Exception ex) { Status = $"Ouverture de l'editeur impossible : {ex.Message}"; }
|
||||
}
|
||||
|
||||
private async Task DeleteOriginalsAsync()
|
||||
{
|
||||
IsBusy = true;
|
||||
|
|
|
|||
360
src/PostIt/PostIt/ViewModels/ReplayEditorPageViewModel.cs
Normal file
360
src/PostIt/PostIt/ViewModels/ReplayEditorPageViewModel.cs
Normal file
|
|
@ -0,0 +1,360 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Media.Imaging;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using PostIt.Services;
|
||||
using Yavsc.Abstract.Streaming;
|
||||
using Yavsc.Api.Client;
|
||||
|
||||
namespace PostIt.ViewModels;
|
||||
|
||||
/// <summary>A mark of the original source timeline, with its local private thumbnail.</summary>
|
||||
public sealed partial class ReplayMarkItem(long timeMs) : ObservableObject
|
||||
{
|
||||
public long TimeMs { get; } = timeMs;
|
||||
public string Time => ReplayControlsState.FormatPreciseTime(TimeMs);
|
||||
[ObservableProperty]
|
||||
public partial Bitmap? Thumbnail { get; set; }
|
||||
/// <summary>The mark lies in a removed range and will be dropped on save.</summary>
|
||||
[ObservableProperty]
|
||||
public partial bool IsRemoved { get; set; }
|
||||
[ObservableProperty]
|
||||
public partial bool IsSelected { get; set; }
|
||||
}
|
||||
|
||||
public sealed record ReplayRangeItem(long StartMs, long EndMs)
|
||||
{
|
||||
public string Label => $"{ReplayControlsState.FormatPreciseTime(StartMs)} → {ReplayControlsState.FormatPreciseTime(EndMs)}"
|
||||
+ $" ({ReplayControlsState.FormatPreciseTime(EndMs - StartMs)})";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Edits the marks and removed ranges of a refined replay draft. Times use the original source timeline;
|
||||
/// a removed range [start, end) drops the frame at its start mark and keeps the frame at its end mark.
|
||||
/// </summary>
|
||||
public sealed partial class ReplayEditorPageViewModel : ViewModelBase
|
||||
{
|
||||
public const int MaxMarks = 500;
|
||||
private readonly PodcastApiClient _client;
|
||||
private PodcastResponse _podcast;
|
||||
private string _status = "";
|
||||
private bool _busy;
|
||||
private bool _dirty;
|
||||
|
||||
public ReplayEditorPageViewModel(PodcastApiClient client, PodcastResponse podcast)
|
||||
{
|
||||
_client = client;
|
||||
_podcast = podcast;
|
||||
AddMarkCommand = new AsyncRelayCommand(AddMarkAsync, () => CanEdit && Marks.Count < MaxMarks);
|
||||
GoToMarkCommand = new RelayCommand<ReplayMarkItem>(m => { if (m is not null) SeekRequested?.Invoke(m.TimeMs); });
|
||||
RemoveMarkCommand = new RelayCommand<ReplayMarkItem>(RemoveMark, _ => CanEdit);
|
||||
ClearMarksCommand = new RelayCommand(ClearMarks, () => CanEdit && Marks.Count > 0);
|
||||
SetRangeStartCommand = new RelayCommand<ReplayMarkItem>(m => Select(m, start: true), _ => CanEdit);
|
||||
SetRangeEndCommand = new RelayCommand<ReplayMarkItem>(m => Select(m, start: false), _ => CanEdit);
|
||||
ClearSelectionCommand = new RelayCommand(() => { RangeStart = null; RangeEnd = null; },
|
||||
() => RangeStart is not null || RangeEnd is not null);
|
||||
RemoveSelectionCommand = new RelayCommand(RemoveSelection,
|
||||
() => CanEdit && RangeStart is not null && RangeEnd is not null);
|
||||
RestoreRangeCommand = new RelayCommand<ReplayRangeItem>(RestoreRange, _ => CanEdit);
|
||||
SaveCommand = new AsyncRelayCommand(() => SaveAsync(), () => CanEdit && IsDirty);
|
||||
ReloadCommand = new AsyncRelayCommand(ReloadAsync, () => !IsBusy);
|
||||
PublishCommand = new AsyncRelayCommand(PublishAsync,
|
||||
() => CanEdit && (IsDirty || _podcast.Draft?.PublishedRevision != _podcast.Draft?.Revision));
|
||||
Load(podcast, keepThumbnails: false);
|
||||
}
|
||||
|
||||
public PodcastApiClient PodcastClient => _client;
|
||||
public PodcastResponse Podcast => _podcast;
|
||||
public string Title => $"Raffinage : {_podcast.Title}";
|
||||
public long SourceBytes => _podcast.Draft?.SourceBytes ?? 0;
|
||||
/// <summary>Duration used by the server to validate marks and ranges.</summary>
|
||||
public long SourceDurationMs => (long)Math.Ceiling(_podcast.DurationSeconds * 1000);
|
||||
public ObservableCollection<ReplayMarkItem> Marks { get; } = new();
|
||||
public ObservableCollection<ReplayRangeItem> RemovedRanges { get; } = new();
|
||||
|
||||
/// <summary>Requests the player to show this source time.</summary>
|
||||
public event Action<long>? SeekRequested;
|
||||
/// <summary>Captures a private thumbnail of the frame currently shown; set by the view.</summary>
|
||||
public Func<CancellationToken, Task<Bitmap?>>? CaptureThumbnail { get; set; }
|
||||
|
||||
[ObservableProperty]
|
||||
public partial long CurrentTimeMs { get; set; }
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(SelectionSummary))]
|
||||
public partial ReplayMarkItem? RangeStart { get; set; }
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(SelectionSummary))]
|
||||
public partial ReplayMarkItem? RangeEnd { get; set; }
|
||||
|
||||
public string CurrentTime => ReplayControlsState.FormatPreciseTime(CurrentTimeMs);
|
||||
public string SelectionSummary => (RangeStart, RangeEnd) switch
|
||||
{
|
||||
(null, null) => "Choisissez une marque de debut et une marque de fin.",
|
||||
({ } s, null) => $"Debut {s.Time} ; choisissez la marque de fin.",
|
||||
(null, { } e) => $"Fin {e.Time} ; choisissez la marque de debut.",
|
||||
var (s, e) => $"Plage a supprimer : {s.Time} → {e.Time}. L'image de la marque de debut est supprimee, celle de la marque de fin est conservee."
|
||||
};
|
||||
public string DurationSummary
|
||||
{
|
||||
get
|
||||
{
|
||||
var removed = RemovedRanges.Sum(r => r.EndMs - r.StartMs);
|
||||
return $"Source : {ReplayControlsState.FormatPreciseTime(SourceDurationMs)} ; resultat estime : "
|
||||
+ $"{ReplayControlsState.FormatPreciseTime(Math.Max(0, SourceDurationMs - removed))} ({RemovedRanges.Count} plage(s) supprimee(s)).";
|
||||
}
|
||||
}
|
||||
public string DraftState => _podcast.Draft switch
|
||||
{
|
||||
null => "Brouillon indisponible.",
|
||||
{ State: PodcastDraftState.Publishing } d => $"Publication de la revision {d.Revision} en cours : modification impossible.",
|
||||
{ State: not PodcastDraftState.Ready } => "Brouillon non modifiable pour le moment.",
|
||||
{ Error: { Length: > 0 } error } => $"Derniere publication en echec : {error}",
|
||||
{ PublishedRevision: { } p } d when p == d.Revision => $"Revision {d.Revision} publiee.",
|
||||
var d => $"Revision {d.Revision}, non publiee."
|
||||
};
|
||||
|
||||
public string Status { get => _status; private set => SetProperty(ref _status, value); }
|
||||
public bool IsBusy
|
||||
{
|
||||
get => _busy;
|
||||
private set { if (SetProperty(ref _busy, value)) UpdateCommands(); }
|
||||
}
|
||||
public bool IsDirty
|
||||
{
|
||||
get => _dirty;
|
||||
private set { if (SetProperty(ref _dirty, value)) UpdateCommands(); }
|
||||
}
|
||||
public bool CanEdit => !IsBusy && _podcast.Draft?.State == PodcastDraftState.Ready && !_podcast.OriginalsDeleted;
|
||||
|
||||
public IAsyncRelayCommand AddMarkCommand { get; }
|
||||
public IRelayCommand<ReplayMarkItem> GoToMarkCommand { get; }
|
||||
public IRelayCommand<ReplayMarkItem> RemoveMarkCommand { get; }
|
||||
public IRelayCommand ClearMarksCommand { get; }
|
||||
public IRelayCommand<ReplayMarkItem> SetRangeStartCommand { get; }
|
||||
public IRelayCommand<ReplayMarkItem> SetRangeEndCommand { get; }
|
||||
public IRelayCommand ClearSelectionCommand { get; }
|
||||
public IRelayCommand RemoveSelectionCommand { get; }
|
||||
public IRelayCommand<ReplayRangeItem> RestoreRangeCommand { get; }
|
||||
public IAsyncRelayCommand SaveCommand { get; }
|
||||
public IAsyncRelayCommand ReloadCommand { get; }
|
||||
public IAsyncRelayCommand PublishCommand { get; }
|
||||
public override bool CanNavigateNext { get => false; protected set { } }
|
||||
public override bool CanNavigatePrevious { get => true; protected set { } }
|
||||
|
||||
partial void OnCurrentTimeMsChanged(long value) => OnPropertyChanged(nameof(CurrentTime));
|
||||
partial void OnRangeStartChanged(ReplayMarkItem? oldValue, ReplayMarkItem? newValue) => UpdateSelection(oldValue, newValue);
|
||||
partial void OnRangeEndChanged(ReplayMarkItem? oldValue, ReplayMarkItem? newValue) => UpdateSelection(oldValue, newValue);
|
||||
|
||||
private void UpdateSelection(ReplayMarkItem? oldValue, ReplayMarkItem? newValue)
|
||||
{
|
||||
if (oldValue is not null) oldValue.IsSelected = ReferenceEquals(oldValue, RangeStart) || ReferenceEquals(oldValue, RangeEnd);
|
||||
if (newValue is not null) newValue.IsSelected = true;
|
||||
UpdateCommands();
|
||||
}
|
||||
|
||||
private async Task AddMarkAsync()
|
||||
{
|
||||
var time = Math.Clamp(CurrentTimeMs, 0, SourceDurationMs);
|
||||
if (Marks.Any(m => m.TimeMs == time))
|
||||
{
|
||||
Status = $"Une marque existe deja a {ReplayControlsState.FormatPreciseTime(time)}.";
|
||||
return;
|
||||
}
|
||||
var mark = new ReplayMarkItem(time);
|
||||
var index = Marks.TakeWhile(m => m.TimeMs < time).Count();
|
||||
Marks.Insert(index, mark);
|
||||
UpdateRemovedMarks();
|
||||
IsDirty = true;
|
||||
Status = $"Marque ajoutee a {mark.Time}.";
|
||||
UpdateCommands();
|
||||
if (CaptureThumbnail is { } capture)
|
||||
{
|
||||
try { mark.Thumbnail = await capture(CancellationToken.None); }
|
||||
catch (Exception ex) { Status = $"Marque ajoutee a {mark.Time}, sans miniature : {ex.Message}"; }
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveMark(ReplayMarkItem? mark)
|
||||
{
|
||||
if (mark is null || !Marks.Remove(mark)) return;
|
||||
if (ReferenceEquals(RangeStart, mark)) RangeStart = null;
|
||||
if (ReferenceEquals(RangeEnd, mark)) RangeEnd = null;
|
||||
mark.Thumbnail?.Dispose();
|
||||
IsDirty = true;
|
||||
UpdateCommands();
|
||||
}
|
||||
|
||||
private void ClearMarks()
|
||||
{
|
||||
RangeStart = null;
|
||||
RangeEnd = null;
|
||||
foreach (var mark in Marks) mark.Thumbnail?.Dispose();
|
||||
Marks.Clear();
|
||||
IsDirty = true;
|
||||
UpdateCommands();
|
||||
}
|
||||
|
||||
private void Select(ReplayMarkItem? mark, bool start)
|
||||
{
|
||||
if (mark is null) return;
|
||||
if (start) RangeStart = mark;
|
||||
else RangeEnd = mark;
|
||||
if (ReferenceEquals(RangeStart, RangeEnd)) { if (start) RangeEnd = null; else RangeStart = null; }
|
||||
}
|
||||
|
||||
private void RemoveSelection()
|
||||
{
|
||||
if (RangeStart is not { } a || RangeEnd is not { } b) return;
|
||||
var range = new ReplayRange(Math.Min(a.TimeMs, b.TimeMs), Math.Max(a.TimeMs, b.TimeMs));
|
||||
if (!TrySetRanges(RemovedRanges.Select(r => new ReplayRange(r.StartMs, r.EndMs)).Append(range))) return;
|
||||
RangeStart = null;
|
||||
RangeEnd = null;
|
||||
Status = "Plage ajoutee aux suppressions. Les marques qu'elle contient seront retirees a l'enregistrement.";
|
||||
}
|
||||
|
||||
private void RestoreRange(ReplayRangeItem? range)
|
||||
{
|
||||
if (range is null) return;
|
||||
if (TrySetRanges(RemovedRanges.Where(r => r != range).Select(r => new ReplayRange(r.StartMs, r.EndMs))))
|
||||
Status = $"Plage {range.Label} retablie.";
|
||||
}
|
||||
|
||||
private bool TrySetRanges(IEnumerable<ReplayRange> ranges)
|
||||
{
|
||||
IReadOnlyList<ReplayRange> normalized;
|
||||
try { normalized = ReplayEditPlan.RemovedRanges(ranges.ToArray(), SourceDurationMs); }
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
Status = $"Plage refusee : {ex.Message.Split(" (Parameter")[0]}";
|
||||
return false;
|
||||
}
|
||||
RemovedRanges.Clear();
|
||||
foreach (var range in normalized) RemovedRanges.Add(new(range.StartMs, range.EndMs));
|
||||
UpdateRemovedMarks();
|
||||
IsDirty = true;
|
||||
OnPropertyChanged(nameof(DurationSummary));
|
||||
UpdateCommands();
|
||||
return true;
|
||||
}
|
||||
|
||||
private void UpdateRemovedMarks()
|
||||
{
|
||||
foreach (var mark in Marks)
|
||||
mark.IsRemoved = RemovedRanges.Any(r => mark.TimeMs >= r.StartMs && mark.TimeMs < r.EndMs);
|
||||
}
|
||||
|
||||
/// <summary>Saves local changes; returns false on failure, including a revision conflict.</summary>
|
||||
public async Task<bool> SaveAsync()
|
||||
{
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var draft = _podcast.Draft ?? throw new InvalidOperationException("Brouillon indisponible.");
|
||||
var saved = await _client.SaveDraftAsync(_podcast.Id, new SavePodcastDraftRequest
|
||||
{
|
||||
Revision = draft.Revision,
|
||||
Marks = Marks.Select(m => m.TimeMs).ToArray(),
|
||||
RemovedRanges = RemovedRanges.Select(r => new PodcastDraftRange(r.StartMs, r.EndMs)).ToArray()
|
||||
});
|
||||
Load(saved, keepThumbnails: true);
|
||||
Status = $"Brouillon enregistre (revision {saved.Draft?.Revision}).";
|
||||
return true;
|
||||
}
|
||||
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
|
||||
{
|
||||
Status = "Enregistrement refuse : le brouillon a ete modifie ailleurs ou n'est plus modifiable. "
|
||||
+ "Rechargez-le (vos modifications locales seront perdues).";
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Status = $"Enregistrement impossible : {ex.Message}";
|
||||
return false;
|
||||
}
|
||||
finally { IsBusy = false; }
|
||||
}
|
||||
|
||||
private async Task ReloadAsync()
|
||||
{
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var manifest = await _client.GetAsync(_podcast.Id);
|
||||
Load(manifest.Podcast, keepThumbnails: true);
|
||||
Status = "Brouillon recharge depuis le serveur.";
|
||||
}
|
||||
catch (Exception ex) { Status = $"Rechargement impossible : {ex.Message}"; }
|
||||
finally { IsBusy = false; }
|
||||
}
|
||||
|
||||
private async Task PublishAsync()
|
||||
{
|
||||
if (IsDirty && !await SaveAsync()) return;
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var draft = _podcast.Draft ?? throw new InvalidOperationException("Brouillon indisponible.");
|
||||
Load(await _client.PublishDraftAsync(_podcast.Id, draft.Revision), keepThumbnails: true);
|
||||
Status = $"Publication de la revision {draft.Revision} demandee ; le MP4 remplacera le replay une fois prepare.";
|
||||
}
|
||||
catch (Exception ex) { Status = $"Publication impossible : {ex.Message}"; }
|
||||
finally { IsBusy = false; }
|
||||
}
|
||||
|
||||
private void Load(PodcastResponse podcast, bool keepThumbnails)
|
||||
{
|
||||
var thumbnails = keepThumbnails ? Marks.Where(m => m.Thumbnail is not null).ToDictionary(m => m.TimeMs, m => m.Thumbnail) : new Dictionary<long, Bitmap?>();
|
||||
var marks = podcast.Draft?.Marks ?? [];
|
||||
foreach (var mark in Marks)
|
||||
if (!marks.Contains(mark.TimeMs)) mark.Thumbnail?.Dispose();
|
||||
_podcast = podcast;
|
||||
RangeStart = null;
|
||||
RangeEnd = null;
|
||||
Marks.Clear();
|
||||
foreach (var time in marks.Order())
|
||||
Marks.Add(new ReplayMarkItem(time) { Thumbnail = thumbnails.GetValueOrDefault(time) });
|
||||
RemovedRanges.Clear();
|
||||
foreach (var range in (podcast.Draft?.RemovedRanges ?? []).OrderBy(r => r.StartMs))
|
||||
RemovedRanges.Add(new(range.StartMs, range.EndMs));
|
||||
UpdateRemovedMarks();
|
||||
IsDirty = false;
|
||||
OnPropertyChanged(nameof(Podcast));
|
||||
OnPropertyChanged(nameof(DraftState));
|
||||
OnPropertyChanged(nameof(DurationSummary));
|
||||
OnPropertyChanged(nameof(CanEdit));
|
||||
UpdateCommands();
|
||||
}
|
||||
|
||||
private void UpdateCommands()
|
||||
{
|
||||
OnPropertyChanged(nameof(CanEdit));
|
||||
AddMarkCommand?.NotifyCanExecuteChanged();
|
||||
RemoveMarkCommand?.NotifyCanExecuteChanged();
|
||||
ClearMarksCommand?.NotifyCanExecuteChanged();
|
||||
SetRangeStartCommand?.NotifyCanExecuteChanged();
|
||||
SetRangeEndCommand?.NotifyCanExecuteChanged();
|
||||
ClearSelectionCommand?.NotifyCanExecuteChanged();
|
||||
RemoveSelectionCommand?.NotifyCanExecuteChanged();
|
||||
RestoreRangeCommand?.NotifyCanExecuteChanged();
|
||||
SaveCommand?.NotifyCanExecuteChanged();
|
||||
ReloadCommand?.NotifyCanExecuteChanged();
|
||||
PublishCommand?.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
/// <summary>Releases the local thumbnails when leaving the editor.</summary>
|
||||
public void ReleaseThumbnails()
|
||||
{
|
||||
foreach (var mark in Marks)
|
||||
{
|
||||
mark.Thumbnail?.Dispose();
|
||||
mark.Thumbnail = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -158,7 +158,10 @@
|
|||
<StackPanel Spacing="8" IsVisible="{Binding HasDraftSummary}">
|
||||
<TextBlock Text="Raffinage du replay" FontWeight="SemiBold" />
|
||||
<TextBlock Text="{Binding DraftSummary}" TextWrapping="Wrap" />
|
||||
<Button Content="Publier le brouillon" Command="{Binding PublishDraftCommand}" />
|
||||
<WrapPanel>
|
||||
<Button Content="Editer les marques et plages" Command="{Binding EditDraftCommand}" Margin="0,0,8,8" />
|
||||
<Button Content="Publier le brouillon sans modification" Command="{Binding PublishDraftCommand}" Margin="0,0,8,8" />
|
||||
</WrapPanel>
|
||||
<CheckBox x:Name="ConfirmDeleteOriginals"
|
||||
Content="Je confirme la suppression definitive des originaux et du brouillon (le MP4 publie est conserve)" />
|
||||
<Button Content="Supprimer les originaux" Command="{Binding DeleteOriginalsCommand}"
|
||||
|
|
|
|||
91
src/PostIt/PostIt/Views/Video/ReplayEditorPage.axaml
Normal file
91
src/PostIt/PostIt/Views/Video/ReplayEditorPage.axaml
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
<ContentPage
|
||||
x:Class="PostIt.Views.Blogs.ReplayEditorPage"
|
||||
xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:PostIt.ViewModels"
|
||||
x:DataType="vm:ReplayEditorPageViewModel">
|
||||
<Grid ColumnDefinitions="2*,*" RowDefinitions="Auto,*,Auto,Auto" Margin="16" ColumnSpacing="16" RowSpacing="8">
|
||||
<TextBlock Grid.ColumnSpan="2" Text="{Binding Title}" FontSize="22" TextWrapping="Wrap" />
|
||||
<Border Grid.Row="1" Background="Black" BorderThickness="1" BorderBrush="Green" MinHeight="240">
|
||||
<ContentControl x:Name="VideoSurface" />
|
||||
</Border>
|
||||
<WrapPanel Grid.Row="2">
|
||||
<Button Content="◀ Image precedente" Click="PreviousFrame_Click" Margin="0,0,8,8"
|
||||
AutomationProperties.Name="Reculer d'une image" />
|
||||
<Button Content="Image suivante ▶" Click="NextFrame_Click" Margin="0,0,8,8"
|
||||
AutomationProperties.Name="Avancer d'une image" />
|
||||
<Button Content="Ajouter une marque (Ctrl+M)" Command="{Binding AddMarkCommand}" HotKey="Ctrl+M" Margin="0,0,8,8" />
|
||||
<TextBlock Text="{Binding CurrentTime, StringFormat='Position : {0}'}" VerticalAlignment="Center" />
|
||||
</WrapPanel>
|
||||
<TextBlock x:Name="PlaybackStatus" Grid.Row="3" TextWrapping="Wrap" />
|
||||
<ScrollViewer Grid.Row="1" Grid.RowSpan="3" Grid.Column="1">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="{Binding DraftState}" TextWrapping="Wrap" />
|
||||
<TextBlock Text="{Binding DurationSummary}" TextWrapping="Wrap" />
|
||||
<TextBlock Text="Marques" FontWeight="SemiBold" />
|
||||
<TextBlock Text="Les temps sont ceux de la source originale. Les miniatures restent locales et sont effacees en quittant l'editeur."
|
||||
TextWrapping="Wrap" />
|
||||
<ItemsControl ItemsSource="{Binding Marks}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:ReplayMarkItem">
|
||||
<Border BorderBrush="Gray" BorderThickness="1" CornerRadius="4" Padding="6" Margin="0,0,0,6">
|
||||
<Grid ColumnDefinitions="Auto,*" ColumnSpacing="8">
|
||||
<Image Source="{Binding Thumbnail}" Width="96" Height="54" Stretch="Uniform" />
|
||||
<StackPanel Grid.Column="1" Spacing="4">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<TextBlock Text="{Binding Time}" FontWeight="SemiBold" />
|
||||
<TextBlock Text="(supprimee)" IsVisible="{Binding IsRemoved}" />
|
||||
<TextBlock Text="✓ selectionnee" IsVisible="{Binding IsSelected}" />
|
||||
</StackPanel>
|
||||
<WrapPanel>
|
||||
<Button Content="Aller" Margin="0,0,4,4"
|
||||
Command="{Binding $parent[ContentPage].((vm:ReplayEditorPageViewModel)DataContext).GoToMarkCommand}"
|
||||
CommandParameter="{Binding}" />
|
||||
<Button Content="Debut" Margin="0,0,4,4"
|
||||
Command="{Binding $parent[ContentPage].((vm:ReplayEditorPageViewModel)DataContext).SetRangeStartCommand}"
|
||||
CommandParameter="{Binding}" />
|
||||
<Button Content="Fin" Margin="0,0,4,4"
|
||||
Command="{Binding $parent[ContentPage].((vm:ReplayEditorPageViewModel)DataContext).SetRangeEndCommand}"
|
||||
CommandParameter="{Binding}" />
|
||||
<Button Content="Retirer" Margin="0,0,4,4"
|
||||
Command="{Binding $parent[ContentPage].((vm:ReplayEditorPageViewModel)DataContext).RemoveMarkCommand}"
|
||||
CommandParameter="{Binding}" />
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<Button Content="Retirer toutes les marques" Command="{Binding ClearMarksCommand}" />
|
||||
<TextBlock Text="Plage a supprimer" FontWeight="SemiBold" />
|
||||
<TextBlock Text="{Binding SelectionSummary}" TextWrapping="Wrap" />
|
||||
<WrapPanel>
|
||||
<Button Content="Supprimer cette plage" Command="{Binding RemoveSelectionCommand}" Margin="0,0,8,8" />
|
||||
<Button Content="Annuler la selection" Command="{Binding ClearSelectionCommand}" Margin="0,0,8,8" />
|
||||
</WrapPanel>
|
||||
<TextBlock Text="Plages supprimees" FontWeight="SemiBold" />
|
||||
<ItemsControl ItemsSource="{Binding RemovedRanges}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:ReplayRangeItem">
|
||||
<Grid ColumnDefinitions="*,Auto" Margin="0,0,0,4">
|
||||
<TextBlock Text="{Binding Label}" VerticalAlignment="Center" TextWrapping="Wrap" />
|
||||
<Button Grid.Column="1" Content="Retablir"
|
||||
Command="{Binding $parent[ContentPage].((vm:ReplayEditorPageViewModel)DataContext).RestoreRangeCommand}"
|
||||
CommandParameter="{Binding}" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<WrapPanel>
|
||||
<Button Content="Enregistrer le brouillon" Command="{Binding SaveCommand}" Margin="0,0,8,8" />
|
||||
<Button Content="Recharger" Command="{Binding ReloadCommand}" Margin="0,0,8,8" />
|
||||
<Button Content="Publier" Command="{Binding PublishCommand}" Margin="0,0,8,8" />
|
||||
</WrapPanel>
|
||||
<TextBlock Text="La publication enregistre d'abord les modifications, puis remplace le replay une fois le MP4 prepare."
|
||||
TextWrapping="Wrap" />
|
||||
<TextBlock Text="{Binding Status}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
</ContentPage>
|
||||
169
src/PostIt/PostIt/Views/Video/ReplayEditorPage.axaml.cs
Normal file
169
src/PostIt/PostIt/Views/Video/ReplayEditorPage.axaml.cs
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Media.Imaging;
|
||||
using Avalonia.Threading;
|
||||
using LibVLCSharp.Shared;
|
||||
using PostIt.Services;
|
||||
using PostIt.ViewModels;
|
||||
|
||||
namespace PostIt.Views.Blogs;
|
||||
|
||||
/// <summary>Plays the owner-only draft source and captures marks for <see cref="ReplayEditorPageViewModel"/>.</summary>
|
||||
public partial class ReplayEditorPage : ContentPage
|
||||
{
|
||||
private readonly DispatcherTimer _positionTimer = new() { Interval = TimeSpan.FromMilliseconds(100) };
|
||||
private LibVLC? _libVlc;
|
||||
private MediaPlayer? _player;
|
||||
private PodcastReplayMediaInput? _input;
|
||||
private ReplayEditorPageViewModel? _vm;
|
||||
private string? _snapshotDirectory;
|
||||
private Task _snapshot = Task.CompletedTask;
|
||||
|
||||
public ReplayEditorPage()
|
||||
{
|
||||
InitializeComponent();
|
||||
_positionTimer.Tick += (_, _) =>
|
||||
{
|
||||
if (_player is { } player && _vm is { } vm) vm.CurrentTimeMs = Math.Max(0, player.Time);
|
||||
};
|
||||
}
|
||||
|
||||
protected override void OnNavigatedTo(NavigatedToEventArgs e)
|
||||
{
|
||||
base.OnNavigatedTo(e);
|
||||
InitializePlayer();
|
||||
}
|
||||
|
||||
protected override void OnNavigatedFrom(NavigatedFromEventArgs e)
|
||||
{
|
||||
ReleasePlayer();
|
||||
base.OnNavigatedFrom(e);
|
||||
}
|
||||
|
||||
protected override void OnDetachedFromVisualTree(Avalonia.VisualTreeAttachmentEventArgs e)
|
||||
{
|
||||
ReleasePlayer();
|
||||
base.OnDetachedFromVisualTree(e);
|
||||
}
|
||||
|
||||
private void InitializePlayer()
|
||||
{
|
||||
ReleasePlayer();
|
||||
if (Design.IsDesignMode || DataContext is not ReplayEditorPageViewModel vm) return;
|
||||
try
|
||||
{
|
||||
if (vm.SourceBytes <= 0) throw new InvalidOperationException("La source du brouillon n'est pas disponible.");
|
||||
_vm = vm;
|
||||
vm.SeekRequested += Seek;
|
||||
vm.CaptureThumbnail = CaptureThumbnailAsync;
|
||||
_snapshotDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"PostIt", "replay-editor", Guid.NewGuid().ToString("N"));
|
||||
_input = new PodcastReplayMediaInput(vm.PodcastClient, vm.Podcast.Id, vm.SourceBytes, draftSource: true);
|
||||
_input.Failed += InputFailed;
|
||||
_libVlc = new LibVLC();
|
||||
_player = new MediaPlayer(_libVlc);
|
||||
using var media = new Media(_libVlc, _input);
|
||||
var controls = new PostIt.Controls.ReplayControls(_player, replay: true);
|
||||
controls.PlaybackFailed += () => PlaybackStatus.Text = "Impossible de reprendre la lecture.";
|
||||
var surface = Platform.CreateVideoSurface?.Invoke(_player, true, () => PlaybackStatus.Text = "Impossible de reprendre la lecture.")
|
||||
?? new LibVLCSharp.Avalonia.VideoView { MediaPlayer = _player, Content = controls };
|
||||
VideoSurface.Content = surface;
|
||||
var player = _player;
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
if (ReferenceEquals(_player, player) && surface is LibVLCSharp.Avalonia.VideoView desktopVideo)
|
||||
desktopVideo.TryUpdateNativeControlPosition();
|
||||
}, DispatcherPriority.Loaded);
|
||||
PlaybackStatus.Text = "Source privee du brouillon.";
|
||||
if (!_player.Play(media)) PlaybackStatus.Text = "Impossible de lire la source du brouillon.";
|
||||
_positionTimer.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ReleasePlayer();
|
||||
PlaybackStatus.Text = $"Editeur indisponible : {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private void ReleasePlayer()
|
||||
{
|
||||
_positionTimer.Stop();
|
||||
if (_vm is not null)
|
||||
{
|
||||
_vm.SeekRequested -= Seek;
|
||||
_vm.CaptureThumbnail = null;
|
||||
_vm.ReleaseThumbnails();
|
||||
_vm = null;
|
||||
}
|
||||
_input?.Cancel();
|
||||
// The native snapshot must not run against a disposed player.
|
||||
try { _snapshot.Wait(TimeSpan.FromSeconds(2)); }
|
||||
catch (AggregateException) { }
|
||||
if (VideoSurface.Content is LibVLCSharp.Avalonia.VideoView desktopVideo) desktopVideo.MediaPlayer = null;
|
||||
if (VideoSurface.Content is IDisposable nativeSurface) nativeSurface.Dispose();
|
||||
VideoSurface.Content = null;
|
||||
if (_player is not null)
|
||||
{
|
||||
_player.Stop();
|
||||
_player.Dispose();
|
||||
_player = null;
|
||||
}
|
||||
_libVlc?.Dispose();
|
||||
_libVlc = null;
|
||||
if (_input is not null)
|
||||
{
|
||||
_input.Failed -= InputFailed;
|
||||
_input.Dispose();
|
||||
_input = null;
|
||||
}
|
||||
if (_snapshotDirectory is not null)
|
||||
{
|
||||
try { if (Directory.Exists(_snapshotDirectory)) Directory.Delete(_snapshotDirectory, true); }
|
||||
catch (IOException) { }
|
||||
_snapshotDirectory = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void InputFailed(string message) => Dispatcher.UIThread.Post(() => PlaybackStatus.Text = message);
|
||||
|
||||
private void Seek(long timeMs)
|
||||
{
|
||||
if (_player is not { IsSeekable: true } player) return;
|
||||
if (player.IsPlaying) player.SetPause(true);
|
||||
player.Time = timeMs;
|
||||
}
|
||||
|
||||
private void PreviousFrame_Click(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_player is not { IsSeekable: true } player) return;
|
||||
var frameMs = player.Fps > 0 ? 1000.0 / player.Fps : 1000.0 / 30;
|
||||
if (player.IsPlaying) player.SetPause(true);
|
||||
player.Time = Math.Max(0, player.Time - (long)Math.Ceiling(frameMs));
|
||||
}
|
||||
|
||||
private void NextFrame_Click(object? sender, RoutedEventArgs e) => _player?.NextFrame();
|
||||
|
||||
/// <summary>
|
||||
/// Snapshots the displayed frame into a private temporary file, loads it in memory and deletes the file:
|
||||
/// thumbnails of the private source never reach a shared cache.
|
||||
/// </summary>
|
||||
private async Task<Bitmap?> CaptureThumbnailAsync(CancellationToken ct)
|
||||
{
|
||||
if (_player is not { } player || _snapshotDirectory is not { } directory) return null;
|
||||
Directory.CreateDirectory(directory);
|
||||
var path = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".png");
|
||||
try
|
||||
{
|
||||
var snapshot = Task.Run(() => player.TakeSnapshot(0, path, 160, 0), ct);
|
||||
_snapshot = snapshot;
|
||||
if (!await snapshot || !File.Exists(path)) return null;
|
||||
await using var file = File.OpenRead(path);
|
||||
return new Bitmap(file);
|
||||
}
|
||||
finally { File.Delete(path); }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
namespace Yavsc.Services;
|
||||
namespace Yavsc.Abstract.Streaming;
|
||||
|
||||
/// <summary>A half-open time range [StartMs, EndMs) in the original replay timeline.</summary>
|
||||
public readonly record struct ReplayRange(long StartMs, long EndMs)
|
||||
|
|
@ -8,6 +8,7 @@ public readonly record struct ReplayRange(long StartMs, long EndMs)
|
|||
public long DurationMs => EndMs - StartMs;
|
||||
}
|
||||
|
||||
/// <summary>Validation and planning of replay cuts, shared by the server and the PostIt editor.</summary>
|
||||
public static class ReplayEditPlan
|
||||
{
|
||||
public const int MaxRemovedRanges = 200;
|
||||
|
|
@ -43,4 +44,22 @@ public static class ReplayEditPlan
|
|||
throw new ArgumentException("Ces suppressions retireraient toute la vidéo.", nameof(removed));
|
||||
return kept;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes removals as the server applies them: clamped to the source, merged when they overlap or touch,
|
||||
/// and ordered. Throws like <see cref="KeptRanges"/> for invalid or total removals.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<ReplayRange> RemovedRanges(IEnumerable<ReplayRange> removed, long durationMs)
|
||||
{
|
||||
var kept = KeptRanges(removed, durationMs);
|
||||
var result = new List<ReplayRange>();
|
||||
var position = 0L;
|
||||
foreach (var range in kept)
|
||||
{
|
||||
if (range.StartMs > position) result.Add(new ReplayRange(position, range.StartMs));
|
||||
position = range.EndMs;
|
||||
}
|
||||
if (position < durationMs) result.Add(new ReplayRange(position, durationMs));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
using Yavsc.Abstract.Streaming;
|
||||
|
||||
namespace Yavsc.Services;
|
||||
|
||||
public interface IPodcastReplayEditor
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Abstract.Streaming;
|
||||
|
||||
namespace Yavsc.Services;
|
||||
|
||||
|
|
|
|||
|
|
@ -212,6 +212,9 @@ public sealed class PodcastReplayTests : IDisposable
|
|||
Assert.Throws<ArgumentException>(() => ReplayEditPlan.KeptRanges([new(5000, 6000)], 5000));
|
||||
Assert.Throws<ArgumentException>(() => ReplayEditPlan.KeptRanges(
|
||||
Enumerable.Range(0, ReplayEditPlan.MaxRemovedRanges + 1).Select(i => new ReplayRange(i * 10, i * 10 + 5)), 5000));
|
||||
Assert.Equal([new ReplayRange(0, 3000), new ReplayRange(4000, 5000)],
|
||||
ReplayEditPlan.RemovedRanges([new(2000, 3000), new(1000, 2500), new(-500, 1000), new(4000, 9000)], 5000));
|
||||
Assert.Throws<ArgumentException>(() => ReplayEditPlan.RemovedRanges([new(0, 2000), new(2000, 5000)], 5000));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
|
|
|
|||
Loading…
Reference in a new issue