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. The Board (owner request of 2026-11-06) shows the same /// renders in two lanes, Published and Workspace (), with the workspace's sent renders beside them. /// public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVideosSection { private IReadOnlyList _entries = []; private IReadOnlyList _rows = []; private IReadOnlyList _sent = []; private IReadOnlyList _sentRows = []; private IReadOnlyList _publishedRows = []; private IReadOnlyList _workspaceRows = []; 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); 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) ---- /// 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: those not sent yet, and those sent whose file is still there (the Board's). 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.Section = this; row.SelectionChanged += OnSelectionChanged; row.PosterRequested += OnPosterRequested; } OnPropertyChanged(nameof(IsEmpty)); OnPropertyChanged(nameof(IsNoMatch)); OnSelectionChanged(null); } } /// The workspace's sent renders whose file is still in its exports/, before the filters (the Board's alone). public IReadOnlyList SentEntries => _sent; /// The Board's Published lane: renders filed at this PC's archive or the server, newest first. public IReadOnlyList PublishedRows { get => _publishedRows; private set => Set(ref _publishedRows, value); } /// The Board's Workspace lane: the workspace's renders not sent yet and those sent, newest first. public IReadOnlyList WorkspaceRows { get => _workspaceRows; private set => Set(ref _workspaceRows, value); } /// The Published lane's count. public string PublishedCountText => Formatting.Count(_publishedRows.Count); /// The Workspace lane's count. public string WorkspaceCountText => Formatting.Count(_workspaceRows.Count); /// The Published lane is empty and the Workspace lane is not ("No videos" in the lane; both empty is the section's empty state). public bool IsPublishedEmpty => _publishedRows.Count == 0 && _workspaceRows.Count > 0; /// The Workspace lane is empty and the Published lane is not. public bool IsWorkspaceEmpty => _workspaceRows.Count == 0 && _publishedRows.Count > 0; /// The rows of the list and the Board's sent rows: what a selection can hold. private IEnumerable AllRows => _rows.Concat(_sentRows); 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 && (_sent.Count == 0 || !IsBoard); /// Videos, none of which the filters keep: "No videos" and Clear filters. public bool IsNoMatch => !_isLoading && !IsEmpty && (IsBoard ? _publishedRows.Count + _workspaceRows.Count == 0 : _rows.Count == 0); /// The cards (0), the list (1) or the Board (2), kept for the next run (Settings: ). 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> 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; } /// The sequence chip: the videos of every sequence again, the other filters kept. public ICommand ClearSequenceCommand { get; } /// Reads this PC's, the server's and the workspace's videos again (). public ICommand RefreshCommand { 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(); } /// The editor's links to this section () narrow it the same way. void Chronos.App.Editor.IVideosSection.ShowSequence(Guid? sequenceId) => ShowSequence(sequenceId); // ---- 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 => [.. AllRows.Where(r => r.IsSelected)]; public bool HasSelection => AllRows.Any(r => r.IsSelected); /// "Selected: 3". public string SelectionText => Loc.L("Videos.Selected", Formatting.Count(AllRows.Count(r => r.IsSelected))); public ICommand ClearSelectionCommand { get; } // ---- Actions ---- public ICommand PlayCommand { get; } /// The toolbar's Play tooltip: why the selection does not play here, else what Play does. 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; } /// Copy to folder, or Download for the server's videos alone. public string CopyText => CopyTextOf(SelectedRows); public string CopyToolTip => CopyToolTipOf(SelectedRows); public string CopyOnServerToolTip => CopyOnServerToolTipOf(SelectedRows); public string DeleteToolTip => DeleteToolTipOf(SelectedRows); /// Show in folder's tooltip: why it waits (more than one video, a server's video alone, a file gone), else what it does. public string ShowInFolderToolTip => ShowInFolderToolTipOf(SelectedRows); /// Open in Edit's tooltip: why it waits (more than one video, a server's video alone), else what it does. public string OpenInEditToolTip => OpenInEditToolTipOf(SelectedRows); /// The row's Copy to folder or Download tooltip (its context menu). public string RowCopyToolTip(VideoRowViewModel row) => CopyToolTipOf(Targets(row)); /// What the row's menu acts on: the selection when the row is part of it, else the row alone (as the commands do). internal IReadOnlyList TargetsOf(VideoRowViewModel row) => Targets(row); internal static string PlayToolTipOf(IReadOnlyList rows) => rows switch { [var one] => one.PlayToolTip, { Count: > 1 } => Loc.L("Tooltips.Videos.SelectOne"), _ => Loc.L("Tooltips.Videos.Play"), }; internal static string CopyTextOf(IReadOnlyList 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 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 rows) => CopyOnServerBlocker(rows) ?? Loc.L("Tooltips.Videos.CopyOnServer"); internal string DeleteToolTipOf(IReadOnlyList rows) => DeleteBlocker(rows) ?? Loc.L("Tooltips.Videos.Delete"); internal static string ShowInFolderToolTipOf(IReadOnlyList 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 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; } /// 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; 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> 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 []; } } /// The server's renders this PC downloaded, with their copies here (). private async Task> WithLocalCopiesAsync(IReadOnlyList entries) { List 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)[.. 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 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 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)); } /// The rows of , each kept from while its render reads the same. private static IReadOnlyList Reuse(IReadOnlyList rows, IEnumerable 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)), ]; } /// The Board's sent rows, wired as the list's are. private void SetSentRows(IReadOnlyList 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(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(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}"); } } /// 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") : 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"); } /// 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.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"); } /// A render Copy to folder takes: this PC's file, or the server's alone (downloaded). private bool Copyable(VideoEntry entry) => !entry.IsUnsent && !entry.IsWorkspaceSent && !entry.Missing && (entry.IsLocal || (entry.IsOnServer && _server.State == VideoServerState.Available)); /// Open in Edit: a render of this PC's archive, or a workspace's whose project's home is this PC's archive. 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); } /// /// 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, 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(); } /// 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); } }