The seven parcels merged without textual conflicts; this connects what each left to the others: - Save frame renders through the Core still path (RenderTarget.StillFrame) instead of the interim one-frame project in a hidden folder, and is named by ExportNaming.StillPath; a missing encoder reports its own notice. - Render progress counts the output program's entries, so loops, boomerang and fades no longer overshoot; the Export panel shows RenderSetup.Program (the boomerang-over-star-trails fallback included). - A videos trash entry is titled by its sequence and carries the path it was deleted from, as the panel's restore message and the desktop row expect. - The desktop sets the videos library's protected folders (workspace) and its server connection; the server protects its data folder for copy jobs too. - Render menu and Export footer open Videos filtered on the sequence; the Videos section implements IVideosSection; the editor's group states are kept in AppSettings.EditorGroups and survive a restart. - Rail tooltips and the shortcut test follow the Videos shift (Ctrl+4 Videos, Archive/Jobs/Server Ctrl+5..7); the trash Restore button binds its row tooltip. Refs #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
805 lines
35 KiB
C#
805 lines
35 KiB
C#
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.
|
||
/// </summary>
|
||
public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVideosSection
|
||
{
|
||
private IReadOnlyList<VideoEntry> _entries = [];
|
||
private IReadOnlyList<VideoRowViewModel> _rows = [];
|
||
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);
|
||
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) ----
|
||
|
||
/// <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 not sent yet.</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.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));
|
||
}
|
||
}
|
||
|
||
/// <summary>No video anywhere: "No videos".</summary>
|
||
public bool IsEmpty => !_isLoading && _entries.Count == 0;
|
||
|
||
/// <summary>Videos, none of which the filters keep: "No videos" and Clear filters.</summary>
|
||
public bool IsNoMatch => !_isLoading && _entries.Count > 0 && _rows.Count == 0;
|
||
|
||
/// <summary>The cards (0) or the list (1).</summary>
|
||
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<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>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 => [.. _rows.Where(r => r.IsSelected)];
|
||
|
||
public bool HasSelection => _rows.Any(r => r.IsSelected);
|
||
|
||
/// <summary>"Selected: 3".</summary>
|
||
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; }
|
||
|
||
/// <summary>Copy to folder, or Download for the server's videos alone.</summary>
|
||
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");
|
||
|
||
/// <summary>The row's Copy to folder or Download tooltip (its context menu).</summary>
|
||
public string RowCopyToolTip(VideoRowViewModel row) => CopyBlocker([row]) ?? Loc.L(row.Entry.IsLocal ? "Tooltips.Videos.Copy" : "Tooltips.Videos.Download");
|
||
|
||
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;
|
||
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<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 [];
|
||
}
|
||
}
|
||
|
||
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 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<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(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}");
|
||
}
|
||
}
|
||
|
||
/// <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") : 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.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");
|
||
}
|
||
|
||
/// <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.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);
|
||
}
|
||
|
||
/// <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);
|
||
}
|
||
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();
|
||
}
|
||
|
||
/// <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);
|
||
}
|
||
}
|