diff --git a/src/Chronos.App/Archive/TrashDialogViewModel.cs b/src/Chronos.App/Archive/TrashDialogViewModel.cs
index 0962c9e3..6cc735ca 100644
--- a/src/Chronos.App/Archive/TrashDialogViewModel.cs
+++ b/src/Chronos.App/Archive/TrashDialogViewModel.cs
@@ -2,6 +2,7 @@ using System.Globalization;
using System.IO;
using System.Windows.Input;
using Chronos.App.Infrastructure;
+using Chronos.App.Videos;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
@@ -9,6 +10,7 @@ using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
+using Chronos.Data.Videos;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
@@ -22,9 +24,16 @@ public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
/// "Photos", "Sequence": what the entry holds.
public string KindText => TrashEmptyPlans.KindText(Entry.Kind);
- /// "Photos · 12 photos · 340 MB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).
- public string Detail => string.Join(Loc.Separator, KindText, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes),
- Formatting.LeftToRight(Entry.Folder));
+ ///
+ /// "Photos · 12 photos · 340 MB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language); a videos
+ /// entry has no photos: "Videos · 1.2 GB · …".
+ ///
+ public string Detail => Entry.Kind == TrashKind.Videos
+ ? string.Join(Loc.Separator, KindText, Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder))
+ : string.Join(Loc.Separator, KindText, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder));
+
+ /// What Restore brings back: the render into its sequence's renders, or the sequence or photos.
+ public string RestoreToolTip => Entry.Kind == TrashKind.Videos ? Loc.L("Tooltips.Archive.TrashRestoreVideo") : Loc.L("Tooltips.Archive.TrashRestore");
/// "Deleted 02/10/2026 18:04".
public string DeletedText => Loc.L("Archive.Trash.Deleted", Formatting.Date(Entry.DeletedAt) + " " + Formatting.TimeOfDay(Entry.DeletedAt));
@@ -175,6 +184,11 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
BusyText = Loc.L("Archive.Trash.Restoring", entry.Title);
try
{
+ if (entry.Kind == TrashKind.Videos)
+ {
+ await RestoreVideoAsync(entry);
+ return;
+ }
var result = await Task.Run(() => _archives.RestoreEntryAsync(entry.ArchiveId, entry.Name, _followUps));
Log.Info("archive", $"{entry.Title} restored from the trash ({entry.Kind}, {result.Photos} photo(s), {result.Kept.Count} kept)");
BusyText = null;
@@ -205,6 +219,27 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
}
}
+ ///
+ /// A render deleted from Videos goes back among its sequence's renders after its hash is checked (the videos library
+ /// refuses a file that changed in the trash, or a sequence that is gone, and says why).
+ ///
+ private async Task RestoreVideoAsync(TrashEntry entry)
+ {
+ try
+ {
+ var render = await Task.Run(() => _archives.Videos.RestoreAsync(entry.ArchiveId, entry.Name));
+ Log.Info("archive", $"{entry.Title} restored from the trash (render {render.Id})");
+ Rows = [.. _rows.Where(r => r.Entry != entry)];
+ await _restored();
+ }
+ catch (VideoLibraryException ex)
+ {
+ Log.Warning("archive", $"Restoring {entry.Title} failed: {ex.Code}", ex);
+ var text = VideoText.Error(ex, entry.Title);
+ ShowMessage(text, text);
+ }
+ }
+
///
/// The line of what a restore kept in the trash, and its tooltip: one reason's sentence ("2 photos stayed in the trash:
/// they could not be moved back."), or how many stayed when they stayed for different reasons. The tooltip holds that
diff --git a/src/Chronos.App/Infrastructure/AppSettings.cs b/src/Chronos.App/Infrastructure/AppSettings.cs
index 1a385bad..ad8dbec5 100644
--- a/src/Chronos.App/Infrastructure/AppSettings.cs
+++ b/src/Chronos.App/Infrastructure/AppSettings.cs
@@ -110,6 +110,12 @@ public sealed class AppSettings
public string FolderTemplate { get; set; } = TemplateDefaults.Folder;
public string FileTemplate { get; set; } = TemplateDefaults.File;
+ ///
+ /// Where Videos › Copy to folder puts copies of renders (owner review 1, R9): Videos\Chronos by default, null or empty
+ /// when unset (Copy then says why it cannot run). Never inside the archive or the workspace.
+ ///
+ public string? VideosFolder { get; set; } = Videos.VideosFolders.Default();
+
/// Proxy long edge of new archives (also written into the open archive); 0 = full size, -1 = no proxies.
public int ProxyLongEdge { get; set; } = 1920;
diff --git a/src/Chronos.App/Jobs/JobNotices.cs b/src/Chronos.App/Jobs/JobNotices.cs
index 62a02834..b0bb6966 100644
--- a/src/Chronos.App/Jobs/JobNotices.cs
+++ b/src/Chronos.App/Jobs/JobNotices.cs
@@ -41,7 +41,7 @@ public static class JobNotices
private static bool Announces(JobKind kind) =>
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert or JobKind.WorkspaceRender or JobKind.WorkspaceSend
- or JobKind.WorkspaceMove;
+ or JobKind.WorkspaceMove or JobKind.VideoCopy;
///
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
diff --git a/src/Chronos.App/Sections/SettingsView.xaml b/src/Chronos.App/Sections/SettingsView.xaml
index bdc4980f..69d859cf 100644
--- a/src/Chronos.App/Sections/SettingsView.xaml
+++ b/src/Chronos.App/Sections/SettingsView.xaml
@@ -192,6 +192,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Chronos.App/Sections/SettingsViewModel.cs b/src/Chronos.App/Sections/SettingsViewModel.cs
index b086f64a..544a9910 100644
--- a/src/Chronos.App/Sections/SettingsViewModel.cs
+++ b/src/Chronos.App/Sections/SettingsViewModel.cs
@@ -8,6 +8,7 @@ using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Settings;
using Chronos.App.Shell;
+using Chronos.App.Videos;
using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
@@ -79,7 +80,7 @@ public sealed class SettingsViewModel : SectionViewModel
new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", .. ShowsStartup ? (string[])["Settings.General.Startup"] : [],
"Settings.General.Notifications", .. ProductFeatures.AdsEnabled ? (string[])["Settings.General.Usage"] : []]),
new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies",
- "Settings.Archive.Thumbnails"]),
+ "Settings.Archive.Thumbnails", "Settings.Archive.VideosFolder"]),
new(SettingsPage.Import, ["Import.Scan.Sessions", "Import.Label.Scan", "Import.Scan.Subfolders", "Import.Scan.Verify", "Import.Label.Duplicates",
"Import.Label.After", "Import.After.Eject"]),
new(SettingsPage.Analysis, ["Settings.Analysis.Width", "Settings.Analysis.Night", "Settings.Analysis.Stars", "Settings.Analysis.Deep"]),
@@ -121,6 +122,12 @@ public sealed class SettingsViewModel : SectionViewModel
Save();
_ = OfferReorganizeAsync(UpdateArchiveAsync(a => a with { Templates = a.Templates with { File = v } }), ReorganizeParts.Files);
}, () => Loc.L("Tooltips.Settings.FileTemplate"));
+ // Where Videos › Copy to folder puts copies (owner review 1, R9): empty leaves it unset; never inside the archive or the workspace.
+ VideosFolder = new EditableField(_s.VideosFolder ?? string.Empty, ValidateVideosFolder, v =>
+ {
+ _s.VideosFolder = v.Trim().Length == 0 ? null : Path.GetFullPath(v.Trim());
+ Save();
+ }, () => Loc.L("Tooltips.Settings.VideosFolder"));
FolderTemplate.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
@@ -216,6 +223,8 @@ public sealed class SettingsViewModel : SectionViewModel
});
BrowseArchiveCommand = new RelayCommand(() => Browse(ArchiveRoot, "Settings.Archive.PickTitle"));
BrowseCacheCommand = new RelayCommand(() => Browse(CacheFolder, "Settings.Storage.PickTitle"));
+ BrowseVideosCommand = new RelayCommand(() => Browse(VideosFolder, "Settings.Archive.VideosPickTitle"));
+ OpenVideosFolderCommand = new RelayCommand(OpenVideosFolder, () => !string.IsNullOrWhiteSpace(_s.VideosFolder));
ResetMemoryCommand = new RelayCommand(() => MemoryBudget = MemoryAuto, () => !IsMemoryAuto);
ResetParallelismCommand = new RelayCommand(() =>
{
@@ -400,6 +409,11 @@ public sealed class SettingsViewModel : SectionViewModel
public EditableField FileTemplate { get; }
public ICommand BrowseArchiveCommand { get; }
+ /// Archive › Videos folder: where Videos › Copy to folder puts copies of renders.
+ public EditableField VideosFolder { get; }
+ public ICommand BrowseVideosCommand { get; }
+ public ICommand OpenVideosFolderCommand { get; }
+
/// "1.8 TB free".
public string? ArchiveFreeText
{
@@ -1236,7 +1250,7 @@ public sealed class SettingsViewModel : SectionViewModel
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend,
- JobKind.WorkspaceMove,
+ JobKind.WorkspaceMove, JobKind.VideoCopy,
];
/// Stores for , keeping only the levels that differ from the defaults.
@@ -1259,6 +1273,28 @@ public sealed class SettingsViewModel : SectionViewModel
? null
: Loc.L("Errors.Number.DecimalRange", min.ToString("0.##", Loc.Culture), max.ToString("0.##", Loc.Culture));
+ /// Empty leaves the videos folder unset; a path must be absolute and outside the archive and the workspace.
+ private string? ValidateVideosFolder(string text) =>
+ text.Trim().Length == 0 ? null
+ : VideosFolders.Problem(text.Trim(), _s.LastArchivePath, Shell.Services.Workspace.Root) is { } problem ? VideoText.FolderReason(problem) : null;
+
+ /// Opens the videos folder in Explorer, creating it first (it is Chronos's own folder for copies).
+ private void OpenVideosFolder()
+ {
+ if (string.IsNullOrWhiteSpace(_s.VideosFolder)) return;
+ try
+ {
+ Directory.CreateDirectory(_s.VideosFolder);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
+ {
+ Log.Warning("settings", $"The videos folder could not be created: {ex.Message}");
+ Shell.ReportError(ex);
+ return;
+ }
+ ShellActions.Reveal(_s.VideosFolder);
+ }
+
private void Browse(EditableField field, string titleKey)
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L(titleKey), field.Value.Length > 0 ? field.Value : null);
@@ -1620,8 +1656,10 @@ public sealed class SettingsViewModel : SectionViewModel
_s.FileTemplate = defaults.FileTemplate;
_s.ProxyLongEdge = defaults.ProxyLongEdge;
_s.ThumbnailLongEdge = defaults.ThumbnailLongEdge;
+ _s.VideosFolder = defaults.VideosFolder;
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
+ VideosFolder.Load(_s.VideosFolder ?? string.Empty);
UpdatePreview();
Save();
OnAllPropertiesChanged();
@@ -1682,6 +1720,7 @@ public sealed class SettingsViewModel : SectionViewModel
ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
+ VideosFolder.Load(_s.VideosFolder ?? string.Empty);
LoadImportFields();
LoadAnalysisFields();
Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture));
@@ -1765,6 +1804,7 @@ public sealed class SettingsViewModel : SectionViewModel
ArchiveRoot.Refresh();
FolderTemplate.Refresh();
FileTemplate.Refresh();
+ VideosFolder.Refresh();
SessionGap.Refresh();
MinimumFrames.Refresh();
// Decimals are written in the language's own way ("6.25", "6,25").
diff --git a/src/Chronos.App/Sections/VideosView.xaml b/src/Chronos.App/Sections/VideosView.xaml
new file mode 100644
index 00000000..5efd810f
--- /dev/null
+++ b/src/Chronos.App/Sections/VideosView.xaml
@@ -0,0 +1,247 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Chronos.App/Sections/VideosView.xaml.cs b/src/Chronos.App/Sections/VideosView.xaml.cs
new file mode 100644
index 00000000..189ea611
--- /dev/null
+++ b/src/Chronos.App/Sections/VideosView.xaml.cs
@@ -0,0 +1,28 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using Chronos.App.Videos;
+
+namespace Chronos.App.Sections;
+
+/// Videos: every render made from the photos, here and on the server, in cards or a list, with a player beside them.
+public partial class VideosView : UserControl
+{
+ public VideosView() => InitializeComponent();
+
+ private VideosViewModel? Model => DataContext as VideosViewModel;
+
+ /// A double click plays the render (or shows "Cannot play here" when it cannot).
+ private void OnItemDoubleClick(object sender, MouseButtonEventArgs e)
+ {
+ if (sender is not ListBoxItem { DataContext: VideoRowViewModel row } || Model is not { } model) return;
+ if (model.PlayCommand.CanExecute(row)) model.PlayCommand.Execute(row);
+ e.Handled = true;
+ }
+
+ /// A card asks for its cover only once it is on screen.
+ private void OnCardLoaded(object sender, RoutedEventArgs e)
+ {
+ if (sender is FrameworkElement { DataContext: VideoRowViewModel row }) row.RequestPoster();
+ }
+}
diff --git a/src/Chronos.App/Sections/VideosViewModel.cs b/src/Chronos.App/Sections/VideosViewModel.cs
new file mode 100644
index 00000000..ccf10108
--- /dev/null
+++ b/src/Chronos.App/Sections/VideosViewModel.cs
@@ -0,0 +1,801 @@
+using System.IO;
+using System.Net.Http;
+using System.Windows.Input;
+using System.Windows.Media;
+using Chronos.App.Infrastructure;
+using Chronos.App.Library;
+using Chronos.App.Shell;
+using Chronos.App.Videos;
+using Chronos.App.Workspace;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.Localization;
+using Chronos.Core.Model;
+using Chronos.Core.Windows.Security;
+using Chronos.Data;
+using Chronos.Data.Archiving;
+using Chronos.Data.Archiving.Jobs;
+using Chronos.Data.Videos;
+using Chronos.Protocol;
+using Chronos.Protocol.Client;
+using Chronos.Ui.Mvvm;
+
+namespace Chronos.App.Sections;
+
+///
+/// The Videos section (owner review 1, R9; decisions 20 and 21): every render of this PC's archive, of the signed-in server
+/// and of the workspace (not sent yet) in one list, merged by render id, with filters, an order, cards or a list, and the
+/// actions on the selection: Play in the pane on the right, Show in folder, Copy (or Download) to the videos folder checked
+/// by hash, Copy on server, Delete… into the trash after a dry run, Open in Edit, and Send for the workspace's renders.
+/// An older server, or none, leaves this PC's videos with the reason.
+///
+public sealed class VideosViewModel : SectionViewModel
+{
+ private IReadOnlyList _entries = [];
+ private IReadOnlyList _rows = [];
+ private IReadOnlyList> _kinds = [];
+ private IReadOnlyList> _codecs = [];
+ private IReadOnlyList> _years = [];
+ private IReadOnlyList> _sources = [];
+ private IReadOnlyList> _sorts = [];
+ private FilterOption _kind = null!;
+ private FilterOption _codec = null!;
+ private FilterOption _year = null!;
+ private FilterOption _source = null!;
+ private FilterOption _sort = null!;
+ private string _searchText = string.Empty;
+ private Guid? _sequenceId;
+ private string? _sequenceTitle;
+ private int _layoutIndex;
+ private bool _isLoading;
+ private int _loads;
+ private VideoServer _server = VideoServer.SignedOut;
+ private VideoPlayerViewModel? _player;
+ private readonly Dictionary> _sequences = [];
+
+ public VideosViewModel(ShellViewModel shell)
+ : base(SectionKey.Videos, "Icon.Videos")
+ {
+ Shell = shell;
+ var services = shell.Services;
+ LocalLibrary = () => services.Archives?.Videos;
+ ServerVideos = () => ServerOf(services);
+ WorkspaceRenders = ct => ReadWorkspaceAsync(services, ct);
+ Folder = () => services.Settings.VideosFolder;
+ Enqueue = async request =>
+ {
+ if (services.Engine is not { } engine) throw new InvalidOperationException("The job engine is not running.");
+ await engine.EnqueueAsync(request);
+ };
+ Posters = (entry, width, ct) => PosterAsync(services, entry, width, ct);
+ BuildOptions();
+
+ PlayCommand = new RelayCommand(p => Play(Target(p)), p => Target(p) is { Entry.HasLocalFile: true });
+ ShowInFolderCommand = new RelayCommand(p => ShowInFolder(Target(p)), p => Target(p) is { Entry.HasLocalFile: true });
+ CopyCommand = new AsyncRelayCommand((p, _) => CopyAsync(Targets(p)), p => CopyBlocker(Targets(p)) is null);
+ CopyOnServerCommand = new AsyncRelayCommand((p, _) => CopyOnServerAsync(Targets(p)), p => CopyOnServerBlocker(Targets(p)) is null);
+ DeleteCommand = new AsyncRelayCommand((p, _) => DeleteAsync(Targets(p)), p => DeleteBlocker(Targets(p)) is null);
+ OpenInEditCommand = new RelayCommand(p => OpenInEdit(Target(p)), p => Target(p) is { } row && CanOpen(row.Entry));
+ SendCommand = new AsyncRelayCommand((p, _) => SendAsync(Targets(p)), p => Targets(p).Any(r => r.Entry.IsUnsent));
+ ClearFiltersCommand = new RelayCommand(ClearFilters, () => Filter.IsFiltered);
+ ClearSelectionCommand = new RelayCommand(() =>
+ {
+ foreach (var row in _rows) row.IsSelected = false;
+ }, () => HasSelection);
+ ClosePlayerCommand = new RelayCommand(() => Player = null);
+ }
+
+ public ShellViewModel Shell { get; }
+
+ // ---- Sources (tests substitute their own) ----
+
+ /// This PC's videos library; null while the index is not open.
+ internal Func LocalLibrary { get; set; }
+
+ /// The signed-in server's videos, and what the account may do there.
+ internal Func ServerVideos { get; set; }
+
+ /// The workspace's renders not sent yet.
+ internal Func>> WorkspaceRenders { get; set; }
+
+ /// Queues a job of this PC (a copy into the videos folder).
+ internal Func Enqueue { get; set; }
+
+ /// The poster of a card: the sequence's cover, or the still itself.
+ internal Func> Posters { get; set; }
+
+ /// The videos folder of this PC (Settings › Archive); null or empty while unset.
+ internal Func Folder { get; set; }
+
+ // ---- List ----
+
+ /// Every render, merged, before the filters.
+ public IReadOnlyList Entries
+ {
+ get => _entries;
+ private set
+ {
+ _entries = value;
+ BuildOptions();
+ Apply();
+ }
+ }
+
+ /// The renders the filters keep, in the chosen order.
+ public IReadOnlyList Rows
+ {
+ get => _rows;
+ private set
+ {
+ foreach (var row in _rows)
+ {
+ row.SelectionChanged -= OnSelectionChanged;
+ row.PosterRequested -= OnPosterRequested;
+ }
+ if (!Set(ref _rows, value)) return;
+ foreach (var row in _rows)
+ {
+ row.SelectionChanged += OnSelectionChanged;
+ row.PosterRequested += OnPosterRequested;
+ }
+ OnPropertyChanged(nameof(IsEmpty));
+ OnPropertyChanged(nameof(IsNoMatch));
+ OnSelectionChanged(null);
+ }
+ }
+
+ public bool IsLoading
+ {
+ get => _isLoading;
+ private set
+ {
+ if (!Set(ref _isLoading, value)) return;
+ OnPropertyChanged(nameof(IsEmpty));
+ OnPropertyChanged(nameof(IsNoMatch));
+ }
+ }
+
+ /// No video anywhere: "No videos".
+ public bool IsEmpty => !_isLoading && _entries.Count == 0;
+
+ /// Videos, none of which the filters keep: "No videos" and Clear filters.
+ public bool IsNoMatch => !_isLoading && _entries.Count > 0 && _rows.Count == 0;
+
+ /// The cards (0) or the list (1).
+ public int LayoutIndex
+ {
+ get => _layoutIndex;
+ set
+ {
+ if (value is < 0 or > 1 || !Set(ref _layoutIndex, value)) return;
+ OnPropertyChanged(nameof(IsGrid));
+ OnPropertyChanged(nameof(IsList));
+ }
+ }
+
+ public bool IsGrid => _layoutIndex == 0;
+ public bool IsList => _layoutIndex == 1;
+
+ // ---- Filters ----
+
+ public string SearchText
+ {
+ get => _searchText;
+ set
+ {
+ if (Set(ref _searchText, value ?? string.Empty)) Apply();
+ }
+ }
+
+ public IReadOnlyList> Kinds { get => _kinds; private set => Set(ref _kinds, value); }
+ public IReadOnlyList> Codecs { get => _codecs; private set => Set(ref _codecs, value); }
+ public IReadOnlyList> Years { get => _years; private set => Set(ref _years, value); }
+ public IReadOnlyList> Sources { get => _sources; private set => Set(ref _sources, value); }
+ public IReadOnlyList> Sorts { get => _sorts; private set => Set(ref _sorts, value); }
+
+ public FilterOption SelectedKind
+ {
+ get => _kind;
+ set => SetFilter(ref _kind, value ?? _kinds[0]);
+ }
+
+ public FilterOption SelectedCodec
+ {
+ get => _codec;
+ set => SetFilter(ref _codec, value ?? _codecs[0]);
+ }
+
+ public FilterOption SelectedYear
+ {
+ get => _year;
+ set => SetFilter(ref _year, value ?? _years[0]);
+ }
+
+ public FilterOption SelectedSource
+ {
+ get => _source;
+ set => SetFilter(ref _source, value ?? _sources[0]);
+ }
+
+ public FilterOption SelectedSort
+ {
+ get => _sort;
+ set => SetFilter(ref _sort, value ?? _sorts[0]);
+ }
+
+ public bool IsKindFiltered => _kind is { IsAny: false };
+ public bool IsCodecFiltered => _codec is { IsAny: false };
+ public bool IsYearFiltered => _year is { IsAny: false };
+ public bool IsSourceFiltered => _source is { IsAny: false };
+
+ /// The sequence the list is narrowed to (the Export footer's and the Render menu's "Videos"); null for all.
+ public Guid? SequenceId => _sequenceId;
+
+ /// The title of that sequence, shown as a chip that clears it.
+ public string? SequenceFilterText => _sequenceId is null ? null : _sequenceTitle ?? _entries.FirstOrDefault(e => e.SequenceId == _sequenceId)?.Title;
+
+ public bool IsSequenceFiltered => _sequenceId is not null;
+
+ /// The filters and the order in force.
+ public VideoFilter Filter => new()
+ {
+ Text = _searchText,
+ Kind = _kind?.Value,
+ Codec = _codec?.Value,
+ Year = _year?.Value,
+ Source = _source?.Value ?? VideoSourceFilter.All,
+ SequenceId = _sequenceId,
+ Sort = _sort?.Value,
+ };
+
+ public ICommand ClearFiltersCommand { get; }
+
+ /// Narrows the list to the videos of one sequence (null: every sequence).
+ public void ShowSequence(Guid? sequenceId, string? title = null)
+ {
+ _sequenceId = sequenceId;
+ _sequenceTitle = sequenceId is null ? null : title;
+ OnPropertyChanged(nameof(SequenceId));
+ OnPropertyChanged(nameof(SequenceFilterText));
+ OnPropertyChanged(nameof(IsSequenceFiltered));
+ Apply();
+ }
+
+ // ---- Server ----
+
+ /// How the signed-in server's videos reach the list.
+ public VideoServerState ServerState => _server.State;
+
+ /// The server's videos are not listed: the status line says why.
+ public bool IsServerLimited => _server.State != VideoServerState.Available && (_server.State != VideoServerState.SignedOut || Shell.Services.Server.HasSavedSession);
+
+ /// "Server not reachable", or "Server" greyed out with its reason in .
+ public string ServerStatusText => _server.State == VideoServerState.Unreachable ? Loc.L("Videos.ServerUnreachable") : Loc.L("Videos.Source.Server");
+
+ public string? ServerStatusToolTip => _server.State switch
+ {
+ VideoServerState.Old => Loc.L("Tooltips.Videos.ServerOld"),
+ VideoServerState.SignedOut => Loc.L("Tooltips.Videos.ServerOffline"),
+ VideoServerState.Unreachable => Loc.L("Tooltips.Videos.ServerOffline"),
+ _ => null,
+ };
+
+ // ---- Selection ----
+
+ public IReadOnlyList SelectedRows => [.. _rows.Where(r => r.IsSelected)];
+
+ public bool HasSelection => _rows.Any(r => r.IsSelected);
+
+ /// "Selected: 3".
+ public string SelectionText => Loc.L("Videos.Selected", Formatting.Count(_rows.Count(r => r.IsSelected)));
+
+ public ICommand ClearSelectionCommand { get; }
+
+ // ---- Actions ----
+
+ public ICommand PlayCommand { get; }
+ public ICommand ShowInFolderCommand { get; }
+ public ICommand CopyCommand { get; }
+ public ICommand CopyOnServerCommand { get; }
+ public ICommand DeleteCommand { get; }
+ public ICommand OpenInEditCommand { get; }
+ public ICommand SendCommand { get; }
+
+ /// Copy to folder, or Download for the server's videos alone.
+ public string CopyText => SelectedRows is { Count: > 0 } rows && rows.All(r => !r.Entry.IsLocal && r.Entry.IsOnServer) ? Loc.L("Videos.Download") : Loc.L("Videos.Copy");
+
+ public string CopyToolTip => CopyBlocker(SelectedRows) ?? (SelectedRows.All(r => !r.Entry.IsLocal) && SelectedRows.Count > 0
+ ? Loc.L("Tooltips.Videos.Download")
+ : Loc.L("Tooltips.Videos.Copy"));
+
+ public string CopyOnServerToolTip => CopyOnServerBlocker(SelectedRows) ?? Loc.L("Tooltips.Videos.CopyOnServer");
+
+ public string DeleteToolTip => DeleteBlocker(SelectedRows) ?? Loc.L("Tooltips.Videos.Delete");
+
+ /// The row's Copy to folder or Download tooltip (its context menu).
+ public string RowCopyToolTip(VideoRowViewModel row) => CopyBlocker([row]) ?? Loc.L(row.Entry.IsLocal ? "Tooltips.Videos.Copy" : "Tooltips.Videos.Download");
+
+ public ICommand ClosePlayerCommand { get; }
+
+ /// The player pane on the right; null while closed.
+ public VideoPlayerViewModel? Player
+ {
+ get => _player;
+ private set
+ {
+ if (!Set(ref _player, value)) return;
+ OnPropertyChanged(nameof(IsPlayerOpen));
+ }
+ }
+
+ public bool IsPlayerOpen => _player is not null;
+
+ /// Reads the three places again and lists what they hold (the filters stay).
+ public async Task RefreshAsync()
+ {
+ var load = ++_loads;
+ IsLoading = true;
+ try
+ {
+ var server = ServerVideos();
+ var localTask = ReadLocalAsync();
+ var serverTask = ReadServerAsync(server);
+ var workspaceTask = ReadWorkspaceSafeAsync();
+ var local = await localTask;
+ var (remote, state) = await serverTask;
+ var workspace = await workspaceTask;
+ if (load != _loads) return;
+ _server = state;
+ Entries = VideoSources.Merge(local, remote, workspace);
+ OnPropertyChanged(nameof(ServerState));
+ OnPropertyChanged(nameof(IsServerLimited));
+ OnPropertyChanged(nameof(ServerStatusText));
+ OnPropertyChanged(nameof(ServerStatusToolTip));
+ OnPropertyChanged(nameof(SequenceFilterText));
+ }
+ finally
+ {
+ if (load == _loads) IsLoading = false;
+ }
+ }
+
+ protected override void OnActivated() => _ = RefreshAsync();
+
+ protected override void OnLanguageChanged()
+ {
+ BuildOptions();
+ // The rows' words are made with them: made again in the new language.
+ Rows = [];
+ Apply();
+ base.OnLanguageChanged();
+ }
+
+ private async Task> ReadLocalAsync()
+ {
+ try
+ {
+ return await Task.Run(() => VideoSources.ReadLocalAsync(LocalLibrary()));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or InvalidDataException)
+ {
+ Log.Warning("videos", "The videos of this PC could not be listed", ex);
+ Shell.ReportError(ex);
+ return [];
+ }
+ }
+
+ private static async Task<(IReadOnlyList Entries, VideoServer State)> ReadServerAsync(VideoServer server)
+ {
+ if (server is not { State: VideoServerState.Available, Connect: { } connect }) return ([], server);
+ try
+ {
+ using var remote = connect();
+ return (await VideoSources.ReadServerAsync(remote), server);
+ }
+ catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException)
+ {
+ Log.Warning("videos", "The server's videos could not be listed", ex);
+ return ([], server with { State = VideoServerState.Unreachable, Connect = null });
+ }
+ }
+
+ private async Task> ReadWorkspaceSafeAsync()
+ {
+ try
+ {
+ return await WorkspaceRenders(CancellationToken.None);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or WorkspaceException or DatabaseException)
+ {
+ Log.Warning("videos", "The workspace's renders could not be listed", ex);
+ return [];
+ }
+ }
+
+ private static async Task> ReadWorkspaceAsync(AppServices services, CancellationToken cancellationToken)
+ {
+ var workspace = services.Workspace;
+ if (!workspace.IsAvailable || !Directory.Exists(workspace.Root)) return [];
+ var projects = await workspace.ListAsync(cancellationToken);
+ return await Task.Run(() => VideoSources.ReadWorkspace(workspace.Store, projects), cancellationToken);
+ }
+
+ /// The signed-in session's server, its capability and the account's rights.
+ private static VideoServer ServerOf(AppServices services)
+ {
+ var session = services.Server;
+ if (!session.IsConnected || session.Flow is not { Address: { } address, Token: { } token, Info: { } info }) return VideoServer.SignedOut;
+ return VideoServer.Of(info, session.User?.Permissions ?? 0, () =>
+ new ChronosRemoteVideos(new ChronosClient(address, new CertificatePinning(session.Fingerprints), $"Chronos ({Environment.MachineName})") { Token = token }));
+ }
+
+ private void Apply()
+ {
+ // A row is kept while its render reads the same (its selection and its poster with it).
+ var cache = _rows.ToDictionary(r => r.Entry.Id);
+ Rows = [.. Filter.Apply(_entries).Select(e => cache.TryGetValue(e.Id, out var row)
+ ? row.Entry == e ? row : new VideoRowViewModel(e) { IsSelected = row.IsSelected, Poster = row.Poster }
+ : new VideoRowViewModel(e))];
+ if (_player is { } player && !_entries.Any(e => e.Id == player.Entry.Id)) Player = null;
+ OnPropertyChanged(nameof(Filter));
+ }
+
+ private void SetFilter(ref FilterOption field, FilterOption value, [System.Runtime.CompilerServices.CallerMemberName] string? name = null)
+ {
+ if (EqualityComparer>.Default.Equals(field, value)) return;
+ field = value;
+ OnPropertyChanged(name);
+ OnPropertyChanged(nameof(IsKindFiltered));
+ OnPropertyChanged(nameof(IsCodecFiltered));
+ OnPropertyChanged(nameof(IsYearFiltered));
+ OnPropertyChanged(nameof(IsSourceFiltered));
+ Apply();
+ }
+
+ private void ClearFilters()
+ {
+ _searchText = string.Empty;
+ _kind = _kinds[0];
+ _codec = _codecs[0];
+ _year = _years[0];
+ _source = _sources[0];
+ _sequenceId = null;
+ _sequenceTitle = null;
+ OnAllPropertiesChanged();
+ Apply();
+ }
+
+ /// The choices of the filters: kinds, sources and orders fixed, codecs and years those the videos have; each choice kept.
+ private void BuildOptions()
+ {
+ var kind = _kind?.Value;
+ var codec = _codec?.Value;
+ var year = _year?.Value;
+ var source = _source?.Value ?? VideoSourceFilter.All;
+ var sort = _sort?.Value;
+ var allKinds = Loc.L("Videos.Kind.All");
+ Kinds =
+ [
+ new(null, allKinds, allKinds, IsAny: true),
+ .. new[] { RenderKind.Video, RenderKind.Still, RenderKind.Sequence }.Select(k => new FilterOption(k, VideoText.Kind(k), VideoText.Kind(k))),
+ ];
+ var allCodecs = Loc.L("Videos.Codec.All");
+ Codecs =
+ [
+ new(null, allCodecs, allCodecs, IsAny: true),
+ .. _entries.Select(e => e.Codec).OfType().Where(c => c.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase)
+ .Append(codec).OfType().Distinct(StringComparer.OrdinalIgnoreCase)
+ .Select(c => new FilterOption(c, VideoSources.CodecText(c), VideoSources.CodecText(c))).OrderBy(o => o.Label, StringComparer.CurrentCulture),
+ ];
+ var allYears = Loc.L("Videos.Year.All");
+ Years =
+ [
+ new(null, allYears, allYears, IsAny: true),
+ .. _entries.Select(e => (int?)e.Year).Append(year).OfType().Distinct().OrderDescending()
+ .Select(y => new FilterOption(y, y.ToString(Loc.Culture), y.ToString(Loc.Culture))),
+ ];
+ var allSources = Loc.L("Videos.Source.All");
+ Sources =
+ [
+ new(VideoSourceFilter.All, allSources, allSources, IsAny: true),
+ new(VideoSourceFilter.Local, Loc.L("Videos.Source.Local"), Loc.L("Videos.Source.Local")),
+ new(VideoSourceFilter.Server, Loc.L("Videos.Source.Server"), Loc.L("Videos.Source.Server")),
+ new(VideoSourceFilter.NotSent, Loc.L("Videos.Source.NotSent"), Loc.L("Videos.Source.NotSent")),
+ ];
+ Sorts = [.. VideoSorts.All.Select(s => new FilterOption(s, SortText(s), SortText(s), IsAny: s == VideoSorts.Newest))];
+ _kind = _kinds.First(o => o.Value == kind);
+ _codec = _codecs.FirstOrDefault(o => string.Equals(o.Value, codec, StringComparison.OrdinalIgnoreCase)) ?? _codecs[0];
+ _year = _years.First(o => o.Value == year);
+ _source = _sources.First(o => o.Value == source);
+ _sort = _sorts.FirstOrDefault(o => o.Value == sort) ?? _sorts[0];
+ OnPropertyChanged(nameof(SelectedKind));
+ OnPropertyChanged(nameof(SelectedCodec));
+ OnPropertyChanged(nameof(SelectedYear));
+ OnPropertyChanged(nameof(SelectedSource));
+ OnPropertyChanged(nameof(SelectedSort));
+ }
+
+ private static string SortText(string sort) => sort switch
+ {
+ VideoSorts.Oldest => Loc.L("Videos.Sort.Oldest"),
+ VideoSorts.Largest => Loc.L("Videos.Sort.Largest"),
+ VideoSorts.Title => Loc.L("Videos.Sort.Title"),
+ _ => Loc.L("Videos.Sort.Newest"),
+ };
+
+ private void OnSelectionChanged(VideoRowViewModel? row)
+ {
+ OnPropertyChanged(nameof(HasSelection));
+ OnPropertyChanged(nameof(SelectedRows));
+ OnPropertyChanged(nameof(SelectionText));
+ OnPropertyChanged(nameof(CopyText));
+ OnPropertyChanged(nameof(CopyToolTip));
+ OnPropertyChanged(nameof(CopyOnServerToolTip));
+ OnPropertyChanged(nameof(DeleteToolTip));
+ CommandManager.InvalidateRequerySuggested();
+ }
+
+ private async void OnPosterRequested(VideoRowViewModel row)
+ {
+ try
+ {
+ row.Poster = await Posters(row.Entry, 472, CancellationToken.None);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or DatabaseException or InvalidOperationException
+ or OperationCanceledException)
+ {
+ Log.Info("videos", $"The poster of {row.Entry.FileName} could not be loaded: {ex.Message}");
+ }
+ }
+
+ /// A still shows itself; any other render of this PC its sequence's cover.
+ private async Task PosterAsync(AppServices services, VideoEntry entry, int width, CancellationToken cancellationToken)
+ {
+ if (entry.Kind == RenderKind.Still && entry.HasLocalFile && VideoSources.ShowsAsImage(entry.LocalPath))
+ {
+ return await Task.Run(() =>
+ {
+ using var stream = File.OpenRead(entry.LocalPath!);
+ return ThumbnailService.DecodeStream(stream, 1, width);
+ }, cancellationToken);
+ }
+ if (!entry.IsLocal || services.Database is not { } db || services.Thumbnails is not { } thumbnails) return null;
+ if (!_sequences.TryGetValue(entry.SequenceId, out var sequence)) _sequences[entry.SequenceId] = sequence = db.Sequences.GetAsync(entry.SequenceId, cancellationToken);
+ return await sequence is { } found ? await thumbnails.HeroAsync(found, width, cancellationToken) : null;
+ }
+
+ // ---- What the actions apply to ----
+
+ /// A row's own menu acts on the row, or on the selection when the row is part of it; the toolbar on the selection.
+ private IReadOnlyList Targets(object? parameter) =>
+ parameter is VideoRowViewModel row ? row.IsSelected ? SelectedRows : [row] : SelectedRows;
+
+ private VideoRowViewModel? Target(object? parameter) => Targets(parameter) is [var one] ? one : null;
+
+ private string? FolderProblem()
+ {
+ var folder = Folder();
+ var problem = VideosFolders.Problem(folder, Shell.Services.Settings.LastArchivePath, Shell.Services.Workspace.Root);
+ return problem ?? LocalLibrary()?.FolderProblem(folder);
+ }
+
+ /// Why Copy to folder cannot run on ; null when it can.
+ internal string? CopyBlocker(IReadOnlyList rows)
+ {
+ if (rows.Count == 0) return Loc.L("Tooltips.Videos.Copy");
+ if (!rows.Any(r => Copyable(r.Entry))) return rows.All(r => r.Entry.Missing) ? Loc.L("Tooltips.Videos.Missing") : Loc.L("Tooltips.Videos.WorkspaceRow");
+ if (FolderProblem() is { } problem) return VideoText.FolderReason(problem);
+ return LocalLibrary() is { IsAvailable: true } ? null : Loc.L("Tooltips.Videos.Copy");
+ }
+
+ /// Why Copy on server cannot run on ; null when it can.
+ internal string? CopyOnServerBlocker(IReadOnlyList rows)
+ {
+ if (_server.State != VideoServerState.Available) return ServerStatusToolTip;
+ if (!_server.CanEdit) return Loc.L("Tooltips.Videos.NoEditRight");
+ return rows.Any(r => r.Entry is { IsOnServer: true, Missing: false }) ? null : Loc.L("Tooltips.Videos.OnServer");
+ }
+
+ /// Why Delete… cannot run on ; null when it can.
+ internal string? DeleteBlocker(IReadOnlyList rows)
+ {
+ if (rows.Count == 0) return Loc.L("Tooltips.Videos.Delete");
+ if (rows.All(r => r.Entry.IsUnsent)) return Loc.L("Tooltips.Videos.WorkspaceRow");
+ var local = rows.Any(r => r.Entry.IsLocal) && LocalLibrary() is { IsAvailable: true };
+ var server = rows.Any(r => !r.Entry.IsLocal && r.Entry.IsOnServer);
+ if (local) return null;
+ if (server && _server.State != VideoServerState.Available) return ServerStatusToolTip;
+ if (server && !_server.CanDelete) return Loc.L("Tooltips.Videos.NoDeleteRight");
+ return server ? null : Loc.L("Tooltips.Videos.Delete");
+ }
+
+ /// A render Copy to folder takes: this PC's file, or the server's alone (downloaded).
+ private bool Copyable(VideoEntry entry) =>
+ !entry.IsUnsent && !entry.Missing && (entry.IsLocal || (entry.IsOnServer && _server.State == VideoServerState.Available));
+
+ private static bool CanOpen(VideoEntry entry) => entry.IsLocal || entry is { IsUnsent: true, WorkspaceServerHome: false };
+
+ // ---- Actions ----
+
+ private void Play(VideoRowViewModel? row)
+ {
+ if (row is null) return;
+ Player = new VideoPlayerViewModel(row.Entry, ClosePlayerCommand, new RelayCommand(() => ShowInFolder(row), () => row.Entry.HasLocalFile));
+ }
+
+ private static void ShowInFolder(VideoRowViewModel? row)
+ {
+ if (row?.Entry is { HasLocalFile: true, LocalPath: { } path }) ShellActions.Reveal(path);
+ }
+
+ private void OpenInEdit(VideoRowViewModel? row)
+ {
+ if (row is not null && CanOpen(row.Entry)) Shell.OpenSequence(row.Entry.SequenceId);
+ }
+
+ ///
+ /// Copy to folder: this PC's renders are copied into the videos folder, the server's alone downloaded there, each checked
+ /// by hash (a job of this PC); the renders themselves are never touched.
+ ///
+ internal async Task CopyAsync(IReadOnlyList rows)
+ {
+ if (CopyBlocker(rows) is { } blocker)
+ {
+ Shell.Notify(blocker, isError: true);
+ return;
+ }
+ var folder = Path.GetFullPath(Folder()!);
+ var library = LocalLibrary()!;
+ var copyable = rows.Select(r => r.Entry).Where(Copyable).ToList();
+ try
+ {
+ foreach (var (fromServer, ids) in new[] { (false, copyable.Where(e => e.IsLocal)), (true, copyable.Where(e => !e.IsLocal)) })
+ {
+ IReadOnlyList list = [.. ids.Select(e => e.Id)];
+ if (list.Count == 0) continue;
+ await Enqueue(library.CopyJob(new VideoCopyParameters(list, folder, fromServer, Environment.MachineName)));
+ }
+ Shell.Notify(Loc.L("Videos.Copy.Queued"), Loc.L("Videos.Target.Copy", Formatting.Count(copyable.Count)), Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"),
+ () => Shell.Navigate(SectionKey.Jobs));
+ }
+ catch (VideoLibraryException ex)
+ {
+ Shell.Notify(VideoText.Error(ex), isError: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or InvalidOperationException)
+ {
+ Shell.ReportError(ex);
+ }
+ }
+
+ /// Copy on server: the server copies its renders into its own videos folder, checked by hash.
+ internal async Task CopyOnServerAsync(IReadOnlyList rows)
+ {
+ var blocker = CopyOnServerBlocker(rows);
+ if (blocker is not null || _server.Connect is not { } connect)
+ {
+ Shell.Notify(blocker ?? Loc.L("Tooltips.Videos.ServerOffline"), isError: true);
+ return;
+ }
+ IReadOnlyList ids = [.. rows.Where(r => r.Entry is { IsOnServer: true, Missing: false }).Select(r => r.Entry.Id)];
+ try
+ {
+ using var remote = connect();
+ await remote.CopyAsync(ids);
+ Shell.Notify(Loc.L("Videos.Copy.Queued"), Loc.L("Videos.Target.Copy", Formatting.Count(ids.Count)));
+ }
+ catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException)
+ {
+ Log.Warning("videos", "Copying videos on the server failed", ex);
+ Shell.Notify(ErrorText.ForServer(ex), isError: true);
+ }
+ }
+
+ ///
+ /// Delete…: the dry run first (this PC's renders and the server's alone apart), then one confirmation saying what goes,
+ /// its bytes, what stays and why, and that copies in the videos folder stay; then each delete with its plan's
+ /// fingerprint, which a changed plan refuses with nothing moved.
+ ///
+ internal async Task DeleteAsync(IReadOnlyList rows)
+ {
+ if (DeleteBlocker(rows) is { } blocker)
+ {
+ Shell.Notify(blocker, isError: true);
+ return;
+ }
+ var library = LocalLibrary();
+ IReadOnlyList localIds = library is { IsAvailable: true } ? [.. rows.Where(r => r.Entry.IsLocal).Select(r => r.Entry.Id)] : [];
+ IReadOnlyList serverIds = _server is { State: VideoServerState.Available, CanDelete: true }
+ ? [.. rows.Where(r => !r.Entry.IsLocal && r.Entry.IsOnServer).Select(r => r.Entry.Id)]
+ : [];
+ VideoDeletePlans plans;
+ try
+ {
+ var local = localIds.Count > 0 ? await Task.Run(() => library!.PlanDeleteAsync(localIds)) : null;
+ VideoDeletePlanDto? server = null;
+ if (serverIds.Count > 0 && _server.Connect is { } connect)
+ {
+ using var remote = connect();
+ server = await remote.PlanDeleteAsync(serverIds);
+ }
+ plans = new VideoDeletePlans(local, server);
+ }
+ catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or TaskCanceledException or UntrustedCertificateException)
+ {
+ Shell.Notify(ErrorText.ForServer(ex), isError: true);
+ return;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
+ {
+ Shell.ReportError(ex);
+ return;
+ }
+ LastDeletePlans = plans;
+ if (plans.Request() is not { } request)
+ {
+ if (plans.Blocked > 0) Shell.Notify(Loc.L("Videos.Delete.Blocked", Formatting.Count(plans.Blocked)), string.Join(Environment.NewLine, plans.Lines()), isError: true);
+ return;
+ }
+ if (!Shell.Services.Dialogs.Confirm(request)) return;
+ var deleted = 0;
+ try
+ {
+ if (plans.Local is { Items.Count: > 0 } localPlan)
+ {
+ var result = await Task.Run(() => library!.DeleteAsync([.. localPlan.Items.Select(i => i.Render.Id)], localPlan.Fingerprint, Environment.MachineName));
+ deleted += result.Deleted.Count;
+ }
+ if (plans.Server is { Items.Count: > 0 } serverPlan && _server.Connect is { } connect)
+ {
+ using var remote = connect();
+ var result = await remote.DeleteAsync([.. serverPlan.Items.Select(i => i.Id)], serverPlan.Fingerprint);
+ deleted += result.Items.Count;
+ }
+ Shell.Notify(Loc.L("Videos.Delete.Done", Formatting.Count(deleted)));
+ }
+ catch (VideoLibraryException ex)
+ {
+ Shell.Notify(VideoText.Error(ex), isError: true);
+ }
+ catch (ChronosApiException ex) when (ex.Error?.Code == VideoErrors.PlanChanged)
+ {
+ Shell.Notify(Loc.L("Errors.Videos.Fingerprint"), isError: true);
+ }
+ catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or TaskCanceledException or UntrustedCertificateException)
+ {
+ Shell.Notify(ErrorText.ForServer(ex), isError: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
+ {
+ Shell.ReportError(ex);
+ }
+ await RefreshAsync();
+ }
+
+ /// The plans of the last Delete… (tests).
+ internal VideoDeletePlans? LastDeletePlans { get; private set; }
+
+ /// Send: queues the sending home of the workspace projects' renders not sent yet.
+ private async Task SendAsync(IReadOnlyList rows)
+ {
+ foreach (var project in rows.Select(r => r.Entry).Where(e => e.IsUnsent && e.WorkspaceProjectId is not null).Select(e => e.WorkspaceProjectId!.Value).Distinct())
+ {
+ try
+ {
+ if (await Shell.Services.Workspace.SendRendersAsync(project))
+ Shell.Notify(Loc.L("Editor.Render.Sending"), null, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
+ }
+ catch (Exception ex) when (ex is WorkspaceException or IOException or InvalidDataException or UnauthorizedAccessException or DatabaseException)
+ {
+ Log.Warning("videos", $"The renders of workspace project {project} could not be queued to be sent", ex);
+ Shell.Notify(Loc.L("Editor.Render.SendFailed"), ex is WorkspaceException ? ex.Message : ErrorText.For(ex), isError: true);
+ }
+ }
+ }
+
+ /// What Send does for , worded for its project's home.
+ public static string SendToolTip(VideoRowViewModel row)
+ {
+ ArgumentNullException.ThrowIfNull(row);
+ return WorkspaceText.ForHome("Tooltips.Editor.Render.SendAgain", row.Entry.WorkspaceServerHome);
+ }
+}
diff --git a/src/Chronos.App/Shell/MainWindow.xaml b/src/Chronos.App/Shell/MainWindow.xaml
index 0f23e5f0..f8666ac4 100644
--- a/src/Chronos.App/Shell/MainWindow.xaml
+++ b/src/Chronos.App/Shell/MainWindow.xaml
@@ -13,20 +13,22 @@
-
+
-
-
-
+
+
+
+
-
-
-
+
+
+
+
diff --git a/src/Chronos.App/Shell/SectionTemplates.xaml b/src/Chronos.App/Shell/SectionTemplates.xaml
index 3a66caf2..a72f1ac2 100644
--- a/src/Chronos.App/Shell/SectionTemplates.xaml
+++ b/src/Chronos.App/Shell/SectionTemplates.xaml
@@ -6,6 +6,8 @@
+
+
diff --git a/src/Chronos.App/Shell/SectionViewModel.cs b/src/Chronos.App/Shell/SectionViewModel.cs
index 625ae2b5..fc596ccc 100644
--- a/src/Chronos.App/Shell/SectionViewModel.cs
+++ b/src/Chronos.App/Shell/SectionViewModel.cs
@@ -10,6 +10,9 @@ public enum SectionKey
/// One sequence analysed, edited and rendered step by step (owner review 1, R7; formerly Sequence).
Edit,
+
+ /// Every render of this PC, of the server and of the workspace in one list (owner review 1, R9; Ctrl+4).
+ Videos,
Archive,
Jobs,
Server,
diff --git a/src/Chronos.App/Shell/ShellViewModel.cs b/src/Chronos.App/Shell/ShellViewModel.cs
index 8d678b32..79dea1b8 100644
--- a/src/Chronos.App/Shell/ShellViewModel.cs
+++ b/src/Chronos.App/Shell/ShellViewModel.cs
@@ -44,12 +44,14 @@ public sealed class ShellViewModel : LocalizedViewModel
Sequence = new SequenceViewModel(this);
// The workspace's clean-up never takes the project open in Edit (phase 5c).
services.Workspace.OpenProject = () => Sequence.OpenProjectId;
+ Videos = new VideosViewModel(this);
Archive = new ArchiveViewModel(this);
Jobs = new JobsViewModel(this);
Server = new ServerViewModel(this);
Settings = new SettingsViewModel(this);
About = new AboutViewModel(this);
- TopSections = [Library, Import, Sequence, Archive, Jobs, Server];
+ // Videos after Edit (owner review 1, R9, decision 20): Ctrl+4, then Archive, Jobs and Server at Ctrl+5…7.
+ TopSections = [Library, Import, Sequence, Videos, Archive, Jobs, Server];
// About is the last page of Settings (owner review 2, R5): Settings alone docks at the bottom of the rail.
BottomSections = [Settings];
foreach (var section in AllSections) section.InCollapsedRail = _isRailCollapsed;
@@ -57,7 +59,7 @@ public sealed class ShellViewModel : LocalizedViewModel
Library.IsSelected = true;
Library.PropertyChanged += OnCurrentChanged;
- // The rail and its shortcuts (Ctrl+1…6, Ctrl+,) navigate only while no first-run dialog covers the shell.
+ // The rail and its shortcuts (Ctrl+1…7, Ctrl+,) navigate only while no first-run dialog covers the shell.
NavigateCommand = new RelayCommand(p =>
{
if (p is SectionViewModel s) Navigate(s.Key);
@@ -75,6 +77,10 @@ public sealed class ShellViewModel : LocalizedViewModel
public LibraryViewModel Library { get; }
public ImportViewModel Import { get; }
public SequenceViewModel Sequence { get; }
+
+ /// The videos library (owner review 1, R9).
+ public VideosViewModel Videos { get; }
+
public ArchiveViewModel Archive { get; }
public JobsViewModel Jobs { get; }
public ServerViewModel Server { get; }
@@ -194,6 +200,16 @@ public sealed class ShellViewModel : LocalizedViewModel
///
internal void KeepSequence(Guid? sequenceId) => CurrentSequenceId = sequenceId;
+ ///
+ /// Opens Videos, narrowed to the renders of (the Export footer's "Videos (n)" and the Render
+ /// menu's "Videos"), or to every render with null; names the sequence in its filter chip.
+ ///
+ public void OpenVideos(Guid? sequenceId = null, string? title = null)
+ {
+ Videos.ShowSequence(sequenceId, title);
+ Navigate(SectionKey.Videos);
+ }
+
/// Closes the first-run overlay for good.
public void CompleteWelcome()
{
@@ -362,6 +378,7 @@ public sealed class ShellViewModel : LocalizedViewModel
Jobs.Dispose();
Library.Dispose();
Import.Dispose();
+ Videos.Dispose();
Archive.Dispose();
Server.Dispose();
Settings.Dispose();
diff --git a/src/Chronos.App/Videos/VideoPlayerPane.xaml b/src/Chronos.App/Videos/VideoPlayerPane.xaml
new file mode 100644
index 00000000..59cc7721
--- /dev/null
+++ b/src/Chronos.App/Videos/VideoPlayerPane.xaml
@@ -0,0 +1,40 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Chronos.App/Videos/VideoPlayerPane.xaml.cs b/src/Chronos.App/Videos/VideoPlayerPane.xaml.cs
new file mode 100644
index 00000000..4baec7d9
--- /dev/null
+++ b/src/Chronos.App/Videos/VideoPlayerPane.xaml.cs
@@ -0,0 +1,43 @@
+using System.Windows;
+using System.Windows.Controls;
+
+namespace Chronos.App.Videos;
+
+/// The player pane: plays the render in-process and falls back to "Cannot play here" when Windows cannot decode it.
+public partial class VideoPlayerPane : UserControl
+{
+ public VideoPlayerPane()
+ {
+ InitializeComponent();
+ DataContextChanged += (_, _) => Start();
+ }
+
+ private VideoPlayerViewModel? Model => DataContext as VideoPlayerViewModel;
+
+ private void OnMediaLoaded(object sender, RoutedEventArgs e) => Start();
+
+ /// A new render plays from its start.
+ private void Start()
+ {
+ if (!Media.IsLoaded) return;
+ if (Model is { IsVideo: true })
+ {
+ Media.Position = TimeSpan.Zero;
+ Media.Play();
+ }
+ else
+ {
+ Media.Stop();
+ }
+ }
+
+ private void OnReplay(object sender, RoutedEventArgs e) => Start();
+
+ private void OnMediaOpened(object sender, RoutedEventArgs e)
+ {
+ // A file that opens without a video stream (audio alone, a codec Windows lacks) shows nothing: said as such.
+ if (!Media.HasVideo) Model?.MediaFailed(null);
+ }
+
+ private void OnMediaFailed(object? sender, ExceptionRoutedEventArgs e) => Model?.MediaFailed(e.ErrorException);
+}
diff --git a/src/Chronos.App/Videos/VideoPlayerViewModel.cs b/src/Chronos.App/Videos/VideoPlayerViewModel.cs
new file mode 100644
index 00000000..fce20d2e
--- /dev/null
+++ b/src/Chronos.App/Videos/VideoPlayerViewModel.cs
@@ -0,0 +1,132 @@
+using System.IO;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.Localization;
+using Chronos.Core.Model;
+using Chronos.Ui.Mvvm;
+
+namespace Chronos.App.Videos;
+
+/// What the player pane shows (decision 21).
+public enum VideoPlayerMode
+{
+ /// A video file, played in-process by Windows Media Foundation (WPF MediaElement).
+ Video,
+
+ /// A still, a GIF or an APNG, shown as an image.
+ Image,
+
+ /// Windows cannot decode the file here (or it is not on this PC): "Cannot play here", Show in folder stays.
+ CannotPlay,
+}
+
+///
+/// The right-hand player pane of the Videos section (decision 21): one render played in-process, never handed to another
+/// program (BRIEF §8.6). A file Windows cannot decode says so, and Show in folder stays offered.
+///
+public sealed class VideoPlayerViewModel : ObservableObject
+{
+ /// The longest edge an image is decoded at for the pane.
+ public const int ImageEdge = 1600;
+
+ private VideoPlayerMode _mode;
+ private ImageSource? _image;
+
+ public VideoPlayerViewModel(VideoEntry entry, ICommand close, ICommand showInFolder)
+ {
+ ArgumentNullException.ThrowIfNull(entry);
+ Entry = entry;
+ CloseCommand = close;
+ ShowInFolderCommand = showInFolder;
+ _mode = ModeOf(entry);
+ if (_mode == VideoPlayerMode.Video) Source = new Uri(entry.LocalPath!, UriKind.Absolute);
+ }
+
+ public VideoEntry Entry { get; }
+
+ public string Title => Entry.Title;
+
+ public string DetailsText => VideoText.Details(Entry);
+
+ public VideoPlayerMode Mode
+ {
+ get => _mode;
+ private set
+ {
+ if (!Set(ref _mode, value)) return;
+ OnPropertyChanged(nameof(IsVideo));
+ OnPropertyChanged(nameof(IsImage));
+ OnPropertyChanged(nameof(CannotPlay));
+ }
+ }
+
+ public bool IsVideo => _mode == VideoPlayerMode.Video;
+ public bool IsImage => _mode == VideoPlayerMode.Image;
+ public bool CannotPlay => _mode == VideoPlayerMode.CannotPlay;
+
+ /// The video file the MediaElement plays; null for an image or a file that cannot play.
+ public Uri? Source { get; }
+
+ /// The still (or the first frame of a GIF or APNG), decoded at once asked for.
+ public ImageSource? Image
+ {
+ get
+ {
+ if (_image is null && _mode == VideoPlayerMode.Image) _image = LoadImage();
+ return _image;
+ }
+ }
+
+ public string CannotPlayText => Loc.L("Videos.Player.CannotPlay");
+
+ public string CannotPlayToolTip => Loc.L("Tooltips.Videos.CannotPlay");
+
+ public ICommand CloseCommand { get; }
+
+ public ICommand ShowInFolderCommand { get; }
+
+ /// Show in folder applies: the file is on this PC.
+ public bool CanShowInFolder => Entry.HasLocalFile;
+
+ /// The MediaElement could not open or decode the file (a codec Windows lacks, HEVC without its extension).
+ public void MediaFailed(Exception? error)
+ {
+ Log.Info("videos", $"{Entry.FileName} cannot play here: {error?.Message}");
+ Mode = VideoPlayerMode.CannotPlay;
+ }
+
+ /// How plays: as a video or an image when its file is here and of a kind the pane shows, else not.
+ public static VideoPlayerMode ModeOf(VideoEntry entry)
+ {
+ ArgumentNullException.ThrowIfNull(entry);
+ if (!entry.HasLocalFile || entry.Kind == RenderKind.Sequence || !File.Exists(entry.LocalPath)) return VideoPlayerMode.CannotPlay;
+ if (entry.Kind == RenderKind.Still || VideoSources.ShowsAsImage(entry.LocalPath)) return VideoPlayerMode.Image;
+ return VideoSources.PlaysAsVideo(entry.LocalPath) ? VideoPlayerMode.Video : VideoPlayerMode.CannotPlay;
+ }
+
+ private BitmapSource? LoadImage()
+ {
+ try
+ {
+ using var stream = File.OpenRead(Entry.LocalPath!);
+ var image = new BitmapImage();
+ image.BeginInit();
+ image.CacheOption = BitmapCacheOption.OnLoad;
+ image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
+ if (Entry.Width >= Entry.Height) image.DecodePixelWidth = Math.Min(ImageEdge, Math.Max(1, Entry.Width));
+ else image.DecodePixelHeight = Math.Min(ImageEdge, Math.Max(1, Entry.Height));
+ image.StreamSource = stream;
+ image.EndInit();
+ image.Freeze();
+ return image;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or InvalidOperationException or ArgumentException)
+ {
+ Log.Info("videos", $"{Entry.FileName} cannot be shown here: {ex.Message}");
+ Mode = VideoPlayerMode.CannotPlay;
+ return null;
+ }
+ }
+}
diff --git a/src/Chronos.App/Videos/VideoRows.cs b/src/Chronos.App/Videos/VideoRows.cs
new file mode 100644
index 00000000..792dc0de
--- /dev/null
+++ b/src/Chronos.App/Videos/VideoRows.cs
@@ -0,0 +1,213 @@
+using System.Globalization;
+using System.Windows.Media;
+using Chronos.App.Archiving;
+using Chronos.App.Infrastructure;
+using Chronos.Core.Localization;
+using Chronos.Core.Model;
+using Chronos.Data.Videos;
+using Chronos.Protocol;
+using Chronos.Ui.Controls;
+using Chronos.Ui.Mvvm;
+using Chronos.Ui.Visuals;
+
+namespace Chronos.App.Videos;
+
+/// The words of the Videos section: kinds, states, details and the errors of the videos library.
+public static class VideoText
+{
+ /// "Videos", "Stills", "Image sequences"; a newer kind as it is.
+ public static string Kind(string kind) => kind switch
+ {
+ RenderKind.Video => Loc.L("Videos.Kind.Video"),
+ RenderKind.Still => Loc.L("Videos.Kind.Still"),
+ RenderKind.Sequence => Loc.L("Videos.Kind.Sequence"),
+ _ => kind,
+ };
+
+ /// "0:42" for a video; empty for a still, which has no duration.
+ public static string Duration(VideoEntry entry)
+ {
+ ArgumentNullException.ThrowIfNull(entry);
+ return entry.Kind == RenderKind.Still || entry.DurationSeconds <= 0 ? string.Empty : Formatting.Elapsed(TimeSpan.FromSeconds(entry.DurationSeconds));
+ }
+
+ /// "3840×2160 · HEVC" (the size and codec, left to right in every language).
+ public static string Format(VideoEntry entry)
+ {
+ ArgumentNullException.ThrowIfNull(entry);
+ var size = entry.Width > 0 && entry.Height > 0
+ ? entry.Width.ToString(CultureInfo.InvariantCulture) + "×" + entry.Height.ToString(CultureInfo.InvariantCulture)
+ : string.Empty;
+ var codec = VideoSources.CodecText(entry.Codec);
+ return size.Length == 0 ? codec : codec.Length == 0 ? size : size + Loc.Separator + codec;
+ }
+
+ /// "3840×2160 · HEVC · 0:42 · 1.2 GB" (Videos.Details).
+ public static string Details(VideoEntry entry)
+ {
+ ArgumentNullException.ThrowIfNull(entry);
+ return Loc.L("Videos.Details", entry.Width.ToString(CultureInfo.InvariantCulture), entry.Height.ToString(CultureInfo.InvariantCulture),
+ VideoSources.CodecText(entry.Codec), Duration(entry), Formatting.Bytes(entry.Bytes));
+ }
+
+ /// The state chips of a render: where its file is, whether it was copied, and a missing file.
+ public static IReadOnlyList States(VideoEntry entry)
+ {
+ ArgumentNullException.ThrowIfNull(entry);
+ var states = new List();
+ if (entry.Missing) states.Add(new CardStatus(StatusKind.Warning, Loc.L("Videos.State.Missing"), Loc.L("Tooltips.Videos.Missing")));
+ if (entry.IsUnsent) states.Add(new CardStatus(StatusKind.Queued, Loc.L("Videos.State.NotSent"), Loc.L("Tooltips.Videos.NotSent")));
+ else if (entry.IsLocal && entry.IsOnServer) states.Add(new CardStatus(StatusKind.Synced, Loc.L("Videos.State.HereAndServer"), Loc.L("Tooltips.Videos.HereAndServer")));
+ else if (entry.IsLocal) states.Add(new CardStatus(StatusKind.Done, Loc.L("Videos.State.Here"), Loc.L("Tooltips.Videos.Here")));
+ else if (entry.IsOnServer) states.Add(new CardStatus(StatusKind.Remote, Loc.L("Videos.State.OnServer"), Loc.L("Tooltips.Videos.OnServer")));
+ if (entry.Copies.Count > 0)
+ {
+ states.Add(new CardStatus(StatusKind.Rendered, Loc.L("Videos.State.Copied"),
+ Loc.L("Tooltips.Videos.Copied", string.Join(Environment.NewLine, entry.Copies.Select(Formatting.LeftToRight)))));
+ }
+ return states;
+ }
+
+ /// The sentence of a videos library error (); is the file or sequence it is about.
+ public static string Error(VideoLibraryException ex, string? name = null)
+ {
+ ArgumentNullException.ThrowIfNull(ex);
+ return ex.Code switch
+ {
+ VideoErrors.FolderUnset => Loc.L("Errors.Videos.FolderUnset"),
+ VideoErrors.FolderInvalid => Loc.L("Errors.Videos.FolderInsideArchive"),
+ VideoErrors.PlanChanged => Loc.L("Errors.Videos.Fingerprint"),
+ VideoErrors.HashMismatch => Loc.L("Errors.Videos.TrashMismatch"),
+ VideoErrors.NoSpace => Loc.L("Errors.Videos.NoSpace", name ?? string.Empty),
+ VideoErrors.SequenceGone => Loc.L("Errors.Videos.SequenceGone", name ?? string.Empty),
+ VideoErrors.Busy => Loc.L("Errors.Videos.Busy", name ?? string.Empty),
+ _ => ex.Message,
+ };
+ }
+
+ /// Why a copy into 's folder is refused (a tooltip), from .
+ public static string FolderReason(string problem) =>
+ problem == VideoErrors.FolderUnset ? Loc.L("Tooltips.Videos.FolderUnset") : Loc.L("Errors.Videos.FolderInsideArchive");
+
+ /// "In use by a job", "Not found".
+ public static string BlockReason(string reason) =>
+ reason == VideoBlockReasons.Busy ? Loc.L("Videos.Blocked.Busy") : Loc.L("Videos.Blocked.NotFound");
+}
+
+/// One render of the Videos section, as a card of the grid or a row of the list.
+public sealed class VideoRowViewModel(VideoEntry entry) : ObservableObject
+{
+ private bool _isSelected;
+ private ImageSource? _poster;
+ private bool _posterRequested;
+
+ public VideoEntry Entry { get; } = entry;
+
+ public string Title => Entry.Title;
+
+ /// The preset name (and the project's, when a project was rendered).
+ public string Subtitle => Entry.ProjectName is { Length: > 0 } project ? Entry.PresetName + Loc.Separator + project : Entry.PresetName;
+
+ public string DetailsText => VideoText.Details(Entry);
+ public string FormatText => VideoText.Format(Entry);
+ public string DurationText => VideoText.Duration(Entry);
+ public string SizeText => Formatting.Bytes(Entry.Bytes);
+ public string DateText => Formatting.Date(Entry.Created) + " " + Formatting.TimeOfDay(Entry.Created);
+ public string KindText => VideoText.Kind(Entry.Kind);
+ public IReadOnlyList States { get; } = VideoText.States(entry);
+
+ /// The card's and the row's tooltip: what it is, then how to select it.
+ public string ToolTip => Entry.IsUnsent ? Loc.L("Tooltips.Videos.WorkspaceRow") : Loc.L("Tooltips.Videos.Select");
+
+ /// The file name, left to right in every language.
+ public string FileNameText => Formatting.LeftToRight(Entry.FileName);
+
+ public bool IsSelected
+ {
+ get => _isSelected;
+ set
+ {
+ if (Set(ref _isSelected, value)) SelectionChanged?.Invoke(this);
+ }
+ }
+
+ /// The sequence's cover, or the still itself; null until loaded ().
+ public ImageSource? Poster
+ {
+ get => _poster;
+ internal set => Set(ref _poster, value);
+ }
+
+ /// The card came on screen: its poster is loaded once by .
+ public void RequestPoster()
+ {
+ if (_posterRequested || _poster is not null) return;
+ _posterRequested = true;
+ PosterRequested?.Invoke(this);
+ }
+
+ internal event Action? SelectionChanged;
+
+ internal event Action? PosterRequested;
+}
+
+///
+/// The dry run of a delete of videos (decision 17) in the words of its confirmation: what goes into the trash (and how
+/// many bytes), the renders whose file is missing (only their entry goes), the renders left where they are and why, and
+/// that copies in the videos folder stay. This PC's renders and the server's are planned apart and confirmed together.
+///
+public sealed record VideoDeletePlans(VideoDeletePlan? Local, VideoDeletePlanDto? Server)
+{
+ /// The renders that go.
+ public int Count => (Local?.Items.Count ?? 0) + (Server?.Items.Count ?? 0);
+
+ /// The bytes that move into the trash.
+ public long Bytes => (Local?.Bytes ?? 0) + (Server?.Bytes ?? 0);
+
+ /// The renders left where they are.
+ public int Blocked => (Local?.Blocked.Count ?? 0) + (Server?.Blocked.Count ?? 0);
+
+ /// The renders whose file is missing: only their entry goes.
+ public int Missing => (Local?.Items.Count(i => i.Missing) ?? 0) + (Server?.Items.Count(i => i.Missing) ?? 0);
+
+ /// The lines of what goes, then of what stays and why ( each, the rest counted).
+ public IReadOnlyList Lines()
+ {
+ var goes = (Local?.Items.Select(i => (i.SequenceTitle, i.FileName, i.Render.Bytes, i.Missing)) ?? [])
+ .Concat(Server?.Items.Select(i => (i.SequenceTitle, FileName: i.FileName ?? string.Empty, i.Bytes, i.Missing)) ?? []).ToList();
+ var lines = new List();
+ foreach (var (title, file, bytes, missing) in goes.Take(DeletePlans.ListedLines))
+ {
+ lines.Add(Loc.L("Archive.Delete.Line", title, Formatting.LeftToRight(file),
+ missing ? Loc.L("Videos.State.Missing") : Formatting.Bytes(bytes)));
+ }
+ if (goes.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", goes.Count - DeletePlans.ListedLines));
+ var stays = (Local?.Blocked.Select(b => (b.Video?.SequenceTitle ?? b.RenderId.ToString("D"), b.Reason)) ?? [])
+ .Concat(Server?.Blocked.Select(b => (b.Id.ToString("D"), b.Reason)) ?? []).ToList();
+ if (stays.Count > 0) lines.Add(Loc.L("Videos.Delete.Blocked", Formatting.Count(stays.Count)));
+ foreach (var (name, reason) in stays.Take(DeletePlans.ListedLines)) lines.Add(name + Loc.Separator + VideoText.BlockReason(reason));
+ if (stays.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", stays.Count - DeletePlans.ListedLines));
+ return lines;
+ }
+
+ /// The confirmation of moving the planned renders into the trash; null when nothing would go.
+ public ConfirmRequest? Request()
+ {
+ if (Count == 0) return null;
+ var message = Loc.L("Videos.Delete.Summary", Formatting.Count(Count), Formatting.Bytes(Bytes)) + Environment.NewLine + Loc.L("Videos.Delete.CopiesStay");
+ if (Missing > 0) message += Environment.NewLine + Loc.L("Videos.Delete.Missing");
+ return new ConfirmRequest
+ {
+ Heading = Loc.L("Videos.Delete.Title"),
+ Message = message,
+ Detail = string.Join(Environment.NewLine, Lines()),
+ IsDetailMonospaced = false,
+ DetailToolTip = Loc.L("Tooltips.Videos.Delete"),
+ SafeText = Loc.L("Archive.Delete.Keep"),
+ SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
+ ActionText = Loc.L("Videos.Delete.Confirm"),
+ ActionToolTip = Loc.L("Tooltips.Videos.DeleteConfirm"),
+ IsDestructive = true,
+ };
+ }
+}
diff --git a/src/Chronos.App/Videos/VideoSources.cs b/src/Chronos.App/Videos/VideoSources.cs
new file mode 100644
index 00000000..42c7a98e
--- /dev/null
+++ b/src/Chronos.App/Videos/VideoSources.cs
@@ -0,0 +1,474 @@
+using System.IO;
+using Chronos.App.Workspace;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.Export;
+using Chronos.Core.Model;
+using Chronos.Core.Video;
+using Chronos.Data.Videos;
+using Chronos.Data.Workspaces;
+using Chronos.Protocol;
+using Chronos.Protocol.Client;
+
+namespace Chronos.App.Videos;
+
+/// Which renders the Videos section lists (its Source filter, owner review 1, R9).
+public enum VideoSourceFilter
+{
+ All,
+
+ /// Renders whose file is on this PC: the archive's and the workspace's not sent yet.
+ Local,
+
+ /// Renders the signed-in server holds.
+ Server,
+
+ /// Renders of workspace projects not at their home yet.
+ NotSent,
+}
+
+/// How the signed-in server's videos reach the Videos section.
+public enum VideoServerState
+{
+ /// Listed with this PC's.
+ Available,
+
+ /// Not signed in to a server: this PC's videos alone.
+ SignedOut,
+
+ /// The server's Chronos has no videos library (no ): this PC's videos alone.
+ Old,
+
+ /// The server did not answer: this PC's videos alone.
+ Unreachable,
+}
+
+///
+/// One render of the Videos section (decision 20): the archive's, the signed-in server's and the workspace's renders merged
+/// by render id, with where its file is. WPF-free.
+///
+public sealed record VideoEntry
+{
+ public required Guid Id { get; init; }
+ public required Guid SequenceId { get; init; }
+
+ /// The sequence's display title.
+ public required string Title { get; init; }
+
+ public required string PresetName { get; init; }
+ public string? Codec { get; init; }
+ public int Width { get; init; }
+ public int Height { get; init; }
+ public double Fps { get; init; }
+ public double DurationSeconds { get; init; }
+ public long Bytes { get; init; }
+ public DateTimeOffset Created { get; init; }
+
+ /// , , or a newer kind as it is.
+ public required string Kind { get; init; }
+
+ /// The file (or folder) name.
+ public required string FileName { get; init; }
+
+ /// The file (or folder) on this PC; null for a render the server alone holds.
+ public string? LocalPath { get; init; }
+
+ /// The render is in this PC's index (its archive).
+ public bool IsLocal { get; init; }
+
+ /// The signed-in server holds the render.
+ public bool IsOnServer { get; init; }
+
+ /// A workspace render not at its home yet: read-only here (Play, Show in folder, Send).
+ public bool IsUnsent { get; init; }
+
+ /// The file is not where it was recorded (here, or on the server for a render the server alone holds).
+ public bool Missing { get; init; }
+
+ /// The workspace project of an unsent render; null otherwise.
+ public Guid? WorkspaceProjectId { get; init; }
+
+ /// The workspace project's home is a server.
+ public bool WorkspaceServerHome { get; init; }
+
+ /// The project rendered; null for a render of the sequence's settings.
+ public string? ProjectName { get; init; }
+
+ /// The paths of its verified copies in videos folders (of this PC and of the server).
+ public IReadOnlyList Copies { get; init; } = [];
+
+ /// The render's file is on this PC.
+ public bool HasLocalFile => LocalPath is not null && !Missing;
+
+ /// The year the render was made (UTC, as the server filters it).
+ public int Year => Created.UtcDateTime.Year;
+}
+
+/// The filters and the order of the Videos section; every member optional, combined with "and".
+public sealed record VideoFilter
+{
+ public static VideoFilter None { get; } = new();
+
+ /// Text in the title, the preset name or the file name (any case).
+ public string? Text { get; init; }
+
+ /// One of ; null for every kind.
+ public string? Kind { get; init; }
+
+ /// A codec as recorded; null for every codec.
+ public string? Codec { get; init; }
+
+ public int? Year { get; init; }
+
+ public VideoSourceFilter Source { get; init; }
+
+ /// The renders of one sequence (the Export footer's and the Render menu's "Videos").
+ public Guid? SequenceId { get; init; }
+
+ /// One of ; null for newest first.
+ public string? Sort { get; init; }
+
+ /// Anything narrows the list (the order alone does not).
+ public bool IsFiltered => !string.IsNullOrWhiteSpace(Text) || Kind is not null || Codec is not null || Year is not null || Source != VideoSourceFilter.All
+ || SequenceId is not null;
+
+ public bool Matches(VideoEntry entry)
+ {
+ ArgumentNullException.ThrowIfNull(entry);
+ if (SequenceId is { } sequence && entry.SequenceId != sequence) return false;
+ if (Kind is { } kind && !string.Equals(entry.Kind, kind, StringComparison.Ordinal)) return false;
+ if (Codec is { } codec && !string.Equals(entry.Codec, codec, StringComparison.OrdinalIgnoreCase)) return false;
+ if (Year is { } year && entry.Year != year) return false;
+ if (Source switch
+ {
+ VideoSourceFilter.Local => !entry.IsLocal && !entry.IsUnsent,
+ VideoSourceFilter.Server => !entry.IsOnServer,
+ VideoSourceFilter.NotSent => !entry.IsUnsent,
+ _ => false,
+ })
+ return false;
+ if (Text?.Trim() is { Length: > 0 } text
+ && !entry.Title.Contains(text, StringComparison.CurrentCultureIgnoreCase)
+ && !entry.PresetName.Contains(text, StringComparison.CurrentCultureIgnoreCase)
+ && !entry.FileName.Contains(text, StringComparison.CurrentCultureIgnoreCase))
+ return false;
+ return true;
+ }
+
+ /// The entries that match, in the chosen order (ties newest first, then by id, so the order is stable).
+ public IReadOnlyList Apply(IEnumerable entries)
+ {
+ ArgumentNullException.ThrowIfNull(entries);
+ var matching = entries.Where(Matches);
+ IOrderedEnumerable ordered = Sort switch
+ {
+ VideoSorts.Oldest => matching.OrderBy(e => e.Created),
+ VideoSorts.Largest => matching.OrderByDescending(e => e.Bytes).ThenByDescending(e => e.Created),
+ VideoSorts.Title => matching.OrderBy(e => e.Title, StringComparer.CurrentCultureIgnoreCase).ThenByDescending(e => e.Created),
+ _ => matching.OrderByDescending(e => e.Created),
+ };
+ return [.. ordered.ThenBy(e => e.Id)];
+ }
+}
+
+///
+/// The signed-in server's videos library (/api/v1/videos) as the Videos section uses it; one connection, disposed
+/// after use. Tests substitute a fake server.
+///
+public interface IRemoteVideos : IDisposable
+{
+ /// One page of the server's videos.
+ Task ListAsync(VideoQueryDto query, CancellationToken cancellationToken = default);
+
+ /// The dry run of deleting into the server's trash.
+ Task PlanDeleteAsync(IReadOnlyList ids, CancellationToken cancellationToken = default);
+
+ /// The delete as planned; a changed plan is a 409 plan_changed.
+ Task DeleteAsync(IReadOnlyList ids, string fingerprint, CancellationToken cancellationToken = default);
+
+ /// Queues the copy of into the server's videos folder.
+ Task CopyAsync(IReadOnlyList ids, CancellationToken cancellationToken = default);
+}
+
+/// over a signed-in , which it owns.
+public sealed class ChronosRemoteVideos(ChronosClient client) : IRemoteVideos
+{
+ public Task ListAsync(VideoQueryDto query, CancellationToken cancellationToken = default) => client.ListVideosAsync(query, cancellationToken);
+
+ public Task PlanDeleteAsync(IReadOnlyList ids, CancellationToken cancellationToken = default) =>
+ client.PlanDeleteVideosAsync(ids, cancellationToken);
+
+ public Task DeleteAsync(IReadOnlyList ids, string fingerprint, CancellationToken cancellationToken = default) =>
+ client.DeleteVideosAsync(ids, fingerprint, cancellationToken);
+
+ public Task CopyAsync(IReadOnlyList ids, CancellationToken cancellationToken = default) => client.CopyVideosAsync(ids, cancellationToken);
+
+ public void Dispose() => client.Dispose();
+}
+
+///
+/// The signed-in server as the Videos section sees it: whether its videos can be listed, a connection when they can, and
+/// what the account may do there.
+///
+/// A new connection to the server; null unless is .
+public sealed record VideoServer(VideoServerState State, Func? Connect = null, bool CanEdit = false, bool CanDelete = false)
+{
+ public static VideoServer SignedOut { get; } = new(VideoServerState.SignedOut);
+
+ /// The server of for an account of : without the capability.
+ public static VideoServer Of(ServerInfo? info, long permissions, Func connect)
+ {
+ ArgumentNullException.ThrowIfNull(connect);
+ if (info is null) return SignedOut;
+ if (!info.Capabilities.Contains(ServerCapabilities.Videos)) return new VideoServer(VideoServerState.Old);
+ return new VideoServer(VideoServerState.Available, connect, (permissions & (long)Permissions.Edit) != 0, (permissions & (long)Permissions.Delete) != 0);
+ }
+}
+
+/// Reading and merging the three places renders are (decision 20): the archive, the signed-in server, the workspace.
+public static class VideoSources
+{
+ /// Pages read from one place at most (500 videos each).
+ public const int MaxPages = 40;
+
+ /// Extensions the player pane plays with Windows Media Foundation (decision 21).
+ private static readonly string[] VideoExtensions = [".mp4", ".m4v", ".mov", ".wmv", ".avi", ".mkv", ".webm"];
+
+ /// Extensions the player pane shows as an image (stills, GIF, APNG).
+ private static readonly string[] ImageExtensions = [".png", ".apng", ".jpg", ".jpeg", ".tif", ".tiff", ".gif", ".bmp"];
+
+ /// A render of this PC's index.
+ public static VideoEntry FromLocal(VideoItem item)
+ {
+ ArgumentNullException.ThrowIfNull(item);
+ var render = item.Render;
+ return new VideoEntry
+ {
+ Id = render.Id,
+ SequenceId = render.SequenceId,
+ Title = item.SequenceTitle,
+ PresetName = render.PresetName,
+ Codec = render.Codec,
+ Width = render.Width,
+ Height = render.Height,
+ Fps = render.Fps,
+ DurationSeconds = render.DurationSeconds,
+ Bytes = render.Bytes,
+ Created = render.Created,
+ Kind = item.Kind,
+ FileName = item.FileName,
+ LocalPath = item.FullPath,
+ IsLocal = true,
+ Missing = item.Missing,
+ ProjectName = item.ProjectName,
+ Copies = [.. item.Copies.Select(c => c.Path)],
+ };
+ }
+
+ /// A render of the signed-in server.
+ public static VideoEntry FromServer(VideoDto video)
+ {
+ ArgumentNullException.ThrowIfNull(video);
+ return new VideoEntry
+ {
+ Id = video.Id,
+ SequenceId = video.SequenceId,
+ Title = video.SequenceTitle,
+ PresetName = video.PresetName,
+ Codec = video.Codec,
+ Width = video.Width,
+ Height = video.Height,
+ Fps = video.Fps,
+ DurationSeconds = video.DurationSeconds,
+ Bytes = video.Bytes,
+ Created = video.Created,
+ Kind = video.Kind,
+ FileName = video.FileName ?? video.PresetName,
+ IsOnServer = true,
+ Missing = video.State == VideoStates.Missing,
+ ProjectName = video.ProjectName,
+ Copies = [.. video.Copies.Select(c => c.Path)],
+ };
+ }
+
+ /// A workspace render not sent yet ( its file on this PC).
+ public static VideoEntry FromWorkspace(WorkspaceRenderEntry render, WorkspaceEntry project, string path, bool exists)
+ {
+ ArgumentNullException.ThrowIfNull(render);
+ ArgumentNullException.ThrowIfNull(project);
+ return new VideoEntry
+ {
+ Id = render.RenderId,
+ SequenceId = project.SequenceId,
+ Title = project.SequenceTitle,
+ PresetName = render.PresetName,
+ Codec = render.Codec,
+ Width = render.Width,
+ Height = render.Height,
+ Fps = render.Fps,
+ DurationSeconds = render.DurationSeconds,
+ Bytes = render.Size,
+ Created = render.Rendered,
+ Kind = RenderKind.Of(null, render.Codec),
+ FileName = Path.GetFileName(path.TrimEnd('/', '\\')),
+ LocalPath = path,
+ IsUnsent = true,
+ Missing = !exists,
+ WorkspaceProjectId = project.ProjectId,
+ WorkspaceServerHome = project.IsServerHome,
+ ProjectName = project.Name,
+ };
+ }
+
+ ///
+ /// One list, one entry per render id: this PC's renders first (their file here), marked when the server holds the same
+ /// render too ("Here and on server"); the server's other renders; then the workspace's renders that neither holds yet.
+ ///
+ public static IReadOnlyList Merge(IEnumerable local, IEnumerable server, IEnumerable workspace)
+ {
+ ArgumentNullException.ThrowIfNull(local);
+ ArgumentNullException.ThrowIfNull(server);
+ ArgumentNullException.ThrowIfNull(workspace);
+ var merged = new Dictionary();
+ var order = new List();
+ foreach (var entry in local)
+ {
+ if (merged.TryAdd(entry.Id, entry)) order.Add(entry.Id);
+ }
+ foreach (var entry in server)
+ {
+ if (merged.TryGetValue(entry.Id, out var here))
+ {
+ merged[entry.Id] = here with { IsOnServer = true, Copies = [.. here.Copies.Concat(entry.Copies).Distinct(StringComparer.OrdinalIgnoreCase)] };
+ }
+ else if (merged.TryAdd(entry.Id, entry))
+ {
+ order.Add(entry.Id);
+ }
+ }
+ // A workspace render the archive or the server holds was sent: the library's entry stands for it.
+ foreach (var entry in workspace)
+ {
+ if (merged.TryAdd(entry.Id, entry)) order.Add(entry.Id);
+ }
+ return [.. order.Select(id => merged[id])];
+ }
+
+ /// Every render of this PC's index ( pages at most); none while the library is not there.
+ public static async Task> ReadLocalAsync(IVideoLibrary? library, CancellationToken cancellationToken = default)
+ {
+ if (library is null || !library.IsAvailable) return [];
+ var entries = new List();
+ string? cursor = null;
+ for (var page = 0; page < MaxPages; page++)
+ {
+ var read = await library.ListAsync(new VideoQuery { Cursor = cursor, Limit = VideoQuery.MaxLimit }, cancellationToken).ConfigureAwait(false);
+ entries.AddRange(read.Items.Select(FromLocal));
+ cursor = read.Next;
+ if (cursor is null) break;
+ }
+ return entries;
+ }
+
+ /// Every render of the server ( pages at most).
+ public static async Task> ReadServerAsync(IRemoteVideos remote, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(remote);
+ var entries = new List();
+ string? cursor = null;
+ for (var page = 0; page < MaxPages; page++)
+ {
+ var read = await remote.ListAsync(new VideoQueryDto(Cursor: cursor, Limit: VideoQuery.MaxLimit), cancellationToken).ConfigureAwait(false);
+ entries.AddRange(read.Items.Select(FromServer));
+ cursor = read.Next;
+ if (cursor is null) break;
+ }
+ return entries;
+ }
+
+ ///
+ /// The workspace renders not at their home yet, of every project whose ledger reads (one that does not is logged and
+ /// skipped: it never hides the others).
+ ///
+ public static IReadOnlyList ReadWorkspace(WorkspaceStore store, IEnumerable projects)
+ {
+ ArgumentNullException.ThrowIfNull(store);
+ ArgumentNullException.ThrowIfNull(projects);
+ var entries = new List();
+ foreach (var project in projects.Where(p => p.IsReadable))
+ {
+ try
+ {
+ var folder = store.Project(project.ProjectId);
+ foreach (var render in folder.ReadRenders().Unsent)
+ {
+ var path = folder.ExportFile(render.File);
+ entries.Add(FromWorkspace(render, project, path, File.Exists(path) || Directory.Exists(path)));
+ }
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ Log.Warning("videos", $"The render ledger of workspace project {project.ProjectId} cannot be read", ex);
+ }
+ }
+ return entries;
+ }
+
+ /// "H.264", "HEVC", "PNG"… for a codec as recorded; the recorded name in capitals for one this Chronos does not know.
+ public static string CodecText(string? codec) =>
+ codec is null or { Length: 0 } ? string.Empty
+ : Enum.TryParse(codec, ignoreCase: true, out var known) && Enum.IsDefined(known) ? ExportNaming.CodecLabel(known)
+ : codec.ToUpperInvariant();
+
+ /// The player pane can play the file as a video.
+ public static bool PlaysAsVideo(string? path) => path is not null && VideoExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase);
+
+ /// The player pane shows the file as an image.
+ public static bool ShowsAsImage(string? path) => path is not null && ImageExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase);
+}
+
+/// The videos folder of this PC (decision 15): where Copy to folder puts renders.
+public static class VideosFolders
+{
+ /// %USERPROFILE%\Videos\Chronos; null when Windows names no videos folder (decision 15, Q12).
+ public static string? Default()
+ {
+ var videos = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
+ return string.IsNullOrEmpty(videos) ? null : Path.Combine(videos, "Chronos");
+ }
+
+ ///
+ /// Why cannot be the videos folder, as one of : unset, or inside (or
+ /// equal to) the archive root or the workspace; null when it can.
+ ///
+ public static string? Problem(string? folder, params string?[] refused)
+ {
+ if (string.IsNullOrWhiteSpace(folder)) return VideoErrors.FolderUnset;
+ string full;
+ try
+ {
+ if (!Path.IsPathFullyQualified(folder)) return VideoErrors.FolderInvalid;
+ full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
+ }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
+ {
+ return VideoErrors.FolderInvalid;
+ }
+ foreach (var root in refused)
+ {
+ if (string.IsNullOrWhiteSpace(root)) continue;
+ string other;
+ try
+ {
+ other = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root));
+ }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
+ {
+ continue;
+ }
+ if (string.Equals(full, other, StringComparison.OrdinalIgnoreCase)
+ || full.StartsWith(other + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
+ return VideoErrors.FolderInvalid;
+ }
+ return null;
+ }
+}
diff --git a/tests/Chronos.App.Tests/Videos/VideosSectionTests.cs b/tests/Chronos.App.Tests/Videos/VideosSectionTests.cs
new file mode 100644
index 00000000..4b6b1199
--- /dev/null
+++ b/tests/Chronos.App.Tests/Videos/VideosSectionTests.cs
@@ -0,0 +1,551 @@
+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);
+ }
+
+ [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);
+ });
+
+ [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();
+ 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);
+ section.LayoutIndex = 1;
+ section.Rows[0].IsSelected = true;
+ 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();
+ }
+
+ /// 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; } = [];
+
+ 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); 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 DeleteAsync(IReadOnlyList 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 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;
+ }
+}