Wire the phase 5 parcels into one working whole. - Save frame works in a workspace project. WorkspaceSequenceSource now makes still jobs (IProjectStills) routed like its renders: with the originals on this PC, a WorkspaceRender still into exports/; with proxies only, the home's still job with the portable settings and the project id. The tooltip for a source that saves no frames is now a real string. - The Export footer has Save project file again for library sequences; workspace projects keep it in their project menu only. - Sync render downloads are hashed and compared with the server's sha256 (one retry, then the job fails without filing the file), and uploads and downloads carry the render kind, so a saved frame no longer counts as a recent preset. - Add the missing en/it strings: still frame out of the sequence (Core and both job handlers), keyframes not applicable, workspace stills, Videos refresh / clear sequence / play-from-server tips, the videos-folder creation error, and the admin panel kind labels, play and trash tips. - Delete the export history, batch and card strings no longer used from English and prune them from every culture. - Videos: the sequence chip clears only the sequence filter (desktop and admin panel), the desktop remembers cards or list, and a Refresh button. Refs #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
568 lines
30 KiB
C#
568 lines
30 KiB
C#
using System.IO;
|
||
using System.Net.Http;
|
||
using System.Windows.Input;
|
||
using Chronos.App.Infrastructure;
|
||
using Chronos.App.Jobs;
|
||
using Chronos.App.Sections;
|
||
using Chronos.App.Settings;
|
||
using Chronos.App.Shell;
|
||
using Chronos.App.Tests.Windows;
|
||
using Chronos.App.Videos;
|
||
using Chronos.Core.Localization;
|
||
using Chronos.Core.Model;
|
||
using Chronos.Core.Windows.Shell;
|
||
using Chronos.Data.Archiving.Jobs;
|
||
using Chronos.Data.Videos;
|
||
using Chronos.Protocol;
|
||
using Chronos.Testing;
|
||
using Chronos.Ui.Controls;
|
||
using Chronos.Ui.Mvvm;
|
||
|
||
namespace Chronos.App.Tests.Videos;
|
||
|
||
/// <summary>
|
||
/// The Videos library's sources (owner review 1, R9; decision 20): this PC's, the server's and the workspace's renders
|
||
/// merged by render id, the filters and the orders, the videos folder's checks, the player's fallback, and the copy's toast.
|
||
/// </summary>
|
||
public sealed class VideoSourcesTests
|
||
{
|
||
private static readonly Guid Harbour = Guid.CreateVersion7();
|
||
private static readonly Guid Comet = Guid.CreateVersion7();
|
||
|
||
[Test]
|
||
public void OneRowPerRenderWhereverItIs()
|
||
{
|
||
var shared = Guid.CreateVersion7();
|
||
var local = new[] { Local(shared, Harbour, "Harbour sunset", 100), Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 200) };
|
||
var server = new[] { Server(shared, Harbour, "Harbour sunset", 100, copies: ["/videos/harbour.mp4"]), Server(Guid.CreateVersion7(), Comet, "Comet", 300) };
|
||
var unsent = Unsent(Guid.CreateVersion7(), Comet);
|
||
// A render the workspace sent home already is the archive's: the workspace's row of it is dropped.
|
||
var sentAlready = Unsent(local[1].Id, Harbour);
|
||
|
||
var merged = VideoSources.Merge(local, server, [unsent, sentAlready]);
|
||
|
||
Assert.Equal(4, merged.Count);
|
||
Assert.Equal(merged.Count, merged.Select(e => e.Id).Distinct().Count());
|
||
var twin = merged.Single(e => e.Id == shared);
|
||
Assert.True(twin is { IsLocal: true, IsOnServer: true, IsUnsent: false }, "here and on the server: one row");
|
||
Assert.Equal(local[0].LocalPath, twin.LocalPath);
|
||
Assert.Contains("/videos/harbour.mp4", twin.Copies);
|
||
Assert.True(merged.Single(e => e.Id == server[1].Id) is { IsLocal: false, IsOnServer: true, LocalPath: null });
|
||
Assert.True(merged.Single(e => e.Id == local[1].Id) is { IsLocal: true, IsUnsent: false });
|
||
Assert.True(merged.Single(e => e.Id == unsent.Id).IsUnsent);
|
||
|
||
// Play says why it waits: only on the server, or gone from this PC.
|
||
Assert.Equal(Loc.L("Tooltips.Videos.Play"), VideoText.PlayToolTip(twin));
|
||
Assert.Equal(Loc.L("Tooltips.Videos.PlayServer"), VideoText.PlayToolTip(merged.Single(e => e.Id == server[1].Id)));
|
||
Assert.Equal(Loc.L("Tooltips.Videos.Missing"), VideoText.PlayToolTip(local[1] with { Missing = true }));
|
||
}
|
||
|
||
[Test]
|
||
public void TheFiltersNarrowAndTheOrdersSort()
|
||
{
|
||
var now = DateTimeOffset.UtcNow;
|
||
var old = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 500) with { Created = new DateTimeOffset(2024, 6, 1, 12, 0, 0, TimeSpan.Zero) };
|
||
var still = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 50) with { Kind = RenderKind.Still, Codec = "png", Created = now.AddDays(-1) };
|
||
var remote = Server(Guid.CreateVersion7(), Comet, "Comet over the lake", 900) with { Codec = "hevc", Created = now };
|
||
var unsent = Unsent(Guid.CreateVersion7(), Comet) with { Created = now.AddHours(-2) };
|
||
VideoEntry[] all = [old, still, remote, unsent];
|
||
|
||
Assert.SequenceEqual([remote.Id, unsent.Id, still.Id, old.Id], VideoFilter.None.Apply(all).Select(e => e.Id), "newest first by default");
|
||
Assert.SequenceEqual([old.Id, still.Id, unsent.Id, remote.Id], new VideoFilter { Sort = VideoSorts.Oldest }.Apply(all).Select(e => e.Id));
|
||
Assert.Equal(remote.Id, new VideoFilter { Sort = VideoSorts.Largest }.Apply(all)[0].Id);
|
||
Assert.Equal("Comet over the lake", new VideoFilter { Sort = VideoSorts.Title }.Apply(all)[0].Title);
|
||
|
||
Assert.SequenceEqual([still.Id], new VideoFilter { Kind = RenderKind.Still }.Apply(all).Select(e => e.Id));
|
||
Assert.SequenceEqual([remote.Id], new VideoFilter { Codec = "HEVC" }.Apply(all).Select(e => e.Id), "codecs match in any case");
|
||
Assert.SequenceEqual([old.Id], new VideoFilter { Year = 2024 }.Apply(all).Select(e => e.Id));
|
||
Assert.SequenceEqual([remote.Id], new VideoFilter { Source = VideoSourceFilter.Server }.Apply(all).Select(e => e.Id));
|
||
Assert.SequenceEqual([unsent.Id], new VideoFilter { Source = VideoSourceFilter.NotSent }.Apply(all).Select(e => e.Id));
|
||
Assert.Equal(3, new VideoFilter { Source = VideoSourceFilter.Local }.Apply(all).Count, "this PC: the archive's and the workspace's");
|
||
Assert.Equal(2, new VideoFilter { SequenceId = Comet }.Apply(all).Count);
|
||
Assert.SequenceEqual([unsent.Id], new VideoFilter { Text = "INSTAGRAM" }.Apply(all).Select(e => e.Id), "the preset name, in any case");
|
||
Assert.Equal(2, new VideoFilter { Text = "harbour" }.Apply(all).Count, "the title, the preset or the file name");
|
||
Assert.False(new VideoFilter { Sort = VideoSorts.Largest }.IsFiltered, "the order alone narrows nothing");
|
||
Assert.True(new VideoFilter { SequenceId = Comet }.IsFiltered);
|
||
}
|
||
|
||
[Test]
|
||
public void AnOlderServerIsToldApartFromOneWithVideos()
|
||
{
|
||
static IRemoteVideos Connect() => throw new InvalidOperationException("not connected");
|
||
var old = new ServerInfo("Studio NAS", "1.3.0", 1, [], null, [], new ServerLimits(0, 0));
|
||
Assert.Equal(VideoServerState.Old, VideoServer.Of(old, long.MaxValue, Connect).State);
|
||
Assert.Null(VideoServer.Of(old, long.MaxValue, Connect).Connect);
|
||
Assert.Equal(VideoServerState.SignedOut, VideoServer.Of(null, 0, Connect).State);
|
||
var current = old with { Capabilities = [ServerCapabilities.Videos] };
|
||
var reader = VideoServer.Of(current, 0, Connect);
|
||
Assert.True(reader is { State: VideoServerState.Available, CanEdit: false, CanDelete: false });
|
||
var editor = VideoServer.Of(current, (long)(Permissions.Edit | Permissions.Delete), Connect);
|
||
Assert.True(editor is { CanEdit: true, CanDelete: true });
|
||
}
|
||
|
||
[Test]
|
||
public void TheVideosFolderMustBeAbsoluteAndOutsideTheArchiveAndTheWorkspace()
|
||
{
|
||
var root = Path.Combine(Path.GetTempPath(), "chronos-videos-folder");
|
||
var archive = Path.Combine(root, "Archive");
|
||
var workspace = Path.Combine(root, "Workspace");
|
||
Assert.Equal(VideoErrors.FolderUnset, VideosFolders.Problem(null, archive));
|
||
Assert.Equal(VideoErrors.FolderUnset, VideosFolders.Problem(" ", archive));
|
||
Assert.Equal(VideoErrors.FolderInvalid, VideosFolders.Problem("relative\\videos", archive));
|
||
Assert.Equal(VideoErrors.FolderInvalid, VideosFolders.Problem(archive, archive, workspace));
|
||
Assert.Equal(VideoErrors.FolderInvalid, VideosFolders.Problem(Path.Combine(archive, "2026", "Videos"), archive, workspace));
|
||
Assert.Equal(VideoErrors.FolderInvalid, VideosFolders.Problem(Path.Combine(workspace, "Videos") + Path.DirectorySeparatorChar, archive, workspace));
|
||
Assert.Null(VideosFolders.Problem(Path.Combine(root, "Videos"), archive, workspace));
|
||
// A sibling whose name starts like the archive's is not inside it.
|
||
Assert.Null(VideosFolders.Problem(archive + " videos", archive, workspace));
|
||
Assert.Null(VideosFolders.Problem(Path.Combine(root, "Videos"), null, null));
|
||
if (VideosFolders.Default() is { } folder) Assert.True(Path.IsPathFullyQualified(folder) && folder.EndsWith("Chronos", StringComparison.Ordinal));
|
||
}
|
||
|
||
[Test]
|
||
public void ThePlayerSaysCannotPlayHereWhenWindowsCannotDecodeTheRender()
|
||
{
|
||
var folder = Directory.CreateTempSubdirectory("chronos-player").FullName;
|
||
try
|
||
{
|
||
var mp4 = Path.Combine(folder, "harbour.mp4");
|
||
var png = Path.Combine(folder, "harbour.png");
|
||
var odd = Path.Combine(folder, "harbour.xyz");
|
||
foreach (var path in new[] { mp4, png, odd }) File.WriteAllBytes(path, [0, 1, 2, 3]);
|
||
var video = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 4) with { LocalPath = mp4, FileName = "harbour.mp4" };
|
||
|
||
Assert.Equal(VideoPlayerMode.Video, VideoPlayerViewModel.ModeOf(video));
|
||
Assert.Equal(VideoPlayerMode.Image, VideoPlayerViewModel.ModeOf(video with { LocalPath = png, Kind = RenderKind.Still }));
|
||
Assert.Equal(VideoPlayerMode.CannotPlay, VideoPlayerViewModel.ModeOf(video with { LocalPath = odd }), "an extension Windows does not play");
|
||
Assert.Equal(VideoPlayerMode.CannotPlay, VideoPlayerViewModel.ModeOf(video with { LocalPath = Path.Combine(folder, "gone.mp4") }), "the file is gone");
|
||
Assert.Equal(VideoPlayerMode.CannotPlay, VideoPlayerViewModel.ModeOf(video with { Kind = RenderKind.Sequence, LocalPath = folder }), "a folder of images");
|
||
Assert.Equal(VideoPlayerMode.CannotPlay, VideoPlayerViewModel.ModeOf(video with { LocalPath = null, IsLocal = false, IsOnServer = true }), "the server's alone");
|
||
|
||
// Windows fails to decode the file once it is opened: the pane says so and keeps Show in folder.
|
||
var player = new VideoPlayerViewModel(video, new RelayCommand(() => { }), new RelayCommand(() => { }));
|
||
Assert.True(player is { IsVideo: true, CannotPlay: false });
|
||
Assert.NotNull(player.Source);
|
||
player.MediaFailed(new InvalidOperationException("0xC00D36C4"));
|
||
Assert.True(player is { Mode: VideoPlayerMode.CannotPlay, IsVideo: false, CannotPlay: true, CanShowInFolder: true });
|
||
Assert.Equal(Loc.L("Videos.Player.CannotPlay"), player.CannotPlayText);
|
||
}
|
||
finally
|
||
{
|
||
Directory.Delete(folder, recursive: true);
|
||
}
|
||
}
|
||
|
||
[Test]
|
||
public void ACopyToTheVideosFolderEndsWithAToast()
|
||
{
|
||
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.VideoCopy, State = JobState.Done };
|
||
Assert.Equal(JobNotice.Done, JobNotices.For(JobState.Running, job));
|
||
Assert.Equal(JobNotice.Failed, JobNotices.For(JobState.Running, job with { State = JobState.Failed }));
|
||
}
|
||
|
||
internal static VideoEntry Local(Guid id, Guid sequence, string title, long bytes) => new()
|
||
{
|
||
Id = id,
|
||
SequenceId = sequence,
|
||
Title = title,
|
||
PresetName = "YouTube 4K",
|
||
Codec = "h264",
|
||
Width = 3840,
|
||
Height = 2160,
|
||
Fps = 25,
|
||
DurationSeconds = 12,
|
||
Bytes = bytes,
|
||
Created = DateTimeOffset.UtcNow.AddMinutes(-bytes),
|
||
Kind = RenderKind.Video,
|
||
FileName = "harbour.mp4",
|
||
LocalPath = Path.Combine(Path.GetTempPath(), "harbour-" + id.ToString("N") + ".mp4"),
|
||
IsLocal = true,
|
||
};
|
||
|
||
private static VideoEntry Server(Guid id, Guid sequence, string title, long bytes, IReadOnlyList<string>? copies = null) =>
|
||
VideoSources.FromServer(new VideoDto(id, sequence, "YouTube 4K", "h264", 3840, 2160, 25, 12, bytes, DateTimeOffset.UtcNow.AddMinutes(-bytes), "server", null, null,
|
||
null, RenderKind.Video, title, null, null, null, VideoStates.Ok, [.. (copies ?? []).Select(p => new VideoCopyDto(p, DateTimeOffset.UtcNow))],
|
||
"comet.mp4"));
|
||
|
||
private static VideoEntry Unsent(Guid id, Guid sequence) => new()
|
||
{
|
||
Id = id,
|
||
SequenceId = sequence,
|
||
Title = "Comet over the lake",
|
||
PresetName = "Instagram",
|
||
Codec = "h264",
|
||
Bytes = 10,
|
||
Created = DateTimeOffset.UtcNow,
|
||
Kind = RenderKind.Video,
|
||
FileName = "comet-instagram.mp4",
|
||
LocalPath = Path.Combine(Path.GetTempPath(), "comet-instagram.mp4"),
|
||
IsUnsent = true,
|
||
WorkspaceProjectId = Guid.CreateVersion7(),
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// The Videos section in the shell: an older server leaves this PC's videos with the reason, Delete… runs the dry run first
|
||
/// and shows its bytes and what stays, Copy to folder says why without a videos folder, and Ctrl+4 opens it (Archive Ctrl+5).
|
||
/// </summary>
|
||
[WindowsOnly]
|
||
[Serial]
|
||
[Timeout(120_000)]
|
||
public sealed class VideosSectionTests(TestContext context)
|
||
{
|
||
[Test]
|
||
public Task AnOlderServerListsThisPcsVideosWithTheReason() => WithSectionAsync(async (shell, section, library, _) =>
|
||
{
|
||
var info = new ServerInfo("Studio NAS", "1.3.0", 1, [], null, [], new ServerLimits(0, 0));
|
||
section.ServerVideos = () => VideoServer.Of(info, long.MaxValue, () => throw new InvalidOperationException("an older server is never asked"));
|
||
await section.RefreshAsync();
|
||
|
||
Assert.Equal(library.Items.Count, section.Rows.Count);
|
||
Assert.True(section.Rows.All(r => r.Entry.IsLocal));
|
||
Assert.Equal(VideoServerState.Old, section.ServerState);
|
||
Assert.True(section.IsServerLimited, "the status line shows");
|
||
Assert.Equal(Loc.L("Tooltips.Videos.ServerOld"), section.ServerStatusToolTip);
|
||
Assert.Equal(Loc.L("Tooltips.Videos.ServerOld"), section.CopyOnServerBlocker(section.Rows));
|
||
|
||
// A server with the library lists its videos with this PC's, one row per render.
|
||
var remote = new FakeRemote([Dto(library.Items[0]), Dto(library.Items[0]) with { Id = Guid.CreateVersion7(), FileName = "server-only.mp4" }]);
|
||
section.ServerVideos = () => VideoServer.Of(info with { Capabilities = [ServerCapabilities.Videos] }, (long)Permissions.Edit, () => remote);
|
||
await section.RefreshAsync();
|
||
Assert.Equal(VideoServerState.Available, section.ServerState);
|
||
Assert.False(section.IsServerLimited);
|
||
Assert.Equal(library.Items.Count + 1, section.Rows.Count);
|
||
Assert.True(section.Rows.Single(r => r.Entry.Id == library.Items[0].Render.Id).Entry is { IsLocal: true, IsOnServer: true });
|
||
|
||
// The server stops answering: this PC's videos stay, with the reason.
|
||
section.ServerVideos = () => VideoServer.Of(info with { Capabilities = [ServerCapabilities.Videos] }, 0, () => new FakeRemote([], fails: true));
|
||
await section.RefreshAsync();
|
||
Assert.Equal(VideoServerState.Unreachable, section.ServerState);
|
||
Assert.Equal(library.Items.Count, section.Rows.Count);
|
||
Assert.Equal(Loc.L("Videos.ServerUnreachable"), section.ServerStatusText);
|
||
Assert.Empty(shell.PendingToasts.Where(t => t.IsError));
|
||
});
|
||
|
||
[Test]
|
||
public Task TheFiltersOfTheSectionNarrowItsRows() => WithSectionAsync(async (_, section, library, _) =>
|
||
{
|
||
await section.RefreshAsync();
|
||
Assert.Equal(3, section.Rows.Count);
|
||
section.SelectedKind = section.Kinds.Single(k => k.Value == RenderKind.Still);
|
||
Assert.True(section.IsKindFiltered);
|
||
Assert.Equal(library.Items[2].Render.Id, Assert.NotNull(section.Rows.SingleOrDefault()).Entry.Id);
|
||
section.SelectedKind = section.Kinds[0];
|
||
section.SearchText = "no such video";
|
||
Assert.True(section.IsNoMatch);
|
||
Assert.True(section.ClearFiltersCommand.CanExecute(null));
|
||
section.ClearFiltersCommand.Execute(null);
|
||
Assert.Equal(3, section.Rows.Count);
|
||
section.SelectedSort = section.Sorts.Single(s => s.Value == VideoSorts.Largest);
|
||
Assert.Equal(library.Items.Max(i => i.Render.Bytes), section.Rows[0].Entry.Bytes);
|
||
// The Export footer's Videos: one sequence's renders, its title as the chip that clears it.
|
||
section.ShowSequence(library.Items[1].Render.SequenceId, "Comet");
|
||
Assert.True(section.IsSequenceFiltered);
|
||
Assert.Equal("Comet", section.SequenceFilterText);
|
||
Assert.True(section.Rows.All(r => r.Entry.SequenceId == library.Items[1].Render.SequenceId));
|
||
// Selected rows stay selected when the list is made again.
|
||
section.Rows[0].IsSelected = true;
|
||
section.SearchText = "comet";
|
||
Assert.True(section.Rows[0].IsSelected);
|
||
Assert.True(section.HasSelection);
|
||
// The chip's × clears the sequence only: the search and the order stay.
|
||
Assert.True(section.ClearSequenceCommand.CanExecute(null));
|
||
section.ClearSequenceCommand.Execute(null);
|
||
Assert.False(section.IsSequenceFiltered);
|
||
Assert.Equal("comet", section.SearchText);
|
||
Assert.Equal(VideoSorts.Largest, section.SelectedSort.Value);
|
||
Assert.False(section.ClearSequenceCommand.CanExecute(null));
|
||
});
|
||
|
||
[Test]
|
||
public Task DeleteRunsTheDryRunFirstAndShowsItsBytesAndWhatStays() => WithSectionAsync(async (shell, section, library, dialogs) =>
|
||
{
|
||
await section.RefreshAsync();
|
||
foreach (var row in section.Rows.Where(r => r.Entry.Id != library.Items[2].Render.Id)) row.IsSelected = true;
|
||
var selected = section.SelectedRows;
|
||
Assert.Equal(2, selected.Count);
|
||
Assert.Null(section.DeleteBlocker(selected));
|
||
|
||
// Kept: the plan was made, nothing was deleted.
|
||
dialogs.Answer = false;
|
||
await section.DeleteAsync(selected);
|
||
Assert.SequenceEqual(["plan"], library.Calls);
|
||
var request = Assert.NotNull(dialogs.Requests.SingleOrDefault());
|
||
var plans = Assert.NotNull(section.LastDeletePlans);
|
||
Assert.Equal(1, plans.Blocked);
|
||
Assert.True(request.IsDestructive);
|
||
Assert.Contains(Formatting.Bytes(library.Items[0].Render.Bytes), request.Message, "the bytes that go (a missing file counts nothing)");
|
||
Assert.Contains(Loc.L("Videos.Delete.Missing"), request.Message);
|
||
Assert.Contains(Loc.L("Videos.Delete.Blocked", Formatting.Count(1)), request.Detail!);
|
||
Assert.Contains(VideoText.BlockReason(VideoBlockReasons.Busy), request.Detail!);
|
||
|
||
// Confirmed: the delete gives back the plan's fingerprint.
|
||
dialogs.Answer = true;
|
||
await section.DeleteAsync(selected);
|
||
Assert.SequenceEqual(["plan", "plan", "delete:fingerprint-2"], library.Calls);
|
||
Assert.Contains(shell.PendingToasts, t => t.Title == Loc.L("Videos.Delete.Done", Formatting.Count(2)) && !t.IsError);
|
||
Assert.Equal(1, section.Rows.Count);
|
||
});
|
||
|
||
[Test]
|
||
public Task ACopyWithoutAVideosFolderSaysWhy() => WithSectionAsync(async (shell, section, library, _) =>
|
||
{
|
||
var queued = new List<ArchiveJobRequest>();
|
||
section.Enqueue = request =>
|
||
{
|
||
queued.Add(request);
|
||
return Task.CompletedTask;
|
||
};
|
||
await section.RefreshAsync();
|
||
var row = section.Rows.Single(r => r.Entry.Id == library.Items[0].Render.Id);
|
||
row.IsSelected = true;
|
||
|
||
section.Folder = () => null;
|
||
Assert.Equal(Loc.L("Tooltips.Videos.FolderUnset"), section.CopyBlocker([row]));
|
||
Assert.Equal(Loc.L("Tooltips.Videos.FolderUnset"), section.CopyToolTip);
|
||
Assert.False(section.CopyCommand.CanExecute(null));
|
||
await section.CopyAsync([row]);
|
||
Assert.Empty(queued);
|
||
Assert.Contains(shell.PendingToasts, t => t.Title == Loc.L("Tooltips.Videos.FolderUnset") && t.IsError);
|
||
|
||
// Inside the workspace: refused too.
|
||
section.Folder = () => Path.Combine(shell.Services.Workspace.Root, "Videos");
|
||
Assert.Equal(Loc.L("Errors.Videos.FolderInsideArchive"), section.CopyBlocker([row]));
|
||
|
||
// A folder of its own: one copy job of this PC's render, the folder given in full.
|
||
var folder = context.CreateTempDirectory("videos-folder");
|
||
section.Folder = () => folder;
|
||
Assert.Null(section.CopyBlocker([row]));
|
||
await section.CopyAsync([row]);
|
||
var job = Assert.NotNull(queued.SingleOrDefault());
|
||
Assert.Equal(JobKind.VideoCopy, job.Kind);
|
||
var parameters = Assert.NotNull(VideoCopyParameters.Read(job.ParametersJson));
|
||
Assert.SequenceEqual([row.Entry.Id], parameters.RenderIds);
|
||
Assert.Equal(Path.GetFullPath(folder), parameters.Folder);
|
||
Assert.False(parameters.FromServer);
|
||
});
|
||
|
||
[Test]
|
||
public Task CtrlFourOpensVideosAndCtrlFiveTheArchive() => WithSectionAsync(async (shell, section, _, _) =>
|
||
{
|
||
Assert.SequenceEqual([SectionKey.Library, SectionKey.Import, SectionKey.Edit, SectionKey.Videos, SectionKey.Archive, SectionKey.Jobs, SectionKey.Server],
|
||
shell.TopSections.Select(s => s.Key));
|
||
var window = new MainWindow(shell);
|
||
try
|
||
{
|
||
var bindings = window.InputBindings.OfType<KeyBinding>().Where(b => b.Modifiers == ModifierKeys.Control).ToList();
|
||
foreach (var (key, expected) in new[]
|
||
{
|
||
(Key.D4, SectionKey.Videos), (Key.NumPad4, SectionKey.Videos), (Key.D5, SectionKey.Archive), (Key.NumPad5, SectionKey.Archive),
|
||
(Key.D6, SectionKey.Jobs), (Key.D7, SectionKey.Server),
|
||
})
|
||
{
|
||
var binding = bindings.Single(b => b.Key == key);
|
||
Assert.True(binding.Command.CanExecute(binding.CommandParameter), $"Ctrl+{key}");
|
||
binding.Command.Execute(binding.CommandParameter);
|
||
Assert.Equal(expected, shell.Current.Key, $"Ctrl+{key}");
|
||
}
|
||
shell.OpenVideos(Guid.CreateVersion7(), "Harbour sunset");
|
||
Assert.Same(section, shell.Current);
|
||
Assert.Equal("Harbour sunset", section.SequenceFilterText);
|
||
await section.RefreshAsync();
|
||
}
|
||
finally
|
||
{
|
||
window.Close();
|
||
}
|
||
});
|
||
|
||
[Test]
|
||
public Task TheSectionLaysOutAsCardsAListAndWithThePlayer() => WithSectionAsync(async (shell, section, library, _) =>
|
||
{
|
||
await section.RefreshAsync();
|
||
var view = new VideosView { DataContext = section };
|
||
Layout(view);
|
||
Assert.Equal(LibraryLayout.Grid, shell.Services.Settings.VideosLayout);
|
||
section.LayoutIndex = 1;
|
||
Assert.Equal(LibraryLayout.List, shell.Services.Settings.VideosLayout, "the list is kept for the next run");
|
||
Assert.Equal(1, new VideosViewModel(shell).LayoutIndex, "and a new section opens on it");
|
||
section.Rows[0].IsSelected = true;
|
||
Assert.Equal(Loc.L("Tooltips.Videos.Play"), section.PlayToolTip);
|
||
Assert.True(section.PlayCommand.CanExecute(null));
|
||
section.PlayCommand.Execute(null);
|
||
var player = Assert.NotNull(section.Player);
|
||
Assert.Equal(library.Items[0].Render.Id, player.Entry.Id);
|
||
Layout(view);
|
||
section.ClosePlayerCommand.Execute(null);
|
||
Assert.False(section.IsPlayerOpen);
|
||
// Settings › Archive shows the videos folder row.
|
||
shell.Settings.Page = SettingsPage.Archive;
|
||
var field = shell.Settings.VideosFolder;
|
||
Assert.Equal(shell.Services.Settings.VideosFolder ?? string.Empty, field.Text);
|
||
Layout(new SettingsView { DataContext = shell.Settings });
|
||
field.Text = Path.Combine(shell.Services.Workspace.Root, "Videos");
|
||
Assert.False(field.Commit(), "never inside the workspace");
|
||
Assert.Equal(Loc.L("Errors.Videos.FolderInsideArchive"), field.Error);
|
||
field.Text = string.Empty;
|
||
Assert.True(field.Commit());
|
||
Assert.Null(shell.Services.Settings.VideosFolder);
|
||
var folder = context.CreateTempDirectory("videos-setting");
|
||
field.Text = folder;
|
||
Assert.True(field.Commit());
|
||
Assert.Equal(Path.GetFullPath(folder), shell.Services.Settings.VideosFolder);
|
||
Assert.True(shell.Settings.OpenVideosFolderCommand.CanExecute(null));
|
||
});
|
||
|
||
private static void Layout(System.Windows.FrameworkElement view)
|
||
{
|
||
view.Measure(new System.Windows.Size(1200, 800));
|
||
view.Arrange(new System.Windows.Rect(0, 0, 1200, 800));
|
||
view.UpdateLayout();
|
||
}
|
||
|
||
/// <summary>The section of a shell on a fresh data folder, reading <see cref="FakeLibrary"/>, signed out, no workspace renders.</summary>
|
||
private Task WithSectionAsync(Func<ShellViewModel, VideosViewModel, FakeLibrary, ScriptedDialogs, Task> body) => ScreenHost.RunAsync(async () =>
|
||
{
|
||
var directory = context.CreateTempDirectory("videos-section");
|
||
var environment = AppEnvironment.From(AppPaths.Resolve(Directory.CreateDirectory(Path.Combine(directory, "app")).FullName,
|
||
Directory.CreateDirectory(Path.Combine(directory, "local")).FullName, []));
|
||
UiLanguage.Apply("en");
|
||
var dialogs = new ScriptedDialogs();
|
||
var settings = new AppSettings { Language = "en", FirstRunCompleted = true, CheckForUpdates = false };
|
||
var services = new AppServices(environment, settings, () => { }, dialogs);
|
||
var shell = new ShellViewModel(services);
|
||
var library = new FakeLibrary(directory);
|
||
var section = shell.Videos;
|
||
section.LocalLibrary = () => library;
|
||
section.ServerVideos = () => VideoServer.SignedOut;
|
||
section.WorkspaceRenders = _ => Task.FromResult<IReadOnlyList<VideoEntry>>([]);
|
||
section.Posters = (_, _, _) => Task.FromResult<System.Windows.Media.ImageSource?>(null);
|
||
try
|
||
{
|
||
await body(shell, section, library, dialogs);
|
||
}
|
||
finally
|
||
{
|
||
shell.Dispose();
|
||
await services.DisposeAsync();
|
||
}
|
||
});
|
||
|
||
private static VideoDto Dto(VideoItem item) =>
|
||
new(item.Render.Id, item.Render.SequenceId, item.Render.PresetName, item.Render.Codec, item.Render.Width, item.Render.Height, item.Render.Fps,
|
||
item.Render.DurationSeconds, item.Render.Bytes, item.Render.Created, null, null, null, null, item.Kind, item.SequenceTitle, null, null, null, VideoStates.Ok, [],
|
||
item.FileName);
|
||
|
||
/// <summary>This PC's videos library: a video, a missing one and a still; its delete plan leaves one render, busy, where it is.</summary>
|
||
private sealed class FakeLibrary : IVideoLibrary
|
||
{
|
||
private int _plans;
|
||
|
||
public FakeLibrary(string folder)
|
||
{
|
||
var harbour = Guid.CreateVersion7();
|
||
var comet = Guid.CreateVersion7();
|
||
Items =
|
||
[
|
||
Item(harbour, "Harbour sunset", Path.Combine(folder, "harbour-4k.mp4"), 40_000_000, null, missing: false, DateTimeOffset.UtcNow.AddHours(-1)),
|
||
Item(comet, "Comet", Path.Combine(folder, "comet.mp4"), 9_000_000, null, missing: true, DateTimeOffset.UtcNow.AddHours(-2)),
|
||
Item(harbour, "Harbour sunset", Path.Combine(folder, "harbour.png"), 2_000_000, RenderKind.Still, missing: false, DateTimeOffset.UtcNow.AddHours(-3)),
|
||
];
|
||
File.WriteAllBytes(Items[0].FullPath, [0, 1, 2]);
|
||
}
|
||
|
||
public List<VideoItem> Items { get; }
|
||
|
||
public List<string> Calls { get; } = [];
|
||
|
||
public bool IsAvailable => true;
|
||
|
||
public Task<VideoPage> ListAsync(VideoQuery query, CancellationToken cancellationToken = default) => Task.FromResult(new VideoPage([.. Items], null, Items.Count));
|
||
|
||
public Task<VideoItem?> GetAsync(Guid renderId, CancellationToken cancellationToken = default) => Task.FromResult(Items.FirstOrDefault(i => i.Render.Id == renderId));
|
||
|
||
public Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default)
|
||
{
|
||
lock (Calls) Calls.Add("plan");
|
||
// Both go (the missing one only loses its row); another render, being sent, is named as staying.
|
||
var wanted = Items.Where(i => renderIds.Contains(i.Render.Id)).ToList();
|
||
var stays = new VideoBlocked(Items[2].Render.Id, VideoBlockReasons.Busy, Items[2]);
|
||
return Task.FromResult(new VideoDeletePlan(wanted, [stays], "fingerprint-" + Interlocked.Increment(ref _plans)));
|
||
}
|
||
|
||
public Task<VideoDeleteResult> DeleteAsync(IReadOnlyList<Guid> renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default)
|
||
{
|
||
lock (Calls) Calls.Add("delete:" + fingerprint);
|
||
var gone = Items.Where(i => renderIds.Contains(i.Render.Id)).ToList();
|
||
Items.RemoveAll(gone.Contains);
|
||
return Task.FromResult(new VideoDeleteResult(gone, [], []));
|
||
}
|
||
|
||
public Task<Render> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||
|
||
public string? FolderProblem(string? folder) => string.IsNullOrWhiteSpace(folder) ? VideoErrors.FolderUnset : null;
|
||
|
||
public ArchiveJobRequest CopyJob(VideoCopyParameters parameters) =>
|
||
new(JobKind.VideoCopy, parameters.RenderIds, null, parameters.ToJson(), JobPriority.User);
|
||
|
||
private static VideoItem Item(Guid sequence, string title, string path, long bytes, string? kind, bool missing, DateTimeOffset created) => new()
|
||
{
|
||
Render = new Render
|
||
{
|
||
Id = Guid.CreateVersion7(),
|
||
SequenceId = sequence,
|
||
PresetName = kind == RenderKind.Still ? "Still" : "YouTube 4K",
|
||
OutputPath = Path.GetFileName(path),
|
||
Codec = kind == RenderKind.Still ? "png" : "h264",
|
||
Width = 3840,
|
||
Height = 2160,
|
||
Fps = 25,
|
||
DurationSeconds = kind == RenderKind.Still ? 0 : 12,
|
||
Bytes = bytes,
|
||
Created = created,
|
||
Kind = kind,
|
||
},
|
||
SequenceTitle = title,
|
||
FullPath = path,
|
||
Missing = missing,
|
||
};
|
||
}
|
||
|
||
/// <summary>The signed-in server's videos library; <c>fails</c>: the server does not answer.</summary>
|
||
private sealed class FakeRemote(IReadOnlyList<VideoDto> videos, bool fails = false) : IRemoteVideos
|
||
{
|
||
public Task<VideoPageDto> ListAsync(VideoQueryDto query, CancellationToken cancellationToken = default) =>
|
||
fails ? throw new HttpRequestException("unreachable") : Task.FromResult(new VideoPageDto(videos, null, videos.Count));
|
||
|
||
public Task<VideoDeletePlanDto> PlanDeleteAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||
|
||
public Task<VideoDeletePlanDto> DeleteAsync(IReadOnlyList<Guid> ids, string fingerprint, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||
|
||
public Task<VideoCopyResultDto> CopyAsync(IReadOnlyList<Guid> ids, CancellationToken cancellationToken = default) => Task.FromResult(new VideoCopyResultDto(Guid.CreateVersion7()));
|
||
|
||
public void Dispose()
|
||
{
|
||
}
|
||
}
|
||
|
||
/// <summary>Records every confirmation asked and answers it as told.</summary>
|
||
private sealed class ScriptedDialogs : IAppDialogs
|
||
{
|
||
public bool Answer { get; set; }
|
||
|
||
public List<ConfirmRequest> Requests { get; } = [];
|
||
|
||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||
|
||
public string? PickJsonFile(string title) => null;
|
||
|
||
public bool Confirm(ConfirmRequest request)
|
||
{
|
||
Requests.Add(request);
|
||
return Answer;
|
||
}
|
||
|
||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||
}
|
||
}
|