fix(copies): close the fifth verification round of owner review 6
The metered hold now records the jobs it paused in the index and forgets any job the user pauses, resumes, retries or cancels, so it never resumes a pause of the user's and still resumes its own after a restart. Drop... reports why its dry run is blocked instead of asking first, and dropping the version Main uses lets Main use the version that stays, with its hero and keyframes. That version reads "In Main". Merges: - A re-plan no longer hashes the other's photos again. - A resumed merge verifies photos flagged damaged while it waited. - A merge is blocked while the other's folder holds photos the index has not read; this is checked again under the lease before the trash. - Choose each offers Keep both, Kept and Other, and blocks until every differing photo is chosen. - Classes are named by role. The Compare dialog: - Its headings stay over their columns. - The Projects part scrolls. - Every confirmation line carries its own prefix, and a merge's facts carry none. - A server card in a match offers Compare... alone. The Italian strings follow the glossary. Finding 9 (a local drop counting 0 photos) is not reproduced; a test now keeps the count at 2. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2c06e7ac2b
commit
bf7701d279
159 files changed
+1759
-126
No files matched your search
@@ -45,6 +45,20 @@ internal sealed class SampleCopyEngine : ICopyEngine
|
||||
|
||||
public void Add(SampleCopy pair) => _pairs.Add(pair);
|
||||
|
||||
/// <summary>
|
||||
/// Gives pair <paramref name="copyId"/> <paramref name="count"/> projects a side for a while (the Projects part's scroll,
|
||||
/// server-copies-projects-many); the returned action puts its own back.
|
||||
/// </summary>
|
||||
internal Action WithManyProjects(Guid copyId, int count)
|
||||
{
|
||||
var at = _pairs.FindIndex(p => p.Copy.Id == copyId);
|
||||
var saved = _pairs[at];
|
||||
IReadOnlyList<ProjectLine> Lines(string suffix, int days) =>
|
||||
[SampleCopies.Project("Main", true, 2, days), .. Enumerable.Range(1, count - 1).Select(i => SampleCopies.Project($"Cut {i:00}{suffix}", false, 1 + i % 3, days + i))];
|
||||
_pairs[at] = saved with { Projects = saved.Projects with { Here = Lines(string.Empty, 1), There = Lines(" NAS", 3) } };
|
||||
return () => _pairs[at] = saved;
|
||||
}
|
||||
|
||||
/// <summary>Raises <see cref="Found"/> as a detection run would (the matches-found toast).</summary>
|
||||
public void RaiseFound(CopyFindResult result) => _found?.Invoke(result);
|
||||
|
||||
|
||||
@@ -677,7 +677,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
|
||||
var started = startEngine && handlers.Count > 0;
|
||||
if (started) await Engine.StartAsync(ct);
|
||||
Jobs = new EngineJobQueue(database, Engine, started);
|
||||
Jobs = new EngineJobQueue(database, Engine, started, Sync.Uploads.Forget);
|
||||
// Two copies of a sequence among this PC's archives are looked for by themselves (owner review 6, #73).
|
||||
if (!Environment.IsCapture)
|
||||
{
|
||||
|
||||
@@ -47,12 +47,16 @@ public sealed class EngineJobQueue : IJobQueue, IDisposable
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly JobEngine _engine;
|
||||
private readonly bool _started;
|
||||
private readonly Action<Guid>? _acted;
|
||||
|
||||
public EngineJobQueue(ChronosDatabase db, JobEngine engine, bool started)
|
||||
/// <param name="acted">Told of each job the user paused, resumed, retried or cancelled through this queue (the metered
|
||||
/// hold forgets it, UploadHold.Forget); null for none.</param>
|
||||
public EngineJobQueue(ChronosDatabase db, JobEngine engine, bool started, Action<Guid>? acted = null)
|
||||
{
|
||||
_db = db;
|
||||
_engine = engine;
|
||||
_started = started;
|
||||
_acted = acted;
|
||||
_engine.JobChanged += OnJobChanged;
|
||||
_engine.Progress += OnProgress;
|
||||
}
|
||||
@@ -74,11 +78,23 @@ public sealed class EngineJobQueue : IJobQueue, IDisposable
|
||||
public Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default) =>
|
||||
_engine.EnqueueAsync(kind, targets, targetLabel, priority: priority, cancellationToken: ct);
|
||||
|
||||
public Task PauseAsync(Guid id) => _engine.PauseAsync(id);
|
||||
public async Task PauseAsync(Guid id)
|
||||
{
|
||||
await _engine.PauseAsync(id);
|
||||
_acted?.Invoke(id);
|
||||
}
|
||||
|
||||
public Task ResumeAsync(Guid id) => _engine.ResumeAsync(id);
|
||||
public async Task ResumeAsync(Guid id)
|
||||
{
|
||||
_acted?.Invoke(id);
|
||||
await _engine.ResumeAsync(id);
|
||||
}
|
||||
|
||||
public Task CancelAsync(Guid id) => _engine.CancelAsync(id);
|
||||
public async Task CancelAsync(Guid id)
|
||||
{
|
||||
await _engine.CancelAsync(id);
|
||||
_acted?.Invoke(id);
|
||||
}
|
||||
|
||||
public async Task RaisePriorityAsync(Guid id)
|
||||
{
|
||||
|
||||
@@ -61,8 +61,8 @@ public sealed class VersionsDialogViewModel : ArchiveDialogViewModel
|
||||
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),
|
||||
new VersionRow(this, p, p.FirstFrameId, p.FirstFileName, p.FirstSize, p.SecondFileName, !p.FirstExcluded),
|
||||
new VersionRow(this, p, p.SecondFrameId, p.SecondFileName, p.SecondSize, p.FirstFileName, !p.SecondExcluded),
|
||||
})];
|
||||
}
|
||||
catch (Exception ex) when (Expected(ex))
|
||||
@@ -86,6 +86,12 @@ public sealed class VersionsDialogViewModel : ArchiveDialogViewModel
|
||||
try
|
||||
{
|
||||
var plan = await _engine.PlanDropOwnVersionAsync(SequenceId, row.FrameId, CancellationToken.None);
|
||||
// A plan that cannot go (the archive offline, a job on the sequence) says why before anything is asked.
|
||||
if (!plan.Plan.CanDelete)
|
||||
{
|
||||
ShowMessage(BlockedText(plan.Plan, row.FileName));
|
||||
return;
|
||||
}
|
||||
if (!_confirm(DropRequest(plan, row.FileName))) return;
|
||||
await _engine.DropOwnVersionAsync(plan, CancellationToken.None);
|
||||
}
|
||||
@@ -101,6 +107,15 @@ public sealed class VersionsDialogViewModel : ArchiveDialogViewModel
|
||||
await LoadAsync();
|
||||
}
|
||||
|
||||
/// <summary>Why a drop's dry run cannot go: the archive offline or read-only, a job on the sequence, or the frames changed.</summary>
|
||||
internal static string BlockedText(Data.Archiving.FrameDeletePlan plan, string fileName) => plan.Blocked.FirstOrDefault() switch
|
||||
{
|
||||
_ when plan.Blocked.Count == 0 => Loc.L("Archive.Convert.Blocked.FramesChanged"),
|
||||
Data.Archiving.FrameDeleteBlock.Offline => Loc.L("Errors.Copies.TrashBlocked", fileName, Loc.L("Archive.Delete.Reason.Offline")),
|
||||
Data.Archiving.FrameDeleteBlock.Busy => Loc.L("Errors.Copies.TrashBlocked", fileName, Loc.L("Archive.Delete.Reason.Busy")),
|
||||
_ => Loc.L("Archive.Convert.Blocked.FramesChanged"),
|
||||
};
|
||||
|
||||
/// <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)
|
||||
{
|
||||
@@ -125,13 +140,14 @@ public sealed class VersionsDialogViewModel : ArchiveDialogViewModel
|
||||
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>
|
||||
/// <summary>One version of a photo kept in two: its file, the photo's time, its size, the other version's name, and whether Main uses it.</summary>
|
||||
public sealed class VersionRow
|
||||
{
|
||||
internal VersionRow(VersionsDialogViewModel owner, PhotoVersions photo, Guid frameId, string fileName, long size, string otherFileName)
|
||||
internal VersionRow(VersionsDialogViewModel owner, PhotoVersions photo, Guid frameId, string fileName, long size, string otherFileName, bool inMain = false)
|
||||
{
|
||||
FrameId = frameId;
|
||||
FileName = fileName;
|
||||
InMain = inMain;
|
||||
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));
|
||||
@@ -144,6 +160,9 @@ public sealed class VersionRow
|
||||
|
||||
public string FileName { get; }
|
||||
|
||||
/// <summary>Main's time-lapse and renders use this version (the other is the one a Union keep-both left out).</summary>
|
||||
public bool InMain { get; }
|
||||
|
||||
/// <summary>"16/11/2026 09:12 · 24.1 MB · Other: IMG_0142 (1).CR3".</summary>
|
||||
public string Detail { get; }
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
<!-- 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 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).
|
||||
one in a match that asks for a choice offers Compare… first (owner review 6, #73). A server sequence keeps no
|
||||
versions of its own here: its card in a match offers Compare… alone.
|
||||
-->
|
||||
<ContextMenu x:Key="Menu.Card" x:Shared="False">
|
||||
<MenuItem Header="{l:Loc Library.Action.Versions}" ToolTip="{l:Loc Tooltips.Library.Versions}"
|
||||
@@ -29,6 +30,11 @@
|
||||
Command="{Binding PlacementTarget.Tag.VersionsItemCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
|
||||
CommandParameter="{Binding}" />
|
||||
</ContextMenu>
|
||||
<ContextMenu x:Key="Menu.CardMatchRemote" 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}" />
|
||||
</ContextMenu>
|
||||
<Style x:Key="ListBoxItem.LibraryCard" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Card}">
|
||||
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
|
||||
@@ -41,6 +47,13 @@
|
||||
<DataTrigger Binding="{Binding HasMatch}" Value="True">
|
||||
<Setter Property="ContextMenu" Value="{StaticResource Menu.CardMatch}" />
|
||||
</DataTrigger>
|
||||
<MultiDataTrigger>
|
||||
<MultiDataTrigger.Conditions>
|
||||
<Condition Binding="{Binding IsRemote}" Value="True" />
|
||||
<Condition Binding="{Binding HasMatch}" Value="True" />
|
||||
</MultiDataTrigger.Conditions>
|
||||
<Setter Property="ContextMenu" Value="{StaticResource Menu.CardMatchRemote}" />
|
||||
</MultiDataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<Style x:Key="ListBoxItem.LibraryRow" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
|
||||
@@ -56,6 +69,13 @@
|
||||
<DataTrigger Binding="{Binding HasMatch}" Value="True">
|
||||
<Setter Property="ContextMenu" Value="{StaticResource Menu.CardMatch}" />
|
||||
</DataTrigger>
|
||||
<MultiDataTrigger>
|
||||
<MultiDataTrigger.Conditions>
|
||||
<Condition Binding="{Binding IsRemote}" Value="True" />
|
||||
<Condition Binding="{Binding HasMatch}" Value="True" />
|
||||
</MultiDataTrigger.Conditions>
|
||||
<Setter Property="ContextMenu" Value="{StaticResource Menu.CardMatchRemote}" />
|
||||
</MultiDataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<Style x:Key="Button.Header" TargetType="Button" BasedOn="{StaticResource Button.Subtle}">
|
||||
@@ -146,6 +166,9 @@
|
||||
<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}" />
|
||||
<TextBlock DockPanel.Dock="Right" Text="{l:Loc Server.Copies.Photo.InMain}" ToolTip="{l:Loc Tooltips.Server.Copies.InMain}"
|
||||
Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" Margin="0,0,12,0"
|
||||
Visibility="{Binding InMain, Converter={StaticResource BoolToVisibility}}" />
|
||||
<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}"
|
||||
|
||||
@@ -185,6 +185,9 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
|
||||
public bool HasPhotos => _photos.Count > 0;
|
||||
|
||||
/// <summary>The heading over the last column: "Version" while the rows offer a version choice (Choose each), else "Where".</summary>
|
||||
public string PhotoSideHeading => Loc.L(_photos.Any(p => p.CanChoose) ? "Server.Copies.Photo.Version" : "Server.Copies.Photo.Side");
|
||||
|
||||
/// <summary>"No photos differ.": the selected class holds nothing (or the two sides hold the same photos).</summary>
|
||||
public string? PhotosEmptyText => HasPhotos ? null : Loc.L("Server.Copies.Class.None");
|
||||
|
||||
@@ -437,7 +440,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
: [.. review.Photos.Of(cls.Value).Select(p => new CopyPhotoRow(p, IsMerge,
|
||||
choosing && !IsMerge && cls is PhotoClass.OnlyHere or PhotoClass.OnlyThere,
|
||||
choosing && cls == PhotoClass.Differs, choices, _perPhoto.TryGetValue(p.Key, out var c) ? c : null, () => OnPhotoChanged(p.Key), drop,
|
||||
Swapped, Places))];
|
||||
Swapped, Places, cls == PhotoClass.Versions && !review.ExcludedHere.Contains(p.Key)))];
|
||||
foreach (var row in _photos) row.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName != nameof(CopyPhotoRow.IsSelected)) return;
|
||||
@@ -446,6 +449,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
RaiseSelection();
|
||||
OnPropertyChanged(nameof(HasPhotos));
|
||||
OnPropertyChanged(nameof(PhotosEmptyText));
|
||||
OnPropertyChanged(nameof(PhotoSideHeading));
|
||||
OnPropertyChanged(nameof(CanBringAll));
|
||||
OnPropertyChanged(nameof(CanKeepAllBoth));
|
||||
OnPropertyChanged(nameof(CanTrashHere));
|
||||
@@ -725,6 +729,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
Action? choose = block switch
|
||||
{
|
||||
CopyBlock.DetailsUnchosen => () => Part = CopyDialogPart.Details,
|
||||
CopyBlock.PhotosUnchosen => () => Part = CopyDialogPart.Photos,
|
||||
CopyBlock.KeptUnchosen => RequestKeepFocus,
|
||||
_ => null,
|
||||
};
|
||||
@@ -831,6 +836,12 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
try
|
||||
{
|
||||
var plan = await _engine.PlanDropVersionAsync(Copy.Id, row.Key, remote, CancellationToken.None);
|
||||
// A local side whose dry run cannot go (its archive offline, a job on it) says why before anything is asked.
|
||||
if (new[] { plan.Here, plan.Other }.OfType<Data.Archiving.FrameDeletePlan>().FirstOrDefault(p => p.Blocked.Count > 0) is { } blocked)
|
||||
{
|
||||
ShowMessage(Library.VersionsDialogViewModel.BlockedText(blocked, row.Name));
|
||||
return;
|
||||
}
|
||||
var names = plan.Here.Frames.Select(f => f.FileName).Concat(plan.Other?.Frames.Select(f => f.FileName) ?? []).DefaultIfEmpty(row.Name);
|
||||
var request = TrashRequest(plan.Photos, names, Loc.L("Tooltips.Server.Copies.Drop"), plan.LastCopies);
|
||||
if (!_shell.Services.Dialogs.Confirm(request)) return;
|
||||
@@ -959,7 +970,8 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
if (replaced.Count > 0)
|
||||
{
|
||||
facts.Add(Loc.Plural("Server.Copies.Confirm.Merge.Replaced", replaced.Count, keep.Where));
|
||||
facts.AddRange(replaced.Where(p => !lastKeys.Contains(p.Key) && !lastKeys.Contains(p.Sha256 ?? string.Empty)).Select(p => " " + p.FileName));
|
||||
facts.AddRange(replaced.Where(p => !lastKeys.Contains(p.Key) && !lastKeys.Contains(p.Sha256 ?? string.Empty))
|
||||
.Select(p => " " + Loc.L("Server.Copies.Confirm.Replaced", p.FileName)));
|
||||
}
|
||||
if (only > 0) facts.Add(Loc.Plural("Server.Copies.Confirm.Merge.OnlyHere", only, drop.Where));
|
||||
if (plan.Renders.Count > 0) facts.Add(Loc.Plural("Server.Copies.Plan.Renders", plan.Renders.Count));
|
||||
@@ -968,7 +980,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
Heading = Loc.L("Server.Copies.Confirm.Merge.Title"),
|
||||
Message = Loc.L("Server.Copies.Confirm.Merge.Message", drop.Title, drop.Where, keep.Where),
|
||||
Detail = Lines(plan.LastCopies, facts),
|
||||
Detail = Lines(plan.LastCopies, facts, elsewhere: false),
|
||||
SafeText = Loc.L("Archive.Dialog.Cancel"),
|
||||
SafeToolTip = Loc.L("Tooltips.Server.Copies.Confirm.Safe"),
|
||||
ActionText = Loc.L("Server.Copies.Action.Merge"),
|
||||
@@ -1019,8 +1031,9 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
var last = lasts.Where(l => l.Side == side).ToList();
|
||||
var lastKeys = last.Select(l => l.Key).ToHashSet(StringComparer.Ordinal);
|
||||
// Each line carries its own prefix: a replaced version under an "Only copy:" line never reads as another only copy.
|
||||
var names = last.Select(l => Loc.L("Server.Copies.Confirm.LastCopy", l.FileName))
|
||||
.Concat(trashed.Where(p => p.Action == action && !lastKeys.Contains(p.Key)).Select(p => p.FileName))
|
||||
.Concat(trashed.Where(p => p.Action == action && !lastKeys.Contains(p.Key)).Select(p => Loc.L("Server.Copies.Confirm.Replaced", p.FileName)))
|
||||
.Distinct(StringComparer.Ordinal).ToList();
|
||||
total += names.Count;
|
||||
if (names.Count == 0) continue;
|
||||
@@ -1034,10 +1047,18 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
return string.Join(Environment.NewLine, lines);
|
||||
}
|
||||
|
||||
private static string Lines(IReadOnlyList<LastCopy> lasts, IEnumerable<string> rest)
|
||||
/// <summary>
|
||||
/// The trash and delete confirmations' list: the last copies first, then the photos held elsewhere too, each line with
|
||||
/// its prefix. With <paramref name="elsewhere"/> false (a merge) <paramref name="rest"/> holds facts, not file names,
|
||||
/// and they carry no prefix.
|
||||
/// </summary>
|
||||
internal static string Lines(IReadOnlyList<LastCopy> lasts, IEnumerable<string> rest, bool elsewhere = true)
|
||||
{
|
||||
const int Listed = 10;
|
||||
var all = lasts.Select(l => Loc.L("Server.Copies.Confirm.LastCopy", l.FileName)).Concat(rest).ToList();
|
||||
var only = lasts.Select(l => l.FileName).ToHashSet(StringComparer.Ordinal);
|
||||
var all = lasts.Select(l => Loc.L("Server.Copies.Confirm.LastCopy", l.FileName))
|
||||
.Concat(rest.Where(n => !only.Contains(n)).Distinct(StringComparer.Ordinal)
|
||||
.Select(n => elsewhere ? Loc.L("Server.Copies.Confirm.Elsewhere", n) : n)).ToList();
|
||||
var lines = all.Take(Listed).ToList();
|
||||
if (all.Count > Listed) lines.Add(Loc.Plural("Archive.Delete.More", all.Count - Listed));
|
||||
return string.Join(Environment.NewLine, lines);
|
||||
@@ -1054,14 +1075,24 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
Loc.L(merge ? "Tooltips.Server.Copies.Policy.OtherCopyWins" : "Tooltips.Server.Copies.Policy.OtherWins")),
|
||||
];
|
||||
|
||||
/// <summary>The choices of a Different photo under Choose each.</summary>
|
||||
internal static IReadOnlyList<SettingsOption<PhotoChoice>> VersionChoices(bool merge) =>
|
||||
[
|
||||
new(PhotoChoice.KeepBoth, Loc.L("Server.Copies.Version.Both"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
new(PhotoChoice.TakeHere, Loc.L(merge ? "Server.Copies.Detail.Kept" : "Server.Copies.Version.Here"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
new(PhotoChoice.TakeThere, Loc.L(merge ? "Server.Copies.Detail.Other" : "Server.Copies.Version.There"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
new(PhotoChoice.Leave, Loc.L("Server.Copies.Version.Leave"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
];
|
||||
/// <summary>
|
||||
/// The choices of a Different photo under Choose each. A merge offers no Leave: its other sequence goes to the trash, so
|
||||
/// leaving a photo keeps the kept sequence's version, which Kept already says.
|
||||
/// </summary>
|
||||
internal static IReadOnlyList<SettingsOption<PhotoChoice>> VersionChoices(bool merge) => merge
|
||||
?
|
||||
[
|
||||
new(PhotoChoice.KeepBoth, Loc.L("Server.Copies.Version.Both"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
new(PhotoChoice.TakeHere, Loc.L("Server.Copies.Detail.Kept"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
new(PhotoChoice.TakeThere, Loc.L("Server.Copies.Detail.Other"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
]
|
||||
:
|
||||
[
|
||||
new(PhotoChoice.KeepBoth, Loc.L("Server.Copies.Version.Both"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
new(PhotoChoice.TakeHere, Loc.L("Server.Copies.Version.Here"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
new(PhotoChoice.TakeThere, Loc.L("Server.Copies.Version.There"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
new(PhotoChoice.Leave, Loc.L("Server.Copies.Version.Leave"), Loc.L("Tooltips.Server.Copies.Version")),
|
||||
];
|
||||
|
||||
private static bool Expected(Exception ex) =>
|
||||
ex is Data.DatabaseException or InvalidOperationException or System.Net.Http.HttpRequestException or System.IO.IOException or UnauthorizedAccessException;
|
||||
|
||||
@@ -151,9 +151,10 @@
|
||||
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. -->
|
||||
<!-- The photos of the selected class under column headings that share the rows' widths; the scroll bar always
|
||||
takes its place (the headings' right margin holds it), so the columns never shift when it appears. -->
|
||||
<DockPanel Grid.Row="1" Grid.Column="1" Grid.IsSharedSizeScope="True" Visibility="{Binding HasPhotos, Converter={StaticResource CopyBoolToVisibility}}">
|
||||
<Grid DockPanel.Dock="Top" Margin="15,0,15,4">
|
||||
<Grid DockPanel.Dock="Top" Margin="15,0,25,4">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="CopyPhotoBring" />
|
||||
<ColumnDefinition Width="140" />
|
||||
@@ -165,13 +166,13 @@
|
||||
<TextBlock Grid.Column="1" Text="{l:Loc Server.Copies.Photo.Taken}" Style="{StaticResource Text.ColumnHeader}" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Column="2" Text="{l:Loc Server.Copies.Photo.Name}" Style="{StaticResource Text.ColumnHeader}" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Column="3" Text="{l:Loc Server.Copies.Photo.Size}" Style="{StaticResource Text.ColumnHeader}" TextAlignment="Right" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Column="4" Grid.ColumnSpan="2" Text="{l:Loc Server.Copies.Photo.Side}" Style="{StaticResource Text.ColumnHeader}" Margin="10,0,0,0"
|
||||
<TextBlock Grid.Column="4" Grid.ColumnSpan="2" Text="{Binding PhotoSideHeading}" Style="{StaticResource Text.ColumnHeader}" Margin="10,0,0,0"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
<ListBox ItemsSource="{Binding Photos}" ItemContainerStyle="{StaticResource ListBoxItem.CopyPhoto}" SelectionMode="Extended"
|
||||
infra:ListSelection.SyncsRows="True"
|
||||
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" KeyboardNavigation.TabNavigation="Continue"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible" KeyboardNavigation.TabNavigation="Continue"
|
||||
AutomationProperties.Name="{Binding SelectedClass.Text}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type cp:CopyPhotoRow}">
|
||||
@@ -190,8 +191,14 @@
|
||||
<TextBlock Grid.Column="1" Text="{Binding TimeText}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" FontSize="12" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Column="2" Text="{Binding Name}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" FlowDirection="LeftToRight" FontSize="12" />
|
||||
<TextBlock Grid.Column="3" Text="{Binding SizeText}" VerticalAlignment="Center" TextAlignment="Right" Typography.NumeralAlignment="Tabular" FontSize="12" />
|
||||
<TextBlock Grid.Column="4" Width="110" Text="{Binding SideText}" VerticalAlignment="Center" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0"
|
||||
TextTrimming="CharacterEllipsis" FontSize="12" Visibility="{Binding CanChoose, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
<!-- The side, then "In Main" on the version Main uses (it gives way to the side's name, never to Drop…). -->
|
||||
<DockPanel Grid.Column="4" Width="110" Margin="10,0,0,0" VerticalAlignment="Center"
|
||||
Visibility="{Binding CanChoose, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}">
|
||||
<TextBlock DockPanel.Dock="Right" Text="{l:Loc Server.Copies.Photo.InMain}" ToolTip="{l:Loc Tooltips.Server.Copies.InMain}"
|
||||
Foreground="{DynamicResource Brush.TextMuted}" Margin="6,0,0,0" FontSize="12"
|
||||
Visibility="{Binding InMain, Converter={StaticResource CopyBoolToVisibility}}" />
|
||||
<TextBlock Text="{Binding SideText}" Foreground="{DynamicResource Brush.TextMuted}" TextTrimming="CharacterEllipsis" FontSize="12" />
|
||||
</DockPanel>
|
||||
<ComboBox Grid.Column="5" Width="150" Margin="10,0,0,0" ItemsSource="{Binding Choices}" SelectedItem="{Binding Choice}" DisplayMemberPath="Label"
|
||||
ItemContainerStyle="{StaticResource ComboBoxItem.Option}" ToolTip="{l:Loc Tooltips.Server.Copies.Version}"
|
||||
AutomationProperties.Name="{Binding ChoiceAccessibleName}" Visibility="{Binding CanChoose, Converter={StaticResource CopyBoolToVisibility}}" />
|
||||
@@ -219,7 +226,7 @@
|
||||
<Button Style="{StaticResource Button.Link}" Content="{Binding AllThereText}" Command="{Binding AllThereCommand}" ToolTip="{Binding AllThereToolTip}" />
|
||||
</StackPanel>
|
||||
<!-- Whose value each column holds: this PC and the server, or the kept sequence and the other (they follow the kept one). -->
|
||||
<Grid Grid.Row="1" Margin="0,0,0,6" Visibility="{Binding HasDetails, Converter={StaticResource CopyBoolToVisibility}}">
|
||||
<Grid Grid.Row="1" Margin="0,0,10,6" Visibility="{Binding HasDetails, Converter={StaticResource CopyBoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="180" />
|
||||
<ColumnDefinition Width="*" />
|
||||
@@ -234,7 +241,8 @@
|
||||
<ItemsControl Grid.Row="2" ItemsSource="{Binding Details}" Focusable="False" Visibility="{Binding HasDetails, Converter={StaticResource CopyBoolToVisibility}}">
|
||||
<ItemsControl.Template>
|
||||
<ControlTemplate TargetType="ItemsControl">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" Focusable="False">
|
||||
<!-- The scroll bar always takes its place (the headings' right margin holds it): the columns never shift. -->
|
||||
<ScrollViewer VerticalScrollBarVisibility="Visible" Focusable="False">
|
||||
<ItemsPresenter />
|
||||
</ScrollViewer>
|
||||
</ControlTemplate>
|
||||
@@ -285,8 +293,17 @@
|
||||
<!-- 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}" 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" />
|
||||
<!-- Both lists scroll together: a pair with many projects stays inside the dialog. -->
|
||||
<ScrollViewer Grid.Row="3" Grid.ColumnSpan="2" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ItemsControl ItemsSource="{Binding HereProjects}" ItemTemplate="{StaticResource Template.CopyProjectRow}" Focusable="False" Margin="0,0,14,0" />
|
||||
<ItemsControl Grid.Column="1" ItemsSource="{Binding ThereProjects}" ItemTemplate="{StaticResource Template.CopyProjectRow}" Focusable="False" />
|
||||
</Grid>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
|
||||
<!-- Plan: the kept sequence (merge), what each side receives and loses, the blocks with their one action, Link only. -->
|
||||
|
||||
@@ -21,7 +21,12 @@ public sealed class CopyClassRow(PhotoClassTotal total, CopyPhotoPolicy policy =
|
||||
|
||||
public PhotoClass Class { get; } = total.Class;
|
||||
public StatusKind Kind => CopyText.ClassKind(Class);
|
||||
public string Text => CopyText.Class(Class);
|
||||
|
||||
/// <summary>
|
||||
/// The class's word. A merge with a kept sequence names its sides by role ("Only in kept"), oriented like the tooltip;
|
||||
/// before one is kept, by place ("Only here" is this PC's side).
|
||||
/// </summary>
|
||||
public string Text => isMerge && _places is null ? CopyText.Class(Oriented, merge: true) : CopyText.Class(Class);
|
||||
public string CountText => Formatting.Count(total.Count);
|
||||
public string HereBytesText => total.HereBytes > 0 ? Formatting.Bytes(total.HereBytes) : string.Empty;
|
||||
public string ThereBytesText => total.ThereBytes > 0 ? Formatting.Bytes(total.ThereBytes) : string.Empty;
|
||||
@@ -57,6 +62,7 @@ public sealed class CopyClassRow(PhotoClassTotal total, CopyPhotoPolicy policy =
|
||||
set
|
||||
{
|
||||
if (!Set(ref _swapped, value)) return;
|
||||
OnPropertyChanged(nameof(Text));
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
OnPropertyChanged(nameof(BytesToolTip));
|
||||
}
|
||||
@@ -74,6 +80,7 @@ public sealed class CopyClassRow(PhotoClassTotal total, CopyPhotoPolicy policy =
|
||||
if (_places == value) return;
|
||||
_places = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(Text));
|
||||
OnPropertyChanged(nameof(BytesToolTip));
|
||||
}
|
||||
}
|
||||
@@ -111,11 +118,14 @@ public sealed class CopyPhotoRow : ObservableObject, ISelectableRow
|
||||
|
||||
/// <param name="swapped">A merge keeping the pair's other sequence: the photo's second side is the kept one.</param>
|
||||
/// <param name="places">A merge with no kept sequence yet: the two archives' names its sides read as (not Kept and Other).</param>
|
||||
/// <param name="inMain">A Two versions row: Main's time-lapse and renders use this version (the other is excluded).</param>
|
||||
public CopyPhotoRow(ComparedPhoto photo, bool isMerge, bool canBring, bool canChoose, IReadOnlyList<SettingsOption<PhotoChoice>> choices,
|
||||
PhotoChoice? current, Action changed, Func<CopyPhotoRow, Task>? drop, bool swapped = false, (string Here, string There)? places = null)
|
||||
PhotoChoice? current, Action changed, Func<CopyPhotoRow, Task>? drop, bool swapped = false, (string Here, string There)? places = null,
|
||||
bool inMain = false)
|
||||
{
|
||||
Photo = photo;
|
||||
IsMerge = isMerge;
|
||||
InMain = inMain;
|
||||
_swapped = isMerge && swapped;
|
||||
_places = isMerge ? places : null;
|
||||
CanBring = canBring;
|
||||
@@ -157,6 +167,9 @@ public sealed class CopyPhotoRow : ObservableObject, ISelectableRow
|
||||
public ICommand? DropCommand { get; }
|
||||
public bool CanDrop => DropCommand is not null;
|
||||
|
||||
/// <summary>A Two versions row whose version Main uses: it shows "In Main" beside Drop….</summary>
|
||||
public bool InMain { get; }
|
||||
|
||||
public bool Bring
|
||||
{
|
||||
get => _bring;
|
||||
@@ -185,7 +198,7 @@ public sealed class CopyPhotoRow : ObservableObject, ISelectableRow
|
||||
public PhotoChoice? Chosen => CanBring ? (_bring ? PhotoChoice.Bring : null) : _choice?.Value;
|
||||
|
||||
public string BringAccessibleName => Loc.L("Server.Copies.ControlFor", Name, Loc.L("Server.Copies.Photo.Bring"));
|
||||
public string ChoiceAccessibleName => Loc.L("Server.Copies.ControlFor", Name, _choice?.Label ?? Loc.L("Server.Copies.Version.Leave"));
|
||||
public string ChoiceAccessibleName => Loc.L("Server.Copies.ControlFor", Name, _choice?.Label ?? Loc.L("Server.Copies.Version.None"));
|
||||
public string DropAccessibleName => Loc.L("Server.Copies.ControlFor", Name, Loc.L("Server.Copies.Action.Drop"));
|
||||
|
||||
/// <summary>Sets the tick or the choice without raising one change per row (Bring all, All: keep both).</summary>
|
||||
|
||||
@@ -19,10 +19,13 @@ public static class CopyScenes
|
||||
public static readonly IReadOnlyList<string> Views =
|
||||
[
|
||||
"server-copies", "server-copies-toast", "server-copies-photos", "server-copies-choose", "server-copies-versions",
|
||||
"server-copies-review", "server-copies-details", "server-copies-projects", "server-copies-plan", "server-copies-blocked",
|
||||
"server-copies-merge", "server-sync-copyfound", "server-copies-gone", "edit-picker-twins",
|
||||
"server-copies-review", "server-copies-details", "server-copies-projects", "server-copies-projects-many", "server-copies-plan",
|
||||
"server-copies-blocked", "server-copies-merge", "server-sync-copyfound", "server-copies-gone", "edit-picker-twins",
|
||||
];
|
||||
|
||||
/// <summary>Projects a side in server-copies-projects-many: more than the Projects part shows without scrolling.</summary>
|
||||
public const int ManyProjects = 12;
|
||||
|
||||
/// <summary>The Lighthouse pair (a match found on the server).</summary>
|
||||
public const string Lighthouse = "Lighthouse 2026-08-13";
|
||||
|
||||
@@ -37,6 +40,7 @@ public static class CopyScenes
|
||||
await ShowPickerTwinsAsync(shell);
|
||||
return null;
|
||||
}
|
||||
if (view == "server-copies-projects-many") return await ShowManyProjectsAsync(shell);
|
||||
var server = shell.Server;
|
||||
var sync = server.Sync;
|
||||
var list = sync.Copies;
|
||||
@@ -93,6 +97,23 @@ public static class CopyScenes
|
||||
return dialog;
|
||||
}
|
||||
|
||||
/// <summary>The Projects part of a pair with <see cref="ManyProjects"/> projects a side: the two lists scroll inside the dialog.</summary>
|
||||
private static async Task<CopyDialogViewModel?> ShowManyProjectsAsync(ShellViewModel shell)
|
||||
{
|
||||
if (shell.Services.Sync.Copies is not SampleCopyEngine sample
|
||||
|| sample.Pairs.FirstOrDefault(p => p.Copy.Kind == CopyKind.LocalServer && p.Here.Title == Lighthouse) is not { } pair)
|
||||
return await ShowAsync(shell, "server-copies-projects");
|
||||
var restore = sample.WithManyProjects(pair.Copy.Id, ManyProjects);
|
||||
try
|
||||
{
|
||||
return await ShowAsync(shell, "server-copies-projects");
|
||||
}
|
||||
finally
|
||||
{
|
||||
restore();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Replace photos?": the Lighthouse plan where this PC's version of the different photos wins.</summary>
|
||||
public static async Task<ConfirmRequest?> ReplaceRequestAsync(ShellViewModel shell)
|
||||
{
|
||||
|
||||
@@ -186,6 +186,19 @@ public static class CopyText
|
||||
/// <summary>The word of a photo class ("Only here").</summary>
|
||||
public static string Class(PhotoClass c) => Loc.L("Server.Copies.Class." + c);
|
||||
|
||||
/// <summary>
|
||||
/// The word of a class of a merge read from the kept sequence (<paramref name="c"/> already oriented): the one-sided
|
||||
/// classes name the role, "Only in kept", "Deleted in other"; the others read as always.
|
||||
/// </summary>
|
||||
public static string Class(PhotoClass c, bool merge) => !merge ? Class(c) : c switch
|
||||
{
|
||||
PhotoClass.OnlyHere => Loc.L("Server.Copies.Class.OnlyKept"),
|
||||
PhotoClass.OnlyThere => Loc.L("Server.Copies.Class.OnlyOther"),
|
||||
PhotoClass.DeletedHere => Loc.L("Server.Copies.Class.DeletedKept"),
|
||||
PhotoClass.DeletedThere => Loc.L("Server.Copies.Class.DeletedOther"),
|
||||
_ => Class(c),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// What a class means and what the run does with it under <paramref name="policy"/>: Different by the winning side or
|
||||
/// the per-photo choice, Only here and Only there ticked under Choose each, and a merge's own wording (the other
|
||||
@@ -197,6 +210,7 @@ public static class CopyText
|
||||
{
|
||||
(PhotoClass.Differs, CopyPhotoPolicy.ThisPcWins) => isMerge ? ".KeptWins" : ".ThisPcWins",
|
||||
(PhotoClass.Differs, CopyPhotoPolicy.OtherWins) => isMerge ? ".OtherCopyWins" : ".OtherWins",
|
||||
(PhotoClass.Differs, CopyPhotoPolicy.ChoosePerPhoto) when isMerge => ".ChooseMerge",
|
||||
(PhotoClass.Differs, CopyPhotoPolicy.ChoosePerPhoto) => ".Choose",
|
||||
(PhotoClass.Differs, _) when isMerge => ".Merge",
|
||||
(PhotoClass.OnlyHere or PhotoClass.OnlyThere, _) when isMerge => ".Merge",
|
||||
@@ -223,7 +237,8 @@ public static class CopyText
|
||||
CopyBlock.NeedsNewerServer => Loc.L("Errors.Copies.NeedsNewerServer", server ?? string.Empty),
|
||||
CopyBlock.LinkTaken => Loc.L("Errors.Copies.LinkTaken", title, server ?? string.Empty),
|
||||
CopyBlock.NoSpace => Loc.L("Errors.Copies.NoSpace", title, need ?? string.Empty),
|
||||
CopyBlock.ArchiveOffline or CopyBlock.FolderMoved or CopyBlock.ChangedFile or CopyBlock.DamagedPhotos => Loc.L("Errors.Copies." + block, title),
|
||||
CopyBlock.ArchiveOffline or CopyBlock.FolderMoved or CopyBlock.ChangedFile or CopyBlock.DamagedPhotos or CopyBlock.FolderChanged
|
||||
=> Loc.L("Errors.Copies." + block, title),
|
||||
CopyBlock.UnsentWorkspace => Loc.L("Errors.Copies.Unsent", title),
|
||||
CopyBlock.BothLinked => Loc.L("Errors.Copies.BothLinked", server ?? string.Empty),
|
||||
CopyBlock.TrashBlocked => Loc.L("Errors.Copies.TrashBlocked", title, need ?? string.Empty),
|
||||
@@ -232,5 +247,5 @@ public static class CopyText
|
||||
};
|
||||
|
||||
/// <summary>A block the user settles in the dialog itself: its line gets the one action Choose.</summary>
|
||||
public static bool HasChoose(CopyBlock block) => block is CopyBlock.DetailsUnchosen or CopyBlock.KeptUnchosen;
|
||||
public static bool HasChoose(CopyBlock block) => block is CopyBlock.DetailsUnchosen or CopyBlock.KeptUnchosen or CopyBlock.PhotosUnchosen;
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Workspaces;
|
||||
|
||||
@@ -16,14 +18,18 @@ 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, 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.
|
||||
/// goes off (for the jobs only it holds). Only the jobs it paused are resumed: it keeps their ids in the index
|
||||
/// (<see cref="RecordKey"/>), so the record survives a restart, and forgets one as soon as the user pauses or resumes it
|
||||
/// (<see cref="Forget"/>, from Jobs and the sync table): a pause of the user's is never undone. 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);
|
||||
|
||||
/// <summary>The index setting (app scope) that lists the jobs this hold paused.</summary>
|
||||
internal const string RecordKey = "sync.meteredHeld";
|
||||
|
||||
private readonly Func<Data.ChronosDatabase?> _database;
|
||||
private readonly Func<bool> _optionOn;
|
||||
private readonly Func<bool> _metered;
|
||||
@@ -32,6 +38,9 @@ public sealed class UploadHold : IDisposable
|
||||
private readonly Timer _timer;
|
||||
private JobEngine? _engine;
|
||||
|
||||
/// <summary>The index whose record <see cref="_held"/> holds (read once per index opened).</summary>
|
||||
private Data.ChronosDatabase? _recordOf;
|
||||
|
||||
public UploadHold(AppServices services)
|
||||
: this(() => services.Database, () => services.Settings.PauseUploadsOnMetered, MeteredNetwork.IsMetered)
|
||||
{
|
||||
@@ -61,6 +70,31 @@ public sealed class UploadHold : IDisposable
|
||||
/// <summary>Applies the option and the connection's cost now (the option changed).</summary>
|
||||
public void Request() => _ = ApplyAsync();
|
||||
|
||||
/// <summary>
|
||||
/// The user paused, resumed, retried or cancelled job <paramref name="id"/> (Jobs, the sync table, Matches): it is no
|
||||
/// longer this hold's to resume. A job the connection still holds is paused again at the next pass, and then is.
|
||||
/// </summary>
|
||||
public void Forget(Guid id) => _ = ForgetAsync(id);
|
||||
|
||||
internal async Task ForgetAsync(Guid id)
|
||||
{
|
||||
if (_database() is not { } db) return;
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
await LoadAsync(db);
|
||||
if (_held.Remove(id)) await SaveAsync(db);
|
||||
}
|
||||
catch (Data.DatabaseException ex)
|
||||
{
|
||||
Log.Warning("sync", $"Job {id} could not be taken off the metered hold's record", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_timer.Dispose();
|
||||
@@ -106,12 +140,6 @@ public sealed class UploadHold : IDisposable
|
||||
internal static bool HeldNow(Job job, bool metered, bool optionOn) =>
|
||||
metered && Holds(job) && (optionOn || SyncService.IsAutomaticTransfer(job));
|
||||
|
||||
/// <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()
|
||||
{
|
||||
@@ -122,10 +150,8 @@ public sealed class UploadHold : IDisposable
|
||||
// Read once per pass: the connection's cost and the option.
|
||||
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);
|
||||
}
|
||||
await LoadAsync(db);
|
||||
var before = _held.ToHashSet();
|
||||
if (metered)
|
||||
{
|
||||
foreach (var state in new[] { JobState.Queued, JobState.Running })
|
||||
@@ -148,6 +174,7 @@ public sealed class UploadHold : IDisposable
|
||||
if (job is { State: JobState.Paused }) await engine.ResumeAsync(id);
|
||||
_held.Remove(id);
|
||||
}
|
||||
if (!_held.SetEquals(before)) await SaveAsync(db);
|
||||
}
|
||||
catch (Data.DatabaseException ex)
|
||||
{
|
||||
@@ -158,6 +185,33 @@ public sealed class UploadHold : IDisposable
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the record of <paramref name="db"/> once (a new index opened: its own record).</summary>
|
||||
private async Task LoadAsync(Data.ChronosDatabase db)
|
||||
{
|
||||
if (ReferenceEquals(_recordOf, db)) return;
|
||||
_held.Clear();
|
||||
if (await db.Settings.GetJsonAsync(SettingScope.App, null, RecordKey) is { } json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
if (document.RootElement.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var item in document.RootElement.EnumerateArray())
|
||||
if (item.ValueKind == JsonValueKind.String && Guid.TryParse(item.GetString(), out var id)) _held.Add(id);
|
||||
}
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
Log.Warning("sync", "The metered hold's record could not be read; it starts empty", ex);
|
||||
}
|
||||
}
|
||||
_recordOf = db;
|
||||
}
|
||||
|
||||
private Task SaveAsync(Data.ChronosDatabase db) =>
|
||||
db.Settings.SetJsonAsync(SettingScope.App, null, RecordKey, "[" + string.Join(",", _held.Order().Select(id => $"\"{id:D}\"")) + "]");
|
||||
}
|
||||
|
||||
/// <summary>The connection cost Windows reports (Settings › Network › Metered connection) through <c>INetworkCostManager</c>.</summary>
|
||||
|
||||
@@ -518,10 +518,12 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
|
||||
if (drop.FramesVersion != journal.DropFramesVersion) throw Changed(_dropTitle);
|
||||
EnsureDropReadable(drop);
|
||||
await EnsureFolderReadAsync(drop).ConfigureAwait(false);
|
||||
var keepFrames = await ProcessingFrames.ListAsync(_db, journal.KeepId, _ct).ConfigureAwait(false);
|
||||
var dropFrames = (await ProcessingFrames.ListAsync(_db, journal.DropId, _ct).ConfigureAwait(false))
|
||||
.Where(f => (f.Flags & CopySides.UnusableFlags) == 0).ToList();
|
||||
var total = keepFrames.Count + dropFrames.Count;
|
||||
var allDrop = await ProcessingFrames.ListAsync(_db, journal.DropId, _ct).ConfigureAwait(false);
|
||||
var dropFrames = allDrop.Where(f => (f.Flags & CopySides.UnusableFlags) == 0).ToList();
|
||||
var flagged = allDrop.Where(f => (f.Flags & CopySides.UnusableFlags) != 0).ToList();
|
||||
var total = keepFrames.Count + dropFrames.Count + flagged.Count;
|
||||
var done = 0;
|
||||
|
||||
// What the kept sequence holds now, hashed again.
|
||||
@@ -583,10 +585,96 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
foreach (var sha in failed.Select(f => f.Sha256).Distinct(StringComparer.Ordinal))
|
||||
if (!journal.SettledElsewhere.Contains(sha)) journal.SettledElsewhere.Add(sha);
|
||||
}
|
||||
await VerifyFlaggedAsync(flagged, held, done, total).ConfigureAwait(false);
|
||||
journal.VerifiedDropFramesVersion = drop.FramesVersion;
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plan's damaged-photo rule again (design §5d; owner Q2): a frame of the other a verify flagged Corrupt, or Missing
|
||||
/// although its file is back, changes no frames version, so one flagged since the plan was never listed. Each such
|
||||
/// frame whose file is there is hashed now (its recorded hash says nothing of it) and must be held by the kept
|
||||
/// sequence (hashed again above), be a last copy the plan listed, or be held by another sequence of this index.
|
||||
/// Otherwise, or when the file cannot be read, the merge stops and is planned again, where the plan shows the block.
|
||||
/// </summary>
|
||||
private async Task VerifyFlaggedAsync(IReadOnlyList<Frame> flagged, Dictionary<string, Guid> held, int done, int total)
|
||||
{
|
||||
var elsewhere = new List<(Guid FrameId, string Sha256)>();
|
||||
foreach (var frame in flagged)
|
||||
{
|
||||
_ct.ThrowIfCancellationRequested();
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Verify, frame.FileName, ++done, total)).ConfigureAwait(false);
|
||||
var path = _dropPaths.FromRelative(frame.RelativePath);
|
||||
if (!File.Exists(path)) continue;
|
||||
string? sha;
|
||||
try
|
||||
{
|
||||
sha = await HashAsync(path).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
ForgetJournal();
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.DamagedPhotos", _dropTitle), ex);
|
||||
}
|
||||
if (sha is null) continue;
|
||||
if (!journal.FlaggedVerified.Contains(frame.Id)) journal.FlaggedVerified.Add(frame.Id);
|
||||
if (held.TryGetValue(sha, out var keepFrame))
|
||||
{
|
||||
journal.Verified[frame.Id] = new MergeVerified(sha, keepFrame);
|
||||
continue;
|
||||
}
|
||||
if (journal.Absent.Contains(sha))
|
||||
{
|
||||
if (!journal.Settled.Contains(frame.Id)) journal.Settled.Add(frame.Id);
|
||||
continue;
|
||||
}
|
||||
elsewhere.Add((frame.Id, sha));
|
||||
}
|
||||
if (elsewhere.Count == 0) return;
|
||||
var others = await new CopySides(_db).HeldElsewhereAsync([.. elsewhere.Select(f => f.Sha256)], [journal.DropId, journal.KeepId], _ct)
|
||||
.ConfigureAwait(false);
|
||||
if (elsewhere.Any(f => !others.Contains(f.Sha256)))
|
||||
{
|
||||
ForgetJournal();
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.DamagedPhotos", _dropTitle));
|
||||
}
|
||||
foreach (var (frameId, sha) in elsewhere)
|
||||
{
|
||||
if (!journal.Settled.Contains(frameId)) journal.Settled.Add(frameId);
|
||||
if (!journal.SettledElsewhere.Contains(sha)) journal.SettledElsewhere.Add(sha);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The other's folder is as this index last read it (<see cref="SequenceMerger.FolderChangedAsync"/>): photos copied in
|
||||
/// by hand or filed by another index sharing the archive would otherwise go to the trash unread. Asked at the verify
|
||||
/// and before the links stage, which rewrites the other's sidecar without recording the folder's stamps.
|
||||
/// </summary>
|
||||
private async Task EnsureFolderReadAsync(Sequence drop)
|
||||
{
|
||||
if (!await owner.Merger.FolderChangedAsync(_dropArchive, _dropPaths, drop, _ct).ConfigureAwait(false)) return;
|
||||
ForgetJournal();
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.FolderChanged", _dropTitle));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// At the trash, under the other's lease (after the links stage rewrote its sidecar): no photo was copied in or removed
|
||||
/// since this index last read its folder, and its sidecar's frames are still those the verify read.
|
||||
/// </summary>
|
||||
private async Task<bool> FolderStillReadAsync(SequencePaths folder, CancellationToken ct)
|
||||
{
|
||||
if (await owner.Archives.Indexer.PhotosChangedAsync(_dropArchive, folder, ct).ConfigureAwait(false)) return false;
|
||||
if (!File.Exists(folder.ManifestPath)) return true;
|
||||
try
|
||||
{
|
||||
return ManifestStore.ReadSequence(folder.ManifestPath).Versions.Frames == journal.VerifiedDropFramesVersion;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or System.Text.Json.JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string?> HashAsync(string path)
|
||||
{
|
||||
try
|
||||
@@ -759,7 +847,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
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 CheckTrashAsync(drop, beforeLinks: true).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,
|
||||
@@ -822,7 +910,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
/// 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)
|
||||
private async Task<int> CheckTrashAsync(Sequence drop, bool beforeLinks = false)
|
||||
{
|
||||
if (await owner.Workspace.HasUnsentAsync(journal.DropId, _ct).ConfigureAwait(false))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.Unsent", _dropTitle));
|
||||
@@ -835,6 +923,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
var expected = journal.VerifiedDropFramesVersion ?? throw Changed(_dropTitle);
|
||||
if (drop.FramesVersion != expected) throw Changed(_dropTitle);
|
||||
EnsureDropReadable(drop);
|
||||
if (beforeLinks) await EnsureFolderReadAsync(drop).ConfigureAwait(false);
|
||||
return expected;
|
||||
}
|
||||
|
||||
@@ -859,12 +948,14 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
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 })
|
||||
.ConfigureAwait(false);
|
||||
await owner.Archives.Trash.DeleteAsync(plan, null, null, _ct, journal.JobId, new Dictionary<Guid, int> { [journal.DropId] = expected },
|
||||
FolderStillReadAsync).ConfigureAwait(false);
|
||||
}
|
||||
catch (StaleDeletePlanException ex)
|
||||
{
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.Changed", _dropTitle), ex);
|
||||
// Photos copied into the other since the verify (a scan reads them), or its frames moved: planned again.
|
||||
ForgetJournal();
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.FolderChanged", _dropTitle), ex);
|
||||
}
|
||||
}
|
||||
context.Log(Loc.L("Archive.Log.MergeTrashed", _dropTitle));
|
||||
@@ -908,6 +999,13 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
var dropFrames = await ProcessingFrames.ListAsync(_db, journal.DropId, _ct).ConfigureAwait(false);
|
||||
if (dropFrames.Any(f => (f.Flags & CopySides.UnusableFlags) == 0 && !journal.Verified.ContainsKey(f.Id) && !journal.Settled.Contains(f.Id)))
|
||||
throw Changed(_dropTitle);
|
||||
// A frame flagged Missing or Corrupt since the verify, its file there: never hashed as such, so planned again.
|
||||
if (dropFrames.Any(f => (f.Flags & CopySides.UnusableFlags) != 0 && !journal.FlaggedVerified.Contains(f.Id)
|
||||
&& File.Exists(_dropPaths.FromRelative(f.RelativePath))))
|
||||
{
|
||||
ForgetJournal();
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.DamagedPhotos", _dropTitle));
|
||||
}
|
||||
|
||||
// The photos a third sequence held at the verify: one it no longer holds would leave only with the other, never
|
||||
// listed as a last copy. Planned again, the plan lists it.
|
||||
|
||||
@@ -112,6 +112,12 @@ internal sealed class MergeJournal
|
||||
/// <summary>The dropped sequence's frames version the verify read: the trash refuses another.</summary>
|
||||
public int? VerifiedDropFramesVersion { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The dropped sequence's frames flagged Missing or Corrupt whose file was there at the verify, each hashed then and
|
||||
/// settled (held by the kept sequence, a last copy, or held elsewhere): one flagged since keeps the trash from running.
|
||||
/// </summary>
|
||||
public List<Guid> FlaggedVerified { get; set; } = [];
|
||||
|
||||
public List<string> Replaced { get; set; } = [];
|
||||
|
||||
/// <summary>Keys of losing versions a refused trash step kept (reported at the end).</summary>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
@@ -32,6 +33,21 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
private readonly CopySides _sides = sides ?? throw new ArgumentNullException(nameof(sides));
|
||||
private readonly DbAccess _access = new(db.Database);
|
||||
|
||||
/// <summary>
|
||||
/// The hashes the dry runs read of the other sequence's files, by frame, with the size and last write time they were read
|
||||
/// at: a plan made again (every change of choice in the dialog) reads only the files that are new or changed. Kept in
|
||||
/// memory only, as a dry run writes nothing to the index; the job's Verify stage hashes every file again.
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<Guid, (long Length, DateTime Written, string Sha256)> _hashes = new();
|
||||
|
||||
/// <summary>The most hashes <see cref="_hashes"/> keeps before it starts again.</summary>
|
||||
private const int HashesKept = 200_000;
|
||||
|
||||
private int _filesHashed;
|
||||
|
||||
/// <summary>Files the dry runs read and hashed so far (tests: a plan made again reads only what changed).</summary>
|
||||
internal int FilesHashed => Volatile.Read(ref _filesHashed);
|
||||
|
||||
/// <summary>The name a server key is shown by (default: the key): the links a merge moves and the server both are linked to.</summary>
|
||||
public Func<string, string?>? ServerNames { get; init; }
|
||||
|
||||
@@ -98,6 +114,9 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
var online = ArchiveVolume.Probe(keepPaths) == ArchiveAvailability.Online && ArchiveVolume.Probe(dropPaths) == ArchiveAvailability.Online;
|
||||
if (!online) blocks.Add(CopyBlock.ArchiveOffline);
|
||||
else if (Moved(keepPaths, keepRow) || Moved(dropPaths, dropRow)) blocks.Add(CopyBlock.FolderMoved);
|
||||
// Photos of the other this index has not read (copied in by hand, filed by another index sharing the archive) would
|
||||
// go to the trash with its folder, never copied nor listed: a scan reads them first.
|
||||
else if (await FolderChangedAsync(dropArchive, dropPaths, dropRow, ct).ConfigureAwait(false)) blocks.Add(CopyBlock.FolderChanged);
|
||||
if (await BusyAsync([keep, drop, keepRow.ArchiveId, dropRow.ArchiveId], exceptJob, ct).ConfigureAwait(false)) blocks.Add(CopyBlock.Busy);
|
||||
if (context.UnsentWorkspaceSequences.Contains(drop)) blocks.Add(CopyBlock.UnsentWorkspace);
|
||||
|
||||
@@ -114,6 +133,7 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
}
|
||||
var steps = new List<PhotoStep>();
|
||||
var excluded = new List<string>();
|
||||
var unchosen = 0;
|
||||
foreach (var photo in comparison.Photos)
|
||||
{
|
||||
switch (photo.Class)
|
||||
@@ -123,6 +143,9 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
steps.Add(Step(photo.Key, PhotoAction.Fetch, photo.There!));
|
||||
break;
|
||||
case PhotoClass.Differs:
|
||||
// Under Choose each a photo nobody chose blocks: its other version would go to the trash unasked (Leave,
|
||||
// which a merge does not offer, keeps the kept sequence's version as Kept does).
|
||||
if (choices.Photos == CopyPhotoPolicy.ChoosePerPhoto && !choices.PerPhoto.ContainsKey(photo.Key)) unchosen++;
|
||||
var choice = choices.Photos switch
|
||||
{
|
||||
CopyPhotoPolicy.Union => PhotoChoice.KeepBoth,
|
||||
@@ -136,6 +159,7 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (unchosen > 0) blocks.Add(CopyBlock.PhotosUnchosen);
|
||||
|
||||
// Last copies: drop originals nothing will hold once the copies are made (losers, tombstoned in keep, converted), and
|
||||
// keep's losing versions nothing else holds.
|
||||
@@ -243,6 +267,7 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
LinkNames = [.. moved.Select(ServerName)],
|
||||
BothLinkedServer = bothLinked is null ? null : ServerName(bothLinked),
|
||||
DeletedInOther = comparison.Photos.Count(p => p.Class == PhotoClass.DeletedThere),
|
||||
PhotosUnchosen = unchosen,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -267,8 +292,8 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
}
|
||||
try
|
||||
{
|
||||
var sha = await ContentHash.Sha256Async(dropPaths.FromRelative(frame.RelativePath), null, ct).ConfigureAwait(false);
|
||||
photos.Add(photo with { Sha256 = sha.ToLowerInvariant() });
|
||||
var sha = await HashAsync(frame.Id, dropPaths.FromRelative(frame.RelativePath), ct).ConfigureAwait(false);
|
||||
photos.Add(photo with { Sha256 = sha });
|
||||
changed = true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
@@ -297,7 +322,7 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
if (!File.Exists(path)) continue;
|
||||
try
|
||||
{
|
||||
var sha = (await ContentHash.Sha256Async(path, null, ct).ConfigureAwait(false)).ToLowerInvariant();
|
||||
var sha = await HashAsync(frame.Id, path, ct).ConfigureAwait(false);
|
||||
if (!keepHolds.Contains(sha)) hashes.Add(sha);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
@@ -310,6 +335,48 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
return hashes.Any(h => !held.Contains(h));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The SHA-256 (lower-case) of the other's file <paramref name="path"/> of frame <paramref name="frameId"/>: the one read
|
||||
/// before while the file keeps its size and last write time (<see cref="_hashes"/>), else read now.
|
||||
/// </summary>
|
||||
private async Task<string> HashAsync(Guid frameId, string path, CancellationToken ct)
|
||||
{
|
||||
var file = new FileInfo(path);
|
||||
if (!file.Exists) throw new FileNotFoundException("The photo is not there.", path);
|
||||
var (length, written) = (file.Length, file.LastWriteTimeUtc);
|
||||
if (_hashes.TryGetValue(frameId, out var known) && known.Length == length && known.Written == written) return known.Sha256;
|
||||
var sha = (await ContentHash.Sha256Async(path, null, ct).ConfigureAwait(false)).ToLowerInvariant();
|
||||
Interlocked.Increment(ref _filesHashed);
|
||||
if (_hashes.Count >= HashesKept) _hashes.Clear();
|
||||
_hashes[frameId] = (length, written, sha);
|
||||
return sha;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the other sequence's folder holds photos this index has not read: photos copied in or removed since the
|
||||
/// photo directory's recorded stamp (<see cref="ArchiveIndexer.PhotosChangedAsync"/>), or a sidecar whose frames are not
|
||||
/// the row's (another index of the archive filed or dropped photos). A sidecar that cannot be read, or names another
|
||||
/// sequence, counts. A sidecar rewritten without new frames does not (the merge's own session-key moves rewrite it).
|
||||
/// </summary>
|
||||
internal async Task<bool> FolderChangedAsync(Archive archive, ArchivePaths paths, Sequence row, CancellationToken ct)
|
||||
{
|
||||
var folder = paths.Sequence(row.Folder);
|
||||
if (!File.Exists(folder.ManifestPath)) return false;
|
||||
SequenceManifest manifest;
|
||||
try
|
||||
{
|
||||
manifest = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or JsonException)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (manifest.Id != row.Id) return true;
|
||||
var indexed = await _db.Sequences.GetAsync(row.Id, ct).ConfigureAwait(false);
|
||||
return indexed is null || indexed.FramesVersion != manifest.Versions.Frames
|
||||
|| await _archives.Indexer.PhotosChangedAsync(archive, folder, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues the job that applies <paramref name="plan"/>: the pair goes to <see cref="CopyState.Integrating"/> (its state
|
||||
/// before kept as the previous one), the job targets the kept sequence, then the other (both held from other jobs).
|
||||
@@ -360,7 +427,9 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
return block switch
|
||||
{
|
||||
CopyBlock.Busy => Loc.L("Errors.Copies.Busy"),
|
||||
CopyBlock.ArchiveOffline or CopyBlock.FolderMoved or CopyBlock.ChangedFile or CopyBlock.DamagedPhotos => Loc.L("Errors.Copies." + block, dropTitle),
|
||||
CopyBlock.ArchiveOffline or CopyBlock.FolderMoved or CopyBlock.ChangedFile or CopyBlock.DamagedPhotos or CopyBlock.FolderChanged
|
||||
=> Loc.L("Errors.Copies." + block, dropTitle),
|
||||
CopyBlock.PhotosUnchosen => Loc.L("Errors.Copies.PhotosUnchosen"),
|
||||
CopyBlock.NoSpace => Loc.L("Errors.Copies.NoSpace", keepTitle, Size(plan.CopyBytes + SpaceReserve)),
|
||||
CopyBlock.BothLinked => Loc.L("Errors.Copies.BothLinked", plan.BothLinkedServer ?? string.Empty),
|
||||
CopyBlock.UnsentWorkspace => Loc.L("Errors.Copies.Unsent", dropTitle),
|
||||
|
||||
@@ -206,8 +206,14 @@ public sealed partial class SequenceTrash
|
||||
/// merge: a photo added to the dropped sequence meanwhile refuses that step with <see cref="StaleDeletePlanException"/>,
|
||||
/// nothing of it moved). Sequences it does not name are not checked.
|
||||
/// </param>
|
||||
/// <param name="stillAsPlanned">
|
||||
/// Asked of each sequence's folder under its lease just before it moves (a merge: no photo copied into the dropped
|
||||
/// sequence's folder since its verify); false refuses that step with <see cref="StaleDeletePlanException"/>, nothing of
|
||||
/// it moved. Null: not asked.
|
||||
/// </param>
|
||||
public async Task<IReadOnlyList<TrashEntry>> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default, Guid? exceptJob = null, IReadOnlyDictionary<Guid, int>? expectedFramesVersions = null)
|
||||
CancellationToken cancellationToken = default, Guid? exceptJob = null, IReadOnlyDictionary<Guid, int>? expectedFramesVersions = null,
|
||||
Func<SequencePaths, CancellationToken, Task<bool>>? stillAsPlanned = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
await RevalidateAsync(plan, exceptJob, cancellationToken).ConfigureAwait(false);
|
||||
@@ -217,7 +223,7 @@ public sealed partial class SequenceTrash
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var step = plan.Steps[i];
|
||||
int? expected = expectedFramesVersions is not null && expectedFramesVersions.TryGetValue(step.Sequence.Id, out var version) ? version : null;
|
||||
if (await DeleteOneAsync(step, deletedBy, expected, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry);
|
||||
if (await DeleteOneAsync(step, deletedBy, expected, stillAsPlanned, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry);
|
||||
progress?.Report(i + 1);
|
||||
}
|
||||
return entries;
|
||||
@@ -381,7 +387,8 @@ public sealed partial class SequenceTrash
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<TrashEntry?> DeleteOneAsync(DeleteStep step, string? deletedBy, int? expectedFramesVersion, CancellationToken cancellationToken)
|
||||
private async Task<TrashEntry?> DeleteOneAsync(DeleteStep step, string? deletedBy, int? expectedFramesVersion,
|
||||
Func<SequencePaths, CancellationToken, Task<bool>>? stillAsPlanned, CancellationToken cancellationToken)
|
||||
{
|
||||
var sequence = step.Sequence;
|
||||
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
|
||||
@@ -405,6 +412,7 @@ public sealed partial class SequenceTrash
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
if (!Directory.Exists(folder.Folder) || (File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id))
|
||||
throw new StaleDeletePlanException(sequence.Id);
|
||||
if (stillAsPlanned is not null && !await stillAsPlanned(folder, cancellationToken).ConfigureAwait(false)) throw new StaleDeletePlanException(sequence.Id);
|
||||
// A photo deletion, a frame replacement, a restore from the trash or an ingest a crash interrupted is settled first,
|
||||
// as any writer does (SequenceWriter.ReadLocked): neither its journal nor the files it moved travel into this entry,
|
||||
// where emptying it would erase them while their own entry still lists them. A restore or a replacement whose entry
|
||||
|
||||
@@ -333,7 +333,7 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
|
||||
// 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);
|
||||
return new OwnVersionDropPlan(plan, partner, partnerName, partnerSha, lasts) { Sha256 = sha, SettingsVersion = sequence.SettingsVersion };
|
||||
}
|
||||
|
||||
public async Task<int> DropOwnVersionAsync(OwnVersionDropPlan plan, CancellationToken ct)
|
||||
@@ -349,13 +349,99 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
|
||||
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)
|
||||
var row = await Db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false);
|
||||
if (row?.FramesVersion != plan.Plan.Sequence.FramesVersion || (plan.SettingsVersion is { } settings && row.SettingsVersion != settings))
|
||||
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");
|
||||
if (plan.Sha256 is { Length: > 0 } dropped) await KeepInMainAsync(sequenceId, plan.PartnerSha256, dropped, plan.SettingsVersion, ct).ConfigureAwait(false);
|
||||
return plan.Plan.Frames.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After one version of a photo kept in two went to the trash of <paramref name="sequenceId"/>: when Main used it and left
|
||||
/// out the one that stays (a Union keep-both excludes the incoming version), the one that stays is used instead, with the
|
||||
/// hero and keyframes of the one that went (<see cref="CopyPayload.KeepVersion"/>), written at the settings version the
|
||||
/// plan read (the trash moves positions without a new version).
|
||||
/// </summary>
|
||||
/// <exception cref="StaleCopyPlanException">Main changed since the plan: the version is in the trash, Main is left as it is.</exception>
|
||||
private async Task KeepInMainAsync(Guid sequenceId, string keepKey, string droppedKey, int? expectedSettings, CancellationToken ct)
|
||||
{
|
||||
if (await Db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false) is not { } row) return;
|
||||
var photos = await SequencePayloadWriter.PhotosAsync(Db, sequenceId, null, ct).ConfigureAwait(false);
|
||||
SyncPayload? kept;
|
||||
try
|
||||
{
|
||||
kept = CopyPayload.KeepVersion(CopyPayload.Portable(SyncPayload.Of(row), photos), keepKey, droppedKey);
|
||||
}
|
||||
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidDataException)
|
||||
{
|
||||
// Settings that are not a project of this Chronos: nothing of Main is read as a choice of versions.
|
||||
return;
|
||||
}
|
||||
if (kept is null) return;
|
||||
try
|
||||
{
|
||||
await new SequencePayloadWriter(Db, _archives).ApplyAsync(sequenceId, kept, expectedSettings ?? row.SettingsVersion, ct).ConfigureAwait(false);
|
||||
Log.Info(LogCategory, $"Sequence {sequenceId}: Main uses the version that stays");
|
||||
}
|
||||
catch (SyncConflictChangedException ex)
|
||||
{
|
||||
throw new StaleCopyPlanException(Loc.L("Errors.Copies.MainChanged", row.DisplayTitle), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="KeepInMainAsync"/> on a server sequence (its Main changed through the API at the version read, three tries
|
||||
/// when it moves meanwhile); an account without the Edit right is told so.
|
||||
/// </summary>
|
||||
private async Task KeepInMainAsync(ISyncRemote remote, Guid remoteId, string keepKey, string droppedKey, string serverName, CancellationToken ct)
|
||||
{
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
var dto = await remote.GetSequenceAsync(remoteId, ct).ConfigureAwait(false);
|
||||
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
|
||||
if (manifest.SettingsVersion != dto.SettingsVersion)
|
||||
{
|
||||
if (attempt >= 3) throw new StaleCopyPlanException(Loc.L("Errors.Copies.MainChanged", dto.Title ?? string.Empty));
|
||||
continue;
|
||||
}
|
||||
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
|
||||
var photos = new FramePhotos(manifest.Frames.Select(f =>
|
||||
(f.Index, new FramePhoto(f.Sha256.Length == 0 ? null : f.Sha256.ToLowerInvariant(), f.Size, captured.GetValueOrDefault(f.Id)))));
|
||||
SyncPayload? kept;
|
||||
try
|
||||
{
|
||||
kept = CopyPayload.KeepVersion(CopyPayload.Portable(SyncPayload.Of(dto, manifest.SettingsJson), photos), keepKey, droppedKey);
|
||||
}
|
||||
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidDataException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (kept is null) return;
|
||||
var placed = kept with { SettingsJson = ProjectContent.Place(kept.SettingsJson ?? string.Empty, photos) };
|
||||
var frames = ProjectSettings.NamesFrames(placed.SettingsJson) ? manifest.FramesVersion : (int?)null;
|
||||
try
|
||||
{
|
||||
await remote.UpdateSequenceAsync(remoteId, placed.ToRequest(dto.SettingsVersion, frames), ct).ConfigureAwait(false);
|
||||
Log.Info(LogCategory, $"Server sequence {remoteId}: Main uses the version that stays");
|
||||
return;
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.Conflict && attempt < 3)
|
||||
{
|
||||
Log.Info(LogCategory, $"Server sequence {remoteId} changed while its Main was being set; reading it again");
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
||||
{
|
||||
throw new StaleCopyPlanException(Loc.L("Errors.Copies.MainChanged", dto.Title ?? string.Empty), ex);
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.Forbidden)
|
||||
{
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.MainNotEdited", serverName), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Deleted on one side ----------------
|
||||
|
||||
public async Task<TrashHerePlan> PlanTrashHereAsync(Guid copyId, IReadOnlyCollection<string> photoKeys, CancellationToken ct)
|
||||
@@ -386,6 +472,7 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
|
||||
var sequence = await Db.Sequences.GetAsync(copy.LocalId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
|
||||
var herePlan = await _archives.FrameTrash.PlanDeleteAsync(copy.LocalId, [.. mine.Select(f => f.FrameId)], sequence.FramesVersion, ct).ConfigureAwait(false);
|
||||
FrameDeletePlan? otherPlan = null;
|
||||
int? otherSettings = null;
|
||||
var (photos, bytes, version) = (0, 0L, 0);
|
||||
if (remoteId is { } id)
|
||||
{
|
||||
@@ -397,11 +484,16 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
|
||||
{
|
||||
var other = await Db.Sequences.GetAsync(copy.OtherId!.Value, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
|
||||
otherPlan = await _archives.FrameTrash.PlanDeleteAsync(other.Id, [.. theirs.Select(f => f.FrameId)], other.FramesVersion, ct).ConfigureAwait(false);
|
||||
otherSettings = other.SettingsVersion;
|
||||
}
|
||||
Guid[] pairSides = copy.OtherId is { } o ? [copy.LocalId, o] : [copy.LocalId];
|
||||
var lasts = await LastCopiesAsync([.. mine.Take(1)], CopySide.ThisPc, pairSides, ct).ConfigureAwait(false);
|
||||
return new DropVersionPlan(copyId, key, partner, herePlan, otherPlan, remoteId, remoteId is null ? [] : [.. theirs.Select(f => f.FrameId)], photos, bytes,
|
||||
version, lasts);
|
||||
version, lasts)
|
||||
{
|
||||
HereSettingsVersion = sequence.SettingsVersion,
|
||||
OtherSettingsVersion = otherSettings,
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<int> DropVersionAsync(DropVersionPlan plan, ISyncRemote? remote, CancellationToken ct)
|
||||
@@ -425,7 +517,9 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
|
||||
// The local plans are checked before the server moves anything, so a stale one moves nothing anywhere.
|
||||
foreach (var local in new[] { plan.Here, plan.Other }.OfType<FrameDeletePlan>())
|
||||
{
|
||||
if ((await Db.Sequences.GetAsync(local.Sequence.Id, ct).ConfigureAwait(false))?.FramesVersion != local.Sequence.FramesVersion)
|
||||
var row = await Db.Sequences.GetAsync(local.Sequence.Id, ct).ConfigureAwait(false);
|
||||
var settings = ReferenceEquals(local, plan.Here) ? plan.HereSettingsVersion : plan.OtherSettingsVersion;
|
||||
if (row?.FramesVersion != local.Sequence.FramesVersion || (settings is { } expected && row.SettingsVersion != expected))
|
||||
throw new StaleCopyPlanException();
|
||||
}
|
||||
var moved = 0;
|
||||
@@ -441,7 +535,18 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
|
||||
moved += local.Frames.Count;
|
||||
}
|
||||
Log.Info(LogCategory, $"Pair {plan.CopyId}: one version of a photo kept in two went to the trash of both sides");
|
||||
await RecountAsync(copy, remote, ct).ConfigureAwait(false);
|
||||
// The photo stays (owner Q3): where Main used the version that went, it uses the one that stays, on both sides.
|
||||
try
|
||||
{
|
||||
await KeepInMainAsync(copy.LocalId, plan.PartnerKey, plan.Key, plan.HereSettingsVersion, ct).ConfigureAwait(false);
|
||||
if (plan.Other is { } other) await KeepInMainAsync(other.Sequence.Id, plan.PartnerKey, plan.Key, plan.OtherSettingsVersion, ct).ConfigureAwait(false);
|
||||
if (remoteId is { } server)
|
||||
await KeepInMainAsync(remote!, server, plan.PartnerKey, plan.Key, ServerName(copy.Server ?? remote!.Server), ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await RecountAsync(copy, remote, ct).ConfigureAwait(false);
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
|
||||
@@ -137,6 +137,65 @@ public static class CopyPayload
|
||||
return portable with { SettingsJson = ProjectContent.Canonical((settings with { PendingFrames = pending }).ToJson()) };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After one version of a photo kept in two went to the trash (design §4.1, Versions; owner Q3: the photo stays): when
|
||||
/// Main left out the version that stays (<paramref name="keepKey"/>) and used the one that went
|
||||
/// (<paramref name="droppedKey"/>), the one that stays is included again; the hero and the keyframes of the one that went
|
||||
/// move to it. Keys as <see cref="ExcludeVersions"/> takes them. Null when nothing changes.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidDataException">The settings are of a newer Chronos.</exception>
|
||||
/// <exception cref="JsonException">The settings are not a project.</exception>
|
||||
public static SyncPayload? KeepVersion(SyncPayload portable, string keepKey, string droppedKey)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(portable);
|
||||
if (Photo(keepKey) is not { } keep || Photo(droppedKey) is not { } dropped) return null;
|
||||
var settings = ProjectSettings.FromJson(SyncRules.NormalizeSettings(portable.SettingsJson));
|
||||
var pending = (settings.PendingFrames ?? []).ToList();
|
||||
var k = pending.FindIndex(p => p.Occurrence == 0 && Names(p, keep));
|
||||
var d = pending.FindIndex(p => p.Occurrence == 0 && Names(p, dropped));
|
||||
var kept = k >= 0 ? pending[k] : null;
|
||||
var gone = d >= 0 ? pending[d] : null;
|
||||
var include = kept is { Excluded: true } && gone is not { Excluded: true };
|
||||
var hero = gone is { Hero: true } && kept is not { Hero: true };
|
||||
var keys = gone is { Keyframes.Count: > 0 } && kept is not { Keyframes.Count: > 0 };
|
||||
if (!include && !hero && !keys) return null;
|
||||
|
||||
var updated = (kept ?? new PendingFrame { Sha256 = keep.Sha256, Size = keep.Size, CapturedAt = keep.CapturedAt }) with
|
||||
{
|
||||
Excluded = kept is { Excluded: true } && !include,
|
||||
Hero = kept is { Hero: true } || hero,
|
||||
Keyframes = keys ? gone!.Keyframes : kept?.Keyframes ?? [],
|
||||
};
|
||||
var rest = gone is null ? null : gone with { Hero = gone.Hero && !hero, Keyframes = keys ? [] : gone.Keyframes };
|
||||
if (k >= 0) pending[k] = updated;
|
||||
else pending.Add(updated);
|
||||
if (d >= 0) pending[d] = rest!;
|
||||
pending.RemoveAll(p => p is { Excluded: false, Hero: false, Keyframes.Count: 0 } && (ReferenceEquals(p, updated) || ReferenceEquals(p, rest)));
|
||||
return portable with
|
||||
{
|
||||
SettingsJson = ProjectContent.Canonical((settings with { PendingFrames = pending.Count == 0 ? null : pending }).ToJson()),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The photos a portable payload's Main excludes from renders, by their canonical SHA-256 (lower-case): which of a
|
||||
/// photo's two versions Main leaves out. Empty for settings that are not a project of this Chronos.
|
||||
/// </summary>
|
||||
public static IReadOnlySet<string> ExcludedKeys(SyncPayload portable)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(portable);
|
||||
try
|
||||
{
|
||||
var settings = ProjectSettings.FromJson(SyncRules.NormalizeSettings(portable.SettingsJson));
|
||||
return (settings.PendingFrames ?? []).Where(p => p is { Excluded: true, Occurrence: 0, Sha256.Length: > 0 })
|
||||
.Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
||||
{
|
||||
return new HashSet<string>(StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Paths whose value moved between two payloads of one side (the apply-time check of design §5c step 5).</summary>
|
||||
public static IReadOnlySet<string> Moved(SyncPayload before, SyncPayload after)
|
||||
{
|
||||
|
||||
@@ -52,6 +52,15 @@ public enum CopyBlock
|
||||
|
||||
/// <summary>The other sequence of a merge holds photos a verify flagged changed or damaged: they would go to the trash unchecked.</summary>
|
||||
DamagedPhotos,
|
||||
|
||||
/// <summary>
|
||||
/// The other sequence of a merge is not as this index last read it (photos copied in by hand, or filed by another index
|
||||
/// sharing the archive): what the index has not read would go to the trash unseen. A scan settles it.
|
||||
/// </summary>
|
||||
FolderChanged,
|
||||
|
||||
/// <summary>A merge under Choose each with Different photos not chosen yet: no version of the other goes to the trash unasked.</summary>
|
||||
PhotosUnchosen,
|
||||
}
|
||||
|
||||
/// <summary>The choices of an Integrate: photo policy, per-photo choices (by photo key), per-detail sides (by path), projects.</summary>
|
||||
@@ -121,6 +130,9 @@ public sealed record MergePlan(Guid CopyId, Guid KeepId, Guid DropId, MergeChoic
|
||||
|
||||
/// <summary>Photos the kept sequence holds that the other deleted: they stay in the kept one ("Deleted in the other").</summary>
|
||||
public int DeletedInOther { get; init; }
|
||||
|
||||
/// <summary>Different photos left without a choice under Choose each (<see cref="CopyBlock.PhotosUnchosen"/>).</summary>
|
||||
public int PhotosUnchosen { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -150,7 +162,14 @@ public sealed record TrashHerePlan(FrameDeletePlan Plan, IReadOnlyList<LastCopy>
|
||||
/// 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);
|
||||
IReadOnlyList<LastCopy> LastCopies)
|
||||
{
|
||||
/// <summary>The SHA-256 of the version that goes; null when unknown (Main is then not looked at).</summary>
|
||||
public string? Sha256 { get; init; }
|
||||
|
||||
/// <summary>The sequence's settings version the plan read: the drop applies only while it holds; null for no check.</summary>
|
||||
public int? SettingsVersion { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of dropping one version of a photo kept in two versions (design §4.1, Versions): the version
|
||||
@@ -165,6 +184,12 @@ public sealed record DropVersionPlan(Guid CopyId, string Key, string PartnerKey,
|
||||
{
|
||||
/// <summary>Every frame the drop moves, on both sides.</summary>
|
||||
public int Photos => Here.Frames.Count + (Other?.Frames.Count ?? 0) + RemotePhotos;
|
||||
|
||||
/// <summary>The settings version of this PC's copy the plan read (its Main is changed at it); null for no check.</summary>
|
||||
public int? HereSettingsVersion { get; init; }
|
||||
|
||||
/// <summary>The settings version of the other local copy the plan read; null for a server pair or no check.</summary>
|
||||
public int? OtherSettingsVersion { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -93,7 +93,10 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
|
||||
var can = copy.Kind == CopyKind.LocalLocal
|
||||
? await LocalCapabilitiesAsync(copy, local, ct).ConfigureAwait(false)
|
||||
: await ServerCapabilitiesAsync(copy, local, photos, details, capabilities, context, remoteOwner, ct).ConfigureAwait(false);
|
||||
return new CopyReview(copy, hereFacts, thereFacts, photos, details, projectsView, renders, can);
|
||||
return new CopyReview(copy, hereFacts, thereFacts, photos, details, projectsView, renders, can)
|
||||
{
|
||||
ExcludedHere = CopyPayload.ExcludedKeys(CopyPayload.Portable(herePayload, herePhotos)),
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<Sequence> SequenceAsync(Guid id, CancellationToken ct) =>
|
||||
|
||||
@@ -27,7 +27,11 @@ public sealed record CopyFacts(string Title, string Where, Guid? ArchiveId, int
|
||||
|
||||
/// <summary>What the Compare dialog shows of a pair: both sides, the photos, the details line by line, projects, renders, and what can be done.</summary>
|
||||
public sealed record CopyReview(FoundCopy Copy, CopyFacts Here, CopyFacts There, CopyComparisonResult Photos,
|
||||
IReadOnlyList<DetailLine> Details, CopyProjectsView Projects, CopyRendersView Renders, CopyCapabilities Can);
|
||||
IReadOnlyList<DetailLine> Details, CopyProjectsView Projects, CopyRendersView Renders, CopyCapabilities Can)
|
||||
{
|
||||
/// <summary>The photos (by key) this PC's Main leaves out: of a photo kept in two versions, the one Main does not use.</summary>
|
||||
public IReadOnlySet<string> ExcludedHere { get; init; } = new HashSet<string>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Whether Integrate (or Merge), Link only and Delete on server are possible, and why not (<see cref="CopyBlock"/>s).</summary>
|
||||
public sealed record CopyCapabilities(bool Integrate, bool LinkOnly, bool DeleteThere, IReadOnlyList<CopyBlock> Blocks);
|
||||
|
||||
@@ -14,6 +14,12 @@ public sealed record PhotoVersions(Guid FirstFrameId, string FirstFileName, stri
|
||||
public long FirstSize { get; init; }
|
||||
|
||||
public long SecondSize { get; init; }
|
||||
|
||||
/// <summary>Main leaves the first version out (a Union keep-both excludes the incoming one): its renders use the second.</summary>
|
||||
public bool FirstExcluded { get; init; }
|
||||
|
||||
/// <summary>Main leaves the second version out.</summary>
|
||||
public bool SecondExcluded { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -67,6 +73,7 @@ public sealed class CopySides(ChronosDatabase db)
|
||||
public async Task<IReadOnlyList<PhotoVersions>> VersionsAsync(Guid sequenceId, CancellationToken ct)
|
||||
{
|
||||
var frames = await Processing.SequenceFrames.ListAsync(_db, sequenceId, ct).ConfigureAwait(false);
|
||||
var excluded = ExcludedIndices((await _db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false))?.SettingsJson);
|
||||
var result = new List<PhotoVersions>();
|
||||
foreach (var group in frames.Where(f => (f.Flags & UnusableFlags) == 0 && f.Sha256 is { Length: > 0 } && f.CapturedAt is not null)
|
||||
.GroupBy(f => CopyComparer.Millisecond(f.CapturedAt!.Value)))
|
||||
@@ -80,11 +87,27 @@ public sealed class CopySides(ChronosDatabase db)
|
||||
CapturedAt = versions[0].CapturedAt,
|
||||
FirstSize = versions[0].Size,
|
||||
SecondSize = versions[1].Size,
|
||||
FirstExcluded = excluded.Contains(versions[0].Index),
|
||||
SecondExcluded = excluded.Contains(versions[1].Index),
|
||||
});
|
||||
}
|
||||
return [.. result.OrderBy(v => frames.First(f => f.Id == v.FirstFrameId).Index)];
|
||||
}
|
||||
|
||||
/// <summary>The frame positions Main excludes from renders; none for settings that are not a project of this Chronos.</summary>
|
||||
private static HashSet<int> ExcludedIndices(string? settingsJson)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(settingsJson)) return [];
|
||||
try
|
||||
{
|
||||
return [.. Core.Project.ProjectSettings.FromJson(settingsJson).ExcludedFrames];
|
||||
}
|
||||
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidDataException)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The raw SHA-256 (lower-case) of <paramref name="sha256"/> that a usable frame (not Missing or Corrupt) of any sequence
|
||||
/// of this index other than <paramref name="except"/> holds: what is not the last copy of its photo. Batched.
|
||||
|
||||
Reference in new issue
Block a user