Files
Chronos/src/Chronos.App/Sections/VideosViewModel.cs
T
Alby96andClaude Opus 5.5 5a6efbb72f feat(videos): board of published and workspace renders; card line starts with the preset
The Videos section and the admin Videos page gain a Board view with two
lanes, newest first, each with a count and the list's filters: Published
(library and server renders, including those sent from a workspace) and
Workspace (workspace exports, unsent ones plus sent ones marked Sent).
Cards show the sequence, project and version when known, preset, kind,
date and state chips, and reuse the existing actions; no new store.

Video cards now start with the preset ("4K archive · HEVC · 0:41 · 1.4 GB")
and Formatting.Bytes keeps number and unit together with a no-break space
(#28). The capture tool adds the videos-board scene in both themes.

Refs #29

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 17:13:26 +01:00

994 lines
46 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
/// <summary>
/// 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. The Board (owner request of 2026-11-06) shows the same
/// renders in two lanes, Published and Workspace (<see cref="VideoBoard"/>), with the workspace's sent renders beside them.
/// </summary>
public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVideosSection
{
private IReadOnlyList<VideoEntry> _entries = [];
private IReadOnlyList<VideoRowViewModel> _rows = [];
private IReadOnlyList<VideoEntry> _sent = [];
private IReadOnlyList<VideoRowViewModel> _sentRows = [];
private IReadOnlyList<VideoRowViewModel> _publishedRows = [];
private IReadOnlyList<VideoRowViewModel> _workspaceRows = [];
private IReadOnlyList<FilterOption<string?>> _kinds = [];
private IReadOnlyList<FilterOption<string?>> _codecs = [];
private IReadOnlyList<FilterOption<int?>> _years = [];
private IReadOnlyList<FilterOption<VideoSourceFilter>> _sources = [];
private IReadOnlyList<FilterOption<string?>> _sorts = [];
private FilterOption<string?> _kind = null!;
private FilterOption<string?> _codec = null!;
private FilterOption<int?> _year = null!;
private FilterOption<VideoSourceFilter> _source = null!;
private FilterOption<string?> _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<Guid, Task<Sequence?>> _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);
ClearSequenceCommand = new RelayCommand(() => ShowSequence(null), () => IsSequenceFiltered);
RefreshCommand = new AsyncRelayCommand(RefreshAsync);
_layoutIndex = services.Settings.VideosLayout switch
{
LibraryLayout.List => 1,
LibraryLayout.Board => 2,
_ => 0,
};
ClearSelectionCommand = new RelayCommand(() =>
{
foreach (var row in AllRows) row.IsSelected = false;
}, () => HasSelection);
ClosePlayerCommand = new RelayCommand(() => Player = null);
}
public ShellViewModel Shell { get; }
// ---- Sources (tests substitute their own) ----
/// <summary>This PC's videos library; null while the index is not open.</summary>
internal Func<IVideoLibrary?> LocalLibrary { get; set; }
/// <summary>The signed-in server's videos, and what the account may do there.</summary>
internal Func<VideoServer> ServerVideos { get; set; }
/// <summary>The workspace's renders: those not sent yet, and those sent whose file is still there (the Board's).</summary>
internal Func<CancellationToken, Task<IReadOnlyList<VideoEntry>>> WorkspaceRenders { get; set; }
/// <summary>Queues a job of this PC (a copy into the videos folder).</summary>
internal Func<ArchiveJobRequest, Task> Enqueue { get; set; }
/// <summary>The poster of a card: the sequence's cover, or the still itself.</summary>
internal Func<VideoEntry, int, CancellationToken, Task<ImageSource?>> Posters { get; set; }
/// <summary>The videos folder of this PC (Settings › Archive); null or empty while unset.</summary>
internal Func<string?> Folder { get; set; }
// ---- List ----
/// <summary>Every render, merged, before the filters.</summary>
public IReadOnlyList<VideoEntry> Entries
{
get => _entries;
private set
{
_entries = value;
BuildOptions();
Apply();
}
}
/// <summary>The renders the filters keep, in the chosen order.</summary>
public IReadOnlyList<VideoRowViewModel> 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.Section = this;
row.SelectionChanged += OnSelectionChanged;
row.PosterRequested += OnPosterRequested;
}
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(IsNoMatch));
OnSelectionChanged(null);
}
}
/// <summary>The workspace's sent renders whose file is still in its <c>exports/</c>, before the filters (the Board's alone).</summary>
public IReadOnlyList<VideoEntry> SentEntries => _sent;
/// <summary>The Board's Published lane: renders filed at this PC's archive or the server, newest first.</summary>
public IReadOnlyList<VideoRowViewModel> PublishedRows { get => _publishedRows; private set => Set(ref _publishedRows, value); }
/// <summary>The Board's Workspace lane: the workspace's renders not sent yet and those sent, newest first.</summary>
public IReadOnlyList<VideoRowViewModel> WorkspaceRows { get => _workspaceRows; private set => Set(ref _workspaceRows, value); }
/// <summary>The Published lane's count.</summary>
public string PublishedCountText => Formatting.Count(_publishedRows.Count);
/// <summary>The Workspace lane's count.</summary>
public string WorkspaceCountText => Formatting.Count(_workspaceRows.Count);
/// <summary>The Published lane is empty and the Workspace lane is not ("No videos" in the lane; both empty is the section's empty state).</summary>
public bool IsPublishedEmpty => _publishedRows.Count == 0 && _workspaceRows.Count > 0;
/// <summary>The Workspace lane is empty and the Published lane is not.</summary>
public bool IsWorkspaceEmpty => _workspaceRows.Count == 0 && _publishedRows.Count > 0;
/// <summary>The rows of the list and the Board's sent rows: what a selection can hold.</summary>
private IEnumerable<VideoRowViewModel> AllRows => _rows.Concat(_sentRows);
public bool IsLoading
{
get => _isLoading;
private set
{
if (!Set(ref _isLoading, value)) return;
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(IsNoMatch));
}
}
/// <summary>No video anywhere: "No videos".</summary>
public bool IsEmpty => !_isLoading && _entries.Count == 0 && (_sent.Count == 0 || !IsBoard);
/// <summary>Videos, none of which the filters keep: "No videos" and Clear filters.</summary>
public bool IsNoMatch => !_isLoading && !IsEmpty && (IsBoard ? _publishedRows.Count + _workspaceRows.Count == 0 : _rows.Count == 0);
/// <summary>The cards (0), the list (1) or the Board (2), kept for the next run (Settings: <see cref="AppSettings.VideosLayout"/>).</summary>
public int LayoutIndex
{
get => _layoutIndex;
set
{
if (value is < 0 or > 2 || !Set(ref _layoutIndex, value)) return;
Shell.Services.Settings.VideosLayout = value switch
{
1 => LibraryLayout.List,
2 => LibraryLayout.Board,
_ => LibraryLayout.Grid,
};
// The sent renders show on the Board alone: off it, none of them stays selected out of sight.
if (value != 2)
{
foreach (var row in _sentRows) row.IsSelected = false;
}
OnPropertyChanged(nameof(IsGrid));
OnPropertyChanged(nameof(IsList));
OnPropertyChanged(nameof(IsBoard));
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(IsNoMatch));
}
}
public bool IsGrid => _layoutIndex == 0;
public bool IsList => _layoutIndex == 1;
public bool IsBoard => _layoutIndex == 2;
// ---- Filters ----
public string SearchText
{
get => _searchText;
set
{
if (Set(ref _searchText, value ?? string.Empty)) Apply();
}
}
public IReadOnlyList<FilterOption<string?>> Kinds { get => _kinds; private set => Set(ref _kinds, value); }
public IReadOnlyList<FilterOption<string?>> Codecs { get => _codecs; private set => Set(ref _codecs, value); }
public IReadOnlyList<FilterOption<int?>> Years { get => _years; private set => Set(ref _years, value); }
public IReadOnlyList<FilterOption<VideoSourceFilter>> Sources { get => _sources; private set => Set(ref _sources, value); }
public IReadOnlyList<FilterOption<string?>> Sorts { get => _sorts; private set => Set(ref _sorts, value); }
public FilterOption<string?> SelectedKind
{
get => _kind;
set => SetFilter(ref _kind, value ?? _kinds[0]);
}
public FilterOption<string?> SelectedCodec
{
get => _codec;
set => SetFilter(ref _codec, value ?? _codecs[0]);
}
public FilterOption<int?> SelectedYear
{
get => _year;
set => SetFilter(ref _year, value ?? _years[0]);
}
public FilterOption<VideoSourceFilter> SelectedSource
{
get => _source;
set => SetFilter(ref _source, value ?? _sources[0]);
}
public FilterOption<string?> 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 };
/// <summary>The sequence the list is narrowed to (the Export footer's and the Render menu's "Videos"); null for all.</summary>
public Guid? SequenceId => _sequenceId;
/// <summary>The title of that sequence, shown as a chip that clears it.</summary>
public string? SequenceFilterText => _sequenceId is null ? null : _sequenceTitle ?? _entries.FirstOrDefault(e => e.SequenceId == _sequenceId)?.Title;
public bool IsSequenceFiltered => _sequenceId is not null;
/// <summary>The filters and the order in force.</summary>
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; }
/// <summary>The sequence chip: the videos of every sequence again, the other filters kept.</summary>
public ICommand ClearSequenceCommand { get; }
/// <summary>Reads this PC's, the server's and the workspace's videos again (<see cref="RefreshAsync"/>).</summary>
public ICommand RefreshCommand { get; }
/// <summary>Narrows the list to the videos of one sequence (null: every sequence).</summary>
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();
}
/// <summary>The editor's links to this section (<see cref="Chronos.App.Editor.VideosLink"/>) narrow it the same way.</summary>
void Chronos.App.Editor.IVideosSection.ShowSequence(Guid? sequenceId) => ShowSequence(sequenceId);
// ---- Server ----
/// <summary>How the signed-in server's videos reach the list.</summary>
public VideoServerState ServerState => _server.State;
/// <summary>The server's videos are not listed: the status line says why.</summary>
public bool IsServerLimited => _server.State != VideoServerState.Available && (_server.State != VideoServerState.SignedOut || Shell.Services.Server.HasSavedSession);
/// <summary>"Server not reachable", or "Server" greyed out with its reason in <see cref="ServerStatusToolTip"/>.</summary>
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<VideoRowViewModel> SelectedRows => [.. AllRows.Where(r => r.IsSelected)];
public bool HasSelection => AllRows.Any(r => r.IsSelected);
/// <summary>"Selected: 3".</summary>
public string SelectionText => Loc.L("Videos.Selected", Formatting.Count(AllRows.Count(r => r.IsSelected)));
public ICommand ClearSelectionCommand { get; }
// ---- Actions ----
public ICommand PlayCommand { get; }
/// <summary>The toolbar's Play tooltip: why the selection does not play here, else what Play does.</summary>
public string PlayToolTip => PlayToolTipOf(SelectedRows);
public ICommand ShowInFolderCommand { get; }
public ICommand CopyCommand { get; }
public ICommand CopyOnServerCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand OpenInEditCommand { get; }
public ICommand SendCommand { get; }
/// <summary>Copy to folder, or Download for the server's videos alone.</summary>
public string CopyText => CopyTextOf(SelectedRows);
public string CopyToolTip => CopyToolTipOf(SelectedRows);
public string CopyOnServerToolTip => CopyOnServerToolTipOf(SelectedRows);
public string DeleteToolTip => DeleteToolTipOf(SelectedRows);
/// <summary>Show in folder's tooltip: why it waits (more than one video, a server's video alone, a file gone), else what it does.</summary>
public string ShowInFolderToolTip => ShowInFolderToolTipOf(SelectedRows);
/// <summary>Open in Edit's tooltip: why it waits (more than one video, a server's video alone), else what it does.</summary>
public string OpenInEditToolTip => OpenInEditToolTipOf(SelectedRows);
/// <summary>The row's Copy to folder or Download tooltip (its context menu).</summary>
public string RowCopyToolTip(VideoRowViewModel row) => CopyToolTipOf(Targets(row));
/// <summary>What the row's menu acts on: the selection when the row is part of it, else the row alone (as the commands do).</summary>
internal IReadOnlyList<VideoRowViewModel> TargetsOf(VideoRowViewModel row) => Targets(row);
internal static string PlayToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[var one] => one.PlayToolTip,
{ Count: > 1 } => Loc.L("Tooltips.Videos.SelectOne"),
_ => Loc.L("Tooltips.Videos.Play"),
};
internal static string CopyTextOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows is { Count: > 0 } && rows.All(r => !r.Entry.IsLocal && r.Entry.IsOnServer) ? Loc.L("Videos.Download") : Loc.L("Videos.Copy");
internal string CopyToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
CopyBlocker(rows) ?? (rows.Count > 0 && rows.All(r => !r.Entry.IsLocal) ? Loc.L("Tooltips.Videos.Download") : Loc.L("Tooltips.Videos.Copy"));
internal string CopyOnServerToolTipOf(IReadOnlyList<VideoRowViewModel> rows) => CopyOnServerBlocker(rows) ?? Loc.L("Tooltips.Videos.CopyOnServer");
internal string DeleteToolTipOf(IReadOnlyList<VideoRowViewModel> rows) => DeleteBlocker(rows) ?? Loc.L("Tooltips.Videos.Delete");
internal static string ShowInFolderToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[{ Entry.HasLocalFile: true }] or [] => Loc.L("Tooltips.Videos.ShowInFolder"),
[{ Entry.Missing: true }] => Loc.L("Tooltips.Videos.Missing"),
[_] => Loc.L("Tooltips.Videos.ServerOnly"),
_ => Loc.L("Tooltips.Videos.SelectOne"),
};
internal static string OpenInEditToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[var one] when CanOpen(one.Entry) => Loc.L("Tooltips.Videos.OpenInEdit"),
[{ Entry.IsUnsent: true }] => Loc.L("Tooltips.Videos.WorkspaceRow"),
[{ Entry.IsWorkspaceSent: true } sent] => WorkspaceText.ForHome("Tooltips.Videos.SentRow", sent.Entry.WorkspaceServerHome),
[_] => Loc.L("Tooltips.Videos.ServerOnly"),
[] => Loc.L("Tooltips.Videos.OpenInEdit"),
_ => Loc.L("Tooltips.Videos.SelectOne"),
};
public ICommand ClosePlayerCommand { get; }
/// <summary>The player pane on the right; null while closed.</summary>
public VideoPlayerViewModel? Player
{
get => _player;
private set
{
if (!Set(ref _player, value)) return;
OnPropertyChanged(nameof(IsPlayerOpen));
}
}
public bool IsPlayerOpen => _player is not null;
/// <summary>Reads the three places again and lists what they hold (the filters stay).</summary>
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;
var merged = await WithLocalCopiesAsync(VideoSources.Merge(local, remote, workspace));
if (load != _loads) return;
_server = state;
_sent = [.. workspace.Where(e => e.IsWorkspaceSent)];
Entries = merged;
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 = [];
SetSentRows([]);
Apply();
base.OnLanguageChanged();
}
private async Task<IReadOnlyList<VideoEntry>> 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 [];
}
}
/// <summary>The server's renders this PC downloaded, with their copies here (<see cref="VideoSources.WithLocalCopies"/>).</summary>
private async Task<IReadOnlyList<VideoEntry>> WithLocalCopiesAsync(IReadOnlyList<VideoEntry> entries)
{
List<Guid> serverOnly = [.. entries.Where(e => e.IsOnServer && !e.IsLocal && !e.IsUnsent).Select(e => e.Id)];
if (serverOnly.Count == 0 || LocalLibrary() is not { IsAvailable: true } library) return entries;
try
{
return await Task.Run(async () =>
{
var copies = await library.CopiesAsync(serverOnly);
var paths = copies.ToDictionary(c => c.Key, c => (IReadOnlyList<string>)[.. c.Value.Select(copy => copy.Path)]);
return VideoSources.WithLocalCopies(entries, paths, p => File.Exists(p) || Directory.Exists(p));
});
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("videos", "The copies of the server's videos on this PC could not be read", ex);
return entries;
}
}
private static async Task<(IReadOnlyList<VideoEntry> 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<IReadOnlyList<VideoEntry>> 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<IReadOnlyList<VideoEntry>> 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);
}
/// <summary>The signed-in session's server, its capability and the account's rights.</summary>
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 filter = Filter;
Rows = Reuse(_rows, filter.Apply(_entries));
// The Board: the same rows in their lanes, and the workspace's sent renders as rows of their own (a sent render's id is
// its home entry's too).
var (published, workspace) = VideoBoard.Split(_entries, _sent, filter);
SetSentRows(Reuse(_sentRows, workspace.Where(e => e.IsWorkspaceSent)));
var listed = _rows.ToDictionary(r => r.Entry.Id);
var sent = _sentRows.ToDictionary(r => r.Entry.Id);
PublishedRows = [.. published.Select(e => listed[e.Id])];
WorkspaceRows = [.. workspace.Select(e => e.IsWorkspaceSent ? sent[e.Id] : listed[e.Id])];
OnPropertyChanged(nameof(PublishedCountText));
OnPropertyChanged(nameof(WorkspaceCountText));
OnPropertyChanged(nameof(IsPublishedEmpty));
OnPropertyChanged(nameof(IsWorkspaceEmpty));
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(IsNoMatch));
if (_player is { } player && !_entries.Concat(_sent).Any(e => e.Id == player.Entry.Id)) Player = null;
OnPropertyChanged(nameof(Filter));
}
/// <summary>The rows of <paramref name="entries"/>, each kept from <paramref name="rows"/> while its render reads the same.</summary>
private static IReadOnlyList<VideoRowViewModel> Reuse(IReadOnlyList<VideoRowViewModel> rows, IEnumerable<VideoEntry> entries)
{
var cache = rows.ToDictionary(r => r.Entry.Id);
return
[
.. 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)),
];
}
/// <summary>The Board's sent rows, wired as the list's are.</summary>
private void SetSentRows(IReadOnlyList<VideoRowViewModel> rows)
{
foreach (var row in _sentRows)
{
row.SelectionChanged -= OnSelectionChanged;
row.PosterRequested -= OnPosterRequested;
}
var changed = _sentRows.Any(r => r.IsSelected) || rows.Any(r => r.IsSelected);
_sentRows = rows;
foreach (var row in _sentRows)
{
row.Section = this;
row.SelectionChanged += OnSelectionChanged;
row.PosterRequested += OnPosterRequested;
}
if (changed) OnSelectionChanged(null);
}
private void SetFilter<T>(ref FilterOption<T> field, FilterOption<T> value, [System.Runtime.CompilerServices.CallerMemberName] string? name = null)
{
if (EqualityComparer<FilterOption<T>>.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();
}
/// <summary>The choices of the filters: kinds, sources and orders fixed, codecs and years those the videos have; each choice kept.</summary>
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<string?>(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<string>().Where(c => c.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase)
.Append(codec).OfType<string>().Distinct(StringComparer.OrdinalIgnoreCase)
.Select(c => new FilterOption<string?>(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<int>().Distinct().OrderDescending()
.Select(y => new FilterOption<int?>(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<string?>(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(PlayToolTip));
OnPropertyChanged(nameof(CopyToolTip));
OnPropertyChanged(nameof(CopyOnServerToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
OnPropertyChanged(nameof(ShowInFolderToolTip));
OnPropertyChanged(nameof(OpenInEditToolTip));
// A row's menu acts on the selection it is part of: its words follow the selection too.
foreach (var each in AllRows) each.RefreshMenu();
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}");
}
}
/// <summary>A still shows itself; any other render of this PC its sequence's cover.</summary>
private async Task<ImageSource?> PosterAsync(AppServices services, VideoEntry entry, int width, CancellationToken cancellationToken)
{
if (entry.Kind == RenderKind.Still && entry.HasLocalFile && VideoSources.ShowsAsImage(entry.LocalPath))
{
return await Task.Run<ImageSource?>(() =>
{
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 ----
/// <summary>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.</summary>
private IReadOnlyList<VideoRowViewModel> 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);
}
/// <summary>Why Copy to folder cannot run on <paramref name="rows"/>; null when it can.</summary>
internal string? CopyBlocker(IReadOnlyList<VideoRowViewModel> 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")
: rows.All(r => r.Entry.IsWorkspaceSent) ? WorkspaceText.ForHome("Tooltips.Videos.SentRow", rows[0].Entry.WorkspaceServerHome)
: Loc.L("Tooltips.Videos.WorkspaceRow");
}
if (FolderProblem() is { } problem) return VideoText.FolderReason(problem);
return LocalLibrary() is { IsAvailable: true } ? null : Loc.L("Tooltips.Videos.Copy");
}
/// <summary>Why Copy on server cannot run on <paramref name="rows"/>; null when it can.</summary>
internal string? CopyOnServerBlocker(IReadOnlyList<VideoRowViewModel> 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");
}
/// <summary>Why Delete… cannot run on <paramref name="rows"/>; null when it can.</summary>
internal string? DeleteBlocker(IReadOnlyList<VideoRowViewModel> rows)
{
if (rows.Count == 0) return Loc.L("Tooltips.Videos.Delete");
if (rows.All(r => r.Entry.IsWorkspaceSent)) return WorkspaceText.ForHome("Tooltips.Videos.SentRow", rows[0].Entry.WorkspaceServerHome);
if (rows.All(r => r.Entry.IsUnsent || r.Entry.IsWorkspaceSent)) 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");
}
/// <summary>A render Copy to folder takes: this PC's file, or the server's alone (downloaded).</summary>
private bool Copyable(VideoEntry entry) =>
!entry.IsUnsent && !entry.IsWorkspaceSent && !entry.Missing && (entry.IsLocal || (entry.IsOnServer && _server.State == VideoServerState.Available));
/// <summary>Open in Edit: a render of this PC's archive, or a workspace's whose project's home is this PC's archive.</summary>
private static bool CanOpen(VideoEntry entry) => entry.IsLocal || (entry is { WorkspaceServerHome: false } && (entry.IsUnsent || entry.IsWorkspaceSent));
// ---- 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);
}
/// <summary>
/// Copy to folder: this PC's renders are copied into the videos folder, the server's alone downloaded there, each checked
/// by hash (a <see cref="JobKind.VideoCopy"/> job of this PC); the renders themselves are never touched.
/// </summary>
internal async Task CopyAsync(IReadOnlyList<VideoRowViewModel> 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<Guid> 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);
}
}
/// <summary>Copy on server: the server copies its renders into its own videos folder, checked by hash.</summary>
internal async Task CopyOnServerAsync(IReadOnlyList<VideoRowViewModel> 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<Guid> 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);
}
}
/// <summary>
/// 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.
/// </summary>
internal async Task DeleteAsync(IReadOnlyList<VideoRowViewModel> rows)
{
if (DeleteBlocker(rows) is { } blocker)
{
Shell.Notify(blocker, isError: true);
return;
}
var library = LocalLibrary();
IReadOnlyList<Guid> localIds = library is { IsAvailable: true } ? [.. rows.Where(r => r.Entry.IsLocal).Select(r => r.Entry.Id)] : [];
IReadOnlyList<Guid> 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, rows.DistinctBy(r => r.Entry.Id).ToDictionary(r => r.Entry.Id, r => VideoDeletePlans.NameOf(r.Entry)));
}
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
{
// Each delete asks for exactly the ids that were planned, blocked ones included: its fingerprint covers them all, and
// what is blocked stays where it is.
if (plans.Local is { Items.Count: > 0 } localPlan)
{
var result = await Task.Run(() => library!.DeleteAsync(localIds, 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(serverIds, 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();
}
/// <summary>The plans of the last Delete… (tests).</summary>
internal VideoDeletePlans? LastDeletePlans { get; private set; }
/// <summary>Send: queues the sending home of the workspace projects' renders not sent yet.</summary>
private async Task SendAsync(IReadOnlyList<VideoRowViewModel> 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);
}
}
}
/// <summary>What Send does for <paramref name="row"/>, worded for its project's home.</summary>
public static string SendToolTip(VideoRowViewModel row)
{
ArgumentNullException.ThrowIfNull(row);
return WorkspaceText.ForHome("Tooltips.Editor.Render.SendAgain", row.Entry.WorkspaceServerHome);
}
}