fix(copies): close the owner review 6 verification findings
A merge could still trash photos it never verified, resume against a pair the user had answered meanwhile, and take different unhashed photos for copies; the dialog and the lists worded several facts wrongly or lost them on refresh. - Merge: a retry resumes only while the pair is still the job's; Verify requires the other archive online and its folder in place, stops on an unreadable photo, files a differing unhashed photo as a second version and must cover every frame before Trash; the plan hashes unmatched unhashed photos first, lists "Deleted in the other" and names the relinked servers; second versions stay discoverable (CopySides.VersionsAsync). - Integrate: a retry after a failure before the journal runs again. - Sync: a sequence back after a 404 stays Linked while its link holds; a local cull no longer asks for attention. - Block lines of both planners name the right sequence, archive, server and space through one formatter. - Compare dialog: one Details row per setting with worded values, Projects headings, Choose focuses the kept-sequence radios, the photo selection reaches rows outside the viewport, the Replace confirmation lists the losers per side, plan lines read as queued. - Matches and Library: counts first and grouped, integrating shown as a share, local matches name the other archive, the Library keeps its match and "deleted on server" statuses across a refresh. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d10577b175
commit
b34b6b6fe0
41 files changed
+1046
-193
No files matched your search
@@ -357,7 +357,7 @@ public sealed class SampleData
|
||||
];
|
||||
engine.Add(new SampleCopy(Copy(lighthouse, CopyKind.LocalServer, CopyState.Candidate, photos),
|
||||
SampleCopies.Facts(lighthouse, main.Name, 1_204), SampleCopies.Facts(lighthouse, ServerName, 1_180), photos,
|
||||
[new DetailLine("title", "Lighthouse 2026-08-13", "Lighthouse"), new DetailLine("rating", "4", "3"),
|
||||
[new DetailLine("sequence.title", "Lighthouse 2026-08-13", "Lighthouse"), new DetailLine("sequence.rating", "4", "3"),
|
||||
new DetailLine("exposure.deflickerWindow", "41", "33")], Projects(other: true)));
|
||||
|
||||
// (2) Meteor night: kept apart.
|
||||
@@ -383,7 +383,7 @@ public sealed class SampleData
|
||||
];
|
||||
engine.Add(new SampleCopy(Copy(alps, CopyKind.LocalLocal, CopyState.Candidate, photos, other: alpsNas.Id),
|
||||
SampleCopies.Facts(alps, main.Name, 940), SampleCopies.Facts(alpsNas, originals.Name, 902, originals: true, servers: [ServerName]), photos,
|
||||
[new DetailLine("rating", "5", "4")], Projects(other: true), PreselectedKeep: alpsNas.Id));
|
||||
[new DetailLine("sequence.rating", "5", "4")], Projects(other: true), PreselectedKeep: alpsNas.Id));
|
||||
|
||||
// (5) Garden 2026: the server deleted its copy.
|
||||
var garden = await SequenceAsync("Garden 2026", main.Id, 480, new DateTime(2026, 5, 2, 6, 0, 0), "Canon EOS R6");
|
||||
|
||||
@@ -223,7 +223,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
return
|
||||
[
|
||||
CopyJobs.CreateIntegrateHandler(sync, archives, services.Sync, sync.Copies),
|
||||
SequenceMerger.CreateHandler(db, new SequenceMerger(db, archives, new CopySides(db)), archives, new ProjectTransplant(),
|
||||
SequenceMerger.CreateHandler(db, new SequenceMerger(db, archives, new CopySides(db)) { ServerNames = services.ServerNameOf }, archives, new ProjectTransplant(),
|
||||
new WorkspaceCopyGuard(services.Workspace)),
|
||||
];
|
||||
}
|
||||
@@ -236,7 +236,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
var sides = new CopySides(database);
|
||||
var homes = CopyJobs.ServerHomes(Sync);
|
||||
return new CopyEngine(sync, archives, new IntegratePlanner(sync, sides, archives.Projects, homes), new SequenceMerger(database, archives, sides),
|
||||
return new CopyEngine(sync, archives, new IntegratePlanner(sync, sides, archives.Projects, homes),
|
||||
new SequenceMerger(database, archives, sides) { ServerNames = ServerNameOf },
|
||||
new CopyReviewBuilder(database, archives.Projects, sides, homes), CopyContext, new WorkspaceCopyGuard(Workspace),
|
||||
refresh: async (remote, ct) =>
|
||||
{
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
|
||||
namespace Chronos.App.Infrastructure;
|
||||
|
||||
/// <summary>A list row whose selection the view model reads (the rows an action such as To trash… works on).</summary>
|
||||
public interface ISelectableRow
|
||||
{
|
||||
bool IsSelected { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps every row's <see cref="ISelectableRow.IsSelected"/> equal to the list's selection, realised or not: a virtualising
|
||||
/// list binds IsSelected only on the rows it shows, so Ctrl+A or Shift+End over a long list left the hidden rows unselected
|
||||
/// in the model, and a recycled container could carry one row's selection to another (owner review 6).
|
||||
/// </summary>
|
||||
public static class ListSelection
|
||||
{
|
||||
public static readonly DependencyProperty SyncsRowsProperty = DependencyProperty.RegisterAttached(
|
||||
"SyncsRows", typeof(bool), typeof(ListSelection), new PropertyMetadata(false, OnSyncsRowsChanged));
|
||||
|
||||
public static bool GetSyncsRows(DependencyObject element) => (bool)element.GetValue(SyncsRowsProperty);
|
||||
|
||||
public static void SetSyncsRows(DependencyObject element, bool value) => element.SetValue(SyncsRowsProperty, value);
|
||||
|
||||
private static void OnSyncsRowsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is not Selector list) return;
|
||||
list.SelectionChanged -= OnSelectionChanged;
|
||||
if (e.NewValue is true) list.SelectionChanged += OnSelectionChanged;
|
||||
}
|
||||
|
||||
internal static void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
foreach (var row in e.RemovedItems.OfType<ISelectableRow>()) row.IsSelected = false;
|
||||
foreach (var row in e.AddedItems.OfType<ISelectableRow>()) row.IsSelected = true;
|
||||
}
|
||||
}
|
||||
@@ -891,6 +891,8 @@ public sealed class LibraryViewModel : SectionViewModel
|
||||
var entry = _entries.GetValueOrDefault(item.Id);
|
||||
var action = MassActions.QuickSync(new SelectedSequence(item.Sequence, entry), Context, out var blocker);
|
||||
item.SetSync(entry, action is not null, action is { } a ? Loc.L("Tooltips.Library.QuickSync." + a) : blocker ?? string.Empty);
|
||||
// The match status survives every reload (a search, a filter, a page): the cards are new each time.
|
||||
item.SetMatch(Shell.Server?.Sync.Copies.StatusOf(item.Id));
|
||||
item.SetQuickBlocker(item.IsRemote
|
||||
? _actions.CanPost ? null : Loc.L("Library.Blocked.NotConnected")
|
||||
: Context.HasEngine ? null : Loc.L("Library.Blocked.NoIndex"));
|
||||
|
||||
@@ -5,12 +5,14 @@ using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Server.Copies;
|
||||
|
||||
namespace Chronos.App.Sections;
|
||||
|
||||
public partial class ServerView : UserControl
|
||||
{
|
||||
private IInputElement? _beforeDialog;
|
||||
private CopyDialogViewModel? _copyDialog;
|
||||
|
||||
public ServerView()
|
||||
{
|
||||
@@ -41,6 +43,9 @@ public partial class ServerView : UserControl
|
||||
private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName != nameof(ServerViewModel.Dialog) || sender is not ServerViewModel model) return;
|
||||
if (_copyDialog is not null) _copyDialog.KeepFocusRequested -= OnKeepFocusRequested;
|
||||
_copyDialog = model.Dialog as CopyDialogViewModel;
|
||||
if (_copyDialog is not null) _copyDialog.KeepFocusRequested += OnKeepFocusRequested;
|
||||
if (model.Dialog is not null)
|
||||
{
|
||||
if (!IsVisible) return;
|
||||
@@ -57,4 +62,19 @@ public partial class ServerView : UserControl
|
||||
Body.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Choose on "Choose the sequence to keep": the keyboard goes to the first Kept sequence radio of the Plan part.</summary>
|
||||
private void OnKeepFocusRequested(object? sender, EventArgs e) =>
|
||||
Dispatcher.BeginInvoke(DispatcherPriority.Input, () => FirstKeepOption(DialogHost)?.Focus());
|
||||
|
||||
internal static RadioButton? FirstKeepOption(DependencyObject root)
|
||||
{
|
||||
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
|
||||
{
|
||||
var child = VisualTreeHelper.GetChild(root, i);
|
||||
if (child is RadioButton { DataContext: CopyKeepOption, IsVisible: true } radio) return radio;
|
||||
if (FirstKeepOption(child) is { } found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -5,23 +5,35 @@ using Chronos.Ui.Mvvm;
|
||||
namespace Chronos.App.Server.Copies;
|
||||
|
||||
/// <summary>
|
||||
/// A detail that differs (the Details part): its label, this PC's and the other side's value, and the side both take
|
||||
/// (nothing preselected: <see cref="ChoiceIndex"/> -1 until the user picks). In a merge the first column is the kept
|
||||
/// A setting that differs (the Details part): its label, this PC's and the other side's value, and the side both take
|
||||
/// (nothing preselected: <see cref="ChoiceIndex"/> -1 until the user picks). The lines of one setting (the members of an
|
||||
/// Auto parameter, the positions parked by photo) are one row and one choice. In a merge the first column is the kept
|
||||
/// sequence's: <paramref name="swapped"/> when that is the pair's other sequence (the line compares the pair's first with it).
|
||||
/// </summary>
|
||||
public sealed class CopyDetailRow(DetailLine line, bool isMerge, Action changed, bool swapped = false) : ObservableObject
|
||||
public sealed class CopyDetailRow(IReadOnlyList<DetailLine> lines, bool isMerge, Action changed, bool swapped = false) : ObservableObject
|
||||
{
|
||||
private int _choiceIndex = -1;
|
||||
|
||||
public DetailLine Line { get; } = line;
|
||||
public CopyDetailRow(DetailLine line, bool isMerge, Action changed, bool swapped = false) : this([line], isMerge, changed, swapped)
|
||||
{
|
||||
}
|
||||
|
||||
public IReadOnlyList<DetailLine> Lines { get; } = lines;
|
||||
public DetailLine Line => Lines[0];
|
||||
|
||||
/// <summary>The first line's path: the row's identity across a rebuild.</summary>
|
||||
public string Path => Line.Path;
|
||||
|
||||
/// <summary>Every path the row's choice answers.</summary>
|
||||
public IEnumerable<string> Paths => Lines.Select(l => l.Path);
|
||||
|
||||
public string Label => SyncText.DetailLabel(Line.Path);
|
||||
private string? First => swapped ? Line.There : Line.Here;
|
||||
private string? Second => swapped ? Line.Here : Line.There;
|
||||
public string HereText => Value(First);
|
||||
public string ThereText => Value(Second);
|
||||
public string HereToolTip => First ?? Loc.L("Server.Sync.None");
|
||||
public string ThereToolTip => Second ?? Loc.L("Server.Sync.None");
|
||||
private string? First(DetailLine l) => swapped ? l.There : l.Here;
|
||||
private string? Second(DetailLine l) => swapped ? l.Here : l.There;
|
||||
public string HereText => Values(First);
|
||||
public string ThereText => Values(Second);
|
||||
public string HereToolTip => Raw(First);
|
||||
public string ThereToolTip => Raw(Second);
|
||||
|
||||
public string HereWord => Loc.L(isMerge ? "Server.Copies.Detail.Kept" : "Server.Copies.Detail.ThisPc");
|
||||
public string ThereWord => Loc.L(isMerge ? "Server.Copies.Detail.Other" : "Server.Copies.Detail.Server");
|
||||
@@ -57,6 +69,11 @@ public sealed class CopyDetailRow(DetailLine line, bool isMerge, Action changed,
|
||||
OnPropertyChanged(nameof(Chosen));
|
||||
}
|
||||
|
||||
private static string Value(string? value) => string.IsNullOrWhiteSpace(value) ? Loc.L("Server.Sync.None")
|
||||
: value.Length <= 40 ? value : string.Concat(value.AsSpan(0, 39), "…");
|
||||
/// <summary>One side's values as the sync words them ("41", "on", "12 photos"), the distinct ones joined.</summary>
|
||||
private string Values(Func<DetailLine, string?> side) =>
|
||||
string.Join(Loc.Separator, Lines.Select(l => SyncText.DetailValue(l.Path, side(l))).Distinct(StringComparer.Ordinal));
|
||||
|
||||
/// <summary>One side's raw values for the tooltip.</summary>
|
||||
private string Raw(Func<DetailLine, string?> side) =>
|
||||
string.Join(Environment.NewLine, Lines.Select(l => side(l) ?? Loc.L("Server.Sync.None")));
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Ui.Mvvm;
|
||||
@@ -94,12 +95,15 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
public FoundCopy Copy => _pair.Copy;
|
||||
public bool IsMerge => Copy.Kind == CopyKind.LocalLocal;
|
||||
|
||||
public string Heading => Loc.L(IsMerge ? "Server.Copies.Dialog.Merge" : "Server.Copies.Dialog.Compare");
|
||||
/// <summary>"Compare: Lighthouse": the dialog names the sequence it acts on.</summary>
|
||||
public string Heading => Loc.L(IsMerge ? "Server.Copies.Dialog.MergeTitle" : "Server.Copies.Dialog.CompareTitle", Here.Title);
|
||||
|
||||
/// <summary>"This PC · Lighthouse · 1,204 photos · 18.2 GB".</summary>
|
||||
public string HereText => Loc.L("Server.Copies.Where.ThisPc", CopyText.Facts(Here));
|
||||
/// <summary>"This PC · Main archive · 1,204 photos · 18.2 GB"; with the title first when the two sides' titles differ.</summary>
|
||||
public string HereText => Loc.L("Server.Copies.Where.ThisPc", CopyText.Facts(Here, TitlesDiffer));
|
||||
|
||||
public string ThereText => IsMerge ? Loc.L("Server.Copies.Where.ThisPc", CopyText.Facts(There)) : CopyText.Facts(There);
|
||||
public string ThereText => IsMerge ? Loc.L("Server.Copies.Where.ThisPc", CopyText.Facts(There, TitlesDiffer)) : CopyText.Facts(There, TitlesDiffer);
|
||||
|
||||
private bool TitlesDiffer => !string.Equals(Here.Title, There.Title, StringComparison.CurrentCulture);
|
||||
|
||||
private CopyFacts Here => _review?.Here ?? _pair.Here;
|
||||
private CopyFacts There => _review?.There ?? _pair.There;
|
||||
@@ -123,7 +127,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
OnPropertyChanged(nameof(IsProjects));
|
||||
OnPropertyChanged(nameof(IsPlan));
|
||||
OnPropertyChanged(nameof(ApplyToolTip));
|
||||
if (value == CopyDialogPart.Plan) SchedulePlan(TimeSpan.Zero);
|
||||
if (value == CopyDialogPart.Plan || (value == CopyDialogPart.Projects && (_plan ?? (object?)_merge) is null)) SchedulePlan(TimeSpan.Zero);
|
||||
_apply.RaiseCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
@@ -296,6 +300,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
_review = await _engine.CompareAsync(Copy.Id, Copy.Kind == CopyKind.LocalServer ? _shell.Services.Sync.Remote : null, CancellationToken.None);
|
||||
if (IsClosed) return;
|
||||
Build(_review);
|
||||
if ((_plan?.Projects ?? _merge?.Projects) is { } steps) SetProjectTargets(steps);
|
||||
IsLoaded = true;
|
||||
if (_integrate && _part == CopyDialogPart.Plan && Unchosen > 0) _part = CopyDialogPart.Details;
|
||||
OnAllPropertiesChanged();
|
||||
@@ -354,7 +359,8 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
private void BuildDetails(CopyReview review)
|
||||
{
|
||||
var chosen = _details.GroupBy(d => d.Path, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ChoiceIndex, StringComparer.Ordinal);
|
||||
Details = [.. review.Details.Select(line => new CopyDetailRow(line, IsMerge, Changed, Swapped))];
|
||||
Details = [.. review.Details.GroupBy(line => SyncText.DetailSetting(line.Path), StringComparer.Ordinal)
|
||||
.Select(setting => new CopyDetailRow([.. setting], IsMerge, Changed, Swapped))];
|
||||
foreach (var row in _details) row.SetQuietly(chosen.GetValueOrDefault(row.Path, -1));
|
||||
}
|
||||
|
||||
@@ -478,7 +484,8 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
}
|
||||
|
||||
private Dictionary<string, CopySide> DetailChoices() =>
|
||||
_details.Where(d => d.Chosen is not null).ToDictionary(d => d.Path, d => d.Chosen!.Value, StringComparer.Ordinal);
|
||||
_details.Where(d => d.Chosen is not null).SelectMany(d => d.Paths.Select(p => (Path: p, Side: d.Chosen!.Value)))
|
||||
.DistinctBy(c => c.Path, StringComparer.Ordinal).ToDictionary(c => c.Path, c => c.Side, StringComparer.Ordinal);
|
||||
|
||||
private async Task PlanAsync(CancellationToken ct)
|
||||
{
|
||||
@@ -526,6 +533,17 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
}
|
||||
}
|
||||
|
||||
private string TitleOf(Guid sequenceId) => sequenceId == Copy.LocalId ? Here.Title : There.Title;
|
||||
|
||||
/// <summary>Choose on "Choose the sequence to keep": the view moves the keyboard focus to the Kept sequence radios.</summary>
|
||||
public event EventHandler? KeepFocusRequested;
|
||||
|
||||
private void RequestKeepFocus()
|
||||
{
|
||||
Part = CopyDialogPart.Plan;
|
||||
KeepFocusRequested?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
private CopyFacts? KeptFacts => _keepId is { } keep ? keep == Copy.LocalId ? Here : There : null;
|
||||
private CopyFacts? DroppedFacts => _keepId is { } keep ? keep == Copy.LocalId ? There : Here : null;
|
||||
|
||||
@@ -544,7 +562,11 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
Trash(plan.Photos, PhotoAction.TrashThere, there);
|
||||
var versions = plan.Photos.Count(p => p.Action == PhotoAction.SendVersion);
|
||||
if (versions > 0) there.Add(new(Loc.Plural("Server.Copies.Plan.ServerUsesOurs", versions, ServerName), Loc.L("Tooltips.Server.Copies.Plan.ServerUsesOurs")));
|
||||
if (plan.DetailChanges > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Details", plan.DetailChanges)));
|
||||
// A detail changes on the side that does not keep its own value: this PC takes the server's, the server this PC's.
|
||||
var toHere = _details.Where(d => d.Chosen == CopySide.Other).SelectMany(d => d.Paths).Distinct(StringComparer.Ordinal).Count();
|
||||
var toThere = _details.Where(d => d.Chosen == CopySide.ThisPc).SelectMany(d => d.Paths).Distinct(StringComparer.Ordinal).Count();
|
||||
if (toHere > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Details", toHere)));
|
||||
if (toThere > 0) there.Add(new(Loc.Plural("Server.Copies.Plan.Details", toThere)));
|
||||
var fromHere = plan.Projects.Count(p => p.From == CopySide.ThisPc);
|
||||
var fromThere = plan.Projects.Count - fromHere;
|
||||
if (fromThere > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Projects", fromThere)));
|
||||
@@ -552,8 +574,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
here.Add(new(Loc.L("Server.Copies.Plan.Free", Formatting.Bytes(plan.FreeBytes)), Loc.L("Tooltips.Server.Copies.Plan.Free")));
|
||||
if (plan.QuotaLeftBytes is { } quota) there.Add(new(Loc.L("Server.Copies.Plan.Quota", Formatting.Bytes(quota)), Loc.L("Tooltips.Server.Copies.Plan.Quota")));
|
||||
if (plan.LeftOut > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.LeftOut", plan.LeftOut), Loc.L("Tooltips.Server.Copies.Plan.LeftOut")));
|
||||
foreach (var row in _hereProjects.Concat(_thereProjects))
|
||||
row.SetTarget(plan.Projects.FirstOrDefault(p => p.SourceProjectId == row.Project.Id)?.TargetName);
|
||||
SetProjectTargets(plan.Projects);
|
||||
blocks.AddRange(plan.Blocks.Select(Block));
|
||||
}
|
||||
else if (_merge is { } merge)
|
||||
@@ -563,10 +584,14 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
if (merge.DetailChanges > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Details", merge.DetailChanges)));
|
||||
if (merge.Renders.Count > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Renders", merge.Renders.Count)));
|
||||
if (merge.Projects.Count > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Projects", merge.Projects.Count)));
|
||||
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])));
|
||||
foreach (var link in merge.Links) here.Add(new(Loc.L("Server.Copies.Plan.Relink", link), Loc.L("Tooltips.Server.Copies.Plan.Relink")));
|
||||
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)
|
||||
here.Add(new(Loc.L("Server.Copies.Plan.Relink", link), Loc.L("Tooltips.Server.Copies.Plan.Relink")));
|
||||
here.Add(new(Loc.L("Server.Copies.Plan.Free", Formatting.Bytes(merge.FreeBytes)), Loc.L("Tooltips.Server.Copies.Plan.Free")));
|
||||
if (DroppedFacts is { } dropped)
|
||||
there.Add(new(Loc.Plural("Server.Copies.Plan.DropToTrash", dropped.Photos, Formatting.Bytes(dropped.Bytes)), IsWarning: true));
|
||||
@@ -604,14 +629,24 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Each project row names the project it becomes at the other home (the plan's free name).</summary>
|
||||
private void SetProjectTargets(IReadOnlyList<ProjectStep> steps)
|
||||
{
|
||||
foreach (var row in _hereProjects.Concat(_thereProjects))
|
||||
row.SetTarget(steps.FirstOrDefault(p => p.SourceProjectId == row.Project.Id)?.TargetName);
|
||||
}
|
||||
|
||||
private CopyBlockLine Block(CopyBlock block)
|
||||
{
|
||||
var need = _plan is { } plan ? Formatting.Bytes(plan.FetchBytes) : _merge is { } merge ? Formatting.Bytes(merge.CopyBytes) : null;
|
||||
var text = CopyText.Block(block, Here.Title, ServerName, need, Unchosen);
|
||||
// The sentences the job would fail with: one formatter for both (the kept and the other sequence of a merge by title).
|
||||
var text = _merge is { } merge && IsMerge
|
||||
? SequenceMerger.BlockText(merge, block, TitleOf(merge.KeepId), TitleOf(merge.KeepId == Copy.LocalId ? Copy.OtherId ?? Guid.Empty : Copy.LocalId), Unchosen)
|
||||
: _plan is { } plan ? IntegratePlanner.BlockText(plan, block, Here.Title, plan.Context?.ServerName ?? ServerName, Unchosen)
|
||||
: CopyText.Block(block, Here.Title, ServerName, null, Unchosen);
|
||||
Action? choose = block switch
|
||||
{
|
||||
CopyBlock.DetailsUnchosen => () => Part = CopyDialogPart.Details,
|
||||
CopyBlock.KeptUnchosen => () => Part = CopyDialogPart.Plan,
|
||||
CopyBlock.KeptUnchosen => RequestKeepFocus,
|
||||
_ => null,
|
||||
};
|
||||
return new CopyBlockLine(block, text, choose);
|
||||
@@ -630,7 +665,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
if (_plan is { CanApply: true } plan)
|
||||
{
|
||||
if (plan.Destructive && !_shell.Services.Dialogs.Confirm(ReplaceRequest(plan))) return;
|
||||
if (plan.Destructive && !_shell.Services.Dialogs.Confirm(ReplaceRequest(plan, plan.Context?.ServerName ?? ServerName))) return;
|
||||
IsBusy = true;
|
||||
await _engine.EnqueueIntegrateAsync(jobs, plan, CancellationToken.None);
|
||||
}
|
||||
@@ -773,15 +808,19 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
await LoadAsync();
|
||||
}
|
||||
|
||||
/// <summary>"Replace photos?" (design §8.5): the losing versions per side, the last copies named first.</summary>
|
||||
internal static ConfirmRequest ReplaceRequest(IntegratePlan plan)
|
||||
/// <summary>
|
||||
/// "Replace photos?" (design §8.5): the losing versions under the side that loses them ("On this PC", "On Studio NAS"),
|
||||
/// each side's last copies named first, every photo once.
|
||||
/// </summary>
|
||||
internal static ConfirmRequest ReplaceRequest(IntegratePlan plan, string? server = null)
|
||||
{
|
||||
var trashed = plan.Photos.Where(p => p.Action is PhotoAction.TrashHere or PhotoAction.TrashThere).ToList();
|
||||
var name = server ?? plan.Context?.ServerName ?? string.Empty;
|
||||
return new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Server.Copies.Confirm.Replace.Title"),
|
||||
Message = Loc.Plural("Server.Copies.Confirm.Replace.Message", trashed.Count),
|
||||
Detail = Lines(plan.LastCopies, trashed.Select(p => p.FileName)),
|
||||
Detail = ReplaceLines(plan.LastCopies, trashed, name),
|
||||
SafeText = Loc.L("Archive.Dialog.Cancel"),
|
||||
SafeToolTip = Loc.L("Tooltips.Server.Copies.Confirm.Safe"),
|
||||
ActionText = Loc.L("Server.Copies.Action.IntegrateNow"),
|
||||
@@ -829,6 +868,36 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
|
||||
IsDestructive = true,
|
||||
};
|
||||
|
||||
/// <summary>The Replace confirmation's list: per side a heading, its last copies, then its other losing versions; ten names in all at most.</summary>
|
||||
internal static string ReplaceLines(IReadOnlyList<LastCopy> lasts, IReadOnlyList<PhotoStep> trashed, string server)
|
||||
{
|
||||
const int Listed = 10;
|
||||
var lines = new List<string>();
|
||||
var named = 0;
|
||||
var total = 0;
|
||||
foreach (var (side, action, heading) in new[]
|
||||
{
|
||||
(CopySide.ThisPc, PhotoAction.TrashHere, Loc.L("Server.Copies.Plan.OnThisPc")),
|
||||
(CopySide.Other, PhotoAction.TrashThere, Loc.L("Server.Copies.Plan.OnServer", server)),
|
||||
})
|
||||
{
|
||||
var last = lasts.Where(l => l.Side == side).ToList();
|
||||
var lastKeys = last.Select(l => l.Key).ToHashSet(StringComparer.Ordinal);
|
||||
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))
|
||||
.Distinct(StringComparer.Ordinal).ToList();
|
||||
total += names.Count;
|
||||
if (names.Count == 0) continue;
|
||||
var room = Listed - named;
|
||||
if (room <= 0) continue;
|
||||
lines.Add(heading);
|
||||
lines.AddRange(names.Take(room).Select(n => " " + n));
|
||||
named += Math.Min(room, names.Count);
|
||||
}
|
||||
if (total > named) lines.Add(Loc.Plural("Archive.Delete.More", total - named));
|
||||
return string.Join(Environment.NewLine, lines);
|
||||
}
|
||||
|
||||
private static string Lines(IReadOnlyList<LastCopy> lasts, IEnumerable<string> rest)
|
||||
{
|
||||
const int Listed = 10;
|
||||
|
||||
@@ -107,6 +107,7 @@
|
||||
Visibility="{Binding CanDeleteThere, Converter={StaticResource CopyBoolToVisibility}}" />
|
||||
</WrapPanel>
|
||||
<ListBox Grid.Row="1" Grid.Column="1" 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"
|
||||
AutomationProperties.Name="{Binding SelectedClass.Text}" Visibility="{Binding HasPhotos, Converter={StaticResource CopyBoolToVisibility}}">
|
||||
@@ -128,7 +129,7 @@
|
||||
<TextBlock Grid.Column="3" Text="{Binding SizeText}" VerticalAlignment="Center" TextAlignment="Right" Typography.NumeralAlignment="Tabular" FontSize="12" />
|
||||
<TextBlock Grid.Column="4" Text="{Binding SideText}" VerticalAlignment="Center" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0"
|
||||
TextTrimming="CharacterEllipsis" FontSize="12" />
|
||||
<ComboBox Grid.Column="5" Width="120" ItemsSource="{Binding Choices}" SelectedItem="{Binding Choice}" DisplayMemberPath="Label"
|
||||
<ComboBox Grid.Column="5" Width="150" 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}}" />
|
||||
<Button Grid.Column="5" Style="{StaticResource Button.Row}" Content="{l:Loc Server.Copies.Action.Drop}" Command="{Binding DropCommand}"
|
||||
@@ -187,6 +188,7 @@
|
||||
<!-- Projects: Copy across or Leave them; each side's projects, and where each goes. -->
|
||||
<Grid Visibility="{Binding IsProjects, Converter={StaticResource CopyBoolToVisibility}}">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
@@ -202,7 +204,10 @@
|
||||
</v:SegmentedControl>
|
||||
<TextBlock Grid.Row="1" Grid.ColumnSpan="2" Text="{Binding ProjectsNote}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,0,8"
|
||||
Visibility="{Binding ProjectsNote, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
|
||||
<ItemsControl Grid.Row="2" ItemsSource="{Binding HereProjects}" Focusable="False" Margin="0,0,14,0">
|
||||
<!-- Each column says whose projects it lists (this PC or the kept sequence, the server or the other one). -->
|
||||
<TextBlock Grid.Row="2" Text="{Binding HereHeading}" FontWeight="SemiBold" Margin="0,0,14,6" TextTrimming="CharacterEllipsis" ToolTip="{Binding HereHeading}" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding ThereHeading}" FontWeight="SemiBold" Margin="0,0,0,6" TextTrimming="CharacterEllipsis" ToolTip="{Binding ThereHeading}" />
|
||||
<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}">
|
||||
@@ -214,7 +219,7 @@
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<ItemsControl Grid.Row="2" Grid.Column="1" ItemsSource="{Binding ThereProjects}" Focusable="False">
|
||||
<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}">
|
||||
|
||||
@@ -141,6 +141,14 @@ public sealed class CopyListViewModel : ObservableObject, IDisposable
|
||||
.Select(p => p.Copy)
|
||||
.FirstOrDefault();
|
||||
|
||||
/// <summary>Where the other sequence of <see cref="PairOf"/>'s pair lies ("Old archive"), seen from <paramref name="sequenceId"/>.</summary>
|
||||
public string? OtherWhere(Guid sequenceId)
|
||||
{
|
||||
var id = PairOf(sequenceId)?.Id;
|
||||
if (_pairs.FirstOrDefault(p => p.Copy.Id == id) is not { } pair) return null;
|
||||
return pair.Copy.Kind == CopyKind.LocalLocal && pair.Copy.OtherId == sequenceId ? pair.Here.Where : pair.There.Where;
|
||||
}
|
||||
|
||||
/// <summary>Reads the pairs again; requests made while a pass runs share the next one.</summary>
|
||||
public async Task ReloadAsync()
|
||||
{
|
||||
@@ -219,18 +227,26 @@ public sealed class CopyListViewModel : ObservableObject, IDisposable
|
||||
/// <summary>The Library's cards and rows of local sequences in pairs that ask for a choice take "Also elsewhere" or "Deleted there".</summary>
|
||||
private void UpdateLibrary()
|
||||
{
|
||||
foreach (var item in _shell.Library.Items)
|
||||
{
|
||||
var pair = _pairs.FirstOrDefault(p => p.Copy.NeedsAttention && (p.Copy.LocalId == item.Id || p.Copy.OtherId == item.Id));
|
||||
item.SetMatch(pair is null ? null : LibraryStatus(pair, item.Id));
|
||||
}
|
||||
foreach (var item in _shell.Library.Items) item.SetMatch(StatusOf(item.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Library status of the card <paramref name="id"/> (a local sequence, or a server sequence of a pair): the status of
|
||||
/// the first pair naming it that asks for a choice; null when none does. Every Library refresh asks it again.
|
||||
/// </summary>
|
||||
internal CardStatus? StatusOf(Guid id)
|
||||
{
|
||||
var pair = _pairs.FirstOrDefault(p => p.Copy.NeedsAttention && (p.Copy.LocalId == id || p.Copy.OtherId == id || p.Copy.RemoteId == id));
|
||||
return pair is null ? null : LibraryStatus(pair, id);
|
||||
}
|
||||
|
||||
/// <summary>The card status of a sequence of <paramref name="pair"/>.</summary>
|
||||
internal static CardStatus LibraryStatus(FoundCopyView pair, Guid sequenceId)
|
||||
{
|
||||
var copy = pair.Copy;
|
||||
if (copy.RemoteGone || copy.Score.DeletedThere > 0)
|
||||
if (copy.RemoteGone)
|
||||
return new CardStatus(StatusKind.Warning, Loc.L("Library.Status.RemoteGone"), Loc.L("Tooltips.Library.Status.RemoteGone", pair.There.Where));
|
||||
if (copy.Score.DeletedThere > 0)
|
||||
return new CardStatus(StatusKind.Warning, Loc.L("Library.Status.DeletedThere"),
|
||||
Loc.L("Tooltips.Library.Status.DeletedThere", pair.There.Where));
|
||||
var other = copy.Kind == CopyKind.LocalLocal && copy.OtherId == sequenceId ? pair.Here : pair.There;
|
||||
|
||||
@@ -26,7 +26,7 @@ public sealed class CopyClassRow(PhotoClassTotal total) : ObservableObject
|
||||
/// A photo of the Photos part's list: capture time, name, size, where it lies, and per policy a Bring tick (Only here,
|
||||
/// Only there under Choose each), a version choice (Different under Choose each) or Drop… (Two versions).
|
||||
/// </summary>
|
||||
public sealed class CopyPhotoRow : ObservableObject
|
||||
public sealed class CopyPhotoRow : ObservableObject, ISelectableRow
|
||||
{
|
||||
private readonly Action _changed;
|
||||
private readonly bool _swapped;
|
||||
|
||||
@@ -7,10 +7,13 @@ using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Server.Copies;
|
||||
|
||||
/// <summary>A line of the Plan part ("Receives 24 photos · 412 MB"); a warning line (last copies) leads its column.</summary>
|
||||
/// <summary>
|
||||
/// A line of the Plan part ("Receives 24 photos · 412 MB"): something that will happen, so a queued glyph, not a done
|
||||
/// tick; a warning line (last copies, the trash) leads its column.
|
||||
/// </summary>
|
||||
public sealed record CopyPlanLine(string Text, string? ToolTip = null, bool IsWarning = false)
|
||||
{
|
||||
public StatusKind Kind => IsWarning ? StatusKind.Warning : StatusKind.Done;
|
||||
public StatusKind Kind => IsWarning ? StatusKind.Warning : StatusKind.Queued;
|
||||
public string ShownToolTip => ToolTip ?? Text;
|
||||
}
|
||||
|
||||
|
||||
@@ -54,13 +54,22 @@ public static class CopyText
|
||||
CopyState.KeptApart => (StatusKind.Offline, Loc.L("Server.Copies.State.KeptApart"),
|
||||
Loc.L("Tooltips.Server.Copies.State.KeptApart", Formatting.Date(copy.AnsweredAt ?? copy.UpdatedAt))),
|
||||
CopyState.Linked => (StatusKind.Synced, Loc.L("Server.Copies.State.Linked"), Loc.L("Tooltips.Server.Copies.State.Linked")),
|
||||
// The share in the cell (it fits the column in both languages); "1,234 of 2,400" in the tooltip.
|
||||
CopyState.Integrating => (StatusKind.Running,
|
||||
Loc.L("Server.Copies.State.Integrating", Formatting.Count(progress?.Done ?? 0), Formatting.Count(progress?.Total ?? 0)),
|
||||
Loc.L("Tooltips.Server.Copies.State.Integrating")),
|
||||
Loc.L("Server.Copies.State.Integrating", Percent(progress)),
|
||||
progress is { Total: > 0 } p
|
||||
? string.Join(Environment.NewLine, Loc.L("Tooltips.Server.Copies.State.Integrating"),
|
||||
Loc.L("Server.Copies.State.Progress", Formatting.Count(p.Done), Formatting.Count(p.Total)))
|
||||
: Loc.L("Tooltips.Server.Copies.State.Integrating")),
|
||||
_ => (StatusKind.Done, Loc.L("Server.Copies.State.Integrated"), Loc.L("Tooltips.Server.Copies.State.Integrated")),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>How far an Integrate or Merge job came, in whole per cent ("51"); "0" before it reports.</summary>
|
||||
private static string Percent((long Done, long Total)? progress) => progress is { Total: > 0 } p
|
||||
? Math.Clamp(p.Done * 100 / p.Total, 0, 100).ToString("0", Loc.Culture)
|
||||
: "0";
|
||||
|
||||
/// <summary>The share of the smaller side's photos the other holds too, in whole per cent ("98").</summary>
|
||||
public static string SharedPercent(CopyScore score) =>
|
||||
Math.Round(Math.Clamp(score.Containment, 0, 1000) / 10.0).ToString("0", Loc.Culture);
|
||||
@@ -69,8 +78,15 @@ public static class CopyText
|
||||
public static string Where(CopyFacts facts, bool isServer) =>
|
||||
Loc.Plural(isServer ? "Server.Copies.Where.Server" : "Server.Copies.Where.Archive", facts.Photos, facts.Where);
|
||||
|
||||
/// <summary>"Lighthouse · 1,204 photos · 18.2 GB": a side of the dialog's header.</summary>
|
||||
public static string Facts(CopyFacts facts) => Loc.Plural("Server.Copies.Facts", facts.Photos, facts.Where, Formatting.Bytes(facts.Bytes));
|
||||
/// <summary>
|
||||
/// "Main archive · 1,204 photos · 18.2 GB": a side of the dialog's header; "Lighthouse · Main archive · 1,204 photos ·
|
||||
/// 18.2 GB" with <paramref name="withTitle"/> (the two sides' titles differ).
|
||||
/// </summary>
|
||||
public static string Facts(CopyFacts facts, bool withTitle = false)
|
||||
{
|
||||
var text = Loc.Plural("Server.Copies.Facts", facts.Photos, facts.Where, Formatting.Bytes(facts.Bytes));
|
||||
return withTitle && facts.Title.Length > 0 ? Loc.L("Server.Copies.Titled", facts.Title, text) : text;
|
||||
}
|
||||
|
||||
/// <summary>The row's buttons in the order of design §8.1.</summary>
|
||||
public static IReadOnlyList<CopyAction> Actions(FoundCopy copy, Core.Model.JobState? job = null)
|
||||
|
||||
@@ -340,8 +340,9 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
/// <summary>What the Matches list adds to the row of <paramref name="entry"/>: its pair and why Upload all left it out.</summary>
|
||||
private SyncMark Mark(SyncEntry entry) => entry.Local is { } local
|
||||
? new SyncMark(Copies.PairOf(local.Id), _skipped.TryGetValue(local.Id, out var why) ? why : null, _shell.Services.Server.Flow.Info?.Name,
|
||||
Host.PhotoFailures.TryGetValue(local.Id, out var failure) && failure.Count >= SyncAgent.NotSentAfter ? failure : null)
|
||||
: new SyncMark(Copies.PairOf(entry.Id), null, _shell.Services.Server.Flow.Info?.Name);
|
||||
Host.PhotoFailures.TryGetValue(local.Id, out var failure) && failure.Count >= SyncAgent.NotSentAfter ? failure : null,
|
||||
Copies.OtherWhere(local.Id))
|
||||
: new SyncMark(Copies.PairOf(entry.Id), null, _shell.Services.Server.Flow.Info?.Name, OtherWhere: Copies.OtherWhere(entry.Id));
|
||||
|
||||
/// <summary>The rule of Upload all local (design §6.4): what it sends, and what it leaves out and why.</summary>
|
||||
/// <param name="busy">The targets of pending Integrate and Merge jobs.</param>
|
||||
|
||||
@@ -52,8 +52,9 @@ public enum SyncAction
|
||||
/// What the Matches list adds to a sync row (owner review 6, #73): the pair the row's sequence is in, why Upload all
|
||||
/// local left it out, and the automatic photo transfers of an integrated pair that failed too often in a row.
|
||||
/// </summary>
|
||||
/// <param name="OtherWhere">Where the pair's other sequence lies ("Old archive"): the tooltip of a match between this PC's archives.</param>
|
||||
public readonly record struct SyncMark(Data.Copies.FoundCopy? Copy, Data.Copies.UploadSkip? Skipped, string? ServerName = null,
|
||||
AutoPhotoFailure? NotSent = null)
|
||||
AutoPhotoFailure? NotSent = null, string? OtherWhere = null)
|
||||
{
|
||||
/// <summary>The row's sequence is in a pair nobody answered yet.</summary>
|
||||
public bool IsCandidate => Copy is { State: Data.Copies.CopyState.Candidate, RemoteGone: false };
|
||||
@@ -197,8 +198,11 @@ public static class SyncText
|
||||
}
|
||||
if (mark.NotSent is { Count: >= SyncAgent.NotSentAfter } failure)
|
||||
return (StatusKind.Warning, Loc.L("Server.Sync.State.NotSent"), Loc.L("Tooltips.Server.Sync.State.NotSent", failure.Reason));
|
||||
// A match between two of this PC's archives names the other archive, not the server.
|
||||
if (mark.IsCandidate)
|
||||
return (StatusKind.Warning, Loc.L("Server.Sync.State.CopyFound"), Loc.L("Tooltips.Server.Sync.State.CopyFound", mark.ServerName ?? mark.Copy!.Server ?? string.Empty));
|
||||
return (StatusKind.Warning, Loc.L("Server.Sync.State.CopyFound"), mark.Copy!.Kind == Data.Copies.CopyKind.LocalLocal
|
||||
? Loc.L("Tooltips.Library.Status.CopyFoundLocal", mark.OtherWhere ?? string.Empty)
|
||||
: Loc.L("Tooltips.Server.Sync.State.CopyFound", mark.ServerName ?? mark.Copy.Server ?? string.Empty));
|
||||
if (mark.Skipped is { } why && entry.Status == SyncStatus.LocalOnly)
|
||||
return (StatusKind.Offline, Loc.L("Server.Sync.State.Skipped"), Loc.L("Tooltips.Server.Sync.State.Skipped", Loc.L("Tooltips.Server.Sync.Skip." + why)));
|
||||
return State(entry);
|
||||
@@ -219,10 +223,59 @@ public static class SyncText
|
||||
/// <summary>The label of a detail line of the Compare dialog ("Deflicker window"); "Other setting" when unknown.</summary>
|
||||
public static string DetailLabel(string path)
|
||||
{
|
||||
if (path == Data.Copies.CopyPayload.PendingFramesPath) return Loc.L("Server.Copies.Detail.Positions");
|
||||
var (key, _) = Setting(path);
|
||||
return key == "Server.Setting.Other" ? Loc.L("Server.Copies.Detail.OtherSetting") : Loc.L(key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The setting a detail line belongs to (the lines of one setting, such as the members of an Auto parameter, are one
|
||||
/// row of the Details part); an unknown path is its own setting.
|
||||
/// </summary>
|
||||
internal static string DetailSetting(string path)
|
||||
{
|
||||
if (path == Data.Copies.CopyPayload.PendingFramesPath) return path;
|
||||
var (key, _) = Setting(path);
|
||||
return key == "Server.Setting.Other" ? path : key;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One side's value of a detail line as the sync's differences word it: a title or tags as text, a setting by its value
|
||||
/// ("41", "on", "auto"), the frame positions as the count of photos they place, "changed" for anything else (the
|
||||
/// raw value is the tooltip's).
|
||||
/// </summary>
|
||||
internal static string DetailValue(string path, string? json)
|
||||
{
|
||||
if (json is null) return Loc.L("Server.Sync.None");
|
||||
if (path == Data.Copies.CopyPayload.PendingFramesPath)
|
||||
{
|
||||
var count = TryParse(json) switch
|
||||
{
|
||||
JsonArray array => array.Count,
|
||||
JsonObject obj => obj.Count,
|
||||
_ => 0,
|
||||
};
|
||||
return Loc.Plural("Shell.Status.Photos", count);
|
||||
}
|
||||
// A title, tags, rating or notes line carries the plain text, not JSON.
|
||||
if (path.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal)) return Text(json);
|
||||
if (TryParse(json) is JsonArray items && items.All(i => i is JsonValue))
|
||||
return items.Count == 0 ? Loc.L("Server.Sync.None") : Shorten(string.Join(", ", items.Select(i => i!.ToString())));
|
||||
return Value(json, Setting(path).Field) ?? Loc.L("Server.Copies.Detail.Changed");
|
||||
|
||||
static JsonNode? TryParse(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonNode.Parse(json);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return JsonValue.Create(json);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One line for the State tooltip: "Deflicker window 41 here, 33 on the server · +2".</summary>
|
||||
public static string ConflictSummary(SyncEntry entry)
|
||||
{
|
||||
|
||||
@@ -45,6 +45,8 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
|
||||
private IWorkspaceGuard Workspace => workspace;
|
||||
|
||||
private SequenceMerger Merger => merger;
|
||||
|
||||
/// <summary>Called before each stage runs (tests: a crash, a change made between stages).</summary>
|
||||
internal Func<MergeStage, Task>? BeforeStage { get; set; }
|
||||
|
||||
@@ -58,7 +60,9 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
var keepPaths = new ArchivePaths(keepArchive.RootPath);
|
||||
try
|
||||
{
|
||||
var journal = MergeJournal.Read(keepPaths, job.Id) ?? await StartAsync(context, parameters, keepRow, keepPaths).ConfigureAwait(false);
|
||||
var journal = MergeJournal.Read(keepPaths, job.Id);
|
||||
if (journal is null) journal = await StartAsync(context, parameters, keepRow, keepPaths).ConfigureAwait(false);
|
||||
else await ResumeAsync(job, parameters, keepPaths, ct).ConfigureAwait(false);
|
||||
var staging = MergeJournal.StagingFor(keepPaths, job.Id);
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
|
||||
await new Run(this, context, journal, keepArchive, keepPaths).RunAsync().ConfigureAwait(false);
|
||||
@@ -101,6 +105,28 @@ 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>
|
||||
/// 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
|
||||
/// it is gone with the other sequence (the trash stage ran before the journal said so). Otherwise the journal is stale:
|
||||
/// it and its staging go and nothing more is applied; the pair, no longer this job's, is left as it is.
|
||||
/// </summary>
|
||||
private async Task ResumeAsync(Job job, MergeJobParameters parameters, ArchivePaths keepPaths, CancellationToken ct)
|
||||
{
|
||||
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;
|
||||
try
|
||||
{
|
||||
MergeJournal.Delete(keepPaths, job.Id);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"The stale journal of merge {job.Id} was not removed", ex);
|
||||
}
|
||||
throw new StaleCopyPlanException();
|
||||
}
|
||||
|
||||
/// <summary>The first run: plans again, refuses a plan that moved or is blocked, and journals it.</summary>
|
||||
private async Task<MergeJournal> StartAsync(JobContext context, MergeJobParameters parameters, Sequence keepRow, ArchivePaths keepPaths)
|
||||
{
|
||||
@@ -196,6 +222,31 @@ 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()
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The other sequence's files are where the index says, on a volume that answers: a verify or a trash never reads an
|
||||
/// absent drive or a moved folder as "nothing there to lose".
|
||||
/// </summary>
|
||||
private void EnsureDropReadable(Sequence drop)
|
||||
{
|
||||
if (ArchiveVolume.Probe(_dropPaths) != ArchiveAvailability.Online)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.ArchiveOffline", _dropTitle));
|
||||
if (drop.Folder.Length > 0 && !SequenceFolders.Holds(_dropPaths.Sequence(drop.Folder), drop.Id))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.FolderMoved", _dropTitle));
|
||||
}
|
||||
|
||||
private async Task EnsureDropUnchangedAsync(int expected)
|
||||
{
|
||||
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false);
|
||||
@@ -215,15 +266,19 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
await EnsureDropUnchangedAsync(journal.DropFramesVersion).ConfigureAwait(false);
|
||||
var frame = await _db.Frames.GetAsync(copy.DropFrameId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.CopyPhoto, copy.FileName, n, journal.Copies.Count)).ConfigureAwait(false);
|
||||
var result = await FileAsync(frame, copy.Sha256).ConfigureAwait(false);
|
||||
var result = await FileAsync(frame, copy.Sha256, planned: copy.Sha256 is { Length: > 0 }).ConfigureAwait(false);
|
||||
journal.Committed[copy.DropFrameId] = result.FrameId;
|
||||
Save();
|
||||
context.Log(Loc.L("Archive.Log.MergeCopied", copy.FileName));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Copies a frame of the other into staging (hash-checked against <paramref name="expected"/>) and files it in the kept sequence.</summary>
|
||||
private async Task<IngestResult> FileAsync(Frame frame, string? expected)
|
||||
/// <summary>
|
||||
/// Copies a frame of the other into staging (hash-checked against <paramref name="expected"/>) and files it in the
|
||||
/// kept sequence. <paramref name="planned"/>: the plan knew the photo's content (else a tombstone of the kept sequence
|
||||
/// may refuse it although the plan listed no last copy: the plan is stale, never this job's to retry).
|
||||
/// </summary>
|
||||
private async Task<IngestResult> FileAsync(Frame frame, string? expected, bool planned)
|
||||
{
|
||||
Directory.CreateDirectory(_staging);
|
||||
var staged = Path.Combine(_staging, frame.Id.ToString("N") + Path.GetExtension(frame.FileName));
|
||||
@@ -251,9 +306,12 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
}
|
||||
catch (PhotoRemovedException)
|
||||
{
|
||||
// Deleted from the kept sequence since the plan: it would be a last copy the plan did not list.
|
||||
File.Delete(staged);
|
||||
throw Changed(_keepTitle);
|
||||
if (planned) throw Changed(_keepTitle); // deleted from the kept sequence since the plan: a last copy the plan did not list
|
||||
// A photo the plan could not compare by content (unhashed) that the kept sequence deleted: a last copy the
|
||||
// plan did not list. Retrying this journal would fail the same way: it goes, and the user plans again.
|
||||
ForgetJournal();
|
||||
throw new StaleCopyPlanException();
|
||||
}
|
||||
if (File.Exists(staged)) File.Delete(staged);
|
||||
return result;
|
||||
@@ -365,6 +423,7 @@ 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);
|
||||
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();
|
||||
@@ -380,18 +439,18 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
if (await HashAsync(keepPaths.FromRelative(frame.RelativePath)).ConfigureAwait(false) is { } sha) held.TryAdd(sha, frame.Id);
|
||||
}
|
||||
|
||||
var failed = new List<string>();
|
||||
var keepRemoved = (await _db.FrameRemovals.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false))
|
||||
.Select(r => r.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
var failed = new List<(Guid FrameId, string Sha256)>();
|
||||
foreach (var frame in dropFrames)
|
||||
{
|
||||
_ct.ThrowIfCancellationRequested();
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Verify, frame.FileName, ++done, total)).ConfigureAwait(false);
|
||||
if (journal.Verified.ContainsKey(frame.Id)) continue;
|
||||
var sha = await HashAsync(_dropPaths.FromRelative(frame.RelativePath)).ConfigureAwait(false);
|
||||
if (sha is null)
|
||||
{
|
||||
// Nothing on disk: nothing of it can be lost.
|
||||
continue;
|
||||
}
|
||||
if (journal.Verified.ContainsKey(frame.Id) || journal.Settled.Contains(frame.Id)) continue;
|
||||
// A usable frame (not flagged Missing) whose file is absent stops the merge (design §5d step 4): it is not
|
||||
// "nothing to lose" until a verify says so.
|
||||
var sha = await HashAsync(_dropPaths.FromRelative(frame.RelativePath)).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
|
||||
if (frame.Sha256 is { Length: > 0 } recorded && !string.Equals(recorded, sha, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
|
||||
if (held.TryGetValue(sha, out var keepFrame))
|
||||
@@ -399,26 +458,33 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
journal.Verified[frame.Id] = new MergeVerified(sha, keepFrame);
|
||||
continue;
|
||||
}
|
||||
if (frame.Sha256 is not { Length: > 0 })
|
||||
if (journal.Absent.Contains(sha))
|
||||
{
|
||||
// A last copy the plan listed (or left out by the user's choice).
|
||||
journal.Settled.Add(frame.Id);
|
||||
continue;
|
||||
}
|
||||
if (frame.Sha256 is not { Length: > 0 } && !keepRemoved.Contains(sha))
|
||||
{
|
||||
// Compared by size and time only, and another photo after all: filed in the kept sequence as a second version.
|
||||
var filed = await FileAsync(frame, sha).ConfigureAwait(false);
|
||||
var filed = await FileAsync(frame, sha, planned: false).ConfigureAwait(false);
|
||||
journal.SecondVersions.Add(frame.Id);
|
||||
journal.Verified[frame.Id] = new MergeVerified(sha, filed.FrameId);
|
||||
held.TryAdd(sha, filed.FrameId);
|
||||
Save();
|
||||
continue;
|
||||
}
|
||||
if (journal.Absent.Contains(sha)) continue;
|
||||
failed.Add(sha);
|
||||
failed.Add((frame.Id, sha));
|
||||
}
|
||||
if (failed.Count > 0)
|
||||
{
|
||||
// A photo held by another sequence of the index is not lost with the other; any other is. The kept
|
||||
// sequence's index rows prove nothing: its files were hashed again above and did not hold it.
|
||||
var others = await new CopySides(_db).HeldElsewhereAsync(failed, [journal.DropId, journal.KeepId], _ct).ConfigureAwait(false);
|
||||
var lost = failed.Count(s => !others.Contains(s));
|
||||
var others = await new CopySides(_db).HeldElsewhereAsync([.. failed.Select(f => f.Sha256)], [journal.DropId, journal.KeepId], _ct)
|
||||
.ConfigureAwait(false);
|
||||
var lost = failed.Where(f => !others.Contains(f.Sha256)).Select(f => f.Sha256).Distinct(StringComparer.Ordinal).Count();
|
||||
if (lost > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.VerifyFailed", lost));
|
||||
journal.Settled.AddRange(failed.Select(f => f.FrameId));
|
||||
}
|
||||
journal.VerifiedDropFramesVersion = drop.FramesVersion;
|
||||
Save();
|
||||
@@ -598,8 +664,16 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
}
|
||||
if (!journal.LinksMoved)
|
||||
{
|
||||
var moved = await new FoundCopyStore(_db).MoveToKeptAsync(journal.DropId, journal.KeepId, keepArchive.Id, journal.SessionKeys, journal.CopyId, _ct)
|
||||
.ConfigureAwait(false);
|
||||
MoveResult moved;
|
||||
try
|
||||
{
|
||||
moved = await new FoundCopyStore(_db).MoveToKeptAsync(journal.DropId, journal.KeepId, keepArchive.Id, journal.SessionKeys, journal.CopyId, _ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (CopyLinkTakenException ex) when (ex.Server is { } key)
|
||||
{
|
||||
throw CopyLinkTakenException.BothLinked(key, owner.Merger.ServerName(key));
|
||||
}
|
||||
foreach (var key in moved.SkippedKeys) context.Log(key);
|
||||
journal.LinksMoved = true;
|
||||
Save();
|
||||
@@ -617,6 +691,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.Unsent", _dropTitle));
|
||||
var expected = journal.VerifiedDropFramesVersion ?? throw Changed(_dropTitle);
|
||||
if (drop.FramesVersion != expected) throw Changed(_dropTitle);
|
||||
EnsureDropReadable(drop);
|
||||
await using (await owner.Archives.Writer.LockAsync(keepPaths, journal.KeepId, _ct).ConfigureAwait(false))
|
||||
{
|
||||
await EnsureVerifiedHeldAsync().ConfigureAwait(false);
|
||||
@@ -636,9 +711,18 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
context.Log(Loc.L("Archive.Log.MergeTrashed", _dropTitle));
|
||||
}
|
||||
|
||||
/// <summary>Every photo the verify found in the kept sequence is still there and usable (read under its lease).</summary>
|
||||
/// <summary>
|
||||
/// Every usable photo of the other was verified (held by the kept sequence, or a last copy the plan listed, or held by
|
||||
/// a third sequence), and every photo the verify found in the kept sequence is still there and usable (read under its lease).
|
||||
/// </summary>
|
||||
private async Task EnsureVerifiedHeldAsync()
|
||||
{
|
||||
// Every usable photo of the other was verified in this journal: a verify cut short (an absent drive, a moved
|
||||
// folder) never lets the rest through unread.
|
||||
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);
|
||||
|
||||
var frames = await ProcessingFrames.ListAsync(_db, journal.KeepId, _ct).ConfigureAwait(false);
|
||||
var byId = frames.Where(f => (f.Flags & CopySides.UnusableFlags) == 0).ToDictionary(f => f.Id);
|
||||
var hashes = byId.Values.Select(f => f.Sha256).OfType<string>().Select(s => s.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
@@ -87,6 +87,9 @@ internal sealed class MergeJournal
|
||||
/// <summary>Drop frames the verify found to be another photo than keep's (unhashed, same size and time) and filed as a second version.</summary>
|
||||
public List<Guid> SecondVersions { get; set; } = [];
|
||||
|
||||
/// <summary>Drop frames the verify found nothing of to lose: last copies the plan listed, or photos a third sequence holds.</summary>
|
||||
public List<Guid> Settled { get; set; } = [];
|
||||
|
||||
/// <summary>The dropped sequence's frames version the verify read: the trash refuses another.</summary>
|
||||
public int? VerifiedDropFramesVersion { get; set; }
|
||||
|
||||
|
||||
@@ -32,8 +32,14 @@ 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 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; }
|
||||
|
||||
internal ChronosDatabase Db => _db;
|
||||
|
||||
/// <summary>The name <paramref name="key"/> is shown by.</summary>
|
||||
internal string ServerName(string key) => ServerNames?.Invoke(key) is { Length: > 0 } name ? name : key;
|
||||
|
||||
internal ArchiveService Archives => _archives;
|
||||
|
||||
/// <summary>The handler of <see cref="JobKind.MergeSequences"/> jobs; register it on the <see cref="JobEngine"/>.</summary>
|
||||
@@ -99,6 +105,13 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
var here = await _sides.LocalAsync(keep, ct).ConfigureAwait(false);
|
||||
var there = await _sides.LocalAsync(drop, ct).ConfigureAwait(false);
|
||||
var comparison = CopyComparer.Compare(here, there);
|
||||
if (online && await HashOnlyThereAsync(comparison, there, dropPaths, ct).ConfigureAwait(false) is { } hashed)
|
||||
{
|
||||
// Compared by content now: a photo the kept sequence deleted reads Deleted here (a last copy when nothing else
|
||||
// holds it), never a copy the kept sequence's tombstone refuses.
|
||||
there = hashed;
|
||||
comparison = CopyComparer.Compare(here, there);
|
||||
}
|
||||
var steps = new List<PhotoStep>();
|
||||
var excluded = new List<string>();
|
||||
foreach (var photo in comparison.Photos)
|
||||
@@ -201,7 +214,8 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
var links = await _access.ListAsync("SELECT server, local_id FROM sync_links WHERE local_id = $1 OR local_id = $2", [keep, drop],
|
||||
r => (Server: r.GetString(0), Local: r.GetGuid(1)), ct).ConfigureAwait(false);
|
||||
var moved = links.Where(l => l.Local == drop).Select(l => l.Server).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList();
|
||||
if (links.GroupBy(l => l.Server, StringComparer.Ordinal).Any(g => g.Select(l => l.Local).Distinct().Count() > 1)) blocks.Add(CopyBlock.BothLinked);
|
||||
var bothLinked = links.GroupBy(l => l.Server, StringComparer.Ordinal).FirstOrDefault(g => g.Select(l => l.Local).Distinct().Count() > 1)?.Key;
|
||||
if (bothLinked is not null) blocks.Add(CopyBlock.BothLinked);
|
||||
|
||||
// The other goes to the trash.
|
||||
var trash = await _archives.Trash.PlanAsync([drop], null, ct, exceptJob).ConfigureAwait(false);
|
||||
@@ -220,7 +234,46 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
projects, sessionKeys, skippedKeys));
|
||||
return new MergePlan(copyId, keep, drop, choices, steps, lastCopies, renders, payload, changes, projects, sessionKeys, skippedKeys, moved, trash,
|
||||
copyBytes, free ?? -1, [.. blocks.Distinct()], keepRow.FramesVersion, keepRow.SettingsVersion, dropRow.FramesVersion, dropRow.SettingsVersion,
|
||||
fingerprint);
|
||||
fingerprint)
|
||||
{
|
||||
LinkNames = [.. moved.Select(ServerName)],
|
||||
BothLinkedServer = bothLinked is null ? null : ServerName(bothLinked),
|
||||
DeletedInOther = comparison.Photos.Count(p => p.Class == PhotoClass.DeletedThere),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The other's unhashed photos only it holds, hashed now (in memory: a dry run writes nothing); null when there are none.
|
||||
/// Matched by size and time only they would be copied blindly, even a photo whose content the kept sequence deleted.
|
||||
/// </summary>
|
||||
private async Task<CopySideInput?> HashOnlyThereAsync(CopyComparisonResult comparison, CopySideInput there, ArchivePaths dropPaths, CancellationToken ct)
|
||||
{
|
||||
var keys = comparison.Photos.Where(p => p.Class == PhotoClass.OnlyThere && p.Key.StartsWith(CopyComparer.UnhashedPrefix, StringComparison.Ordinal))
|
||||
.Select(p => p.Key).ToHashSet(StringComparer.Ordinal);
|
||||
if (keys.Count == 0) return null;
|
||||
var photos = new List<CopyPhotoInput>(there.Photos.Count);
|
||||
var changed = false;
|
||||
foreach (var photo in there.Photos)
|
||||
{
|
||||
if (photo.Unusable || photo.Sha256 is { Length: > 0 } || !keys.Contains(CopyComparer.UnhashedKey(photo.Size, photo.CapturedAt, photo.FrameId))
|
||||
|| await _db.Frames.GetAsync(photo.FrameId, ct).ConfigureAwait(false) is not { } frame)
|
||||
{
|
||||
photos.Add(photo);
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
var sha = await ContentHash.Sha256Async(dropPaths.FromRelative(frame.RelativePath), null, ct).ConfigureAwait(false);
|
||||
photos.Add(photo with { Sha256 = sha.ToLowerInvariant() });
|
||||
changed = true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Unreadable now: left as it is (the job's copy fails on it and says which file).
|
||||
photos.Add(photo);
|
||||
}
|
||||
}
|
||||
return changed ? there with { Photos = photos } : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -260,18 +313,26 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
{
|
||||
var keep = await _db.Sequences.GetAsync(plan.KeepId, ct).ConfigureAwait(false);
|
||||
var drop = await _db.Sequences.GetAsync(plan.DropId, ct).ConfigureAwait(false);
|
||||
var (keepTitle, dropTitle) = (keep?.DisplayTitle ?? string.Empty, drop?.DisplayTitle ?? string.Empty);
|
||||
return plan.Blocks[0] switch
|
||||
return BlockText(plan, plan.Blocks[0], keep?.DisplayTitle ?? string.Empty, drop?.DisplayTitle ?? string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sentence of <paramref name="block"/> of a merge plan, the one the dialog shows and the job fails with: the kept
|
||||
/// sequence for space, the other for where it lies and its trash, the server both are linked to by its name.
|
||||
/// </summary>
|
||||
public static string BlockText(MergePlan plan, CopyBlock block, string keepTitle, string dropTitle, int unchosen = 1)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
return block switch
|
||||
{
|
||||
CopyBlock.Busy => Loc.L("Errors.Copies.Busy"),
|
||||
CopyBlock.ArchiveOffline => Loc.L("Errors.Copies.ArchiveOffline", dropTitle),
|
||||
CopyBlock.FolderMoved => Loc.L("Errors.Copies.FolderMoved", dropTitle),
|
||||
CopyBlock.ArchiveOffline or CopyBlock.FolderMoved or CopyBlock.ChangedFile => Loc.L("Errors.Copies." + block, dropTitle),
|
||||
CopyBlock.NoSpace => Loc.L("Errors.Copies.NoSpace", keepTitle, Size(plan.CopyBytes + SpaceReserve)),
|
||||
CopyBlock.BothLinked => Loc.L("Errors.Copies.BothLinked", string.Empty),
|
||||
CopyBlock.BothLinked => Loc.L("Errors.Copies.BothLinked", plan.BothLinkedServer ?? string.Empty),
|
||||
CopyBlock.UnsentWorkspace => Loc.L("Errors.Copies.Unsent", dropTitle),
|
||||
CopyBlock.TrashBlocked => Loc.L("Errors.Copies.TrashBlocked", dropTitle,
|
||||
plan.Trash.Blocked.Select(b => Loc.L("Archive.Delete.Reason." + b.Reason)).FirstOrDefault() ?? string.Empty),
|
||||
CopyBlock.DetailsUnchosen => Loc.Plural("Errors.Copies.DetailsUnchosen", 1),
|
||||
CopyBlock.DetailsUnchosen => Loc.Plural("Errors.Copies.DetailsUnchosen", Math.Max(1, unchosen)),
|
||||
CopyBlock.KeptUnchosen => Loc.L("Errors.Copies.KeptUnchosen"),
|
||||
_ => Loc.L("Errors.Copies.StalePlan"),
|
||||
};
|
||||
|
||||
@@ -167,9 +167,13 @@ public sealed record FoundCopy
|
||||
/// <summary>Shown in Server › Matches: everything but the plain links every upload or download makes.</summary>
|
||||
public bool IsListed => Evidence != CopyEvidence.Link || State is not CopyState.Linked || RemoteGone || Score.DeletedThere > 0;
|
||||
|
||||
/// <summary>Draws the chip in warning colours, counts in the Server rail badge and gives the Library card its status.</summary>
|
||||
/// <summary>
|
||||
/// Draws the chip in warning colours, counts in the Server rail badge and gives the Library card its status. Photos
|
||||
/// deleted here do not: a local cull is the user's own act, and Compare › Photos › Deleted here offers the server's
|
||||
/// side of it.
|
||||
/// </summary>
|
||||
public bool NeedsAttention => State == CopyState.Candidate || (RemoteGone && State != CopyState.KeptApart)
|
||||
|| (State is CopyState.Integrated or CopyState.Linked && (Score.DeletedThere > 0 || Score.DeletedHere > 0));
|
||||
|| (State is CopyState.Integrated or CopyState.Linked && Score.DeletedThere > 0);
|
||||
|
||||
/// <summary>Whether <paramref name="sequenceId"/> is one of the pair's local sequences.</summary>
|
||||
public bool Names(Guid sequenceId) => LocalId == sequenceId || OtherId == sequenceId;
|
||||
|
||||
@@ -97,6 +97,15 @@ public sealed record MergePlan(Guid CopyId, Guid KeepId, Guid DropId, MergeChoic
|
||||
int KeepFramesVersion, int KeepSettingsVersion, int DropFramesVersion, int DropSettingsVersion, string Fingerprint)
|
||||
{
|
||||
public bool CanApply => Blocks.Count == 0;
|
||||
|
||||
/// <summary><see cref="Links"/> by the names their servers are shown by.</summary>
|
||||
public IReadOnlyList<string> LinkNames { get; init; } = [];
|
||||
|
||||
/// <summary>The name of the server both sequences are linked to (<see cref="CopyBlock.BothLinked"/>); null otherwise.</summary>
|
||||
public string? BothLinkedServer { get; init; }
|
||||
|
||||
/// <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>
|
||||
@@ -189,6 +198,16 @@ public sealed class CopyLinkTakenException : InvalidOperationException
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>The server key both sequences of a merge are linked to (<see cref="BothLinked"/>); null otherwise.</summary>
|
||||
public string? Server { get; private init; }
|
||||
|
||||
/// <summary>The refusal for <paramref name="title"/> already linked to another sequence of <paramref name="server"/>.</summary>
|
||||
public static CopyLinkTakenException For(string title, string server) => new(Loc.L("Errors.Copies.LinkTaken", title, server));
|
||||
|
||||
/// <summary>
|
||||
/// The refusal of a merge whose two sequences are both linked to sequences of the server <paramref name="key"/>, worded
|
||||
/// with <paramref name="name"/> (the caller resolves the key to the name the server is shown by; the key by default).
|
||||
/// </summary>
|
||||
public static CopyLinkTakenException BothLinked(string key, string? name = null) =>
|
||||
new(Loc.L("Errors.Copies.BothLinked", name ?? key)) { Server = key };
|
||||
}
|
||||
@@ -5,6 +5,9 @@ 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);
|
||||
|
||||
/// <summary>
|
||||
/// The two sides of a comparison as <see cref="CopyComparer"/> reads them (owner review 6, #73; design §4.2): a local
|
||||
/// sequence's frames and tombstones, a server sequence's manifest with its frames' capture times, and the last-copy check
|
||||
@@ -48,6 +51,27 @@ public sealed class CopySides(ChronosDatabase db)
|
||||
manifest.Removed ?? []);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The photos one sequence keeps in two versions (owner Q3, design §4.1 Versions): a sub-second capture instant holding
|
||||
/// exactly two usable, hashed frames of different content, as a Union merge or Integrate leaves them. Read from the
|
||||
/// frames themselves, so they stay listed after the pair that made them is gone; each pair once, in index order.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<PhotoVersions>> VersionsAsync(Guid sequenceId, CancellationToken ct)
|
||||
{
|
||||
var frames = await Processing.SequenceFrames.ListAsync(_db, sequenceId, ct).ConfigureAwait(false);
|
||||
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)))
|
||||
{
|
||||
if (group.Key % 1000 == 0) continue;
|
||||
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()));
|
||||
}
|
||||
return [.. result.OrderBy(v => frames.First(f => f.Id == v.FirstFrameId).Index)];
|
||||
}
|
||||
|
||||
/// <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.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Data.Sync;
|
||||
@@ -349,7 +348,7 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
|
||||
var linked = await inner.ListAsync("SELECT server, local_id FROM sync_links WHERE local_id = $1 OR local_id = $2", [drop, keep],
|
||||
r => (Server: r.GetString(0), Local: r.GetGuid(1)), ct).ConfigureAwait(false);
|
||||
var both = linked.GroupBy(l => l.Server, StringComparer.Ordinal).FirstOrDefault(g => g.Select(l => l.Local).Distinct().Count() > 1);
|
||||
if (both is not null) throw new CopyLinkTakenException(Loc.L("Errors.Copies.BothLinked", both.Key));
|
||||
if (both is not null) throw CopyLinkTakenException.BothLinked(both.Key);
|
||||
|
||||
// (1) Session keys.
|
||||
var (keys, skipped) = (0, new List<string>());
|
||||
|
||||
@@ -158,7 +158,15 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
var copy = await copies.GetAsync(parameters.CopyId, ct).ConfigureAwait(false);
|
||||
if (copy is not { State: CopyState.Integrating } || copy.JobId != context.Job.Id) throw new StaleCopyPlanException();
|
||||
if (copy is null || copy.JobId != context.Job.Id) throw new StaleCopyPlanException();
|
||||
if (copy.State != CopyState.Integrating)
|
||||
{
|
||||
// A retry after a failure before the journal was written: the pair kept this job's id, nothing else touched it.
|
||||
if (!await copies.SetStateAsync(copy.Id, copy.State, CopyState.Integrating, new CopyAnswer(null, null, context.Job.Id, null, DateTimeOffset.UtcNow), ct)
|
||||
.ConfigureAwait(false))
|
||||
throw new StaleCopyPlanException();
|
||||
copy = await copies.GetAsync(parameters.CopyId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
|
||||
}
|
||||
var planContext = (parameters.Context ?? IntegrateJobContext.Permissive).ToPlanContext();
|
||||
var plan = await planner.PlanAsync(remote, copy, parameters.Choices, planContext, context.Job.Id, ct).ConfigureAwait(false);
|
||||
if (!plan.CanApply) throw new InvalidOperationException(await planner.BlockMessageAsync(plan, remote, ct).ConfigureAwait(false));
|
||||
|
||||
@@ -219,9 +219,14 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
|
||||
internal async Task<string> BlockMessageAsync(IntegratePlan plan, ISyncRemote remote, CancellationToken ct)
|
||||
{
|
||||
var local = await Db.Sequences.GetAsync(plan.LocalId, ct).ConfigureAwait(false);
|
||||
var title = local?.DisplayTitle ?? string.Empty;
|
||||
var server = plan.Context?.ServerName ?? remote.Server;
|
||||
return plan.Blocks[0] switch
|
||||
return BlockText(plan, plan.Blocks[0], local?.DisplayTitle ?? string.Empty, plan.Context?.ServerName ?? remote.Server);
|
||||
}
|
||||
|
||||
/// <summary>The sentence of <paramref name="block"/> of an Integrate plan, the one the dialog shows and the job fails with.</summary>
|
||||
public static string BlockText(IntegratePlan plan, CopyBlock block, string title, string server, int unchosen = 1)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
return block switch
|
||||
{
|
||||
CopyBlock.NeedsNewerServer => Loc.L("Errors.Copies.NeedsNewerServer", server),
|
||||
CopyBlock.NoUploadRight => Loc.L("Errors.Copies.NoUploadRight"),
|
||||
@@ -231,9 +236,9 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
|
||||
CopyBlock.LinkTaken => Loc.L("Errors.Copies.LinkTaken", title, server),
|
||||
CopyBlock.NoSpace => Loc.L("Errors.Copies.NoSpace", title, Size(plan.FetchBytes + SpaceReserve)),
|
||||
CopyBlock.Busy => Loc.L("Errors.Copies.Busy"),
|
||||
CopyBlock.ArchiveOffline => Loc.L("Errors.Copies.ArchiveOffline", title),
|
||||
CopyBlock.FolderMoved => Loc.L("Errors.Copies.FolderMoved", title),
|
||||
CopyBlock.DetailsUnchosen => Loc.Plural("Errors.Copies.DetailsUnchosen", 1),
|
||||
CopyBlock.ArchiveOffline or CopyBlock.FolderMoved or CopyBlock.ChangedFile => Loc.L("Errors.Copies." + block, title),
|
||||
CopyBlock.UnsentWorkspace => Loc.L("Errors.Copies.Unsent", title),
|
||||
CopyBlock.DetailsUnchosen => Loc.Plural("Errors.Copies.DetailsUnchosen", Math.Max(1, unchosen)),
|
||||
_ => Loc.L("Errors.Copies.StalePlan"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -770,7 +770,8 @@ public sealed class SyncService
|
||||
/// <summary>
|
||||
/// Pairs one 404 marked (design §6.3): a remote listed again is cleared at once and asked about again; one still unlisted
|
||||
/// is asked for once more, no sooner than <see cref="GoneRecheck"/> after it was marked, and a second 404 there makes the
|
||||
/// pair read "deleted on server". The links of those pairs are gone already (the first 404 forgot them).
|
||||
/// pair read "deleted on server". A refresh's first 404 forgot the link (the pair is asked about again); a job's 404
|
||||
/// kept it (the pair stays Linked or Integrated).
|
||||
/// </summary>
|
||||
private async Task AskGoneAgainAsync(ISyncRemote remote, IReadOnlyList<SequenceDto> listing, Guid refreshId, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -804,9 +805,12 @@ public sealed class SyncService
|
||||
async Task BackAsync(FoundCopy pair, Guid remoteId)
|
||||
{
|
||||
await Copies.ClearRemoteGoneAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
|
||||
// No link joins the two any more: the user is asked again.
|
||||
if (pair.State is CopyState.Linked or CopyState.Integrated)
|
||||
await Copies.SetStateAsync(pair.Id, pair.State, CopyState.Candidate, null, cancellationToken).ConfigureAwait(false);
|
||||
if (pair.State is not (CopyState.Linked or CopyState.Integrated)) return;
|
||||
// A 404 a job saw (a transfer, an Integrate) keeps the link: the pair stays as it was. A link the refresh's 404
|
||||
// forgot joins nothing any more: the user is asked again.
|
||||
var link = await _links.GetAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
|
||||
if (link?.LocalId == pair.LocalId) return;
|
||||
await Copies.SetStateAsync(pair.Id, pair.State, CopyState.Candidate, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user