feat(import): import a whole folder as one sequence per format

Owner review 2, R9: Import › Folder… gains a "Group" choice for picked
folders: Sessions (as before) or Whole folder. A whole folder, with its
subfolders when Subfolders is on, becomes one sequence per file format;
camera bodies and pauses are ignored, while RAW+JPEG of the same shots
stays two sequences so no frame is ever doubled. Only the user's splits
break it, and Merge joins a split part back.

The planner implements it (ImportOptions.Grouping, Core, Linux-tested):
the session key is "folder-" plus a hash of this PC's name, the full
path and the format, so an interrupted or repeated import continues the
same sequence; the default title is the folder's name. The plan shows
one row per format with the format and the number of cameras. Cards and
drives always import by sessions; the choice is not part of a card
profile and a folder starts on Sessions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-26 22:00:55 +01:00
1 parent 5209579631
commit 445dfd41a3
14 files changed
+419 -26

No files matched your search

+8 -1
View File
@@ -15,13 +15,18 @@ public enum ImportDestinationKind
/// <summary>
/// The Import form (Import.html): scan, sessions, names, duplicates and after-import choices. Remembered per card as
/// its <see cref="CardProfile"/>; a session gap of 0 minutes in a profile means "do not split into sessions".
/// its <see cref="CardProfile"/>; a session gap of 0 minutes in a profile means "do not split into sessions". The
/// grouping is not in a profile: a card always imports by sessions, and a picked folder starts with them.
/// </summary>
public sealed record ImportChoices
{
public ImportDestinationKind Destination { get; init; } = ImportDestinationKind.Archive;
public string? FolderPath { get; init; }
public bool IncludeSubfolders { get; init; } = true;
/// <summary>"Group" (a picked folder only): its sessions, or the whole folder as one sequence per format.</summary>
public ImportGrouping Grouping { get; init; } = ImportGrouping.Sessions;
public bool SplitSessions { get; init; } = true;
public int GapMinutes { get; init; } = 45;
public int MinimumFrames { get; init; } = 8;
@@ -78,6 +83,7 @@ public sealed record ImportChoices
IncludeSubfolders = IncludeSubfolders,
VerifyCopies = VerifyCopies,
Duplicates = Duplicates,
Grouping = Grouping,
Titles = titles ?? new Dictionary<string, string>(),
SplitBefore = splits ?? new HashSet<string>(),
MergeAt = merges ?? new HashSet<string>(),
@@ -88,6 +94,7 @@ public sealed record ImportChoices
previous.Destination != Destination
|| (Destination == ImportDestinationKind.Folder && !string.Equals(previous.FolderPath, FolderPath, StringComparison.OrdinalIgnoreCase))
|| previous.IncludeSubfolders != IncludeSubfolders
|| previous.Grouping != Grouping
|| previous.SplitSessions != SplitSessions
|| (SplitSessions && previous.GapMinutes != GapMinutes)
|| previous.MinimumFrames != MinimumFrames
+33 -7
View File
@@ -1,4 +1,5 @@
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Archiving;
using Chronos.Core.Import;
using Chronos.Core.Localization;
@@ -40,7 +41,8 @@ public sealed record PlanTotals(int Sessions, int Photos, int CopyCount, long Co
}
/// <summary>One row of the session table: what the planner grouped and where it goes.</summary>
/// <param name="DefaultTitle">Title the sequence gets when the user types none (its folder name).</param>
/// <param name="Title">The title the user typed; null when none.</param>
/// <param name="DefaultTitle">Title the sequence gets when the user types none (a whole folder's name, else its folder name).</param>
/// <param name="IsNew">The session starts a new sequence (false: it continues one imported before).</param>
/// <param name="FirstPath">Card path of the session's first photo (where a merge joins it to the previous session).</param>
/// <param name="MergesInto">Number of the earlier session of the same camera and format it can merge into; null for none.</param>
@@ -116,10 +118,19 @@ public static class ImportPlans
],
};
/// <summary>The plan with the typed session titles (when no template uses <c>{title}</c>, so no name changes).</summary>
/// <summary>
/// The plan with the typed session titles (when no template uses <c>{title}</c>, so no name changes); a session
/// without one keeps its default title (a whole folder's name).
/// </summary>
public static ImportPlan WithTitles(ImportPlan plan, IReadOnlyDictionary<string, string> titles) => plan with
{
Sessions = [.. plan.Sessions.Select(s => s with { Title = titles.TryGetValue(s.SessionKey, out var t) && !string.IsNullOrWhiteSpace(t) ? t.Trim() : null })],
Sessions =
[
.. plan.Sessions.Select(s => s with
{
Title = titles.TryGetValue(s.SessionKey, out var t) && !string.IsNullOrWhiteSpace(t) ? t.Trim() : s.DefaultTitle,
}),
],
};
/// <param name="existingFolders">Folders of sequences already in the archive (a session there continues it).</param>
@@ -135,20 +146,35 @@ public static class ImportPlans
ImportDestinationKind.Folder => s.Folder,
_ => Loc.L(isNew ? "Import.Session.New" : "Import.Session.Adds", s.Folder),
};
return new PlanSessionRow(s.Number, s.SessionKey, s.Title, leaf, TimeText(s), FramesText(s), Formatting.Bytes(s.Items.Sum(i => i.Size)),
PathTemplate.CameraName(s.CameraMake, s.CameraModel), target, isNew, s.Items.Count > 0 ? s.Items[0].SourcePath : string.Empty,
// The field shows a typed title only; the default (a whole folder's name, else the folder's) is its placeholder.
var typed = s.Title is { } title && title != s.DefaultTitle ? title : null;
return new PlanSessionRow(s.Number, s.SessionKey, typed, s.DefaultTitle ?? leaf, TimeText(s), FramesText(s),
Formatting.Bytes(s.Items.Sum(i => i.Size)), CameraText(plan, s), target, isNew, s.Items.Count > 0 ? s.Items[0].SourcePath : string.Empty,
MergeTarget(plan, s)?.Number);
}),
];
/// <summary>
/// "Canon EOS R5"; for a whole folder, one row per format, the format too and how many bodies took the photos:
/// "Canon EOS R5 · CR3", "2 cameras · JPEG".
/// </summary>
private static string CameraText(ImportPlan plan, PlannedSession s)
{
var camera = PathTemplate.CameraName(s.CameraMake, s.CameraModel);
if (plan.Grouping != ImportGrouping.WholeFolder) return camera;
var bodies = s.Cameras > 1 ? Loc.Plural("Import.Session.Cameras", s.Cameras) : camera;
return string.Join(Loc.Separator, new[] { bodies, FormatNames.Of(s.Format) }.Where(t => t.Length > 0));
}
/// <summary>
/// The session <paramref name="session"/> joins when the user merges it (BRIEF §13): the one before it of the same
/// camera body and format, whose last photo precedes its first; sessions of other cameras or formats never merge.
/// A whole folder's parts (split by the user) join the part before them of the same format, whatever the camera.
/// </summary>
public static PlannedSession? MergeTarget(ImportPlan plan, PlannedSession session) =>
plan.Sessions.TakeWhile(s => !ReferenceEquals(s, session))
.LastOrDefault(s => s.CameraMake == session.CameraMake && s.CameraModel == session.CameraModel && s.CameraSerial == session.CameraSerial
&& s.Format == session.Format);
.LastOrDefault(s => s.Format == session.Format && (plan.Grouping == ImportGrouping.WholeFolder
|| (s.CameraMake == session.CameraMake && s.CameraModel == session.CameraModel && s.CameraSerial == session.CameraSerial)));
/// <summary>"Show plan": every file and where it goes, with the conflicts the plan resolved or reports.</summary>
public static PlanDetails Details(ImportPlan plan, ImportDestinationKind destination, bool verify)
+13 -3
View File
@@ -355,17 +355,27 @@
</WrapPanel>
</HeaderedContentControl>
<!-- A picked folder only: its sessions, or the whole folder as one sequence per format. -->
<HeaderedContentControl Style="{StaticResource Import.Row}" Header="{l:Loc Import.Label.Group}"
Visibility="{Binding CanGroupFolder, Converter={StaticResource BoolToVisibility}}">
<WrapPanel>
<RadioButton Content="{l:Loc Import.Group.Sessions}" IsChecked="{Binding GroupBySessions}" ToolTip="{l:Loc Tooltips.Import.GroupSessions}" />
<RadioButton Content="{l:Loc Import.Group.WholeFolder}" IsChecked="{Binding GroupWholeFolder}" ToolTip="{l:Loc Tooltips.Import.WholeFolder}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Import.Row}" Header="{l:Loc Import.Label.Scan}">
<WrapPanel>
<CheckBox Content="{l:Loc Import.Scan.Subfolders}" IsChecked="{Binding IncludeSubfolders}" ToolTip="{l:Loc Tooltips.Import.Subfolders}" />
<CheckBox Content="{l:Loc Import.Scan.Sessions}" IsChecked="{Binding SplitSessions}" ToolTip="{l:Loc Tooltips.Import.Sessions}" />
<StackPanel Orientation="Horizontal" Style="{StaticResource Import.Choice}" IsEnabled="{Binding SplitSessions}">
<CheckBox Content="{l:Loc Import.Scan.Sessions}" IsChecked="{Binding SplitSessions}" IsEnabled="{Binding SessionsApply}"
ToolTip="{Binding SessionsToolTip}" />
<StackPanel Orientation="Horizontal" Style="{StaticResource Import.Choice}" IsEnabled="{Binding GapApplies}">
<TextBlock Text="{l:Loc Import.Scan.Gap}" Style="{StaticResource Text.Unit}" />
<TextBox x:Name="GapBox" Style="{StaticResource TextBox.Small}" Text="{Binding GapMinutes.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding GapMinutes}" ToolTip="{Binding GapMinutes.ToolTip}" AutomationProperties.Name="{l:Loc Import.Scan.GapName}" />
<TextBlock Text="{l:Loc Import.Scan.Minutes}" Style="{StaticResource Text.Unit}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Style="{StaticResource Import.Choice}">
<StackPanel Orientation="Horizontal" Style="{StaticResource Import.Choice}" IsEnabled="{Binding SessionsApply}">
<TextBlock Text="{l:Loc Import.Scan.Minimum}" Style="{StaticResource Text.Unit}" />
<TextBox Style="{StaticResource TextBox.Small}" Text="{Binding MinimumFrames.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding MinimumFrames}" ToolTip="{Binding MinimumFrames.ToolTip}" AutomationProperties.Name="{l:Loc Import.Scan.MinimumName}" />
+56 -5
View File
@@ -120,8 +120,10 @@ public sealed class ImportViewModel : SectionViewModel
// The path is checked only while Folder is the destination; typing one chooses Folder, as "…" does.
FolderPath = new EditableField(string.Empty, text => IsFolderDestination ? ArchiveLocations.Validate(text) : null,
text => Choices = _choices with { FolderPath = text, Destination = ImportDestinationKind.Folder }, () => Loc.L("Tooltips.Import.FolderPath"));
GapMinutes = NumberField(1, 24 * 60, () => _choices.GapMinutes, n => Choices = _choices with { GapMinutes = n }, "Tooltips.Import.Gap");
MinimumFrames = NumberField(1, 1000, () => _choices.MinimumFrames, n => Choices = _choices with { MinimumFrames = n }, "Tooltips.Import.MinimumFrames");
GapMinutes = NumberField(1, 24 * 60, () => _choices.GapMinutes, n => Choices = _choices with { GapMinutes = n },
() => SessionToolTip("Tooltips.Import.Gap"));
MinimumFrames = NumberField(1, 1000, () => _choices.MinimumFrames, n => Choices = _choices with { MinimumFrames = n },
() => SessionToolTip("Tooltips.Import.MinimumFrames"));
FolderTemplate = new EditableField(_choices.FolderTemplate, t => NamingPreview.Validate(t, isFolder: true),
t => Choices = _choices with { FolderTemplate = t }, () => Loc.L("Tooltips.Import.FolderTemplate"));
FileTemplate = new EditableField(_choices.FileTemplate, t => NamingPreview.Validate(t, isFolder: false),
@@ -264,6 +266,11 @@ public sealed class ImportViewModel : SectionViewModel
if (previous == value) return;
_choices = value;
if (value.Destination != previous.Destination) FolderPath.Refresh();
if (value.Grouping != previous.Grouping)
{
GapMinutes.Refresh();
MinimumFrames.Refresh();
}
OnPropertyChanged(string.Empty);
if (value.NeedsNewPlan(previous) || (value.TitlesChangeNames != previous.TitlesChangeNames && _titles.Count > 0)) SchedulePlan();
else ApplyPlan();
@@ -320,6 +327,37 @@ public sealed class ImportViewModel : SectionViewModel
set => Choices = _choices with { IncludeSubfolders = value };
}
/// <summary>"Group" is offered for a picked folder only (BRIEF §12.4): a card or a drive always splits into sessions.</summary>
public bool CanGroupFolder => _selected?.Kind == SourceKind.Folder;
public bool GroupBySessions
{
get => !IsWholeFolder;
set
{
if (value) SetGrouping(ImportGrouping.Sessions);
}
}
/// <summary>The picked folder is one sequence per format: camera bodies and pauses are ignored.</summary>
public bool GroupWholeFolder
{
get => IsWholeFolder;
set
{
if (value && CanGroupFolder) SetGrouping(ImportGrouping.WholeFolder);
}
}
private bool IsWholeFolder => CanGroupFolder && _choices.Grouping == ImportGrouping.WholeFolder;
/// <summary>Sessions, their gap and their minimum do not apply to a whole folder.</summary>
public bool SessionsApply => !IsWholeFolder;
public bool GapApplies => SessionsApply && _choices.SplitSessions;
public string SessionsToolTip => SessionToolTip("Tooltips.Import.Sessions");
public bool SplitSessions
{
get => _choices.SplitSessions;
@@ -340,6 +378,18 @@ public sealed class ImportViewModel : SectionViewModel
public IReadOnlyList<TokenItem> Tokens { get; }
public ICommand InsertTokenCommand { get; }
private void SetGrouping(ImportGrouping grouping)
{
if (_choices.Grouping == grouping) return;
// Splits and merges were made on the other grouping's sessions.
_splits.Clear();
_merges.Clear();
Choices = _choices with { Grouping = grouping };
}
/// <summary>A session control's tooltip, or why it does not apply to a whole folder.</summary>
private string SessionToolTip(string key) => IsWholeFolder ? Loc.L("Import.Blocked.WholeFolder") : Loc.L(key);
/// <summary>The view tells which template field the "{ }" menu writes into.</summary>
public void SetActiveTemplate(bool folder) => _activeTemplateIsFolder = folder;
@@ -966,7 +1016,8 @@ public sealed class ImportViewModel : SectionViewModel
{
if (!cts.IsCancellationRequested) SetStatus(ImportPhase.Planning, Loc.Plural("Import.Status.ReadingCount", n));
});
var options = _choices.ToOptions(_titles, _splits, _merges);
// A card or a drive is always planned by sessions, whatever a folder chose before.
var options = _choices.ToOptions(_titles, _splits, _merges) with { Grouping = IsWholeFolder ? ImportGrouping.WholeFolder : ImportGrouping.Sessions };
var cardId = _selected.Kind == SourceKind.Card ? await RegisteredCardIdAsync() : null;
try
{
@@ -1456,11 +1507,11 @@ public sealed class ImportViewModel : SectionViewModel
else dispatcher.BeginInvoke(action);
}
private static EditableField NumberField(int min, int max, Func<int> current, Action<int> commit, string toolTipKey) =>
private static EditableField NumberField(int min, int max, Func<int> current, Action<int> commit, Func<string> toolTip) =>
new(current().ToString(Loc.Culture),
text => int.TryParse(text.Trim(), NumberStyles.Integer, Loc.Culture, out var n) && n >= min && n <= max
? null
: Loc.L("Errors.Number.Range", min.ToString("N0", Loc.Culture), max.ToString("N0", Loc.Culture)),
text => commit(int.Parse(text.Trim(), NumberStyles.Integer, Loc.Culture)),
() => Loc.L(toolTipKey));
toolTip);
}
+35 -1
View File
@@ -14,6 +14,19 @@ public enum DuplicatePolicy
ImportAgain,
}
/// <summary>How the planner turns the photos of a source into sequences (BRIEF §12.4, §13).</summary>
public enum ImportGrouping
{
/// <summary>One session per camera body and file format, split where the pause between two photos exceeds the gap.</summary>
Sessions,
/// <summary>
/// The whole source (a folder picked on this PC) is one sequence per file format: camera bodies and pauses are
/// ignored. RAW+JPEG of the same shots stays two sequences, so no frame is ever doubled.
/// </summary>
WholeFolder,
}
/// <summary>Card import settings (BRIEF §12.4, §13); the defaults are the brief's.</summary>
public sealed record ImportOptions
{
@@ -25,6 +38,9 @@ public sealed record ImportOptions
public bool VerifyCopies { get; init; } = true;
public DuplicatePolicy Duplicates { get; init; } = DuplicatePolicy.Skip;
/// <summary>Sessions, or the whole source as one sequence per format (the session gap and minimum then do not apply).</summary>
public ImportGrouping Grouping { get; init; } = ImportGrouping.Sessions;
/// <summary>Card paths where the user split a session (a new session starts at that photo).</summary>
public IReadOnlySet<string> SplitBefore { get; init; } = new HashSet<string>();
@@ -65,7 +81,10 @@ public sealed record PlannedItem
public string? Sha256 { get; init; }
}
/// <summary>A session of the plan: one camera body and file format, one sequence in the archive.</summary>
/// <summary>
/// A session of the plan: one camera body and file format (a whole folder: one file format), one sequence in the
/// archive. Its camera is the one of its first photo.
/// </summary>
public sealed record PlannedSession
{
/// <summary>1-based, in order of start time across the import.</summary>
@@ -78,6 +97,10 @@ public sealed record PlannedSession
public string? CameraMake { get; init; }
public string? CameraModel { get; init; }
public string? CameraSerial { get; init; }
/// <summary>Camera bodies among its photos: 1 for a session, possibly more for a whole folder.</summary>
public int Cameras { get; init; } = 1;
public ImageFileFormat Format { get; init; }
public DateTime Start { get; init; }
public DateTime End { get; init; }
@@ -86,6 +109,13 @@ public sealed record PlannedSession
public required string Folder { get; init; }
public string? Title { get; init; }
/// <summary>
/// The title when the user types none: the source folder's name for a whole folder; null names the sequence
/// after its destination folder.
/// </summary>
public string? DefaultTitle { get; init; }
public IReadOnlyList<PlannedItem> Items { get; init; } = [];
}
@@ -99,6 +129,10 @@ public sealed record ImportPlan
public required string SourceRoot { get; init; }
public required string DestinationRoot { get; init; }
public DateTimeOffset Created { get; init; }
/// <summary>How the photos were grouped into <see cref="Sessions"/>.</summary>
public ImportGrouping Grouping { get; init; }
public IReadOnlyList<PlannedSession> Sessions { get; init; } = [];
public IReadOnlyList<ImportProblem> Problems { get; init; } = [];
+55 -9
View File
@@ -2,6 +2,7 @@ using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Archiving;
using Chronos.Core.Imaging;
using Chronos.Core.Naming;
namespace Chronos.Core.Import;
@@ -33,16 +34,29 @@ public static class ImportPlanner
{
var folderTemplate = PathTemplate.Parse(options.FolderTemplate);
var fileTemplate = PathTemplate.Parse(options.FileTemplate);
var wholeFolder = options.Grouping == ImportGrouping.WholeFolder;
var folderName = wholeFolder ? FolderName(sourceRoot) : null;
var drafts = new List<(string Key, List<CardPhoto> Photos)>();
foreach (var body in photos.GroupBy(BodyKey, StringComparer.Ordinal))
// A whole folder groups by file format alone, never by camera body: RAW+JPEG of the same shots must stay two
// sequences, or each frame would appear twice in one.
Func<CardPhoto, string> groupKey = wholeFolder ? FormatKey : BodyKey;
foreach (var group in photos.GroupBy(groupKey, StringComparer.Ordinal))
{
var ordered = body.OrderBy(p => p.CaptureTime).ThenBy(p => p.File.RelativePath, StringComparer.Ordinal).ToList();
var ranges = SessionSplitter.Split(ordered.ConvertAll(p => p.CaptureTime), options.SessionGap, options.MinimumSessionFrames,
i => options.SplitBefore.Contains(ordered[i].File.RelativePath) ? true : options.MergeAt.Contains(ordered[i].File.RelativePath) ? false : null);
foreach (var range in ranges)
var ordered = group.OrderBy(p => p.CaptureTime).ThenBy(p => p.File.RelativePath, StringComparer.Ordinal).ToList();
var times = ordered.ConvertAll(p => p.CaptureTime);
bool? UserBreak(int i) =>
options.SplitBefore.Contains(ordered[i].File.RelativePath) ? true : options.MergeAt.Contains(ordered[i].File.RelativePath) ? false : null;
// Only the user's splits break a whole folder: no pause starts a session and no group is too small to stand.
var ranges = wholeFolder
? SessionSplitter.Split(times, TimeSpan.MaxValue, 1, UserBreak)
: SessionSplitter.Split(times, options.SessionGap, options.MinimumSessionFrames, UserBreak);
for (var r = 0; r < ranges.Count; r++)
{
var members = ordered.GetRange(range.Start, range.Count);
drafts.Add((SessionKey(body.Key, members[0].CaptureTime), members));
var members = ordered.GetRange(ranges[r].Start, ranges[r].Count);
var key = wholeFolder
? FolderKey(sourceRoot, members[0].Metadata.Format, r == 0 ? null : members[0].CaptureTime)
: SessionKey(group.Key, members[0].CaptureTime);
drafts.Add((key, members));
}
}
drafts.Sort((a, b) => a.Photos[0].CaptureTime.CompareTo(b.Photos[0].CaptureTime) is var c and not 0 ? c : string.CompareOrdinal(a.Key, b.Key));
@@ -53,7 +67,7 @@ public static class ImportPlanner
{
var (key, members) = drafts[s];
var first = members[0];
options.Titles.TryGetValue(key, out var title);
var title = options.Titles.GetValueOrDefault(key) ?? folderName;
var context = Context(first, first.CaptureTime, s + 1, 1, title);
var folder = await lookup.FindSessionFolderAsync(key, cancellationToken).ConfigureAwait(false)
?? UniqueFolder(folderTemplate.ExpandFolder(context), claimedFolders, lookup);
@@ -74,11 +88,13 @@ public static class ImportPlanner
CameraMake = first.Metadata.Make,
CameraModel = first.Metadata.Model,
CameraSerial = first.Metadata.BodySerial,
Cameras = CountCameras(members),
Format = first.Metadata.Format,
Start = first.CaptureTime,
End = members[^1].CaptureTime,
Folder = folder,
Title = title,
DefaultTitle = folderName,
Items = items,
});
}
@@ -88,6 +104,7 @@ public static class ImportPlanner
SourceRoot = Path.GetFullPath(sourceRoot),
DestinationRoot = Path.GetFullPath(destinationRoot),
Created = DateTimeOffset.UtcNow,
Grouping = options.Grouping,
Sessions = sessions,
Problems = problems,
AvailableBytes = FreeSpace(destinationRoot),
@@ -139,12 +156,41 @@ public static class ImportPlanner
};
/// <summary>Camera body and file format: RAW+JPEG shooting yields two sequences instead of doubled frames.</summary>
private static string BodyKey(CardPhoto p) => $"{p.Metadata.Make}|{p.Metadata.Model}|{p.Metadata.BodySerial}|{p.Metadata.Format}";
private static string BodyKey(CardPhoto p) => $"{CameraKey(p)}|{p.Metadata.Format}";
private static string CameraKey(CardPhoto p) => $"{p.Metadata.Make}|{p.Metadata.Model}|{p.Metadata.BodySerial}";
/// <summary>Camera bodies that took the photos; a photo without a camera in its metadata is no body of its own.</summary>
private static int CountCameras(List<CardPhoto> photos) =>
System.Math.Max(1, photos.Where(p => p.Metadata.Model is not null).Select(CameraKey).Distinct(StringComparer.Ordinal).Count());
/// <summary>File format alone (a whole folder): RAW+JPEG still yields two sequences instead of doubled frames.</summary>
private static string FormatKey(CardPhoto p) => p.Metadata.Format.ToString();
private static string SessionKey(string bodyKey, DateTime start) =>
"card-" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(bodyKey)))[..8] + "-"
+ start.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
/// <summary>
/// The key of a whole folder's sequence: the same folder of this PC and the same format always give the same key,
/// so an interrupted import resumes into its sequence and a later import of the folder adds to it. A part the user
/// split off also carries the time of its first photo.
/// </summary>
internal static string FolderKey(string sourceRoot, ImageFileFormat format, DateTime? splitAt = null)
{
var path = Path.TrimEndingDirectorySeparator(Path.GetFullPath(sourceRoot));
// Windows compares paths without case: D:\Trip and d:\trip are one folder.
if (OperatingSystem.IsWindows()) path = path.ToUpperInvariant();
// The same path on another PC is another folder: a server files every client's uploads by these keys.
var identity = $"{Environment.MachineName.ToUpperInvariant()}|{path}|{format}";
var key = "folder-" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(identity)))[..16];
return splitAt is { } start ? key + "-" + start.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture) : key;
}
/// <summary>The picked folder's own name, the default title of a whole folder; null for a drive root.</summary>
private static string? FolderName(string sourceRoot) =>
Path.GetFileName(Path.TrimEndingDirectorySeparator(Path.GetFullPath(sourceRoot))) is { Length: > 0 } name ? name : null;
private static string UniqueFolder(string folder, HashSet<string> claimed, IImportLookup lookup)
{
if (folder.Length == 0) folder = "Import";