fix(copies): close the fourth verification round of owner review 6
The fourth verification round of the matches work found 18 defects in the merge, Integrate and Matches surfaces. This commit fixes them: - An Integrate job now carries the planning account's id, so its re-plan decides ownership the way the dialog did. - A merge skips only a project the kept sequence holds a real copy of (name, offset head and history content) and re-points its renders to that copy. - A merge runs its trash checks before the Links stage and records an undo, so an abandoned merge gives the other sequence back its link, session keys and pairs. - The metered hold adopts automatic transfers that were paused before a restart. - Apply in the Compare dialog re-plans when the plan is pending or stale. - The Library's Two versions... lists the second versions a Union merge leaves, each with Drop... (dry run, confirmation, verified partner). A merge job's Open shows that list. - The merge's typed confirmation is the invariant count, and the prompt names it in all 38 languages. - Italian text uses Principale and Gemello. The Main project is named through WorkspaceText in the Projects part and in the twin tooltip. - The session keys tooltip is split into two keys, and To trash... and Delete on server... say why they are disabled. - The capture restores the editor account before the Matches scenes. - Upload again follows SyncHost.CanSendSync (Upload with Edit). - Matches rows trim archive names in the middle on a rebalanced grid; the Projects part rows trim, with the full text in the tooltip. - The sample project targets use ProjectTransplant.FreeName. DECISIONS, CHANGELOG, STATUS 8.7, the request doc and the 16 changed capture baselines are updated. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3c99badcfe
commit
2c06e7ac2b
171 files changed
+1591
-218
No files matched your search
@@ -1,7 +1,9 @@
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.App.DesignTime;
|
||||
@@ -17,6 +19,9 @@ internal sealed record SampleCopy(FoundCopy Copy, CopyFacts Here, CopyFacts Ther
|
||||
/// </summary>
|
||||
internal sealed class SampleCopyEngine : ICopyEngine
|
||||
{
|
||||
/// <summary>The sample server's display name: what a project coming from it is suffixed with on a clash.</summary>
|
||||
private const string SampleServerName = "Studio NAS";
|
||||
|
||||
private readonly List<SampleCopy> _pairs = [];
|
||||
private Action<CopyFindResult>? _found;
|
||||
|
||||
@@ -70,9 +75,17 @@ internal sealed class SampleCopyEngine : ICopyEngine
|
||||
var (steps, leftOut) = Steps(pair, choices.Photos, choices.PerPhoto, merge: false);
|
||||
var blocks = new List<CopyBlock>();
|
||||
if (pair.Details.Any(d => !choices.Details.ContainsKey(d.Path))) blocks.Add(CopyBlock.DetailsUnchosen);
|
||||
// Named as the real planner names them: the name itself when free at the other home, else suffixed with this PC's
|
||||
// name (going to the server) or the server's display name (coming here).
|
||||
var namesThere = pair.Projects.There.Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var namesHere = pair.Projects.Here.Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var projects = choices.Projects == CopyProjects.CopyAcross
|
||||
? pair.Projects.Here.Where(p => !p.IsMain).Select(p => new ProjectStep(CopySide.ThisPc, p.Id, p.Name, p.Name + " (STUDIO-PC)", p.Versions, p.HeadId))
|
||||
.Concat(pair.Projects.There.Where(p => !p.IsMain).Select(p => new ProjectStep(CopySide.Other, p.Id, p.Name, p.Name + " (nas)", p.Versions, p.HeadId)))
|
||||
? pair.Projects.Here.Where(p => !p.IsMain)
|
||||
.Select(p => new ProjectStep(CopySide.ThisPc, p.Id, p.Name, ProjectTransplant.FreeName(p.Name, AppEnvironment.SamplePcName, namesThere), p.Versions,
|
||||
p.HeadId))
|
||||
.Concat(pair.Projects.There.Where(p => !p.IsMain)
|
||||
.Select(p => new ProjectStep(CopySide.Other, p.Id, p.Name, ProjectTransplant.FreeName(p.Name, SampleServerName, namesHere),
|
||||
p.Versions, p.HeadId)))
|
||||
.ToList()
|
||||
: [];
|
||||
var lasts = steps.Where(s => s.Action is PhotoAction.TrashHere or PhotoAction.TrashThere).Take(1)
|
||||
@@ -148,6 +161,14 @@ internal sealed class SampleCopyEngine : ICopyEngine
|
||||
|
||||
public Task<int> DropVersionAsync(DropVersionPlan plan, ISyncRemote? remote, CancellationToken ct) => Task.FromResult(plan.Photos);
|
||||
|
||||
/// <summary>The sample keeps no photo in two versions in one sequence: the list says so.</summary>
|
||||
public Task<IReadOnlyList<PhotoVersions>> VersionsAsync(Guid sequenceId, CancellationToken ct) => Task.FromResult<IReadOnlyList<PhotoVersions>>([]);
|
||||
|
||||
public Task<OwnVersionDropPlan> PlanDropOwnVersionAsync(Guid sequenceId, Guid frameId, CancellationToken ct) =>
|
||||
throw new StaleCopyPlanException(Chronos.Core.Localization.Loc.L("Errors.Copies.OtherVersionGone"));
|
||||
|
||||
public Task<int> DropOwnVersionAsync(OwnVersionDropPlan plan, CancellationToken ct) => Task.FromResult(plan.Plan.Frames.Count);
|
||||
|
||||
public Task<IReadOnlyList<FoundCopy>> ListAllPairsAsync(CancellationToken ct) => Task.FromResult<IReadOnlyList<FoundCopy>>([.. _pairs.Select(p => p.Copy)]);
|
||||
|
||||
public Task<int> TrashHereAsync(Guid copyId, FrameDeletePlan plan, ISyncRemote? remote, CancellationToken ct) => Task.FromResult(plan.Frames.Count);
|
||||
|
||||
@@ -352,7 +352,10 @@ public sealed class SampleData
|
||||
};
|
||||
CopyProjectsView Projects(bool other) => new(
|
||||
[SampleCopies.Project("Main", true, 4, 2), SampleCopies.Project("Vertical", false, 3, 5)],
|
||||
other ? [SampleCopies.Project("Main", true, 2, 9), SampleCopies.Project("Slow pan", false, 1, 9)] : [SampleCopies.Project("Main", true, 2, 9)],
|
||||
// The server has a Vertical of its own: each side's goes to the other under a suffixed name, Slow pan under its own.
|
||||
other
|
||||
? [SampleCopies.Project("Main", true, 2, 9), SampleCopies.Project("Vertical", false, 2, 7), SampleCopies.Project("Slow pan", false, 1, 9)]
|
||||
: [SampleCopies.Project("Main", true, 2, 9)],
|
||||
MainSame: false, ThereKeepsProjects: true);
|
||||
|
||||
// (1) Lighthouse: the card's photos, the Uploader sent part of them.
|
||||
@@ -447,6 +450,13 @@ public sealed class SampleData
|
||||
await _services.Server.RestoreAsync();
|
||||
}
|
||||
|
||||
/// <summary>The signed-in account is an editor again (after <see cref="RestrictAccountAsync"/>); the session is read again.</summary>
|
||||
public async Task RestoreAccountAsync()
|
||||
{
|
||||
_permissions = RolePermissions.Default(UserRole.Editor);
|
||||
await _services.Server.RestoreAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The editor's sample as a sequence the sample server also has (so its Export "Sync" applies), with two copies of
|
||||
/// this PC's settings kept by "Save both" in its <c>.chronos</c> folder.
|
||||
|
||||
@@ -261,7 +261,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
var user = remote is not null ? Server.User : null;
|
||||
var permissions = user?.Permissions ?? 0;
|
||||
var rights = SyncRights.Of(permissions);
|
||||
var rights = remote is null ? default : Sync.Rights;
|
||||
bool Has(Permissions p) => (permissions & (long)p) != 0;
|
||||
var originals = Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType<Guid>().ToHashSet();
|
||||
return new CopyPlanContext(System.Environment.MachineName, remote is null ? null : Server.ServerName, rights.CanUpload, rights.CanFetchOriginals,
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Two versions…: the photos one local sequence keeps in two versions (a Union merge leaves them, and its pair is gone;
|
||||
/// owner Q3, #73), each version with Drop…: a dry run, a confirmation that names the version that stays, then the move of
|
||||
/// the dropped one to the archive trash, applied only while the other is still there and verified by content.
|
||||
/// </summary>
|
||||
public sealed class VersionsDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
private readonly ICopyEngine _engine;
|
||||
private readonly Func<ConfirmRequest, bool> _confirm;
|
||||
private IReadOnlyList<VersionRow> _rows = [];
|
||||
private bool _isLoaded;
|
||||
|
||||
public VersionsDialogViewModel(ICopyEngine engine, Guid sequenceId, string title, Func<ConfirmRequest, bool> confirm, Action<ArchiveDialogViewModel> close)
|
||||
: base(close)
|
||||
{
|
||||
_engine = engine;
|
||||
_confirm = confirm;
|
||||
SequenceId = sequenceId;
|
||||
Title = title;
|
||||
}
|
||||
|
||||
public Guid SequenceId { get; }
|
||||
|
||||
public string Title { get; }
|
||||
|
||||
public string Heading => Loc.L("Library.Versions.Title", Title);
|
||||
|
||||
/// <summary>Each version of each photo kept in two, the photo's two versions side by side.</summary>
|
||||
public IReadOnlyList<VersionRow> Rows
|
||||
{
|
||||
get => _rows;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _rows, value)) return;
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasRows => _rows.Count > 0;
|
||||
|
||||
/// <summary>Read, and no photo is kept in two versions any more.</summary>
|
||||
public bool IsEmpty => _isLoaded && _rows.Count == 0;
|
||||
|
||||
public async Task LoadAsync()
|
||||
{
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var photos = await _engine.VersionsAsync(SequenceId, CancellationToken.None);
|
||||
Rows = [.. photos.SelectMany(p => new[]
|
||||
{
|
||||
new VersionRow(this, p, p.FirstFrameId, p.FirstFileName, p.FirstSize, p.SecondFileName),
|
||||
new VersionRow(this, p, p.SecondFrameId, p.SecondFileName, p.SecondSize, p.FirstFileName),
|
||||
})];
|
||||
}
|
||||
catch (Exception ex) when (Expected(ex))
|
||||
{
|
||||
Log.Warning("library", $"Reading the versions of sequence {SequenceId} failed", ex);
|
||||
ShowError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isLoaded = true;
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drop…: the dry run, the confirmation, then the move of <paramref name="row"/>'s version to the archive trash.</summary>
|
||||
internal async Task DropAsync(VersionRow row)
|
||||
{
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var plan = await _engine.PlanDropOwnVersionAsync(SequenceId, row.FrameId, CancellationToken.None);
|
||||
if (!_confirm(DropRequest(plan, row.FileName))) return;
|
||||
await _engine.DropOwnVersionAsync(plan, CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex) when (Expected(ex))
|
||||
{
|
||||
Log.Warning("library", $"Dropping a version of sequence {SequenceId} failed", ex);
|
||||
ShowError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
await LoadAsync();
|
||||
}
|
||||
|
||||
/// <summary>The confirmation of Drop…: the version that goes (its only copy named first) and the one that stays.</summary>
|
||||
internal static ConfirmRequest DropRequest(OwnVersionDropPlan plan, string fileName)
|
||||
{
|
||||
var gone = plan.LastCopies.Count > 0 ? Loc.L("Server.Copies.Confirm.LastCopy", fileName) : fileName;
|
||||
var message = Loc.L("Tooltips.Library.Versions.Drop");
|
||||
return new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.Plural("Server.Copies.Plan.Trash", plan.Plan.Frames.Count),
|
||||
Message = message,
|
||||
Detail = gone + Environment.NewLine + Loc.L("Library.Versions.Stays", plan.PartnerFileName),
|
||||
IsDetailMonospaced = false,
|
||||
DetailToolTip = Loc.L("Tooltips.Archive.DeletePlan"),
|
||||
SafeText = Loc.L("Archive.Delete.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
|
||||
ActionText = Loc.L("Archive.Delete.Action"),
|
||||
ActionToolTip = message,
|
||||
IsDestructive = true,
|
||||
};
|
||||
}
|
||||
|
||||
private static bool Expected(Exception ex) =>
|
||||
ex is Data.DatabaseException or InvalidOperationException or System.IO.IOException or UnauthorizedAccessException;
|
||||
}
|
||||
|
||||
/// <summary>One version of a photo kept in two: its file, the photo's time, its size and the other version's name.</summary>
|
||||
public sealed class VersionRow
|
||||
{
|
||||
internal VersionRow(VersionsDialogViewModel owner, PhotoVersions photo, Guid frameId, string fileName, long size, string otherFileName)
|
||||
{
|
||||
FrameId = frameId;
|
||||
FileName = fileName;
|
||||
var parts = new List<string>();
|
||||
if (photo.CapturedAt is { } at) parts.Add(at.ToString("g", Loc.Culture));
|
||||
if (size > 0) parts.Add(Formatting.Bytes(size));
|
||||
parts.Add(Loc.L("Library.Versions.Other", otherFileName));
|
||||
Detail = string.Join(Loc.Separator, parts);
|
||||
DropCommand = new AsyncRelayCommand(() => owner.DropAsync(this), () => !owner.IsBusy);
|
||||
}
|
||||
|
||||
public Guid FrameId { get; }
|
||||
|
||||
public string FileName { get; }
|
||||
|
||||
/// <summary>"16/11/2026 09:12 · 24.1 MB · Other: IMG_0142 (1).CR3".</summary>
|
||||
public string Detail { get; }
|
||||
|
||||
public ICommand DropCommand { get; }
|
||||
}
|
||||
@@ -507,7 +507,8 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
{
|
||||
var db = Shell.Services.Database;
|
||||
if (db is null || job.TargetIds.Count == 0) return;
|
||||
// Owner review 6, #73: an Integrate shows its pair in Server › Matches; a merge opens the sequence it kept.
|
||||
// Owner review 6, #73: an Integrate shows its pair in Server › Matches; a merge opens the photos the kept sequence
|
||||
// now has in two versions (Union), or the kept sequence when it has none.
|
||||
if (job.Kind == JobKind.Integrate)
|
||||
{
|
||||
var title = await db.Sequences.GetAsync(job.TargetIds[0]) is { } local ? local.DisplayTitle : null;
|
||||
@@ -517,7 +518,15 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
}
|
||||
if (job.Kind == JobKind.MergeSequences)
|
||||
{
|
||||
Shell.OpenSequence(job.TargetIds[0]);
|
||||
var kept = job.TargetIds[0];
|
||||
if (Shell.Services.Sync.Copies is { } copies && await db.Sequences.GetAsync(kept) is not null
|
||||
&& (await copies.VersionsAsync(kept, CancellationToken.None)).Count > 0)
|
||||
{
|
||||
Shell.Navigate(SectionKey.Library);
|
||||
await Shell.Library.ShowVersionsAsync(kept);
|
||||
return;
|
||||
}
|
||||
Shell.OpenSequence(kept);
|
||||
return;
|
||||
}
|
||||
var targets = job.TargetIds.Distinct().ToList();
|
||||
|
||||
@@ -12,11 +12,22 @@
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Archive/ArchiveDialogs.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
<!-- A double-click is read on the card or row itself: it takes the mouse-down to select, so a gesture on the list never sees it. -->
|
||||
<!-- A card of a sequence in a match that asks for a choice offers Compare… in its menu (owner review 6, #73). -->
|
||||
<!--
|
||||
A card or row of a local sequence offers Two versions… in its menu (the photos it keeps in two versions, owner Q3);
|
||||
one in a match that asks for a choice offers Compare… first (owner review 6, #73).
|
||||
-->
|
||||
<ContextMenu x:Key="Menu.Card" x:Shared="False">
|
||||
<MenuItem Header="{l:Loc Library.Action.Versions}" ToolTip="{l:Loc Tooltips.Library.Versions}"
|
||||
Command="{Binding PlacementTarget.Tag.VersionsItemCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
CommandParameter="{Binding}" />
|
||||
</ContextMenu>
|
||||
<ContextMenu x:Key="Menu.CardMatch" x:Shared="False">
|
||||
<MenuItem Header="{l:Loc Library.Action.Compare}" ToolTip="{l:Loc Tooltips.Library.Compare}"
|
||||
Command="{Binding PlacementTarget.Tag.CompareItemCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
CommandParameter="{Binding}" />
|
||||
<MenuItem Header="{l:Loc Library.Action.Versions}" ToolTip="{l:Loc Tooltips.Library.Versions}"
|
||||
Command="{Binding PlacementTarget.Tag.VersionsItemCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
CommandParameter="{Binding}" />
|
||||
</ContextMenu>
|
||||
<Style x:Key="ListBoxItem.LibraryCard" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Card}">
|
||||
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
|
||||
@@ -24,6 +35,9 @@
|
||||
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}" />
|
||||
<EventSetter Event="MouseDoubleClick" Handler="OnItemDoubleClick" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsRemote}" Value="False">
|
||||
<Setter Property="ContextMenu" Value="{StaticResource Menu.Card}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding HasMatch}" Value="True">
|
||||
<Setter Property="ContextMenu" Value="{StaticResource Menu.CardMatch}" />
|
||||
</DataTrigger>
|
||||
@@ -33,7 +47,16 @@
|
||||
<Setter Property="Height" Value="38" />
|
||||
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
|
||||
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}" />
|
||||
<EventSetter Event="MouseDoubleClick" Handler="OnItemDoubleClick" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsRemote}" Value="False">
|
||||
<Setter Property="ContextMenu" Value="{StaticResource Menu.Card}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding HasMatch}" Value="True">
|
||||
<Setter Property="ContextMenu" Value="{StaticResource Menu.CardMatch}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<Style x:Key="Button.Header" TargetType="Button" BasedOn="{StaticResource Button.Subtle}">
|
||||
<Setter Property="Height" Value="28" />
|
||||
@@ -99,6 +122,48 @@
|
||||
<StackPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
|
||||
<!-- Two versions…: each version of each photo the sequence keeps in two, with Drop…; an empty list says so. -->
|
||||
<DataTemplate DataType="{x:Type lib:VersionsDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="640" MaxHeight="520">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
|
||||
<TextBlock Grid.Row="1" Text="{l:Loc Library.Versions.Empty}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,0"
|
||||
Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}" />
|
||||
<ListBox Grid.Row="1" ItemsSource="{Binding Rows}" MinHeight="120" Margin="0,12,0,0" AutomationProperties.Name="{Binding Heading}"
|
||||
KeyboardNavigation.TabNavigation="Continue" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
|
||||
<ListBox.ItemContainerStyle>
|
||||
<Style TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding FileName}" />
|
||||
</Style>
|
||||
</ListBox.ItemContainerStyle>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type lib:VersionRow}">
|
||||
<DockPanel Height="48">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Content="{l:Loc Server.Copies.Action.Drop}" Command="{Binding DropCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Library.Versions.Drop}" />
|
||||
<StackPanel VerticalAlignment="Center" Margin="0,0,12,0">
|
||||
<TextBlock Text="{Binding FileName}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" ToolTip="{Binding FileName}" />
|
||||
<TextBlock Text="{Binding Detail}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Detail}"
|
||||
Typography.NumeralAlignment="Tabular" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<DockPanel Grid.Row="2" Margin="0,16,0,0">
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Close}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True"
|
||||
IsDefault="True" MinWidth="96" />
|
||||
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
|
||||
</DockPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Save view / Rename view: one name field. -->
|
||||
<DataTemplate DataType="{x:Type lib:ViewNameDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="460">
|
||||
|
||||
@@ -152,6 +152,8 @@ public sealed class LibraryViewModel : SectionViewModel
|
||||
{
|
||||
if (p is SequenceItem item) CompareItem(item);
|
||||
}, p => p is SequenceItem { HasMatch: true });
|
||||
VersionsItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? ShowVersionsAsync(item.Id) : Task.CompletedTask,
|
||||
p => p is SequenceItem { IsRemote: false } && Shell.Services.Sync.Copies is not null);
|
||||
SyncItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? SyncItemAsync(item) : Task.CompletedTask, p => p is SequenceItem { CanSync: true });
|
||||
|
||||
SaveViewCommand = new RelayCommand(() => OpenViewName(rename: false), () => _viewStore is not null);
|
||||
@@ -210,6 +212,20 @@ public sealed class LibraryViewModel : SectionViewModel
|
||||
Shell.Navigate(SectionKey.Server);
|
||||
Shell.Server.Sync.ShowFilter(Chronos.App.Server.SyncFilter.FoundCopies, item.Title);
|
||||
}
|
||||
|
||||
/// <summary>Two versions…: the photos a local sequence keeps in two versions, each with Drop… (owner Q3, #73).</summary>
|
||||
public ICommand VersionsItemCommand { get; }
|
||||
|
||||
/// <summary>Opens Two versions… of local sequence <paramref name="sequenceId"/> (a merge job's Open, the card menu).</summary>
|
||||
public async Task ShowVersionsAsync(Guid sequenceId)
|
||||
{
|
||||
if (Shell.Services.Sync.Copies is not { } copies) return;
|
||||
var title = Items.FirstOrDefault(i => i.Id == sequenceId)?.Title
|
||||
?? (_db is not null && await _db.Sequences.GetAsync(sequenceId) is { } sequence ? sequence.DisplayTitle : string.Empty);
|
||||
var dialog = new VersionsDialogViewModel(copies, sequenceId, title, Shell.Services.Dialogs.Confirm, CloseDialog);
|
||||
OpenDialog(dialog);
|
||||
await dialog.LoadAsync();
|
||||
}
|
||||
public ICommand SaveViewCommand { get; }
|
||||
public ICommand RenameViewCommand { get; }
|
||||
public ICommand DeleteViewCommand { get; }
|
||||
|
||||
@@ -324,13 +324,13 @@
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Server}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.State}" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
<!-- Matches: Sequence · This side · Other side · State. The sides ("1,204 photos · Main archive · 18.2 GB") take the
|
||||
room the narrower actions column leaves (at most three buttons). -->
|
||||
<!-- Matches: Sequence · This side · Other side · State. The sides ("1,204 photos · Main archive") take the room the
|
||||
title and the narrower actions column leave (at most three buttons); the rows use the same widths. -->
|
||||
<Grid Visibility="{Binding IsMatches, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="1.6*" MinWidth="140" />
|
||||
<ColumnDefinition Width="*" MinWidth="160" />
|
||||
<ColumnDefinition Width="*" MinWidth="160" />
|
||||
<ColumnDefinition Width="*" MinWidth="140" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="180" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="180" />
|
||||
<ColumnDefinition Width="160" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="280" />
|
||||
</Grid.ColumnDefinitions>
|
||||
@@ -408,15 +408,15 @@
|
||||
<Border x:Name="RowBorder" Background="Transparent" Padding="14,0">
|
||||
<Grid MinHeight="40">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="1.6*" MinWidth="140" />
|
||||
<ColumnDefinition Width="*" MinWidth="160" />
|
||||
<ColumnDefinition Width="*" MinWidth="160" />
|
||||
<ColumnDefinition Width="*" MinWidth="140" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="180" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="180" />
|
||||
<ColumnDefinition Width="160" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="280" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" ToolTip="{Binding TitleToolTip}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding HereText}" ToolTip="{Binding HereText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding ThereText}" ToolTip="{Binding ThereText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding HereText}" ToolTip="{Binding HereToolTip}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding ThereText}" ToolTip="{Binding ThereToolTip}" Margin="10,0,0,0" />
|
||||
<ui:StatusGlyph Grid.Column="3" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
|
||||
FontSize="13" VerticalAlignment="Center" Margin="10,0,0,0"
|
||||
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding StateAnnouncement}" />
|
||||
|
||||
@@ -199,6 +199,12 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
public ICommand TrashCommand => _trash;
|
||||
public ICommand DeleteThereCommand => _deleteThere;
|
||||
|
||||
/// <summary>To trash…: what it does, or why it waits (no photo selected).</summary>
|
||||
public string TrashToolTip => _photos.Any(p => p.IsSelected) ? Loc.L("Tooltips.Server.Copies.ToTrash") : Loc.L("Tooltips.Server.Copies.SelectFirst");
|
||||
|
||||
/// <summary>Delete on server…: what it does, or why it waits (no photo selected).</summary>
|
||||
public string DeleteThereToolTip => _photos.Any(p => p.IsSelected) ? Loc.L("Tooltips.Server.Copies.DeleteOnServer") : Loc.L("Tooltips.Server.Copies.SelectFirst");
|
||||
|
||||
// ---- Details ----
|
||||
|
||||
public IReadOnlyList<CopyDetailRow> Details { get => _details; private set => Set(ref _details, value); }
|
||||
@@ -435,9 +441,9 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
foreach (var row in _photos) row.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName != nameof(CopyPhotoRow.IsSelected)) return;
|
||||
_trash.RaiseCanExecuteChanged();
|
||||
_deleteThere.RaiseCanExecuteChanged();
|
||||
RaiseSelection();
|
||||
};
|
||||
RaiseSelection();
|
||||
OnPropertyChanged(nameof(HasPhotos));
|
||||
OnPropertyChanged(nameof(PhotosEmptyText));
|
||||
OnPropertyChanged(nameof(CanBringAll));
|
||||
@@ -447,6 +453,15 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
OnPropertyChanged(nameof(SelectedClass));
|
||||
}
|
||||
|
||||
/// <summary>The selection changed: To trash… and Delete on server… follow it, with their tooltips.</summary>
|
||||
private void RaiseSelection()
|
||||
{
|
||||
_trash.RaiseCanExecuteChanged();
|
||||
_deleteThere.RaiseCanExecuteChanged();
|
||||
OnPropertyChanged(nameof(TrashToolTip));
|
||||
OnPropertyChanged(nameof(DeleteThereToolTip));
|
||||
}
|
||||
|
||||
private void OnPhotoChanged(string key)
|
||||
{
|
||||
if (_photos.FirstOrDefault(p => p.Key == key)?.Chosen is { } chosen) _perPhoto[key] = chosen;
|
||||
@@ -502,6 +517,8 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
private void SchedulePlan(TimeSpan delay)
|
||||
{
|
||||
if (!_isLoaded) return;
|
||||
// The plan shown is for the choices before this one: Apply waits for the new plan, never confirms the old.
|
||||
IsPlanning = true;
|
||||
_planning?.Cancel();
|
||||
var run = _planning = new CancellationTokenSource();
|
||||
_ = Delayed();
|
||||
@@ -649,7 +666,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
SetProjectTargets(merge.Projects);
|
||||
if (merge.SessionKeys.Count > 0)
|
||||
here.Add(new(Loc.L("Server.Copies.Plan.SessionKeys", Formatting.Count(merge.SessionKeys.Count)),
|
||||
string.Join(Environment.NewLine, [Loc.L("Tooltips.Server.Copies.Plan.SessionKeys"), .. merge.SkippedSessionKeys])));
|
||||
SessionKeysToolTip(merge.SkippedSessionKeys)));
|
||||
if (merge.DeletedInOther > 0)
|
||||
here.Add(new(Loc.Plural("Server.Copies.Plan.DeletedInOther", merge.DeletedInOther), Loc.L("Tooltips.Server.Copies.Plan.DeletedInOther")));
|
||||
foreach (var link in merge.LinkNames.Count == merge.Links.Count ? merge.LinkNames : merge.Links)
|
||||
@@ -725,6 +742,12 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
if (_shell.Services.Engine is not { } jobs) return;
|
||||
try
|
||||
{
|
||||
if (_isPlanning || !PlanIsCurrent())
|
||||
{
|
||||
// A choice changed since the plan shown: planned again, confirmed only then.
|
||||
SchedulePlan(TimeSpan.Zero);
|
||||
return;
|
||||
}
|
||||
if (_plan is { CanApply: true } plan)
|
||||
{
|
||||
if (plan.Destructive && !_shell.Services.Dialogs.Confirm(ReplaceRequest(plan))) return;
|
||||
@@ -758,6 +781,25 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether the plan shown was made for the kept sequence and the choices the dialog shows now.</summary>
|
||||
private bool PlanIsCurrent()
|
||||
{
|
||||
if (IsMerge)
|
||||
{
|
||||
if (_merge is not { } merge) return true;
|
||||
var choices = MergeChoices();
|
||||
return merge.KeepId == _keepId && merge.Choices.Photos == choices.Photos && Same(merge.Choices.PerPhoto, choices.PerPhoto)
|
||||
&& Same(merge.Choices.Details, choices.Details);
|
||||
}
|
||||
if (_plan is not { } plan) return true;
|
||||
var integrate = IntegrateChoices();
|
||||
return plan.Choices.Photos == integrate.Photos && plan.Choices.Projects == integrate.Projects && Same(plan.Choices.PerPhoto, integrate.PerPhoto)
|
||||
&& Same(plan.Choices.Details, integrate.Details);
|
||||
|
||||
static bool Same<T>(IReadOnlyDictionary<string, T> a, IReadOnlyDictionary<string, T> b) =>
|
||||
a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var v) && EqualityComparer<T>.Default.Equals(v, p.Value));
|
||||
}
|
||||
|
||||
private async Task LinkOnlyAsync()
|
||||
{
|
||||
if (_shell.Services.Sync.Remote is not { } remote) return;
|
||||
@@ -932,11 +974,22 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
ActionText = Loc.L("Server.Copies.Action.Merge"),
|
||||
ActionToolTip = Loc.L("Tooltips.Server.Copies.Confirm.Merge.Action"),
|
||||
IsDestructive = true,
|
||||
TypedConfirmation = drop.Photos.ToString(Loc.Culture),
|
||||
TypedPrompt = Loc.L("Server.Copies.Confirm.Merge.TypedPrompt", drop.Title),
|
||||
TypedConfirmation = MergeTyped(drop.Photos),
|
||||
TypedPrompt = MergeTypedPrompt(drop.Photos, drop.Title),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The session keys line's tooltip: what they do, then the keys the kept archive already maps elsewhere (when any).</summary>
|
||||
internal static string SessionKeysToolTip(IReadOnlyList<string> skipped) => skipped.Count == 0
|
||||
? Loc.L("Tooltips.Server.Copies.Plan.SessionKeys")
|
||||
: Loc.L("Tooltips.Server.Copies.Plan.SessionKeys") + " " + Loc.L("Tooltips.Server.Copies.Plan.SessionKeysKept", string.Join(Loc.Separator, skipped));
|
||||
|
||||
/// <summary>What a merge's confirmation asks to type: the other's photo count, without group separators (as Delete asks).</summary>
|
||||
internal static string MergeTyped(int photos) => photos.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>The prompt of a merge's typed confirmation: it names the very text to type.</summary>
|
||||
internal static string MergeTypedPrompt(int photos, string title) => Loc.L("Server.Copies.Confirm.Merge.TypedPrompt", title, MergeTyped(photos));
|
||||
|
||||
/// <summary>To trash… and Delete on server…: as the Library's delete confirmation, with the last copies named first.</summary>
|
||||
private static ConfirmRequest TrashRequest(int photos, IEnumerable<string> names, string message, IReadOnlyList<LastCopy> lasts) => new()
|
||||
{
|
||||
|
||||
@@ -27,6 +27,27 @@
|
||||
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
|
||||
</Style>
|
||||
|
||||
<!-- A project of the Projects part: its name trims first, versions and date keep their width, the name it gets at the
|
||||
other home on a line of its own (it repeats the name and adds a suffix); the tooltip says the whole row. -->
|
||||
<DataTemplate x:Key="Template.CopyProjectRow" DataType="{x:Type cp:CopyProjectRow}">
|
||||
<Grid Margin="0,0,0,6" ToolTip="{Binding ToolTip}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{Binding Name}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding VersionsText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Text="{Binding ChangedText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Row="1" Grid.ColumnSpan="3" Text="{Binding TargetText}" Foreground="{DynamicResource Brush.Accent}" TextTrimming="CharacterEllipsis"
|
||||
Margin="0,2,0,0" Visibility="{Binding TargetText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- A plan line reads as text to act on, not as a disabled one: the ring stays, the words take the text colour (a
|
||||
style trigger outranks the glyph template's Queued colour); warnings keep theirs. -->
|
||||
<Style x:Key="Status.PlanLine" TargetType="ui:StatusGlyph" BasedOn="{StaticResource {x:Type ui:StatusGlyph}}">
|
||||
@@ -124,10 +145,10 @@
|
||||
<Button Style="{StaticResource Button.Link}" Content="{l:Loc Server.Copies.Photo.AllBoth}" Command="{Binding AllBothCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Copies.AllBoth}" Margin="0,0,14,0" Visibility="{Binding CanKeepAllBoth, Converter={StaticResource CopyBoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Server.Copies.Action.ToTrash}" Command="{Binding TrashCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Copies.ToTrash}" ToolTipService.ShowOnDisabled="True" Margin="0,0,8,0"
|
||||
ToolTip="{Binding TrashToolTip}" ToolTipService.ShowOnDisabled="True" Margin="0,0,8,0"
|
||||
Visibility="{Binding CanTrashHere, Converter={StaticResource CopyBoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Server.Copies.Action.DeleteOnServer}" Command="{Binding DeleteThereCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Copies.DeleteOnServer}" ToolTipService.ShowOnDisabled="True"
|
||||
ToolTip="{Binding DeleteThereToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
Visibility="{Binding CanDeleteThere, Converter={StaticResource CopyBoolToVisibility}}" />
|
||||
</WrapPanel>
|
||||
<!-- The photos of the selected class under column headings that share the rows' widths. -->
|
||||
@@ -264,30 +285,8 @@
|
||||
<!-- Each column says whose projects it lists: this PC and the server, or the pair's two sequences (the lists do not follow the kept one). -->
|
||||
<TextBlock Grid.Row="2" Text="{Binding ProjectsHereHeading}" FontWeight="SemiBold" Margin="0,0,14,6" TextTrimming="CharacterEllipsis" ToolTip="{Binding ProjectsHereHeading}" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding ProjectsThereHeading}" FontWeight="SemiBold" Margin="0,0,0,6" TextTrimming="CharacterEllipsis" ToolTip="{Binding ProjectsThereHeading}" />
|
||||
<ItemsControl Grid.Row="3" ItemsSource="{Binding HereProjects}" Focusable="False" Margin="0,0,14,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type cp:CopyProjectRow}">
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,6" ToolTip="{Binding ToolTip}">
|
||||
<TextBlock Text="{Binding Name}" FontWeight="SemiBold" />
|
||||
<TextBlock Text="{Binding VersionsText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" />
|
||||
<TextBlock Text="{Binding ChangedText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" />
|
||||
<TextBlock Text="{Binding TargetText}" Foreground="{DynamicResource Brush.Accent}" Margin="10,0,0,0" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<ItemsControl Grid.Row="3" Grid.Column="1" ItemsSource="{Binding ThereProjects}" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type cp:CopyProjectRow}">
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,6" ToolTip="{Binding ToolTip}">
|
||||
<TextBlock Text="{Binding Name}" FontWeight="SemiBold" />
|
||||
<TextBlock Text="{Binding VersionsText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" />
|
||||
<TextBlock Text="{Binding ChangedText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" />
|
||||
<TextBlock Text="{Binding TargetText}" Foreground="{DynamicResource Brush.Accent}" Margin="10,0,0,0" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<ItemsControl Grid.Row="3" ItemsSource="{Binding HereProjects}" ItemTemplate="{StaticResource Template.CopyProjectRow}" Focusable="False" Margin="0,0,14,0" />
|
||||
<ItemsControl Grid.Row="3" Grid.Column="1" ItemsSource="{Binding ThereProjects}" ItemTemplate="{StaticResource Template.CopyProjectRow}" Focusable="False" />
|
||||
</Grid>
|
||||
|
||||
<!-- Plan: the kept sequence (merge), what each side receives and loses, the blocks with their one action, Link only. -->
|
||||
|
||||
@@ -96,7 +96,7 @@ public sealed class CopyListViewModel : ObservableObject, IDisposable
|
||||
private bool CanIntegrate => _shell.Services.Server.IsConnected && _shell.Services.Server.Flow.Info?.Capabilities is { } capabilities
|
||||
&& capabilities.Contains(ServerCapabilities.PhotoLookup) && capabilities.Contains(ServerCapabilities.UploadInto);
|
||||
|
||||
private CopyRights Rights => new(Host.Server, ServerName, CanIntegrate, Host.CanUpload);
|
||||
private CopyRights Rights => new(Host.Server, ServerName, CanIntegrate, Host.CanSendSync);
|
||||
|
||||
/// <summary>Raised after each reload (the chip count, the rail badge and the sync rows' marks follow it).</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Ui.Mvvm;
|
||||
@@ -11,19 +12,24 @@ public sealed class CopyProjectRow(ProjectLine project) : ObservableObject
|
||||
private string? _target;
|
||||
|
||||
public ProjectLine Project { get; } = project;
|
||||
public string Name => Project.Name;
|
||||
|
||||
/// <summary>The project's name; the Main project in the UI language ("Principale" in Italian).</summary>
|
||||
public string Name => WorkspaceText.ProjectName(Project.Name, Project.IsMain);
|
||||
|
||||
public string VersionsText => Loc.Plural("Server.Copies.Projects.Versions", Project.Versions);
|
||||
public string ChangedText => Formatting.Date(Project.UpdatedAt);
|
||||
|
||||
/// <summary>"→ Vertical (STUDIO-PC)" once the plan named it; null when it stays or Main.</summary>
|
||||
public string? TargetText => _target is null ? null : Loc.L("Server.Copies.Projects.Target", _target);
|
||||
|
||||
/// <summary>The whole row (the row may cut it), with the name it gets at the other home once the plan named it.</summary>
|
||||
public string ToolTip => Project.IsMain ? Loc.L("Tooltips.Server.Copies.Projects.Main")
|
||||
: string.Join(Loc.Separator, Name, VersionsText, ChangedText);
|
||||
: string.Join(Loc.Separator, new[] { Name, VersionsText, ChangedText, TargetText }.OfType<string>());
|
||||
|
||||
internal void SetTarget(string? target)
|
||||
{
|
||||
_target = target;
|
||||
OnPropertyChanged(nameof(TargetText));
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
}
|
||||
}
|
||||
@@ -81,8 +81,11 @@ public sealed class CopyRow : ObservableObject
|
||||
? _view.Here.Title
|
||||
: string.Join(Loc.Separator, _view.Here.Title, _view.There.Title);
|
||||
|
||||
public string HereText => CopyText.Where(_view.Here, isServer: false);
|
||||
public string ThereText => CopyText.Where(_view.There, isServer: Copy.Kind == CopyKind.LocalServer, Copy.RemoteGone);
|
||||
/// <summary>"1,204 photos · Main archive", a long archive name trimmed in its middle (its end tells two apart); the tooltip says it whole.</summary>
|
||||
public string HereText => CopyText.Where(_view.Here, isServer: false, maxName: CopyText.RowNameLength);
|
||||
public string ThereText => CopyText.Where(_view.There, isServer: Copy.Kind == CopyKind.LocalServer, Copy.RemoteGone, CopyText.RowNameLength);
|
||||
public string HereToolTip => CopyText.Where(_view.Here, isServer: false);
|
||||
public string ThereToolTip => CopyText.Where(_view.There, isServer: Copy.Kind == CopyKind.LocalServer, Copy.RemoteGone);
|
||||
|
||||
public StatusKind StateKind => CopyText.State(Copy, _rights.ServerName, _progress).Kind;
|
||||
public string StateText => CopyText.State(Copy, _rights.ServerName, _progress).Text;
|
||||
@@ -151,6 +154,8 @@ public sealed class CopyRow : ObservableObject
|
||||
OnPropertyChanged(nameof(TitleToolTip));
|
||||
OnPropertyChanged(nameof(HereText));
|
||||
OnPropertyChanged(nameof(ThereText));
|
||||
OnPropertyChanged(nameof(HereToolTip));
|
||||
OnPropertyChanged(nameof(ThereToolTip));
|
||||
OnPropertyChanged(nameof(StateKind));
|
||||
OnPropertyChanged(nameof(StateText));
|
||||
OnPropertyChanged(nameof(StateToolTip));
|
||||
|
||||
@@ -84,8 +84,26 @@ public static class CopyText
|
||||
/// "Main archive · 1,204 photos": where one side of a pair lies; the server's name alone once it deleted its sequence
|
||||
/// (<paramref name="gone"/>: no count is known, and "0 photos" would read as an empty sequence).
|
||||
/// </summary>
|
||||
public static string Where(CopyFacts facts, bool isServer, bool gone = false) => gone && facts.Where.Length > 0 ? facts.Where
|
||||
: Loc.Plural(isServer ? "Server.Copies.Where.Server" : "Server.Copies.Where.Archive", facts.Photos, facts.Where);
|
||||
/// <param name="maxName">Trims a longer archive or server name in its middle (<see cref="MiddleTrim"/>).</param>
|
||||
public static string Where(CopyFacts facts, bool isServer, bool gone = false, int? maxName = null)
|
||||
{
|
||||
var where = maxName is { } max ? MiddleTrim(facts.Where, max) : facts.Where;
|
||||
return gone && where.Length > 0 ? where : Loc.Plural(isServer ? "Server.Copies.Where.Server" : "Server.Copies.Where.Archive", facts.Photos, where);
|
||||
}
|
||||
|
||||
/// <summary>The longest archive or server name a Matches row shows whole.</summary>
|
||||
public const int RowNameLength = 24;
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="text"/> within <paramref name="max"/> characters, its middle replaced by an ellipsis: the start and
|
||||
/// the end stay ("ChronosArch…Studio NAS"), where an end ellipsis would cut what tells two archives apart.
|
||||
/// </summary>
|
||||
internal static string MiddleTrim(string text, int max)
|
||||
{
|
||||
if (text.Length <= max || max < 3) return text;
|
||||
var head = (max - 1) / 2;
|
||||
return text[..head].TrimEnd() + "…" + text[^(max - 1 - head)..].TrimStart();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Main archive · 1,204 photos · 18.2 GB": a side of the dialog's header; "Lighthouse · Main archive · 1,204 photos ·
|
||||
|
||||
@@ -133,6 +133,15 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
/// <summary>The signed-in account may send files (originals, renders) to the server.</summary>
|
||||
public bool CanUpload => Allows(Permissions.Upload);
|
||||
|
||||
/// <summary>The signed-in account's sync rights (<see cref="SyncRights.Of"/>); none while signed out.</summary>
|
||||
public SyncRights Rights => services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
|
||||
|
||||
/// <summary>
|
||||
/// The signed-in account may send a sequence (originals and settings) to the server: Upload with Edit, as the sync table
|
||||
/// and the planners decide it; <see cref="CanUpload"/> alone still sends renders.
|
||||
/// </summary>
|
||||
public bool CanSendSync => Rights.CanUpload;
|
||||
|
||||
/// <summary>The signed-in account may queue renders on the server.</summary>
|
||||
public bool CanRender => Allows(Permissions.Render);
|
||||
|
||||
|
||||
@@ -216,7 +216,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
|
||||
private SyncHost Host => _shell.Services.Sync;
|
||||
|
||||
private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) with { KeepsProjects = Host.HasProjects } : default;
|
||||
private SyncRights Rights => _shell.Services.Server.User is not null ? Host.Rights with { KeepsProjects = Host.HasProjects } : default;
|
||||
|
||||
private IEnumerable<SyncEntry> LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly);
|
||||
|
||||
|
||||
@@ -16,22 +16,33 @@ namespace Chronos.App.Server;
|
||||
/// its renders sent to one, and since owner review 6 the integration of a pair with a server sequence (<see cref="Holds"/>); a copy from or a send to this PC's archive is never held.
|
||||
/// The automatic transfers of an integrated pair's new photos are held on a metered connection even with the option off
|
||||
/// (owner review 6, Q6; <see cref="HeldNow"/>). They are resumed when the connection is no longer metered or the option
|
||||
/// goes off (for the jobs only it holds). Only the jobs it paused are resumed. Checked when the network or one of those
|
||||
/// jobs changes, and every minute.
|
||||
/// goes off (for the jobs only it holds). Only the jobs it paused are resumed, and the paused automatic transfers (they have
|
||||
/// no user pause: a pause of one is this hold's, from before a restart). Checked when the network or one of those jobs
|
||||
/// changes, and every minute.
|
||||
/// </summary>
|
||||
public sealed class UploadHold : IDisposable
|
||||
{
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly AppServices _services;
|
||||
private readonly Func<Data.ChronosDatabase?> _database;
|
||||
private readonly Func<bool> _optionOn;
|
||||
private readonly Func<bool> _metered;
|
||||
private readonly HashSet<Guid> _held = [];
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private readonly Timer _timer;
|
||||
private JobEngine? _engine;
|
||||
|
||||
public UploadHold(AppServices services)
|
||||
: this(() => services.Database, () => services.Settings.PauseUploadsOnMetered, MeteredNetwork.IsMetered)
|
||||
{
|
||||
_services = services;
|
||||
}
|
||||
|
||||
/// <summary>A hold over <paramref name="database"/>, reading the option and the connection's cost through the functions given (tests).</summary>
|
||||
internal UploadHold(Func<Data.ChronosDatabase?> database, Func<bool> optionOn, Func<bool> metered)
|
||||
{
|
||||
_database = database;
|
||||
_optionOn = optionOn;
|
||||
_metered = metered;
|
||||
_timer = new Timer(_ => Request(), null, Interval, Interval);
|
||||
NetworkChange.NetworkAddressChanged += OnNetworkChanged;
|
||||
NetworkChange.NetworkAvailabilityChanged += OnNetworkChanged;
|
||||
@@ -95,15 +106,26 @@ public sealed class UploadHold : IDisposable
|
||||
internal static bool HeldNow(Job job, bool metered, bool optionOn) =>
|
||||
metered && Holds(job) && (optionOn || SyncService.IsAutomaticTransfer(job));
|
||||
|
||||
private async Task ApplyAsync()
|
||||
/// <summary>
|
||||
/// Whether a paused <paramref name="job"/> is this hold's although it did not record pausing it: an automatic transfer has no
|
||||
/// pause of the user's, so a paused one was paused by the hold before the app restarted (the record is in memory only).
|
||||
/// </summary>
|
||||
internal static bool Adopts(Job job) => job.State == JobState.Paused && Holds(job) && SyncService.IsAutomaticTransfer(job);
|
||||
|
||||
/// <summary>One pass: pauses what must be held now and resumes what this hold paused that need not be.</summary>
|
||||
internal async Task ApplyAsync()
|
||||
{
|
||||
if (_engine is not { } engine || _services.Database is not { } db) return;
|
||||
if (_engine is not { } engine || _database() is not { } db) return;
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
// Read once per pass: the connection's cost and the option.
|
||||
var metered = MeteredNetwork.IsMetered();
|
||||
var optionOn = _services.Settings.PauseUploadsOnMetered;
|
||||
var metered = _metered();
|
||||
var optionOn = _optionOn();
|
||||
foreach (var kind in Kinds)
|
||||
{
|
||||
foreach (var job in (await db.Jobs.ListAsync(JobState.Paused, kind, 500)).Items.Where(Adopts)) _held.Add(job.Id);
|
||||
}
|
||||
if (metered)
|
||||
{
|
||||
foreach (var state in new[] { JobState.Queued, JobState.Running })
|
||||
|
||||
@@ -190,6 +190,8 @@ public static class ScreenCapture
|
||||
|
||||
written += await CaptureEditorAsync(window, shell, sample, directory);
|
||||
written += await CaptureRemoteEditorAsync(window, shell, sample, directory);
|
||||
// The remote editor's scenes restricted the account; the matches act as the editor the sample signs in as.
|
||||
await sample.RestoreAccountAsync();
|
||||
written += await CaptureCopiesAsync(window, shell, sample, directory);
|
||||
Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
|
||||
if (written == 0) Environment.ExitCode = 1;
|
||||
|
||||
@@ -31,11 +31,14 @@ public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? seq
|
||||
/// <summary>"Also at nas: Vertical."</summary>
|
||||
public string? TwinToolTip => _twinHome is null ? null : Loc.L("Tooltips.Editor.Picker.Twin", _twinHome, _twinProject ?? string.Empty);
|
||||
|
||||
/// <summary>Marks the item as the twin of <paramref name="project"/> at <paramref name="home"/> (null: none).</summary>
|
||||
/// <summary>
|
||||
/// Marks the item as the twin of <paramref name="project"/> at <paramref name="home"/> (null: none). The other home's
|
||||
/// Main project is named in the UI language ("Principale"), as the picker names this one.
|
||||
/// </summary>
|
||||
public void SetTwin(string? home, string? project)
|
||||
{
|
||||
_twinHome = home;
|
||||
_twinProject = project;
|
||||
_twinProject = project is null ? null : WorkspaceText.ProjectName(project, project == Data.Projects.ProjectService.MainName);
|
||||
OnPropertyChanged(nameof(TwinHome));
|
||||
OnPropertyChanged(nameof(HasTwin));
|
||||
OnPropertyChanged(nameof(TwinToolTip));
|
||||
|
||||
@@ -20,8 +20,10 @@ namespace Chronos.Data.Archiving.Jobs;
|
||||
/// tombstones honoured), move the renders, verify every original of the other is held by the kept one (hashed again on
|
||||
/// both sides) or listed as a last copy, trash the kept sequence's losing versions, write the details, copy the projects,
|
||||
/// move session keys, links and pairs, then move the other to its archive's trash, only while it is still at the frames
|
||||
/// version the verify read and the kept photos verified are still there. A cancel leaves the photos copied so far in the
|
||||
/// kept sequence (nothing of the other is touched before the trash stage) and drops the journal.
|
||||
/// version the verify read and the kept photos verified are still there. Every check that can still abandon the merge runs
|
||||
/// before the links stage changes anything, and again at the trash; a merge abandoned after the links stage (a check that
|
||||
/// fails at the trash, a cancel) gives the other back its keys, links and pairs first (<see cref="MergeLinksUndo"/>). A
|
||||
/// cancel leaves the photos copied so far in the kept sequence and drops the journal.
|
||||
/// </summary>
|
||||
internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger, ArchiveService archives, IProjectCopier projects,
|
||||
IWorkspaceGuard workspace) : ICancelledJobHandler
|
||||
@@ -93,6 +95,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
/// <summary>A cancelled merge: its journal and staging go, and its pair returns to the state it had (when it is still this job's).</summary>
|
||||
private async Task ForgetAsync(Job job, MergeJobParameters parameters, ArchivePaths keepPaths)
|
||||
{
|
||||
await MoveBackAsync(keepPaths, job.Id).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
MergeJournal.Delete(keepPaths, job.Id);
|
||||
@@ -105,6 +108,70 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
await new FoundCopyStore(db).ReleaseAsync(parameters.CopyId, job.Id, null, keepJob: false, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Gives back what the links stage of job <paramref name="jobId"/>'s journal moved (when it has one and the stage began).</summary>
|
||||
private async Task MoveBackAsync(ArchivePaths keepPaths, Guid jobId)
|
||||
{
|
||||
MergeJournal? journal;
|
||||
try
|
||||
{
|
||||
journal = MergeJournal.Read(keepPaths, jobId);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
Log.Warning("archive", $"The journal of merge {jobId} could not be read: what its links stage moved stays with the kept sequence", ex);
|
||||
return;
|
||||
}
|
||||
if (journal is not null) await MoveBackAsync(journal).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gives the other sequence back what the links stage took (<see cref="MergeJournal.LinksUndo"/>): its rows (session keys,
|
||||
/// links, pairs), then the session keys of both manifests; the journal is set back to before the links stage (not saved).
|
||||
/// Nothing when the stage had not begun, or the other is gone (the trash ran). False when it could not be done.
|
||||
/// </summary>
|
||||
internal async Task<bool> MoveBackAsync(MergeJournal journal)
|
||||
{
|
||||
if (journal.LinksUndo is not { } undo) return true;
|
||||
var ct = CancellationToken.None;
|
||||
try
|
||||
{
|
||||
var drop = await db.Sequences.GetAsync(journal.DropId, ct).ConfigureAwait(false);
|
||||
var keep = await db.Sequences.GetAsync(journal.KeepId, ct).ConfigureAwait(false);
|
||||
if (drop is null || keep is null) return true;
|
||||
await new FoundCopyStore(db).MoveBackAsync(journal.DropId, journal.KeepId, keep.ArchiveId, undo.DropArchiveId, undo.Moved, ct).ConfigureAwait(false);
|
||||
var keys = journal.SessionKeys.ToHashSet(StringComparer.Ordinal);
|
||||
var added = keys.Where(k => !undo.KeepKeysBefore.Contains(k, StringComparer.Ordinal)).ToHashSet(StringComparer.Ordinal);
|
||||
var removed = keys.Where(k => undo.DropKeysBefore.Contains(k, StringComparer.Ordinal)).ToList();
|
||||
if (added.Count > 0 && await db.Archives.GetAsync(keep.ArchiveId, ct).ConfigureAwait(false) is { } keepArchive)
|
||||
{
|
||||
var paths = new ArchivePaths(keepArchive.RootPath);
|
||||
if (File.Exists(paths.Sequence(keep.Folder).ManifestPath))
|
||||
await archives.Writer.UpdateAsync(paths, keep.Id, keep.Folder, manifest =>
|
||||
!manifest.SessionKeys.Any(added.Contains) ? null : manifest with { SessionKeys = [.. manifest.SessionKeys.Where(k => !added.Contains(k))] },
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
if (removed.Count > 0 && await db.Archives.GetAsync(drop.ArchiveId, ct).ConfigureAwait(false) is { } dropArchive)
|
||||
{
|
||||
var paths = new ArchivePaths(dropArchive.RootPath);
|
||||
if (File.Exists(paths.Sequence(drop.Folder).ManifestPath))
|
||||
await archives.Writer.UpdateAsync(paths, drop.Id, drop.Folder, manifest =>
|
||||
removed.All(manifest.SessionKeys.Contains) ? null : manifest with { SessionKeys = [.. manifest.SessionKeys.Union(removed, StringComparer.Ordinal)] },
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
journal.LinksUndo = null;
|
||||
journal.KeepKeysWritten = false;
|
||||
journal.DropKeysRemoved = false;
|
||||
journal.LinksMoved = false;
|
||||
if (journal.Stage > MergeStage.Links) journal.Stage = MergeStage.Links;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
Log.Warning("archive", $"Merge {journal.JobId}: what its links stage moved could not be given back to the other sequence", ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A resumed run (a pause, a crash, or a retry after a failure) goes on only while the pair is still this job's: it reads
|
||||
/// Integrating with this job (a failure keeps both; a Keep apart, an Ask again or another merge since clears them), or
|
||||
@@ -116,6 +183,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
var copy = await new FoundCopyStore(db).GetAsync(parameters.CopyId, ct).ConfigureAwait(false);
|
||||
if (copy is { State: CopyState.Integrating } && copy.JobId == job.Id) return;
|
||||
if (copy is null && await db.Sequences.GetAsync(parameters.DropId, ct).ConfigureAwait(false) is null) return;
|
||||
await MoveBackAsync(keepPaths, job.Id).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
MergeJournal.Delete(keepPaths, job.Id);
|
||||
@@ -178,6 +246,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
private ArchivePaths _dropPaths = null!;
|
||||
private string _keepTitle = string.Empty;
|
||||
private string _dropTitle = string.Empty;
|
||||
private bool _forget;
|
||||
|
||||
private long Total => journal.Copies.Count + journal.Renders.Count + journal.Replaces.Count + journal.Projects.Count + 4;
|
||||
|
||||
@@ -198,16 +267,24 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
{
|
||||
_ct.ThrowIfCancellationRequested();
|
||||
if (owner.BeforeStage is { } hook) await hook(journal.Stage).ConfigureAwait(false);
|
||||
switch (journal.Stage)
|
||||
try
|
||||
{
|
||||
case MergeStage.Copy: await CopyAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Renders: await RendersAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Verify: await VerifyAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Replace: await ReplaceAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Details: await DetailsAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Projects: await ProjectsAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Links: await LinksAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Trash: await TrashAsync().ConfigureAwait(false); break;
|
||||
switch (journal.Stage)
|
||||
{
|
||||
case MergeStage.Copy: await CopyAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Renders: await RendersAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Verify: await VerifyAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Replace: await ReplaceAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Details: await DetailsAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Projects: await ProjectsAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Links: await LinksAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Trash: await TrashAsync().ConfigureAwait(false); break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
await AbandonAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
journal.Stage++;
|
||||
Save();
|
||||
@@ -223,16 +300,32 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
|
||||
private InvalidOperationException Changed(string title) => new(Loc.L("Errors.Copies.Changed", title));
|
||||
|
||||
/// <summary>Drops this run's journal and staging: what it planned no longer holds.</summary>
|
||||
private void ForgetJournal()
|
||||
/// <summary>Asks for this run's journal and staging to go as it fails (<see cref="AbandonAsync"/>): what it planned no longer holds.</summary>
|
||||
private void ForgetJournal() => _forget = true;
|
||||
|
||||
/// <summary>
|
||||
/// A stage failed: what the links stage took from the other goes back to it first (a retry runs that stage again, after
|
||||
/// its checks), then the journal goes when <see cref="ForgetJournal"/> asked for it, else it is saved as set back. When
|
||||
/// nothing could be given back, the journal stays (at the stage it reached) so a retry or a cancel tries again.
|
||||
/// </summary>
|
||||
private async Task AbandonAsync()
|
||||
{
|
||||
try
|
||||
var linksBegun = journal.LinksUndo is not null;
|
||||
if (!await owner.MoveBackAsync(journal).ConfigureAwait(false)) return;
|
||||
if (_forget)
|
||||
{
|
||||
MergeJournal.Delete(keepPaths, journal.JobId);
|
||||
try
|
||||
{
|
||||
MergeJournal.Delete(keepPaths, journal.JobId);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"The stale journal of merge {journal.JobId} was not removed", ex);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
else if (linksBegun)
|
||||
{
|
||||
Log.Warning("archive", $"The stale journal of merge {journal.JobId} was not removed", ex);
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -582,6 +675,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
|
||||
private async Task ProjectsAsync()
|
||||
{
|
||||
await RenamesHeldRendersAsync().ConfigureAwait(false);
|
||||
if (journal.Projects.Count == 0) return;
|
||||
var from = new ArchiveProjectHome(_db, owner.Archives.Projects, journal.DropId);
|
||||
var to = new ArchiveProjectHome(_db, owner.Archives.Projects, journal.KeepId);
|
||||
@@ -624,16 +718,33 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
if (failed > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.ProjectsKept", failed));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The renders moved to the kept sequence that name a project of the other the plan left because the kept sequence
|
||||
/// holds its copy already name that copy (and its versions), as those of a copied project do.
|
||||
/// </summary>
|
||||
private async Task RenamesHeldRendersAsync()
|
||||
{
|
||||
var planned = journal.Projects.Select(p => p.SourceProjectId).ToHashSet();
|
||||
IReadOnlyList<SequenceProject>? keepProjects = null;
|
||||
foreach (var project in await _db.Projects.ListBySequenceAsync(journal.DropId, includeDeleted: false, _ct).ConfigureAwait(false))
|
||||
{
|
||||
if (project.IsMain || planned.Contains(project.Id)) continue;
|
||||
keepProjects ??= await _db.Projects.ListBySequenceAsync(journal.KeepId, includeDeleted: false, _ct).ConfigureAwait(false);
|
||||
if (await owner.Merger.HeldAsync(project, keepProjects, _dropArchive.Name, _ct).ConfigureAwait(false) is { } held)
|
||||
await RenamesRendersAsync(project.Id, held.KeptId, held.Versions.Select(v => new TransplantMove(v.Key, v.Value))).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The renders moved to the kept sequence name the project copy (and its versions) instead of the other's.</summary>
|
||||
private async Task RenamesRendersAsync(Guid source, Guid copy)
|
||||
private Task RenamesRendersAsync(Guid source, Guid copy) =>
|
||||
RenamesRendersAsync(source, copy, journal.ProjectSteps.GetValueOrDefault(source)?.Moves ?? []);
|
||||
|
||||
private async Task RenamesRendersAsync(Guid source, Guid copy, IEnumerable<TransplantMove> moves)
|
||||
{
|
||||
var access = new DbAccess(_db.Database);
|
||||
if (journal.ProjectSteps.GetValueOrDefault(source) is { } step)
|
||||
{
|
||||
foreach (var move in step.Moves)
|
||||
await access.ExecuteAsync("UPDATE renders SET project_id = $2, project_version_id = $3 WHERE sequence_id = $1 AND project_version_id = $4",
|
||||
[journal.KeepId, copy, move.Copy, move.Source], _ct).ConfigureAwait(false);
|
||||
}
|
||||
foreach (var move in moves)
|
||||
await access.ExecuteAsync("UPDATE renders SET project_id = $2, project_version_id = $3 WHERE sequence_id = $1 AND project_version_id = $4",
|
||||
[journal.KeepId, copy, move.Copy, move.Source], _ct).ConfigureAwait(false);
|
||||
await access.ExecuteAsync("UPDATE renders SET project_id = $2 WHERE sequence_id = $1 AND project_id = $3", [journal.KeepId, copy, source], _ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
@@ -645,6 +756,17 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Process)).ConfigureAwait(false);
|
||||
var keep = await _db.Sequences.GetAsync(journal.KeepId, _ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
|
||||
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
|
||||
if (journal.LinksUndo is null)
|
||||
{
|
||||
// Nothing of the other is touched while a check before the trash can still abandon the merge.
|
||||
await CheckTrashAsync(drop).ConfigureAwait(false);
|
||||
await using (await owner.Archives.Writer.LockAsync(keepPaths, journal.KeepId, _ct).ConfigureAwait(false))
|
||||
await PlanTrashAsync().ConfigureAwait(false);
|
||||
journal.LinksUndo = new MergeLinksUndo(KeysOf(keepPaths, keep), KeysOf(_dropPaths, drop), _dropArchive.Id,
|
||||
await new FoundCopyStore(_db).UndoOfMoveAsync(journal.DropId, journal.KeepId, keepArchive.Id, journal.SessionKeys, journal.CopyId, _ct)
|
||||
.ConfigureAwait(false));
|
||||
Save();
|
||||
}
|
||||
var keys = journal.SessionKeys.ToHashSet(StringComparer.Ordinal);
|
||||
if (!journal.KeepKeysWritten)
|
||||
{
|
||||
@@ -686,13 +808,22 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The session keys of the manifest of <paramref name="sequence"/> (none when it has no manifest).</summary>
|
||||
private static List<string> KeysOf(ArchivePaths paths, Sequence sequence)
|
||||
{
|
||||
var manifest = paths.Sequence(sequence.Folder).ManifestPath;
|
||||
return sequence.Folder.Length > 0 && File.Exists(manifest) ? [.. ManifestStore.ReadSequence(manifest).SessionKeys] : [];
|
||||
}
|
||||
|
||||
// ---- trash ----
|
||||
|
||||
private async Task TrashAsync()
|
||||
/// <summary>
|
||||
/// The checks before the trash that may abandon the merge, run before the links stage and again at the trash: no
|
||||
/// unsent workspace work, no work saved into the other since the plan, the other at the frames version the verify read
|
||||
/// and readable. Returns that frames version.
|
||||
/// </summary>
|
||||
private async Task<int> CheckTrashAsync(Sequence drop)
|
||||
{
|
||||
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false);
|
||||
if (drop is null) return; // a run that moved it before its journal said so
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Trash, _dropTitle)).ConfigureAwait(false);
|
||||
if (await owner.Workspace.HasUnsentAsync(journal.DropId, _ct).ConfigureAwait(false))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.Unsent", _dropTitle));
|
||||
if (await WorkSinceThePlanAsync(drop).ConfigureAwait(false))
|
||||
@@ -704,12 +835,28 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
var expected = journal.VerifiedDropFramesVersion ?? throw Changed(_dropTitle);
|
||||
if (drop.FramesVersion != expected) throw Changed(_dropTitle);
|
||||
EnsureDropReadable(drop);
|
||||
return expected;
|
||||
}
|
||||
|
||||
/// <summary>Under the kept sequence's lease: every verified photo is still held, and the trash's dry run of the other is not blocked.</summary>
|
||||
private async Task<DeletePlan> PlanTrashAsync()
|
||||
{
|
||||
await EnsureVerifiedHeldAsync().ConfigureAwait(false);
|
||||
var plan = await owner.Archives.Trash.PlanAsync([journal.DropId], null, _ct, journal.JobId).ConfigureAwait(false);
|
||||
if (plan.Blocked.Count > 0)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.TrashBlocked", _dropTitle, Loc.L("Archive.Delete.Reason." + plan.Blocked[0].Reason)));
|
||||
return plan;
|
||||
}
|
||||
|
||||
private async Task TrashAsync()
|
||||
{
|
||||
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false);
|
||||
if (drop is null) return; // a run that moved it before its journal said so
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Trash, _dropTitle)).ConfigureAwait(false);
|
||||
var expected = await CheckTrashAsync(drop).ConfigureAwait(false);
|
||||
await using (await owner.Archives.Writer.LockAsync(keepPaths, journal.KeepId, _ct).ConfigureAwait(false))
|
||||
{
|
||||
await EnsureVerifiedHeldAsync().ConfigureAwait(false);
|
||||
var plan = await owner.Archives.Trash.PlanAsync([journal.DropId], null, _ct, journal.JobId).ConfigureAwait(false);
|
||||
if (plan.Blocked.Count > 0)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.TrashBlocked", _dropTitle, Loc.L("Archive.Delete.Reason." + plan.Blocked[0].Reason)));
|
||||
var plan = await PlanTrashAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await owner.Archives.Trash.DeleteAsync(plan, null, null, _ct, journal.JobId, new Dictionary<Guid, int> { [journal.DropId] = expected })
|
||||
@@ -732,15 +879,14 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
{
|
||||
if (journal.DropSettingsVersion is { } settings && drop.SettingsVersion != settings) return true;
|
||||
var planned = journal.Projects.ToDictionary(p => p.SourceProjectId);
|
||||
HashSet<string>? keepHeads = null;
|
||||
IReadOnlyList<SequenceProject>? keepProjects = null;
|
||||
foreach (var project in await _db.Projects.ListBySequenceAsync(journal.DropId, includeDeleted: false, _ct).ConfigureAwait(false))
|
||||
{
|
||||
if (project.IsMain) continue;
|
||||
if (planned.TryGetValue(project.Id, out var step) && (project.HeadVersionId ?? Guid.Empty) == step.SourceHeadId) continue;
|
||||
// Not planned (or moved on since) is fine only when the kept sequence holds that head already, as the plan saw it.
|
||||
keepHeads ??= await owner.Merger.HeadHashesAsync(
|
||||
await _db.Projects.ListBySequenceAsync(journal.KeepId, includeDeleted: false, _ct).ConfigureAwait(false), _ct).ConfigureAwait(false);
|
||||
if (!await owner.Merger.HeldAlreadyAsync(project, keepHeads, _ct).ConfigureAwait(false)) return true;
|
||||
// Not planned (or moved on since) is fine only when the kept sequence holds a copy of it already, as the plan saw it.
|
||||
keepProjects ??= await _db.Projects.ListBySequenceAsync(journal.KeepId, includeDeleted: false, _ct).ConfigureAwait(false);
|
||||
if (await owner.Merger.HeldAsync(project, keepProjects, _dropArchive.Name, _ct).ConfigureAwait(false) is null) return true;
|
||||
}
|
||||
var renders = await _db.Renders.ListBySequenceAsync(journal.DropId, _ct).ConfigureAwait(false);
|
||||
if (renders.Count == 0) return false;
|
||||
|
||||
@@ -30,6 +30,12 @@ internal sealed record MergeReplace(string Key, Guid KeepFrameId, string FileNam
|
||||
/// <summary>A drop original the verify found in the kept sequence: its SHA-256 now and the keep frame that holds it.</summary>
|
||||
internal sealed record MergeVerified(string Sha256, Guid KeepFrameId);
|
||||
|
||||
/// <summary>
|
||||
/// What a merge's links stage changes, read before it: the session keys each manifest held, the other's archive, and the
|
||||
/// rows <see cref="FoundCopyStore.MoveToKeptAsync"/> moves (<see cref="MoveUndo"/>).
|
||||
/// </summary>
|
||||
internal sealed record MergeLinksUndo(List<string> KeepKeysBefore, List<string> DropKeysBefore, Guid DropArchiveId, MoveUndo Moved);
|
||||
|
||||
/// <summary>
|
||||
/// The journal of a merge (owner review 6, #73; design §5d): <c><keep archive>/.chronos/journal/merge-<job:N>.json</c>,
|
||||
/// written atomically (temp + rename) after each step. It keeps what the confirmed plan decided (a resumed run never plans
|
||||
@@ -123,6 +129,12 @@ internal sealed class MergeJournal
|
||||
|
||||
public bool LinksMoved { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// What the links stage takes from the other sequence, read before its first change: a merge abandoned after it (a check
|
||||
/// before the trash fails, a cancel) gives it back, so the other keeps its keys, links and pairs. Null before the stage.
|
||||
/// </summary>
|
||||
public MergeLinksUndo? LinksUndo { get; set; }
|
||||
|
||||
/// <summary>The journal of job <paramref name="jobId"/> in the archive at <paramref name="paths"/>.</summary>
|
||||
public static string PathFor(ArchivePaths paths, Guid jobId) => Path.Combine(paths.JournalDirectory, $"merge-{jobId:N}.json");
|
||||
|
||||
|
||||
@@ -443,19 +443,18 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The drop's non-Main projects, each with the name it gets at the kept sequence's home; one whose head the kept
|
||||
/// sequence's projects hold already (by content: a merge planned again after an earlier run copied it) is not copied again.
|
||||
/// The drop's non-Main projects, each with the name it gets at the kept sequence's home; one the kept sequence holds a
|
||||
/// copy of already (<see cref="HeldAsync"/>: a merge planned again after an earlier run copied it) is not copied again.
|
||||
/// </summary>
|
||||
private async Task<List<ProjectStep>> ProjectStepsAsync(Guid keep, Guid drop, string dropArchiveName, CancellationToken ct)
|
||||
{
|
||||
var keepProjects = await _db.Projects.ListBySequenceAsync(keep, includeDeleted: false, ct).ConfigureAwait(false);
|
||||
var taken = keepProjects.Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var keepHeads = await HeadHashesAsync(keepProjects, ct).ConfigureAwait(false);
|
||||
var steps = new List<ProjectStep>();
|
||||
foreach (var project in (await _db.Projects.ListBySequenceAsync(drop, includeDeleted: false, ct).ConfigureAwait(false))
|
||||
.Where(p => !p.IsMain).OrderBy(p => p.CreatedAt).ThenBy(p => p.Id))
|
||||
{
|
||||
if (await HeldAlreadyAsync(project, keepHeads, ct).ConfigureAwait(false)) continue;
|
||||
if (await HeldAsync(project, keepProjects, dropArchiveName, ct).ConfigureAwait(false) is not null) continue;
|
||||
var name = FreeName(project.Name, dropArchiveName, taken);
|
||||
taken.Add(name);
|
||||
steps.Add(new ProjectStep(CopySide.Other, project.Id, project.Name, name, project.HeadNumber, project.HeadVersionId ?? Guid.Empty));
|
||||
@@ -463,26 +462,56 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
return steps;
|
||||
}
|
||||
|
||||
/// <summary>The content hashes of the heads of <paramref name="projects"/> (Main and versionless ones left out; an unreadable head too).</summary>
|
||||
internal async Task<HashSet<string>> HeadHashesAsync(IEnumerable<SequenceProject> projects, CancellationToken ct)
|
||||
/// <summary>
|
||||
/// The copy of the drop's <paramref name="project"/> a merge made in the kept sequence already, among
|
||||
/// <paramref name="keepProjects"/>: named after it (its name, or the free name a merge gives it), and holding its whole
|
||||
/// history by content after the Main version it was made from (a transplant). Another project that merely has an
|
||||
/// equal head (two projects made from equal Mains) is not one. Null when there is none, or a history cannot be read.
|
||||
/// </summary>
|
||||
internal async Task<HeldProject?> HeldAsync(SequenceProject project, IReadOnlyList<SequenceProject> keepProjects, string dropArchiveName,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var hashes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var project in projects.Where(p => !p.IsMain && p.HeadVersionId is not null))
|
||||
if (project.IsMain || project.HeadVersionId is null || project.HeadNumber <= 0) return null;
|
||||
List<ProjectVersion>? source = null;
|
||||
foreach (var kept in keepProjects.Where(k => !k.IsMain && k.HeadNumber == project.HeadNumber + 1 && NamedAfter(k.Name, project.Name, dropArchiveName)))
|
||||
{
|
||||
if (await HeadHashAsync(project.Id, ct).ConfigureAwait(false) is { } hash) hashes.Add(hash);
|
||||
source ??= await HistoryAsync(project.Id, ct).ConfigureAwait(false);
|
||||
if (source is null || source.Count != project.HeadNumber) return null;
|
||||
if (await HistoryAsync(kept.Id, ct).ConfigureAwait(false) is not { } copy || copy.Count != source.Count + 1) continue;
|
||||
if (!source.Select((v, i) => string.Equals(v.ContentHash, copy[i + 1].ContentHash, StringComparison.OrdinalIgnoreCase)).All(same => same)) continue;
|
||||
return new HeldProject(kept.Id, source.Select((v, i) => (Source: v.Id, Copy: copy[i + 1].Id)).ToDictionary(m => m.Source, m => m.Copy));
|
||||
}
|
||||
return hashes;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Whether the head of <paramref name="project"/> is one of <paramref name="heads"/> (by content).</summary>
|
||||
internal async Task<bool> HeldAlreadyAsync(SequenceProject project, IReadOnlySet<string> heads, CancellationToken ct) =>
|
||||
heads.Count > 0 && project.HeadVersionId is not null && await HeadHashAsync(project.Id, ct).ConfigureAwait(false) is { } head && heads.Contains(head);
|
||||
|
||||
private async Task<string?> HeadHashAsync(Guid projectId, CancellationToken ct)
|
||||
/// <summary>Whether <paramref name="kept"/> is a name a merge gives the drop's project <paramref name="name"/> (<see cref="FreeName"/>, or a transplant's numbered one).</summary>
|
||||
private static bool NamedAfter(string kept, string name, string archiveName)
|
||||
{
|
||||
foreach (var stem in (string[])[name, Fit(name, $" ({archiveName})")])
|
||||
{
|
||||
if (string.Equals(kept, stem, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
var open = kept.LastIndexOf(" (", StringComparison.Ordinal);
|
||||
if (open < 0 || !kept.EndsWith(')')
|
||||
|| !int.TryParse(kept.AsSpan(open + 2, kept.Length - open - 3), NumberStyles.None, CultureInfo.InvariantCulture, out var n) || n < 2)
|
||||
continue;
|
||||
if (string.Equals(kept, Fit(stem, string.Create(CultureInfo.InvariantCulture, $" ({n})")), StringComparison.OrdinalIgnoreCase)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A project's whole history, oldest first; null when it cannot be read.</summary>
|
||||
private async Task<List<ProjectVersion>?> HistoryAsync(Guid projectId, CancellationToken ct)
|
||||
{
|
||||
const int page = 200;
|
||||
try
|
||||
{
|
||||
return (await _archives.Projects.HeadAsync(projectId, ct).ConfigureAwait(false)).ContentHash;
|
||||
var all = new List<ProjectVersion>();
|
||||
while (true)
|
||||
{
|
||||
var next = await _archives.Projects.VersionsAfterAsync(projectId, all.Count == 0 ? 0 : all[^1].Number, page, ct).ConfigureAwait(false);
|
||||
all.AddRange(next);
|
||||
if (next.Count < page) return all;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is ProjectException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
@@ -501,13 +530,14 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
var candidate = Fit(stem, string.Create(CultureInfo.InvariantCulture, $" ({n})"));
|
||||
if (!taken.Contains(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
static string Fit(string stem, string suffix)
|
||||
{
|
||||
const int max = ProjectService.MaxNameLength;
|
||||
if (suffix.Length >= max) suffix = suffix[..(max / 2)];
|
||||
return (stem.Length + suffix.Length > max ? stem[..(max - suffix.Length)].TrimEnd() : stem) + suffix;
|
||||
}
|
||||
/// <summary>Appends <paramref name="suffix"/>, shortening <paramref name="stem"/> so the whole fits a project name.</summary>
|
||||
private static string Fit(string stem, string suffix)
|
||||
{
|
||||
const int max = ProjectService.MaxNameLength;
|
||||
if (suffix.Length >= max) suffix = suffix[..(max / 2)];
|
||||
return (stem.Length + suffix.Length > max ? stem[..(max - suffix.Length)].TrimEnd() : stem) + suffix;
|
||||
}
|
||||
|
||||
/// <summary>The drop's session keys that move to the kept sequence, and those the kept archive maps to a third sequence already.</summary>
|
||||
@@ -564,3 +594,6 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
foreach (var key in skippedKeys) yield return "skipped:" + key;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A copy of a drop project the kept sequence holds already: the kept project and each drop version's copy there.</summary>
|
||||
internal sealed record HeldProject(Guid KeptId, IReadOnlyDictionary<Guid, Guid> Versions);
|
||||
@@ -316,6 +316,46 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
|
||||
Log.Info(LogCategory, $"Pair {copyId} kept here after its server copy was deleted");
|
||||
}
|
||||
|
||||
// ---------------- Two versions in one sequence ----------------
|
||||
|
||||
public Task<IReadOnlyList<PhotoVersions>> VersionsAsync(Guid sequenceId, CancellationToken ct) => _sides.VersionsAsync(sequenceId, ct);
|
||||
|
||||
public async Task<OwnVersionDropPlan> PlanDropOwnVersionAsync(Guid sequenceId, Guid frameId, CancellationToken ct)
|
||||
{
|
||||
var versions = await _sides.VersionsAsync(sequenceId, ct).ConfigureAwait(false);
|
||||
var photo = versions.FirstOrDefault(v => v.FirstFrameId == frameId || v.SecondFrameId == frameId)
|
||||
?? throw new StaleCopyPlanException(Loc.L("Errors.Copies.OtherVersionGone"));
|
||||
var (sha, name, size, partner, partnerName, partnerSha) = frameId == photo.FirstFrameId
|
||||
? (photo.FirstSha256, photo.FirstFileName, photo.FirstSize, photo.SecondFrameId, photo.SecondFileName, photo.SecondSha256)
|
||||
: (photo.SecondSha256, photo.SecondFileName, photo.SecondSize, photo.FirstFrameId, photo.FirstFileName, photo.FirstSha256);
|
||||
var sequence = await Db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
|
||||
var plan = await _archives.FrameTrash.PlanDeleteAsync(sequenceId, [frameId], sequence.FramesVersion, ct).ConfigureAwait(false);
|
||||
// The photo stays (its other version); this version's content may still be held nowhere else.
|
||||
var elsewhere = await _sides.HeldElsewhereAsync([sha], [sequenceId], ct).ConfigureAwait(false);
|
||||
IReadOnlyList<LastCopy> lasts = elsewhere.Contains(sha) ? [] : [new LastCopy(sha, CopySide.ThisPc, name, size)];
|
||||
return new OwnVersionDropPlan(plan, partner, partnerName, partnerSha, lasts);
|
||||
}
|
||||
|
||||
public async Task<int> DropOwnVersionAsync(OwnVersionDropPlan plan, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
var sequenceId = plan.Plan.Sequence.Id;
|
||||
// The other version must still be there and usable, its file hashed again now: the photo never leaves with this one.
|
||||
var partner = await Db.Frames.GetAsync(plan.PartnerFrameId, ct).ConfigureAwait(false);
|
||||
if (partner is null || partner.SequenceId != sequenceId || (partner.Flags & CopySides.UnusableFlags) != 0
|
||||
|| !await HoldsVerifiedAsync(sequenceId, [new CopyPhotoInput(partner.Id, partner.Index, partner.FileName, plan.PartnerSha256, partner.Size, partner.CapturedAt, false)], ct)
|
||||
.ConfigureAwait(false))
|
||||
{
|
||||
Log.Info(LogCategory, $"Sequence {sequenceId}: the version kept is no longer there; nothing went to the trash");
|
||||
throw new StaleCopyPlanException(Loc.L("Errors.Copies.OtherVersionGone"));
|
||||
}
|
||||
if ((await Db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false))?.FramesVersion != plan.Plan.Sequence.FramesVersion)
|
||||
throw new StaleCopyPlanException();
|
||||
await _archives.FrameTrash.DeleteAsync(plan.Plan, _context(null).PcName, followUps?.Invoke(), ct).ConfigureAwait(false);
|
||||
Log.Info(LogCategory, $"Sequence {sequenceId}: one version of a photo kept in two went to its archive trash");
|
||||
return plan.Plan.Frames.Count;
|
||||
}
|
||||
|
||||
// ---------------- Deleted on one side ----------------
|
||||
|
||||
public async Task<TrashHerePlan> PlanTrashHereAsync(Guid copyId, IReadOnlyCollection<string> photoKeys, CancellationToken ct)
|
||||
|
||||
@@ -15,6 +15,9 @@ namespace Chronos.Data.Copies;
|
||||
public sealed record IntegrateJobContext(string PcName, string? ServerName, bool CanUpload, bool CanFetch, bool CanEdit, bool CanDelete,
|
||||
bool OwnsOrAdmin, bool KeepsProjects, long? QuotaLeft)
|
||||
{
|
||||
/// <summary>The signed-in account's id when the plan was made: an owner who is not an admin plans the same steps in the job.</summary>
|
||||
public Guid? UserId { get; init; }
|
||||
|
||||
/// <summary>Everything allowed: what a job queued without a context plans with.</summary>
|
||||
public static IntegrateJobContext Permissive { get; } = new(Environment.MachineName, null, true, true, true, true, true, true, null);
|
||||
|
||||
@@ -22,11 +25,13 @@ public sealed record IntegrateJobContext(string PcName, string? ServerName, bool
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
return new(context.PcName, context.ServerName, context.CanUpload, context.CanFetch, context.CanEdit, context.CanDelete, context.OwnsOrAdmin,
|
||||
context.KeepsProjects, context.QuotaLeft);
|
||||
context.KeepsProjects, context.QuotaLeft)
|
||||
{ UserId = context.UserId };
|
||||
}
|
||||
|
||||
public CopyPlanContext ToPlanContext() => new(PcName, ServerName, CanUpload, CanFetch, CanEdit, CanDelete, OwnsOrAdmin, KeepsProjects, QuotaLeft,
|
||||
new HashSet<Guid>(), new HashSet<Guid>());
|
||||
new HashSet<Guid>(), new HashSet<Guid>())
|
||||
{ UserId = UserId };
|
||||
}
|
||||
|
||||
/// <summary>The Integrate job of a local↔server pair (owner review 6, #73; design §5c): its handler and how it is queued.</summary>
|
||||
|
||||
@@ -205,6 +205,15 @@ public sealed record LocalOverlap(Guid Low, Guid High, int SharedHashes, int Sha
|
||||
/// <summary>What the links stage of a merge moved (<see cref="FoundCopyStore.MoveToKeptAsync"/>).</summary>
|
||||
public sealed record MoveResult(int SessionKeys, IReadOnlyList<string> SkippedKeys, int Links, int Pairs);
|
||||
|
||||
/// <summary>
|
||||
/// What a merge's links stage is about to move (<see cref="FoundCopyStore.UndoOfMoveAsync"/>), kept so a merge abandoned
|
||||
/// after it can give it back (<see cref="FoundCopyStore.MoveBackAsync"/>): the session keys, the links and the stored pair rows.
|
||||
/// </summary>
|
||||
public sealed record MoveUndo(IReadOnlyList<string> SessionKeys, IReadOnlyList<MovedLink> Links, IReadOnlyList<FoundCopy> Pairs);
|
||||
|
||||
/// <summary>A sync link a merge's links stage re-points: its server and remote sequence.</summary>
|
||||
public sealed record MovedLink(string Server, Guid RemoteId);
|
||||
|
||||
/// <summary>One side's hints (design §3.1): capture range, camera, median interval and title.</summary>
|
||||
public sealed record CopyHintsInput(DateTime? First, DateTime? Last, string? Camera, double? MedianInterval, string? Title);
|
||||
|
||||
|
||||
@@ -143,6 +143,15 @@ public sealed record TrashTherePlan(Guid CopyId, string Server, Guid RemoteId, I
|
||||
/// <summary>The dry run of moving photos of a pair's local copy to its archive trash, with the ones no other sequence of this index holds.</summary>
|
||||
public sealed record TrashHerePlan(FrameDeletePlan Plan, IReadOnlyList<LastCopy> LastCopies);
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of dropping one of the two versions one sequence keeps of a photo (owner Q3; a Union merge leaves them, and
|
||||
/// its pair is gone): the version's frame goes to the sequence's archive trash, the other version (<see cref="PartnerFrameId"/>)
|
||||
/// stays. Applied only while that other version is still there, usable and verified by content. <see cref="LastCopies"/>:
|
||||
/// the version itself when no other sequence of this index holds its content.
|
||||
/// </summary>
|
||||
public sealed record OwnVersionDropPlan(FrameDeletePlan Plan, Guid PartnerFrameId, string PartnerFileName, string PartnerSha256,
|
||||
IReadOnlyList<LastCopy> LastCopies);
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of dropping one version of a photo kept in two versions (design §4.1, Versions): the version
|
||||
/// <see cref="Key"/> goes to the trash of both sides (this PC's copy and the server's, or both local copies of a merge),
|
||||
|
||||
@@ -6,7 +6,15 @@ using Chronos.Protocol;
|
||||
namespace Chronos.Data.Copies;
|
||||
|
||||
/// <summary>One photo a sequence keeps in two versions: each version's frame, file name and SHA-256.</summary>
|
||||
public sealed record PhotoVersions(Guid FirstFrameId, string FirstFileName, string FirstSha256, Guid SecondFrameId, string SecondFileName, string SecondSha256);
|
||||
public sealed record PhotoVersions(Guid FirstFrameId, string FirstFileName, string FirstSha256, Guid SecondFrameId, string SecondFileName, string SecondSha256)
|
||||
{
|
||||
/// <summary>The photo's capture instant (both versions share it).</summary>
|
||||
public DateTime? CapturedAt { get; init; }
|
||||
|
||||
public long FirstSize { get; init; }
|
||||
|
||||
public long SecondSize { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The two sides of a comparison as <see cref="CopyComparer"/> reads them (owner review 6, #73; design §4.2): a local
|
||||
@@ -67,7 +75,12 @@ public sealed class CopySides(ChronosDatabase db)
|
||||
var versions = group.DistinctBy(f => f.Sha256!.ToLowerInvariant(), StringComparer.Ordinal).OrderBy(f => f.Index).ToList();
|
||||
if (versions.Count != 2 || group.Count() != 2) continue;
|
||||
result.Add(new PhotoVersions(versions[0].Id, versions[0].FileName, versions[0].Sha256!.ToLowerInvariant(),
|
||||
versions[1].Id, versions[1].FileName, versions[1].Sha256!.ToLowerInvariant()));
|
||||
versions[1].Id, versions[1].FileName, versions[1].Sha256!.ToLowerInvariant())
|
||||
{
|
||||
CapturedAt = versions[0].CapturedAt,
|
||||
FirstSize = versions[0].Size,
|
||||
SecondSize = versions[1].Size,
|
||||
});
|
||||
}
|
||||
return [.. result.OrderBy(v => frames.First(f => f.Id == v.FirstFrameId).Index)];
|
||||
}
|
||||
|
||||
@@ -442,6 +442,69 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
|
||||
}, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What <see cref="MoveToKeptAsync"/> with these arguments would move, read before it runs so <see cref="MoveBackAsync"/>
|
||||
/// can return it: the session keys it would take from <paramref name="drop"/>, the links naming drop, and the stored rows
|
||||
/// of the pairs naming drop (but <paramref name="exceptCopyId"/>).
|
||||
/// </summary>
|
||||
public async Task<MoveUndo> UndoOfMoveAsync(Guid drop, Guid keep, Guid keepArchiveId, IReadOnlyCollection<string> sessionKeys, Guid? exceptCopyId,
|
||||
CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sessionKeys);
|
||||
var keys = new List<string>();
|
||||
foreach (var key in sessionKeys.Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
var holder = await _db.ScalarAsync<Guid?>("SELECT sequence_id FROM sequence_sessions WHERE archive_id = $1 AND session_key = $2",
|
||||
[keepArchiveId, key], ct).ConfigureAwait(false);
|
||||
if (holder is null || holder == drop) keys.Add(key);
|
||||
}
|
||||
var links = await _db.ListAsync("SELECT server, remote_id FROM sync_links WHERE local_id = $1 ORDER BY server, remote_id", [drop],
|
||||
r => new MovedLink(r.GetString(0), r.GetGuid(1)), ct).ConfigureAwait(false);
|
||||
// The stored rows as they are (their stored state, not the state they read as).
|
||||
var pairs = await _db.ListAsync($"SELECT {Columns}, found_copies.state AS effective_state FROM found_copies WHERE local_id = $1 OR other_id = $1 ORDER BY id",
|
||||
[drop], Map, ct).ConfigureAwait(false);
|
||||
return new MoveUndo(keys, [.. links], [.. pairs.Where(p => p.Id != exceptCopyId && p.LocalId != keep && p.OtherId != keep)]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns what a merge's links stage moved from <paramref name="drop"/> to <paramref name="keep"/> (<paramref name="undo"/>,
|
||||
/// read by <see cref="UndoOfMoveAsync"/> before it), one transaction: the session keys go back to drop in its archive, the
|
||||
/// links naming keep that named drop name drop again (their agreement stays reset: the next comparison settles it), and
|
||||
/// the pairs return to their stored rows. Idempotent; a no-op for what did not move.
|
||||
/// </summary>
|
||||
public Task MoveBackAsync(Guid drop, Guid keep, Guid keepArchiveId, Guid dropArchiveId, MoveUndo undo, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(undo);
|
||||
return _db.InTransactionAsync(async session =>
|
||||
{
|
||||
var inner = new DbAccess(session);
|
||||
foreach (var key in undo.SessionKeys)
|
||||
{
|
||||
await inner.ExecuteAsync("DELETE FROM sequence_sessions WHERE archive_id = $1 AND session_key = $2 AND sequence_id = $3", [keepArchiveId, key, keep], ct)
|
||||
.ConfigureAwait(false);
|
||||
await inner.ExecuteAsync(
|
||||
"INSERT INTO sequence_sessions (archive_id, session_key, sequence_id) VALUES ($1, $2, $3) ON CONFLICT (archive_id, session_key) DO NOTHING",
|
||||
[dropArchiveId, key, drop], ct).ConfigureAwait(false);
|
||||
}
|
||||
foreach (var link in undo.Links)
|
||||
{
|
||||
await inner.ExecuteAsync("UPDATE sync_links SET local_id = $3 WHERE server = $1 AND remote_id = $2 AND local_id = $4", [link.Server, link.RemoteId, drop, keep],
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
var now = _time.GetUtcNow();
|
||||
foreach (var pair in undo.Pairs)
|
||||
{
|
||||
await inner.ExecuteAsync("DELETE FROM found_copies WHERE id = $1", [pair.Id], ct).ConfigureAwait(false);
|
||||
var clash = pair.Kind == CopyKind.LocalServer
|
||||
? await FindRemoteAsync(inner, pair.LocalId, pair.Server!, pair.RemoteId!.Value, ct).ConfigureAwait(false)
|
||||
: await inner.SingleAsync($"{Select} WHERE kind = 1 AND local_id = $1 AND other_id = $2", [pair.LocalId, pair.OtherId!.Value], Map, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (clash is null) await InsertAsync(inner, pair, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
return 0;
|
||||
}, ct);
|
||||
}
|
||||
|
||||
public Task<CopyProbe?> GetProbeAsync(Guid sequenceId, string scope, CancellationToken ct) =>
|
||||
_db.SingleAsync("SELECT sequence_id, scope, frames_version, hashed, probed_at, server_newest FROM copy_probes WHERE sequence_id = $1 AND scope = $2",
|
||||
[sequenceId, scope], r => new CopyProbe(r.GetGuid(0), r.GetString(1), r.GetInt32(2), r.GetInt32(3), r.GetDateTimeOffset(4), r.GetDateTimeOffsetOrNull(5)), ct);
|
||||
|
||||
@@ -65,6 +65,15 @@ public interface ICopyEngine
|
||||
/// </summary>
|
||||
Task<int> DropVersionAsync(DropVersionPlan plan, ISyncRemote? remote, CancellationToken ct);
|
||||
|
||||
/// <summary>The photos local sequence <paramref name="sequenceId"/> keeps in two versions, whatever pair made them (owner Q3).</summary>
|
||||
Task<IReadOnlyList<PhotoVersions>> VersionsAsync(Guid sequenceId, CancellationToken ct);
|
||||
|
||||
/// <summary>The dry run of dropping version <paramref name="frameId"/> of a photo sequence <paramref name="sequenceId"/> keeps in two.</summary>
|
||||
Task<OwnVersionDropPlan> PlanDropOwnVersionAsync(Guid sequenceId, Guid frameId, CancellationToken ct);
|
||||
|
||||
/// <summary>Applies <paramref name="plan"/> while the other version is still there, verified by content; returns the frames moved.</summary>
|
||||
Task<int> DropOwnVersionAsync(OwnVersionDropPlan plan, CancellationToken ct);
|
||||
|
||||
/// <summary>Keeps this PC's sequence of a pair whose server copy was deleted, and stops asking.</summary>
|
||||
Task KeepHereAsync(Guid copyId, CancellationToken ct);
|
||||
|
||||
|
||||
Reference in new issue
Block a user