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; /// /// 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. /// 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 AServersVideoDownloadedHerePlaysFromItsCopy() { var remote = Server(Guid.CreateVersion7(), Comet, "Comet", 300, copies: ["/videos/comet.mp4"]); var gone = Server(Guid.CreateVersion7(), Comet, "Comet", 300); var local = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 100); var copy = @"C:\Users\me\Videos\Chronos\comet.mp4"; var copies = new Dictionary> { [remote.Id] = [copy], [gone.Id] = [@"C:\Users\me\Videos\Chronos\deleted.mp4"], [local.Id] = [@"C:\elsewhere\harbour.mp4"], }; var entries = VideoSources.WithLocalCopies([remote, gone, local], copies, path => path == copy); var downloaded = entries[0]; Assert.Equal(copy, downloaded.LocalPath); Assert.True(downloaded.HasLocalFile, "Play and Show in folder use the copy"); Assert.SequenceEqual(["/videos/comet.mp4", copy], downloaded.Copies); Assert.Contains(VideoText.States(downloaded), s => s.Text == Loc.L("Videos.State.Copied")); Assert.Equal(Loc.L("Tooltips.Videos.Play"), VideoText.PlayToolTip(downloaded)); // A copy deleted since names no file to play, but is still listed; this PC's own render keeps its file. Assert.True(entries[1] is { LocalPath: null, HasLocalFile: false }); Assert.Same(local, entries[2]); } [Test] public void AServersVideoThatStaysIsNamedNotNumbered() { var known = Server(Guid.CreateVersion7(), Comet, "Comet", 300); var unknown = Guid.CreateVersion7(); var server = new VideoDeletePlanDto([], 0, [new VideoBlockedDto(known.Id, VideoBlockReasons.Busy), new VideoBlockedDto(unknown, VideoBlockReasons.NotFound)], "f", DryRun: true); var lines = new VideoDeletePlans(null, server, new Dictionary { [known.Id] = VideoDeletePlans.NameOf(known) }).Lines(); Assert.Contains("Comet" + Loc.Separator + Formatting.LeftToRight("comet.mp4") + Loc.Separator + VideoText.BlockReason(VideoBlockReasons.Busy), lines); Assert.Contains(unknown.ToString("D") + Loc.Separator + VideoText.BlockReason(VideoBlockReasons.NotFound), lines, "an id the section does not show"); } [Test] public void TheDetailsLeaveOutWhatARenderDoesNotHave() { var video = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 1_000_000); var still = video with { Kind = RenderKind.Still, Codec = "PngSequence", DurationSeconds = 0, Width = 6000, Height = 4000 }; Assert.Equal(string.Join(Loc.Separator, "3840×2160", "H.264", VideoText.Duration(video), Formatting.Bytes(video.Bytes)), VideoText.Details(video)); Assert.Equal(string.Join(Loc.Separator, "6000×4000", "PNG", Formatting.Bytes(still.Bytes)), VideoText.Details(still), "no empty duration"); Assert.Equal(string.Join(Loc.Separator, "6000×4000", Formatting.Bytes(still.Bytes)), VideoText.Details(still with { Codec = null })); } [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? 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(), }; } /// /// 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). /// [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) row.IsSelected = true; var selected = section.SelectedRows; Assert.Equal(3, 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 with exactly the ids planned, the one that stays included // (a fingerprint of fewer ids would never match). dialogs.Answer = true; var asked = selected.Select(r => r.Entry.Id).ToList(); await section.DeleteAsync(selected); Assert.SequenceEqual(["plan", "plan", "delete:fingerprint-2"], library.Calls); Assert.SequenceEqual(asked.Order(), library.DeletedIds.Order()); 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 ADisabledActionSaysWhyInTheBarAndInTheMenu() => WithSectionAsync(async (shell, section, library, _) => { await section.RefreshAsync(); var video = section.Rows.Single(r => r.Entry.Id == library.Items[0].Render.Id); var missing = section.Rows.Single(r => r.Entry.Id == library.Items[1].Render.Id); // Signed out: Copy on server gives the server's reason, in the row's menu too. Assert.Equal(Loc.L("Tooltips.Videos.ServerOffline"), video.MenuCopyOnServerToolTip); Assert.Equal(Loc.L("Tooltips.Videos.Missing"), missing.MenuShowInFolderToolTip); Assert.Equal(Loc.L("Tooltips.Videos.ShowInFolder"), video.MenuShowInFolderToolTip); Assert.Equal(Loc.L("Tooltips.Videos.Missing"), missing.MenuCopyToolTip, "the menu's Copy gives the row's reason"); // Two selected: Play, Show in folder and Open in Edit act on one video, and say so. video.IsSelected = true; missing.IsSelected = true; Assert.False(section.PlayCommand.CanExecute(null)); Assert.Equal(Loc.L("Tooltips.Videos.SelectOne"), section.PlayToolTip); Assert.Equal(Loc.L("Tooltips.Videos.SelectOne"), section.ShowInFolderToolTip); Assert.Equal(Loc.L("Tooltips.Videos.SelectOne"), section.OpenInEditToolTip); Assert.Equal(Loc.L("Tooltips.Videos.SelectOne"), video.MenuPlayToolTip, "a selected row's menu acts on the selection"); // A server's video alone: not on this PC. var remote = new VideoRowViewModel(VideoSources.FromServer(Dto(library.Items[0]) with { Id = Guid.CreateVersion7() })); Assert.Equal(Loc.L("Tooltips.Videos.ServerOnly"), VideosViewModel.OpenInEditToolTipOf([remote])); Assert.Equal(Loc.L("Tooltips.Videos.ServerOnly"), VideosViewModel.ShowInFolderToolTipOf([remote])); Assert.Equal(Loc.L("Videos.Download"), VideosViewModel.CopyTextOf([remote])); }); [Test] public Task ACopyWithoutAVideosFolderSaysWhy() => WithSectionAsync(async (shell, section, library, _) => { var queued = new List(); 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().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); // Beside the player, at 1000 px too (a 1200 px window with the rail open), the list keeps its state column in view: // the preset, format and date columns give way. Layout(view, 1000); var pane = Descendants(view).OfType().Single(); var paneLeft = pane.TranslatePoint(new System.Windows.Point(0, 0), view).X; foreach (var header in new[] { "Videos.Column.State", "Videos.Column.Size" }) { var cell = Descendants(view).OfType().First(t => t.Text == Loc.L(header)); Assert.True(cell.ActualWidth > 0, header); Assert.True(cell.TranslatePoint(new System.Windows.Point(cell.ActualWidth, 0), view).X <= paneLeft, $"{header} runs under the player"); } Assert.Equal(System.Windows.Visibility.Collapsed, Descendants(view).OfType().First(t => t.Text == Loc.L("Videos.Column.Date")).Visibility); 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, double width = 1200) { view.Measure(new System.Windows.Size(width, 800)); view.Arrange(new System.Windows.Rect(0, 0, width, 800)); view.UpdateLayout(); } private static IEnumerable Descendants(System.Windows.DependencyObject root) { for (var i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(root); i++) { var child = System.Windows.Media.VisualTreeHelper.GetChild(root, i); yield return child; foreach (var below in Descendants(child)) yield return below; } } /// The section of a shell on a fresh data folder, reading , signed out, no workspace renders. private Task WithSectionAsync(Func 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>([]); section.Posters = (_, _, _) => Task.FromResult(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); /// This PC's videos library: a video, a missing one and a still; its delete plan leaves one render, busy, where it is. 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 Items { get; } public List Calls { get; } = []; /// The ids the last delete was asked for. public List DeletedIds { get; private set; } = []; public bool IsAvailable => true; public Task ListAsync(VideoQuery query, CancellationToken cancellationToken = default) => Task.FromResult(new VideoPage([.. Items], null, Items.Count)); public Task GetAsync(Guid renderId, CancellationToken cancellationToken = default) => Task.FromResult(Items.FirstOrDefault(i => i.Render.Id == renderId)); public Task PlanDeleteAsync(IReadOnlyList renderIds, CancellationToken cancellationToken = default) { lock (Calls) Calls.Add("plan"); // Both go (the missing one only loses its row); the still, being sent, is named as staying. var stays = new VideoBlocked(Items[2].Render.Id, VideoBlockReasons.Busy, Items[2]); var wanted = Items.Where(i => renderIds.Contains(i.Render.Id) && i.Render.Id != stays.RenderId).ToList(); return Task.FromResult(new VideoDeletePlan(wanted, [stays], "fingerprint-" + Interlocked.Increment(ref _plans))); } public Task DeleteAsync(IReadOnlyList renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default) { lock (Calls) Calls.Add("delete:" + fingerprint); DeletedIds = [.. renderIds]; var gone = Items.Where(i => renderIds.Contains(i.Render.Id) && i != Items[2]).ToList(); Items.RemoveAll(gone.Contains); return Task.FromResult(new VideoDeleteResult(gone, [], [])); } public Task 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, }; } /// The signed-in server's videos library; fails: the server does not answer. private sealed class FakeRemote(IReadOnlyList videos, bool fails = false) : IRemoteVideos { public Task ListAsync(VideoQueryDto query, CancellationToken cancellationToken = default) => fails ? throw new HttpRequestException("unreachable") : Task.FromResult(new VideoPageDto(videos, null, videos.Count)); public Task PlanDeleteAsync(IReadOnlyList ids, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task DeleteAsync(IReadOnlyList ids, string fingerprint, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task CopyAsync(IReadOnlyList ids, CancellationToken cancellationToken = default) => Task.FromResult(new VideoCopyResultDto(Guid.CreateVersion7())); public void Dispose() { } } /// Records every confirmation asked and answers it as told. private sealed class ScriptedDialogs : IAppDialogs { public bool Answer { get; set; } public List 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> signIn) => false; } }