using System.IO; using System.Net.Http; using System.Windows.Input; using System.Windows.Media; using Chronos.App.Infrastructure; using Chronos.App.Library; using Chronos.App.Shell; using Chronos.App.Videos; using Chronos.App.Workspace; using Chronos.Core.Diagnostics; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Core.Windows.Security; using Chronos.Data; using Chronos.Data.Archiving; using Chronos.Data.Archiving.Jobs; using Chronos.Data.Videos; using Chronos.Protocol; using Chronos.Protocol.Client; using Chronos.Ui.Mvvm; namespace Chronos.App.Sections; /// /// The Videos section (owner review 1, R9; decisions 20 and 21): every render of this PC's archive, of the signed-in server /// and of the workspace (not sent yet) in one list, merged by render id, with filters, an order, cards or a list, and the /// actions on the selection: Play in the pane on the right, Show in folder, Copy (or Download) to the videos folder checked /// by hash, Copy on server, Delete… into the trash after a dry run, Open in Edit, and Send for the workspace's renders. /// An older server, or none, leaves this PC's videos with the reason. /// public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVideosSection { private IReadOnlyList _entries = []; private IReadOnlyList _rows = []; private IReadOnlyList> _kinds = []; private IReadOnlyList> _codecs = []; private IReadOnlyList> _years = []; private IReadOnlyList> _sources = []; private IReadOnlyList> _sorts = []; private FilterOption _kind = null!; private FilterOption _codec = null!; private FilterOption _year = null!; private FilterOption _source = null!; private FilterOption _sort = null!; private string _searchText = string.Empty; private Guid? _sequenceId; private string? _sequenceTitle; private int _layoutIndex; private bool _isLoading; private int _loads; private VideoServer _server = VideoServer.SignedOut; private VideoPlayerViewModel? _player; private readonly Dictionary> _sequences = []; public VideosViewModel(ShellViewModel shell) : base(SectionKey.Videos, "Icon.Videos") { Shell = shell; var services = shell.Services; LocalLibrary = () => services.Archives?.Videos; ServerVideos = () => ServerOf(services); WorkspaceRenders = ct => ReadWorkspaceAsync(services, ct); Folder = () => services.Settings.VideosFolder; Enqueue = async request => { if (services.Engine is not { } engine) throw new InvalidOperationException("The job engine is not running."); await engine.EnqueueAsync(request); }; Posters = (entry, width, ct) => PosterAsync(services, entry, width, ct); BuildOptions(); PlayCommand = new RelayCommand(p => Play(Target(p)), p => Target(p) is { Entry.HasLocalFile: true }); ShowInFolderCommand = new RelayCommand(p => ShowInFolder(Target(p)), p => Target(p) is { Entry.HasLocalFile: true }); CopyCommand = new AsyncRelayCommand((p, _) => CopyAsync(Targets(p)), p => CopyBlocker(Targets(p)) is null); CopyOnServerCommand = new AsyncRelayCommand((p, _) => CopyOnServerAsync(Targets(p)), p => CopyOnServerBlocker(Targets(p)) is null); DeleteCommand = new AsyncRelayCommand((p, _) => DeleteAsync(Targets(p)), p => DeleteBlocker(Targets(p)) is null); OpenInEditCommand = new RelayCommand(p => OpenInEdit(Target(p)), p => Target(p) is { } row && CanOpen(row.Entry)); SendCommand = new AsyncRelayCommand((p, _) => SendAsync(Targets(p)), p => Targets(p).Any(r => r.Entry.IsUnsent)); ClearFiltersCommand = new RelayCommand(ClearFilters, () => Filter.IsFiltered); ClearSelectionCommand = new RelayCommand(() => { foreach (var row in _rows) row.IsSelected = false; }, () => HasSelection); ClosePlayerCommand = new RelayCommand(() => Player = null); } public ShellViewModel Shell { get; } // ---- Sources (tests substitute their own) ---- /// This PC's videos library; null while the index is not open. internal Func LocalLibrary { get; set; } /// The signed-in server's videos, and what the account may do there. internal Func ServerVideos { get; set; } /// The workspace's renders not sent yet. internal Func>> WorkspaceRenders { get; set; } /// Queues a job of this PC (a copy into the videos folder). internal Func Enqueue { get; set; } /// The poster of a card: the sequence's cover, or the still itself. internal Func> Posters { get; set; } /// The videos folder of this PC (Settings › Archive); null or empty while unset. internal Func Folder { get; set; } // ---- List ---- /// Every render, merged, before the filters. public IReadOnlyList Entries { get => _entries; private set { _entries = value; BuildOptions(); Apply(); } } /// The renders the filters keep, in the chosen order. public IReadOnlyList Rows { get => _rows; private set { foreach (var row in _rows) { row.SelectionChanged -= OnSelectionChanged; row.PosterRequested -= OnPosterRequested; } if (!Set(ref _rows, value)) return; foreach (var row in _rows) { row.SelectionChanged += OnSelectionChanged; row.PosterRequested += OnPosterRequested; } OnPropertyChanged(nameof(IsEmpty)); OnPropertyChanged(nameof(IsNoMatch)); OnSelectionChanged(null); } } public bool IsLoading { get => _isLoading; private set { if (!Set(ref _isLoading, value)) return; OnPropertyChanged(nameof(IsEmpty)); OnPropertyChanged(nameof(IsNoMatch)); } } /// No video anywhere: "No videos". public bool IsEmpty => !_isLoading && _entries.Count == 0; /// Videos, none of which the filters keep: "No videos" and Clear filters. public bool IsNoMatch => !_isLoading && _entries.Count > 0 && _rows.Count == 0; /// The cards (0) or the list (1). public int LayoutIndex { get => _layoutIndex; set { if (value is < 0 or > 1 || !Set(ref _layoutIndex, value)) return; OnPropertyChanged(nameof(IsGrid)); OnPropertyChanged(nameof(IsList)); } } public bool IsGrid => _layoutIndex == 0; public bool IsList => _layoutIndex == 1; // ---- Filters ---- public string SearchText { get => _searchText; set { if (Set(ref _searchText, value ?? string.Empty)) Apply(); } } public IReadOnlyList> Kinds { get => _kinds; private set => Set(ref _kinds, value); } public IReadOnlyList> Codecs { get => _codecs; private set => Set(ref _codecs, value); } public IReadOnlyList> Years { get => _years; private set => Set(ref _years, value); } public IReadOnlyList> Sources { get => _sources; private set => Set(ref _sources, value); } public IReadOnlyList> Sorts { get => _sorts; private set => Set(ref _sorts, value); } public FilterOption SelectedKind { get => _kind; set => SetFilter(ref _kind, value ?? _kinds[0]); } public FilterOption SelectedCodec { get => _codec; set => SetFilter(ref _codec, value ?? _codecs[0]); } public FilterOption SelectedYear { get => _year; set => SetFilter(ref _year, value ?? _years[0]); } public FilterOption SelectedSource { get => _source; set => SetFilter(ref _source, value ?? _sources[0]); } public FilterOption SelectedSort { get => _sort; set => SetFilter(ref _sort, value ?? _sorts[0]); } public bool IsKindFiltered => _kind is { IsAny: false }; public bool IsCodecFiltered => _codec is { IsAny: false }; public bool IsYearFiltered => _year is { IsAny: false }; public bool IsSourceFiltered => _source is { IsAny: false }; /// The sequence the list is narrowed to (the Export footer's and the Render menu's "Videos"); null for all. public Guid? SequenceId => _sequenceId; /// The title of that sequence, shown as a chip that clears it. public string? SequenceFilterText => _sequenceId is null ? null : _sequenceTitle ?? _entries.FirstOrDefault(e => e.SequenceId == _sequenceId)?.Title; public bool IsSequenceFiltered => _sequenceId is not null; /// The filters and the order in force. public VideoFilter Filter => new() { Text = _searchText, Kind = _kind?.Value, Codec = _codec?.Value, Year = _year?.Value, Source = _source?.Value ?? VideoSourceFilter.All, SequenceId = _sequenceId, Sort = _sort?.Value, }; public ICommand ClearFiltersCommand { get; } /// Narrows the list to the videos of one sequence (null: every sequence). public void ShowSequence(Guid? sequenceId, string? title = null) { _sequenceId = sequenceId; _sequenceTitle = sequenceId is null ? null : title; OnPropertyChanged(nameof(SequenceId)); OnPropertyChanged(nameof(SequenceFilterText)); OnPropertyChanged(nameof(IsSequenceFiltered)); Apply(); } /// 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 => [.. _rows.Where(r => r.IsSelected)]; public bool HasSelection => _rows.Any(r => r.IsSelected); /// "Selected: 3". public string SelectionText => Loc.L("Videos.Selected", Formatting.Count(_rows.Count(r => r.IsSelected))); public ICommand ClearSelectionCommand { get; } // ---- Actions ---- public ICommand PlayCommand { get; } public ICommand ShowInFolderCommand { get; } public ICommand CopyCommand { get; } public ICommand CopyOnServerCommand { get; } public ICommand DeleteCommand { get; } public ICommand OpenInEditCommand { get; } public ICommand SendCommand { get; } /// Copy to folder, or Download for the server's videos alone. public string CopyText => SelectedRows is { Count: > 0 } rows && rows.All(r => !r.Entry.IsLocal && r.Entry.IsOnServer) ? Loc.L("Videos.Download") : Loc.L("Videos.Copy"); public string CopyToolTip => CopyBlocker(SelectedRows) ?? (SelectedRows.All(r => !r.Entry.IsLocal) && SelectedRows.Count > 0 ? Loc.L("Tooltips.Videos.Download") : Loc.L("Tooltips.Videos.Copy")); public string CopyOnServerToolTip => CopyOnServerBlocker(SelectedRows) ?? Loc.L("Tooltips.Videos.CopyOnServer"); public string DeleteToolTip => DeleteBlocker(SelectedRows) ?? Loc.L("Tooltips.Videos.Delete"); /// The row's Copy to folder or Download tooltip (its context menu). public string RowCopyToolTip(VideoRowViewModel row) => CopyBlocker([row]) ?? Loc.L(row.Entry.IsLocal ? "Tooltips.Videos.Copy" : "Tooltips.Videos.Download"); public ICommand ClosePlayerCommand { get; } /// The player pane on the right; null while closed. public VideoPlayerViewModel? Player { get => _player; private set { if (!Set(ref _player, value)) return; OnPropertyChanged(nameof(IsPlayerOpen)); } } public bool IsPlayerOpen => _player is not null; /// Reads the three places again and lists what they hold (the filters stay). public async Task RefreshAsync() { var load = ++_loads; IsLoading = true; try { var server = ServerVideos(); var localTask = ReadLocalAsync(); var serverTask = ReadServerAsync(server); var workspaceTask = ReadWorkspaceSafeAsync(); var local = await localTask; var (remote, state) = await serverTask; var workspace = await workspaceTask; if (load != _loads) return; _server = state; Entries = VideoSources.Merge(local, remote, workspace); OnPropertyChanged(nameof(ServerState)); OnPropertyChanged(nameof(IsServerLimited)); OnPropertyChanged(nameof(ServerStatusText)); OnPropertyChanged(nameof(ServerStatusToolTip)); OnPropertyChanged(nameof(SequenceFilterText)); } finally { if (load == _loads) IsLoading = false; } } protected override void OnActivated() => _ = RefreshAsync(); protected override void OnLanguageChanged() { BuildOptions(); // The rows' words are made with them: made again in the new language. Rows = []; Apply(); base.OnLanguageChanged(); } private async Task> ReadLocalAsync() { try { return await Task.Run(() => VideoSources.ReadLocalAsync(LocalLibrary())); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or InvalidDataException) { Log.Warning("videos", "The videos of this PC could not be listed", ex); Shell.ReportError(ex); return []; } } private static async Task<(IReadOnlyList Entries, VideoServer State)> ReadServerAsync(VideoServer server) { if (server is not { State: VideoServerState.Available, Connect: { } connect }) return ([], server); try { using var remote = connect(); return (await VideoSources.ReadServerAsync(remote), server); } catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException) { Log.Warning("videos", "The server's videos could not be listed", ex); return ([], server with { State = VideoServerState.Unreachable, Connect = null }); } } private async Task> ReadWorkspaceSafeAsync() { try { return await WorkspaceRenders(CancellationToken.None); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or WorkspaceException or DatabaseException) { Log.Warning("videos", "The workspace's renders could not be listed", ex); return []; } } private static async Task> ReadWorkspaceAsync(AppServices services, CancellationToken cancellationToken) { var workspace = services.Workspace; if (!workspace.IsAvailable || !Directory.Exists(workspace.Root)) return []; var projects = await workspace.ListAsync(cancellationToken); return await Task.Run(() => VideoSources.ReadWorkspace(workspace.Store, projects), cancellationToken); } /// The signed-in session's server, its capability and the account's rights. private static VideoServer ServerOf(AppServices services) { var session = services.Server; if (!session.IsConnected || session.Flow is not { Address: { } address, Token: { } token, Info: { } info }) return VideoServer.SignedOut; return VideoServer.Of(info, session.User?.Permissions ?? 0, () => new ChronosRemoteVideos(new ChronosClient(address, new CertificatePinning(session.Fingerprints), $"Chronos ({Environment.MachineName})") { Token = token })); } private void Apply() { // A row is kept while its render reads the same (its selection and its poster with it). var cache = _rows.ToDictionary(r => r.Entry.Id); Rows = [.. Filter.Apply(_entries).Select(e => cache.TryGetValue(e.Id, out var row) ? row.Entry == e ? row : new VideoRowViewModel(e) { IsSelected = row.IsSelected, Poster = row.Poster } : new VideoRowViewModel(e))]; if (_player is { } player && !_entries.Any(e => e.Id == player.Entry.Id)) Player = null; OnPropertyChanged(nameof(Filter)); } private void SetFilter(ref FilterOption field, FilterOption value, [System.Runtime.CompilerServices.CallerMemberName] string? name = null) { if (EqualityComparer>.Default.Equals(field, value)) return; field = value; OnPropertyChanged(name); OnPropertyChanged(nameof(IsKindFiltered)); OnPropertyChanged(nameof(IsCodecFiltered)); OnPropertyChanged(nameof(IsYearFiltered)); OnPropertyChanged(nameof(IsSourceFiltered)); Apply(); } private void ClearFilters() { _searchText = string.Empty; _kind = _kinds[0]; _codec = _codecs[0]; _year = _years[0]; _source = _sources[0]; _sequenceId = null; _sequenceTitle = null; OnAllPropertiesChanged(); Apply(); } /// The choices of the filters: kinds, sources and orders fixed, codecs and years those the videos have; each choice kept. private void BuildOptions() { var kind = _kind?.Value; var codec = _codec?.Value; var year = _year?.Value; var source = _source?.Value ?? VideoSourceFilter.All; var sort = _sort?.Value; var allKinds = Loc.L("Videos.Kind.All"); Kinds = [ new(null, allKinds, allKinds, IsAny: true), .. new[] { RenderKind.Video, RenderKind.Still, RenderKind.Sequence }.Select(k => new FilterOption(k, VideoText.Kind(k), VideoText.Kind(k))), ]; var allCodecs = Loc.L("Videos.Codec.All"); Codecs = [ new(null, allCodecs, allCodecs, IsAny: true), .. _entries.Select(e => e.Codec).OfType().Where(c => c.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase) .Append(codec).OfType().Distinct(StringComparer.OrdinalIgnoreCase) .Select(c => new FilterOption(c, VideoSources.CodecText(c), VideoSources.CodecText(c))).OrderBy(o => o.Label, StringComparer.CurrentCulture), ]; var allYears = Loc.L("Videos.Year.All"); Years = [ new(null, allYears, allYears, IsAny: true), .. _entries.Select(e => (int?)e.Year).Append(year).OfType().Distinct().OrderDescending() .Select(y => new FilterOption(y, y.ToString(Loc.Culture), y.ToString(Loc.Culture))), ]; var allSources = Loc.L("Videos.Source.All"); Sources = [ new(VideoSourceFilter.All, allSources, allSources, IsAny: true), new(VideoSourceFilter.Local, Loc.L("Videos.Source.Local"), Loc.L("Videos.Source.Local")), new(VideoSourceFilter.Server, Loc.L("Videos.Source.Server"), Loc.L("Videos.Source.Server")), new(VideoSourceFilter.NotSent, Loc.L("Videos.Source.NotSent"), Loc.L("Videos.Source.NotSent")), ]; Sorts = [.. VideoSorts.All.Select(s => new FilterOption(s, SortText(s), SortText(s), IsAny: s == VideoSorts.Newest))]; _kind = _kinds.First(o => o.Value == kind); _codec = _codecs.FirstOrDefault(o => string.Equals(o.Value, codec, StringComparison.OrdinalIgnoreCase)) ?? _codecs[0]; _year = _years.First(o => o.Value == year); _source = _sources.First(o => o.Value == source); _sort = _sorts.FirstOrDefault(o => o.Value == sort) ?? _sorts[0]; OnPropertyChanged(nameof(SelectedKind)); OnPropertyChanged(nameof(SelectedCodec)); OnPropertyChanged(nameof(SelectedYear)); OnPropertyChanged(nameof(SelectedSource)); OnPropertyChanged(nameof(SelectedSort)); } private static string SortText(string sort) => sort switch { VideoSorts.Oldest => Loc.L("Videos.Sort.Oldest"), VideoSorts.Largest => Loc.L("Videos.Sort.Largest"), VideoSorts.Title => Loc.L("Videos.Sort.Title"), _ => Loc.L("Videos.Sort.Newest"), }; private void OnSelectionChanged(VideoRowViewModel? row) { OnPropertyChanged(nameof(HasSelection)); OnPropertyChanged(nameof(SelectedRows)); OnPropertyChanged(nameof(SelectionText)); OnPropertyChanged(nameof(CopyText)); OnPropertyChanged(nameof(CopyToolTip)); OnPropertyChanged(nameof(CopyOnServerToolTip)); OnPropertyChanged(nameof(DeleteToolTip)); CommandManager.InvalidateRequerySuggested(); } private async void OnPosterRequested(VideoRowViewModel row) { try { row.Poster = await Posters(row.Entry, 472, CancellationToken.None); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or DatabaseException or InvalidOperationException or OperationCanceledException) { Log.Info("videos", $"The poster of {row.Entry.FileName} could not be loaded: {ex.Message}"); } } /// A still shows itself; any other render of this PC its sequence's cover. private async Task PosterAsync(AppServices services, VideoEntry entry, int width, CancellationToken cancellationToken) { if (entry.Kind == RenderKind.Still && entry.HasLocalFile && VideoSources.ShowsAsImage(entry.LocalPath)) { return await Task.Run(() => { using var stream = File.OpenRead(entry.LocalPath!); return ThumbnailService.DecodeStream(stream, 1, width); }, cancellationToken); } if (!entry.IsLocal || services.Database is not { } db || services.Thumbnails is not { } thumbnails) return null; if (!_sequences.TryGetValue(entry.SequenceId, out var sequence)) _sequences[entry.SequenceId] = sequence = db.Sequences.GetAsync(entry.SequenceId, cancellationToken); return await sequence is { } found ? await thumbnails.HeroAsync(found, width, cancellationToken) : null; } // ---- What the actions apply to ---- /// A row's own menu acts on the row, or on the selection when the row is part of it; the toolbar on the selection. private IReadOnlyList Targets(object? parameter) => parameter is VideoRowViewModel row ? row.IsSelected ? SelectedRows : [row] : SelectedRows; private VideoRowViewModel? Target(object? parameter) => Targets(parameter) is [var one] ? one : null; private string? FolderProblem() { var folder = Folder(); var problem = VideosFolders.Problem(folder, Shell.Services.Settings.LastArchivePath, Shell.Services.Workspace.Root); return problem ?? LocalLibrary()?.FolderProblem(folder); } /// Why Copy to folder cannot run on ; null when it can. internal string? CopyBlocker(IReadOnlyList rows) { if (rows.Count == 0) return Loc.L("Tooltips.Videos.Copy"); if (!rows.Any(r => Copyable(r.Entry))) return rows.All(r => r.Entry.Missing) ? Loc.L("Tooltips.Videos.Missing") : Loc.L("Tooltips.Videos.WorkspaceRow"); if (FolderProblem() is { } problem) return VideoText.FolderReason(problem); return LocalLibrary() is { IsAvailable: true } ? null : Loc.L("Tooltips.Videos.Copy"); } /// Why Copy on server cannot run on ; null when it can. internal string? CopyOnServerBlocker(IReadOnlyList rows) { if (_server.State != VideoServerState.Available) return ServerStatusToolTip; if (!_server.CanEdit) return Loc.L("Tooltips.Videos.NoEditRight"); return rows.Any(r => r.Entry is { IsOnServer: true, Missing: false }) ? null : Loc.L("Tooltips.Videos.OnServer"); } /// Why Delete… cannot run on ; null when it can. internal string? DeleteBlocker(IReadOnlyList rows) { if (rows.Count == 0) return Loc.L("Tooltips.Videos.Delete"); if (rows.All(r => r.Entry.IsUnsent)) return Loc.L("Tooltips.Videos.WorkspaceRow"); var local = rows.Any(r => r.Entry.IsLocal) && LocalLibrary() is { IsAvailable: true }; var server = rows.Any(r => !r.Entry.IsLocal && r.Entry.IsOnServer); if (local) return null; if (server && _server.State != VideoServerState.Available) return ServerStatusToolTip; if (server && !_server.CanDelete) return Loc.L("Tooltips.Videos.NoDeleteRight"); return server ? null : Loc.L("Tooltips.Videos.Delete"); } /// A render Copy to folder takes: this PC's file, or the server's alone (downloaded). private bool Copyable(VideoEntry entry) => !entry.IsUnsent && !entry.Missing && (entry.IsLocal || (entry.IsOnServer && _server.State == VideoServerState.Available)); private static bool CanOpen(VideoEntry entry) => entry.IsLocal || entry is { IsUnsent: true, WorkspaceServerHome: false }; // ---- Actions ---- private void Play(VideoRowViewModel? row) { if (row is null) return; Player = new VideoPlayerViewModel(row.Entry, ClosePlayerCommand, new RelayCommand(() => ShowInFolder(row), () => row.Entry.HasLocalFile)); } private static void ShowInFolder(VideoRowViewModel? row) { if (row?.Entry is { HasLocalFile: true, LocalPath: { } path }) ShellActions.Reveal(path); } private void OpenInEdit(VideoRowViewModel? row) { if (row is not null && CanOpen(row.Entry)) Shell.OpenSequence(row.Entry.SequenceId); } /// /// Copy to folder: this PC's renders are copied into the videos folder, the server's alone downloaded there, each checked /// by hash (a job of this PC); the renders themselves are never touched. /// internal async Task CopyAsync(IReadOnlyList rows) { if (CopyBlocker(rows) is { } blocker) { Shell.Notify(blocker, isError: true); return; } var folder = Path.GetFullPath(Folder()!); var library = LocalLibrary()!; var copyable = rows.Select(r => r.Entry).Where(Copyable).ToList(); try { foreach (var (fromServer, ids) in new[] { (false, copyable.Where(e => e.IsLocal)), (true, copyable.Where(e => !e.IsLocal)) }) { IReadOnlyList list = [.. ids.Select(e => e.Id)]; if (list.Count == 0) continue; await Enqueue(library.CopyJob(new VideoCopyParameters(list, folder, fromServer, Environment.MachineName))); } Shell.Notify(Loc.L("Videos.Copy.Queued"), Loc.L("Videos.Target.Copy", Formatting.Count(copyable.Count)), Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs)); } catch (VideoLibraryException ex) { Shell.Notify(VideoText.Error(ex), isError: true); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or InvalidOperationException) { Shell.ReportError(ex); } } /// Copy on server: the server copies its renders into its own videos folder, checked by hash. internal async Task CopyOnServerAsync(IReadOnlyList rows) { var blocker = CopyOnServerBlocker(rows); if (blocker is not null || _server.Connect is not { } connect) { Shell.Notify(blocker ?? Loc.L("Tooltips.Videos.ServerOffline"), isError: true); return; } IReadOnlyList ids = [.. rows.Where(r => r.Entry is { IsOnServer: true, Missing: false }).Select(r => r.Entry.Id)]; try { using var remote = connect(); await remote.CopyAsync(ids); Shell.Notify(Loc.L("Videos.Copy.Queued"), Loc.L("Videos.Target.Copy", Formatting.Count(ids.Count))); } catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException) { Log.Warning("videos", "Copying videos on the server failed", ex); Shell.Notify(ErrorText.ForServer(ex), isError: true); } } /// /// Delete…: the dry run first (this PC's renders and the server's alone apart), then one confirmation saying what goes, /// its bytes, what stays and why, and that copies in the videos folder stay; then each delete with its plan's /// fingerprint, which a changed plan refuses with nothing moved. /// internal async Task DeleteAsync(IReadOnlyList rows) { if (DeleteBlocker(rows) is { } blocker) { Shell.Notify(blocker, isError: true); return; } var library = LocalLibrary(); IReadOnlyList localIds = library is { IsAvailable: true } ? [.. rows.Where(r => r.Entry.IsLocal).Select(r => r.Entry.Id)] : []; IReadOnlyList serverIds = _server is { State: VideoServerState.Available, CanDelete: true } ? [.. rows.Where(r => !r.Entry.IsLocal && r.Entry.IsOnServer).Select(r => r.Entry.Id)] : []; VideoDeletePlans plans; try { var local = localIds.Count > 0 ? await Task.Run(() => library!.PlanDeleteAsync(localIds)) : null; VideoDeletePlanDto? server = null; if (serverIds.Count > 0 && _server.Connect is { } connect) { using var remote = connect(); server = await remote.PlanDeleteAsync(serverIds); } plans = new VideoDeletePlans(local, server); } catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or TaskCanceledException or UntrustedCertificateException) { Shell.Notify(ErrorText.ForServer(ex), isError: true); return; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException) { Shell.ReportError(ex); return; } LastDeletePlans = plans; if (plans.Request() is not { } request) { if (plans.Blocked > 0) Shell.Notify(Loc.L("Videos.Delete.Blocked", Formatting.Count(plans.Blocked)), string.Join(Environment.NewLine, plans.Lines()), isError: true); return; } if (!Shell.Services.Dialogs.Confirm(request)) return; var deleted = 0; try { if (plans.Local is { Items.Count: > 0 } localPlan) { var result = await Task.Run(() => library!.DeleteAsync([.. localPlan.Items.Select(i => i.Render.Id)], localPlan.Fingerprint, Environment.MachineName)); deleted += result.Deleted.Count; } if (plans.Server is { Items.Count: > 0 } serverPlan && _server.Connect is { } connect) { using var remote = connect(); var result = await remote.DeleteAsync([.. serverPlan.Items.Select(i => i.Id)], serverPlan.Fingerprint); deleted += result.Items.Count; } Shell.Notify(Loc.L("Videos.Delete.Done", Formatting.Count(deleted))); } catch (VideoLibraryException ex) { Shell.Notify(VideoText.Error(ex), isError: true); } catch (ChronosApiException ex) when (ex.Error?.Code == VideoErrors.PlanChanged) { Shell.Notify(Loc.L("Errors.Videos.Fingerprint"), isError: true); } catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or TaskCanceledException or UntrustedCertificateException) { Shell.Notify(ErrorText.ForServer(ex), isError: true); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException) { Shell.ReportError(ex); } await RefreshAsync(); } /// The plans of the last Delete… (tests). internal VideoDeletePlans? LastDeletePlans { get; private set; } /// Send: queues the sending home of the workspace projects' renders not sent yet. private async Task SendAsync(IReadOnlyList rows) { foreach (var project in rows.Select(r => r.Entry).Where(e => e.IsUnsent && e.WorkspaceProjectId is not null).Select(e => e.WorkspaceProjectId!.Value).Distinct()) { try { if (await Shell.Services.Workspace.SendRendersAsync(project)) Shell.Notify(Loc.L("Editor.Render.Sending"), null, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs)); } catch (Exception ex) when (ex is WorkspaceException or IOException or InvalidDataException or UnauthorizedAccessException or DatabaseException) { Log.Warning("videos", $"The renders of workspace project {project} could not be queued to be sent", ex); Shell.Notify(Loc.L("Editor.Render.SendFailed"), ex is WorkspaceException ? ex.Message : ErrorText.For(ex), isError: true); } } } /// What Send does for , worded for its project's home. public static string SendToolTip(VideoRowViewModel row) { ArgumentNullException.ThrowIfNull(row); return WorkspaceText.ForHome("Tooltips.Editor.Render.SendAgain", row.Entry.WorkspaceServerHome); } }