feat: owner review 2 phase 3: Library on the web panel, photo trash and web upload (#11)
CI / Build and test (push) Successful in 7m25s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
CI / PostgreSQL 16 integration (push) Successful in 5m20s
CI / PostgreSQL 17 integration (push) Successful in 5m22s
CI / Docker image (push) Successful in 50s
Release / Build, test and publish (push) Successful in 12m1s
Release / Server image (push) Successful in 1m26s
CI / Build and test (push) Successful in 7m25s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
CI / PostgreSQL 16 integration (push) Successful in 5m20s
CI / PostgreSQL 17 integration (push) Successful in 5m22s
CI / Docker image (push) Successful in 50s
Release / Build, test and publish (push) Successful in 12m1s
Release / Server image (push) Successful in 1m26s
- Web panel Library: browse, view, delete sequences and photos, mass operations (analyse, proxies, thumbnails, verify, retag, delete, CSV). It never edits the video. - Photo trash with tombstones (migration 0008): crash-safe delete and restore, hash-checked restore with reasons, and emptying only by an explicit fingerprinted job. Sync and uploads keep deleted photos deleted; an explicit "Upload again" brings one back. - Upload from the web panel: in-house SHA-256 in a worker with a fail-closed self-test, capture time from EXIF, chunked, resumable; no folders. - Desktop trash dialog with photo entries and Empty. - Admin files are revalidated (no-cache + ETag). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #11.
This commit is contained in:
1 parent
af9eeaab9b
commit
9aa818ed47
283 files changed
+24922
-293
No files matched your search
@@ -63,10 +63,13 @@ public abstract class ArchiveDialogViewModel : LocalizedViewModel
|
||||
|
||||
public string? BusyText { get => _busyText; protected set => Set(ref _busyText, value); }
|
||||
|
||||
/// <summary>Why the last dry run or apply stopped (<see cref="ArchiveFailures.Cause"/>); null when nothing failed.</summary>
|
||||
/// <summary>Why the last dry run or apply stopped (<see cref="ArchiveFailures.Cause"/>), or what it left undone; null when nothing failed.</summary>
|
||||
public string? ErrorText { get => _errorText; private set => Set(ref _errorText, value); }
|
||||
|
||||
/// <summary>The failure as the engine reported it, for the tooltip.</summary>
|
||||
/// <summary>
|
||||
/// The tooltip of <see cref="ErrorText"/>: the whole sentence (the line may cut it), then the failure as the engine
|
||||
/// reported it, or what a <see cref="ShowMessage"/> names.
|
||||
/// </summary>
|
||||
public string? ErrorToolTip { get => _errorToolTip; private set => Set(ref _errorToolTip, value); }
|
||||
|
||||
protected void Close() => _close(this);
|
||||
@@ -74,7 +77,17 @@ public abstract class ArchiveDialogViewModel : LocalizedViewModel
|
||||
protected void ShowError(Exception ex)
|
||||
{
|
||||
ErrorText = ArchiveFailures.Cause(ex);
|
||||
ErrorToolTip = ex.Message;
|
||||
ErrorToolTip = ex.Message == ErrorText ? ErrorText : ErrorText + Environment.NewLine + ex.Message;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows a sentence localized already, such as what an action that half succeeded left undone; <paramref name="tip"/>
|
||||
/// details it, and repeats the sentence first (the line may cut it).
|
||||
/// </summary>
|
||||
protected void ShowMessage(string text, string? tip = null)
|
||||
{
|
||||
ErrorText = text;
|
||||
ErrorToolTip = tip is null || tip.StartsWith(text, StringComparison.Ordinal) ? tip ?? text : text + Environment.NewLine + tip;
|
||||
}
|
||||
|
||||
protected void ClearError()
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<Setter Property="AutomationProperties.LiveSetting" Value="Polite" />
|
||||
</Style>
|
||||
|
||||
<!-- A dialog's failure: one sentence in the error colour with its glyph, the engine's own text in the tooltip, announced at once. -->
|
||||
<!-- A dialog's failure: one sentence in the error colour with its glyph, the engine's own text (or what the sentence names) in the tooltip, announced at once. -->
|
||||
<Style x:Key="Status.DialogError" TargetType="ui:StatusGlyph" BasedOn="{StaticResource {x:Type ui:StatusGlyph}}">
|
||||
<Setter Property="Kind" Value="Error" />
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
@@ -203,7 +203,7 @@
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- The archive's trash: deleted sequences, newest first, each with Restore. -->
|
||||
<!-- The archive's trash: deleted sequences and photos deleted from sequences, newest first, each with Restore; Empty… erases them after a dry run and a typed confirmation. -->
|
||||
<DataTemplate DataType="{x:Type ar:TrashDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="640" MaxHeight="520">
|
||||
<Grid>
|
||||
@@ -242,6 +242,9 @@
|
||||
<DockPanel Grid.Row="3" Margin="0,16,0,0">
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Close}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True"
|
||||
IsDefault="True" MinWidth="96" />
|
||||
<!-- Erasing for good: a dry run and a typed confirmation first, never the default button. -->
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Trash.EmptyAction}" Command="{Binding EmptyCommand}" ToolTip="{Binding EmptyToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="0,0,8,0" />
|
||||
<Grid Margin="0,0,12,0">
|
||||
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" />
|
||||
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
|
||||
|
||||
@@ -16,9 +16,11 @@ public static class ArchiveFailures
|
||||
{
|
||||
ArchiveOfflineException offline => Loc.L(offline.Availability == ArchiveAvailability.ReadOnly ? "Archive.Error.ReadOnly" : "Archive.Error.Offline",
|
||||
Formatting.LeftToRight(offline.Root)),
|
||||
// Already one localized sentence each.
|
||||
// Already one localized sentence each; TrashMismatchException is a trash entry none of whose files matches its record
|
||||
// any more (FrameTrash.RestoreAsync). Other IOExceptions and InvalidDataExceptions (a sidecar of another sequence)
|
||||
// carry technical text.
|
||||
LeaseUnavailableException or NewerFormatException or StaleRenamePlanException or NestedRenameException or StaleDeletePlanException
|
||||
or SequenceInLibraryException => ex.Message,
|
||||
or SequenceInLibraryException or TrashMismatchException => ex.Message,
|
||||
UnauthorizedAccessException => Loc.L("Archive.Failed.Access"),
|
||||
DatabaseException => Loc.L("Archive.Failed.Index"),
|
||||
ArgumentException => Loc.L("Archive.Failed.Gone"),
|
||||
|
||||
@@ -32,14 +32,19 @@ public static class SampleReports
|
||||
? new OrphanReport([], [], [])
|
||||
: new OrphanReport([new SequenceOrphans(sequences[2].Folder, ["IMG_0412.CR2", "IMG_0413.CR2"], [])], [sequences[3]], ["2024/2024-12-31 Unsorted"]);
|
||||
|
||||
/// <summary>The trash dialog's rows: the first two sample sequences, deleted an hour and a day ago (nothing moves on disk).</summary>
|
||||
/// <summary>
|
||||
/// The trash dialog's rows: the first sample sequence, deleted an hour ago, and 24 photos of the second, deleted a day ago
|
||||
/// (nothing moves on disk).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<TrashEntry> Trash(Guid archiveId, IReadOnlyList<SequenceLocation> sequences)
|
||||
{
|
||||
var now = SampleData.Now;
|
||||
return
|
||||
[
|
||||
.. sequences.Take(2).Select((s, i) => new TrashEntry(archiveId, s.Id.ToString("N"), s.Id, s.Title ?? s.Folder, s.Folder, 1_200 * (i + 1), 1_206 * (i + 1),
|
||||
31_457_280L * 1_200 * (i + 1), now.AddHours(-1 - (23 * i)), "alberto")),
|
||||
.. sequences.Take(1).Select(s => new TrashEntry(archiveId, s.Id.ToString("N"), s.Id, s.Title ?? s.Folder, s.Folder, 1_200, 1_206,
|
||||
31_457_280L * 1_200, now.AddHours(-1), "alberto")),
|
||||
.. sequences.Skip(1).Take(1).Select(s => new TrashEntry(archiveId, FrameTrash.EntryPrefix + s.Id.ToString("N") + "-20260927180400", s.Id,
|
||||
s.Title ?? s.Folder, s.Folder, 24, 24, 31_457_280L * 24, now.AddHours(-24), "alberto", TrashKind.Photos)),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
@@ -6,18 +7,24 @@ using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Archiving;
|
||||
|
||||
/// <summary>One deleted sequence in the trash: what it was, when it went, and Restore.</summary>
|
||||
/// <summary>One entry of the trash: a deleted sequence or photos deleted from one, when it went, and Restore.</summary>
|
||||
public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
|
||||
{
|
||||
public TrashEntry Entry { get; } = entry;
|
||||
public string Title => Entry.Title;
|
||||
|
||||
/// <summary>"3,600 photos · 96.2 GB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).</summary>
|
||||
public string Detail => string.Join(Loc.Separator, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes), Formatting.LeftToRight(Entry.Folder));
|
||||
/// <summary>"Photos", "Sequence": what the entry holds.</summary>
|
||||
public string KindText => TrashEmptyPlans.KindText(Entry.Kind);
|
||||
|
||||
/// <summary>"Photos · 12 photos · 340 MB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).</summary>
|
||||
public string Detail => string.Join(Loc.Separator, KindText, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes),
|
||||
Formatting.LeftToRight(Entry.Folder));
|
||||
|
||||
/// <summary>"Deleted 02/10/2026 18:04".</summary>
|
||||
public string DeletedText => Loc.L("Archive.Trash.Deleted", Formatting.Date(Entry.DeletedAt) + " " + Formatting.TimeOfDay(Entry.DeletedAt));
|
||||
@@ -25,23 +32,71 @@ public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
|
||||
public ICommand RestoreCommand { get; } = restore;
|
||||
}
|
||||
|
||||
/// <summary>The words of an emptying of the trash (<see cref="TrashEmptyPlan"/>): the destructive, typed confirmation.</summary>
|
||||
public static class TrashEmptyPlans
|
||||
{
|
||||
/// <summary>"Photos", "Sequence", "Replaced".</summary>
|
||||
public static string KindText(TrashKind kind) => Loc.L("Archive.Trash.Kind." + kind);
|
||||
|
||||
/// <summary>The confirmation of erasing the planned entries for good; null when the plan holds none.</summary>
|
||||
public static ConfirmRequest? Request(TrashEmptyPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
if (plan.Entries.Count == 0) return null;
|
||||
var count = plan.Entries.Count.ToString(CultureInfo.InvariantCulture);
|
||||
var lines = plan.Entries.Take(DeletePlans.ListedLines).Select(e => Loc.L("Archive.Delete.Line", e.Title,
|
||||
KindText(e.Kind) + Loc.Separator + Loc.Plural("Shell.Status.Photos", e.Frames), Formatting.Bytes(e.Bytes))).ToList();
|
||||
if (plan.Entries.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", plan.Entries.Count - DeletePlans.ListedLines));
|
||||
return new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.Plural("Archive.Trash.EmptyHeading", plan.Entries.Count),
|
||||
Message = Loc.L("Archive.Trash.EmptyMessage", Loc.Plural("Shell.Status.Photos", plan.Photos), Loc.Plural("Archive.Delete.Files", plan.Files),
|
||||
Formatting.Bytes(plan.Bytes)),
|
||||
Detail = string.Join(Environment.NewLine, lines),
|
||||
IsDetailMonospaced = false,
|
||||
DetailToolTip = Loc.L("Tooltips.Archive.TrashEmptyPlan"),
|
||||
SafeText = Loc.L("Archive.Delete.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
|
||||
ActionText = Loc.L("Archive.Trash.Erase"),
|
||||
ActionToolTip = Loc.Plural("Tooltips.Archive.TrashErase", plan.Entries.Count),
|
||||
IsDestructive = true,
|
||||
TypedConfirmation = count,
|
||||
TypedPrompt = Loc.L("Archive.Delete.Type", count),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The archive's trash (BRIEF §0.2 rule 8): every sequence deleted from the Library or the Archive manager, newest
|
||||
/// first, each restorable into its folder (or a free one next to it) with its ids, settings and renders.
|
||||
/// The archive's trash (BRIEF §0.2 rule 8, §12.5): every sequence deleted from the Library or the Archive manager and the
|
||||
/// photos deleted from sequences (owner review 2, R6), newest first, each restorable — a sequence into its folder (or a
|
||||
/// free one next to it) with its ids, settings and renders, photos into their sequence after their files are re-hashed.
|
||||
/// Empty… erases the entries for good: a dry run, a typed confirmation, then the <c>EmptyTrash</c> job, which refuses when
|
||||
/// the trash changed since.
|
||||
/// </summary>
|
||||
public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
private readonly ArchiveService _archives;
|
||||
private readonly Core.Model.Archive _archive;
|
||||
private readonly Func<Task> _restored;
|
||||
private readonly Func<ConfirmRequest, bool>? _confirm;
|
||||
private readonly Func<ArchiveJobRequest, Task>? _enqueue;
|
||||
private readonly JobEngine? _followUps;
|
||||
private IReadOnlyList<TrashRowViewModel> _rows = [];
|
||||
|
||||
public TrashDialogViewModel(ArchiveService archives, Core.Model.Archive archive, Func<Task> restored, Action<ArchiveDialogViewModel> close)
|
||||
/// <param name="confirm">Asks the typed confirmation of an emptying (null: the trash cannot be emptied here).</param>
|
||||
/// <param name="enqueue">Queues the emptying job and says so (null: the trash cannot be emptied here).</param>
|
||||
/// <param name="followUps">The engine that takes the analyses and images restored photos need again.</param>
|
||||
public TrashDialogViewModel(ArchiveService archives, Core.Model.Archive archive, Func<Task> restored, Action<ArchiveDialogViewModel> close,
|
||||
Func<ConfirmRequest, bool>? confirm = null, Func<ArchiveJobRequest, Task>? enqueue = null, JobEngine? followUps = null)
|
||||
: base(close)
|
||||
{
|
||||
_archives = archives;
|
||||
_archive = archive;
|
||||
_restored = restored;
|
||||
_confirm = confirm;
|
||||
_enqueue = enqueue;
|
||||
_followUps = followUps;
|
||||
EmptyCommand = new AsyncRelayCommand(EmptyAsync, () => CanEmpty);
|
||||
}
|
||||
|
||||
public string Heading => Loc.L("Archive.Trash.Heading", _archive.Name);
|
||||
@@ -55,6 +110,8 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
OnPropertyChanged(nameof(SummaryText));
|
||||
OnPropertyChanged(nameof(EmptyToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,9 +120,17 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
/// <summary>The list shows; an empty trash is its summary sentence alone.</summary>
|
||||
public bool HasRows => _rows.Count > 0;
|
||||
|
||||
/// <summary>"3 sequences · 182 GB", or "The trash is empty".</summary>
|
||||
/// <summary>"3 entries · 182 GB", or "The trash is empty".</summary>
|
||||
public string SummaryText => _rows.Count == 0 ? Loc.L("Archive.Trash.Empty")
|
||||
: Loc.Plural("Shell.Status.Sequences", _rows.Count) + Loc.Separator + Formatting.Bytes(_rows.Sum(r => r.Entry.Bytes));
|
||||
: Loc.Plural("Archive.Trash.Entries", _rows.Count) + Loc.Separator + Formatting.Bytes(_rows.Sum(r => r.Entry.Bytes));
|
||||
|
||||
/// <summary>Empty…: the dry run, the typed confirmation, then the job.</summary>
|
||||
public ICommand EmptyCommand { get; }
|
||||
|
||||
/// <summary>Emptying is offered here, and there is something to erase.</summary>
|
||||
public bool CanEmpty => !IsBusy && HasRows && _confirm is not null && _enqueue is not null;
|
||||
|
||||
public string EmptyToolTip => HasRows ? Loc.L("Tooltips.Archive.TrashEmpty") : Loc.L("Archive.Trash.Empty");
|
||||
|
||||
/// <summary>Reads the trash of the archive (off the UI thread).</summary>
|
||||
public async Task LoadAsync()
|
||||
@@ -75,7 +140,7 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
try
|
||||
{
|
||||
var entries = await Task.Run(() => _archives.ListTrashAsync(_archive.Id));
|
||||
Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => RestoreAsync(e), () => !IsBusy)))];
|
||||
Rows = [.. entries.Select(Row)];
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException)
|
||||
{
|
||||
@@ -92,6 +157,8 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
public void Show(IReadOnlyList<TrashEntry> entries) =>
|
||||
Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => Task.CompletedTask)))];
|
||||
|
||||
private TrashRowViewModel Row(TrashEntry entry) => new(entry, new AsyncRelayCommand(() => RestoreAsync(entry), () => !IsBusy));
|
||||
|
||||
private async Task RestoreAsync(TrashEntry entry)
|
||||
{
|
||||
ClearError();
|
||||
@@ -99,10 +166,21 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
BusyText = Loc.L("Archive.Trash.Restoring", entry.Title);
|
||||
try
|
||||
{
|
||||
await Task.Run(() => _archives.RestoreAsync(entry.ArchiveId, entry.Name));
|
||||
Log.Info("archive", $"{entry.Title} restored from the trash");
|
||||
Rows = [.. _rows.Where(r => r.Entry != entry)];
|
||||
var result = await Task.Run(() => _archives.RestoreEntryAsync(entry.ArchiveId, entry.Name, _followUps));
|
||||
Log.Info("archive", $"{entry.Title} restored from the trash ({entry.Kind}, {result.Photos} photo(s), {result.Kept.Count} kept)");
|
||||
BusyText = null;
|
||||
if (result.Kept.Count > 0)
|
||||
{
|
||||
// Photos that stay in the trash keep their entry, with what is left; the line says how many stayed and why,
|
||||
// and the tooltip repeats it with their names.
|
||||
await LoadAsync();
|
||||
var (text, tip) = KeptText(result.Kept);
|
||||
ShowMessage(text, tip);
|
||||
}
|
||||
else
|
||||
{
|
||||
Rows = [.. _rows.Where(r => r.Entry != entry)];
|
||||
}
|
||||
await _restored();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or SequenceInLibraryException or NewerFormatException
|
||||
@@ -117,4 +195,59 @@ public sealed class TrashDialogViewModel : ArchiveDialogViewModel
|
||||
BusyText = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The line of what a restore kept in the trash, and its tooltip: one reason's sentence ("2 photos stayed in the trash:
|
||||
/// they could not be moved back."), or how many stayed when they stayed for different reasons. The tooltip holds that
|
||||
/// line, then each reason's sentence (when there are several) with its photos' names, one per line, the names counted
|
||||
/// past <see cref="DeletePlans.ListedLines"/> in all.
|
||||
/// </summary>
|
||||
internal static (string Text, string ToolTip) KeptText(IReadOnlyList<KeptPhoto> kept)
|
||||
{
|
||||
var groups = kept.GroupBy(k => k.Reason).OrderBy(g => g.Key).ToList();
|
||||
var text = groups.Count == 1 ? KeptPhoto.Sentence(groups[0].Key, groups[0].Count(), Loc.Culture) : Loc.Plural("Archive.Trash.KeptPhotos", kept.Count);
|
||||
var lines = new List<string> { text };
|
||||
var listed = 0;
|
||||
foreach (var group in groups)
|
||||
{
|
||||
if (groups.Count > 1) lines.Add(KeptPhoto.Sentence(group.Key, group.Count(), Loc.Culture));
|
||||
foreach (var photo in group)
|
||||
{
|
||||
if (listed++ < DeletePlans.ListedLines) lines.Add(Formatting.LeftToRight(photo.Name));
|
||||
}
|
||||
}
|
||||
if (kept.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Trash.KeptMore", kept.Count - DeletePlans.ListedLines));
|
||||
return (text, string.Join(Environment.NewLine, lines));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Empty…: measures every entry (the dry run), asks to type how many entries go, and queues the job that erases exactly
|
||||
/// those; the dialog closes, and the job says how it ended.
|
||||
/// </summary>
|
||||
private async Task EmptyAsync()
|
||||
{
|
||||
if (_confirm is null || _enqueue is null) return;
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
BusyText = Loc.L("Archive.Trash.Checking");
|
||||
TrashEmptyPlan plan;
|
||||
try
|
||||
{
|
||||
plan = await Task.Run(() => _archives.PlanEmptyTrashAsync(_archive.Id));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException)
|
||||
{
|
||||
Log.Warning("archive", "The dry run of emptying the trash failed", ex);
|
||||
ShowError(ex);
|
||||
return;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
BusyText = null;
|
||||
}
|
||||
if (TrashEmptyPlans.Request(plan) is not { } request || !_confirm(request)) return;
|
||||
await _enqueue(ArchiveJobs.EmptyTrash(_archive, plan));
|
||||
Close();
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@ public static class JobNotices
|
||||
|
||||
private static bool Announces(JobKind kind) =>
|
||||
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
|
||||
or JobKind.Move or JobKind.Adopt;
|
||||
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash;
|
||||
|
||||
/// <summary>
|
||||
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
|
||||
|
||||
@@ -782,11 +782,16 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
public async Task OpenTrashAsync()
|
||||
{
|
||||
if (Services.Archives is not { } archives || _archive is not { } archive) return;
|
||||
var engine = Services.Engine;
|
||||
var dialog = new TrashDialogViewModel(archives, archive, async () =>
|
||||
{
|
||||
await LoadAsync();
|
||||
await Shell.Library.RefreshAsync();
|
||||
}, CloseDialog);
|
||||
}, CloseDialog, Services.Dialogs.Confirm, engine is null ? null : async request =>
|
||||
{
|
||||
await engine.EnqueueAsync(request);
|
||||
Queued(request.Kind, archive.Name);
|
||||
}, engine);
|
||||
OpenDialog(dialog);
|
||||
await dialog.LoadAsync();
|
||||
}
|
||||
|
||||
@@ -1130,7 +1130,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
|
||||
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
|
||||
JobKind.Backup, JobKind.Cleanup,
|
||||
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash,
|
||||
];
|
||||
|
||||
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
|
||||
|
||||
@@ -14,6 +14,7 @@ namespace Chronos.Core.Archiving;
|
||||
[JsonSerializable(typeof(SequenceManifest))]
|
||||
[JsonSerializable(typeof(LeaseRecord))]
|
||||
[JsonSerializable(typeof(IngestJournal))]
|
||||
[JsonSerializable(typeof(FrameRemovalJournal))]
|
||||
[JsonSerializable(typeof(RenameJournal))]
|
||||
internal sealed partial class ArchiveJson : JsonSerializerContext;
|
||||
|
||||
|
||||
@@ -30,6 +30,12 @@ public static class ArchiveLayout
|
||||
/// <summary>Moves of an ingest batch that were started but not yet recorded in <see cref="SequenceManifestFile"/>.</summary>
|
||||
public const string IngestJournalFile = "ingest.pending.json";
|
||||
|
||||
/// <summary>Moves of a photo deletion into the trash that were started but not yet recorded in <see cref="SequenceManifestFile"/>.</summary>
|
||||
public const string RemovalJournalFile = "remove.pending.json";
|
||||
|
||||
/// <summary>Moves of photos restored from the trash that were started but not yet settled in <see cref="SequenceManifestFile"/> and the trash record.</summary>
|
||||
public const string RestoreJournalFile = "restore.pending.json";
|
||||
|
||||
/// <summary>Folder names inside a sequence folder that never hold a sequence of their own.</summary>
|
||||
public static bool IsReservedFolder(string name) =>
|
||||
name.Equals(MetaFolder, StringComparison.OrdinalIgnoreCase)
|
||||
@@ -74,11 +80,15 @@ public sealed class SequencePaths
|
||||
internal SequencePaths(ArchivePaths archive, string relativeFolder)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(relativeFolder);
|
||||
Archive = archive;
|
||||
RelativeFolder = relativeFolder.Replace('\\', '/').Trim('/');
|
||||
Folder = archive.FromRelative(RelativeFolder);
|
||||
MetaDirectory = Path.Combine(Folder, ArchiveLayout.MetaFolder);
|
||||
}
|
||||
|
||||
/// <summary>The archive the sequence belongs to.</summary>
|
||||
public ArchivePaths Archive { get; }
|
||||
|
||||
/// <summary>Folder relative to the archive root, forward slashes; empty when the root itself holds the photos (adopted folder).</summary>
|
||||
public string RelativeFolder { get; }
|
||||
|
||||
@@ -92,6 +102,8 @@ public sealed class SequencePaths
|
||||
public string ProjectPath => Path.Combine(MetaDirectory, ArchiveLayout.ProjectFile);
|
||||
public string ThumbsPackPath => Path.Combine(MetaDirectory, ArchiveLayout.ThumbsPackFile);
|
||||
public string IngestJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.IngestJournalFile);
|
||||
public string RemovalJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.RemovalJournalFile);
|
||||
public string RestoreJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.RestoreJournalFile);
|
||||
|
||||
public string Proxy(int index) => Path.Combine(Proxies, ArchiveLayout.ProxyFileName(index));
|
||||
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
|
||||
namespace Chronos.Core.Archiving;
|
||||
|
||||
/// <summary>One file of a photo deletion: where it was in the sequence folder and where it went in the archive's trash.</summary>
|
||||
/// <param name="From">Path relative to the sequence folder (forward slashes).</param>
|
||||
/// <param name="To">Path relative to the archive root (forward slashes), inside the trash entry.</param>
|
||||
public sealed record FrameRemovalMove(string From, string To);
|
||||
|
||||
/// <summary>
|
||||
/// Write-ahead record of a photo deletion (<c>.chronos/remove.pending.json</c>, owner review 2, R6): the trash entry the
|
||||
/// photos move into, the frames leaving the sidecar and every file move. Written before the first move and removed once
|
||||
/// <c>sequence.json</c> no longer lists the frames, so a crash in between is undone by <see cref="Recover"/>: the files go
|
||||
/// back to their places, the entry's record and folder go, and the sequence is as it was. Until the sidecar is written
|
||||
/// the entry's record has its <see cref="PendingRecord"/> name, which the trash never lists, so half an entry can be
|
||||
/// neither restored nor emptied.
|
||||
/// </summary>
|
||||
/// <param name="Record">The entry's record, relative to the archive root (its name once the deletion is complete).</param>
|
||||
/// <param name="Folder">The entry's folder, relative to the archive root.</param>
|
||||
public sealed record FrameRemovalJournal(string Record, string Folder, IReadOnlyList<Guid> Frames, IReadOnlyList<FrameRemovalMove> Moves)
|
||||
{
|
||||
/// <summary>The name a deletion's record has until its sidecar is written.</summary>
|
||||
public static string PendingRecord(string record) => record + ".pending";
|
||||
|
||||
public static void Write(SequencePaths sequence, FrameRemovalJournal journal)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
AtomicFile.WriteAllBytes(sequence.RemovalJournalPath, JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJson.Default.FrameRemovalJournal));
|
||||
}
|
||||
|
||||
public static void Delete(SequencePaths sequence)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
if (File.Exists(sequence.RemovalJournalPath)) File.Delete(sequence.RemovalJournalPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Undoes a deletion a crash interrupted before its sidecar was written: while <paramref name="manifest"/> still lists a
|
||||
/// frame of the journal, each file that reached the trash moves back (one whose place is taken again stays in the trash,
|
||||
/// logged, and so does the entry then, listed under its record's own name), and the entry's record and its emptied
|
||||
/// folder go. A deletion whose sidecar was written is complete: its record takes its own name, and the journal goes.
|
||||
/// Returns whether a deletion was undone. The caller holds the lease.
|
||||
/// </summary>
|
||||
public static bool Recover(SequencePaths sequence, SequenceManifest manifest)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
if (!File.Exists(sequence.RemovalJournalPath)) return false;
|
||||
FrameRemovalJournal? journal;
|
||||
try
|
||||
{
|
||||
journal = JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.RemovalJournalPath), ArchiveJson.Default.FrameRemovalJournal);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
journal = null; // torn while being written: nothing was moved yet
|
||||
}
|
||||
var undone = false;
|
||||
var archive = sequence.Archive;
|
||||
if (journal is not null && manifest.Frames.Any(f => journal.Frames.Contains(f.Id)))
|
||||
{
|
||||
var kept = 0;
|
||||
foreach (var move in journal.Moves)
|
||||
{
|
||||
var trashed = archive.FromRelative(move.To);
|
||||
var place = sequence.File(move.From);
|
||||
if (!File.Exists(trashed)) continue;
|
||||
if (File.Exists(place))
|
||||
{
|
||||
kept++;
|
||||
Log.Warning("archive", $"{sequence.ArchiveRelative(move.From)} is there again; its deleted copy stays in {move.To}");
|
||||
continue;
|
||||
}
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(place)!);
|
||||
File.Move(trashed, place, overwrite: false);
|
||||
}
|
||||
var record = archive.FromRelative(journal.Record);
|
||||
if (kept == 0)
|
||||
{
|
||||
if (File.Exists(record)) File.Delete(record);
|
||||
if (File.Exists(PendingRecord(record))) File.Delete(PendingRecord(record));
|
||||
RemoveEmpty(archive.FromRelative(journal.Folder));
|
||||
}
|
||||
else
|
||||
{
|
||||
// What stays in the trash is listed, restorable and erasable like any entry.
|
||||
Publish(record);
|
||||
}
|
||||
Log.Warning("archive", $"An interrupted photo deletion in {sequence.RelativeFolder} was undone");
|
||||
undone = true;
|
||||
}
|
||||
else if (journal is not null)
|
||||
{
|
||||
Publish(archive.FromRelative(journal.Record));
|
||||
}
|
||||
Delete(sequence);
|
||||
return undone;
|
||||
}
|
||||
|
||||
/// <summary>Gives a deletion's record its own name (<see cref="PendingRecord"/>), once its photos are out of the sidecar.</summary>
|
||||
public static void Publish(string record)
|
||||
{
|
||||
var pending = PendingRecord(record);
|
||||
if (File.Exists(pending) && !File.Exists(record)) File.Move(pending, record, overwrite: false);
|
||||
}
|
||||
|
||||
/// <summary>Removes <paramref name="folder"/> and its subfolders when they hold no file.</summary>
|
||||
public static void RemoveEmpty(string folder)
|
||||
{
|
||||
if (!Directory.Exists(folder)) return;
|
||||
foreach (var child in Directory.EnumerateDirectories(folder)) RemoveEmpty(child);
|
||||
if (!Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder);
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,9 @@ public sealed class LeaseFile : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The current holder of the lease <paramref name="name"/> in <paramref name="locksDirectory"/>, or null when free or unreadable.</summary>
|
||||
public static LeaseRecord? Holder(string locksDirectory, string name) => Read(PathFor(locksDirectory, name));
|
||||
|
||||
/// <summary>The current holder of a lease, or null when free or unreadable.</summary>
|
||||
/// <remarks>
|
||||
/// Readers share read, write and delete so they never block a renewal, a release or a takeover. A renewal rewrites
|
||||
|
||||
@@ -42,6 +42,13 @@ public sealed record SequenceManifest
|
||||
/// <summary>Session keys of automatic grouping (uploads, card imports) that resolve to this sequence.</summary>
|
||||
public IReadOnlyList<string> SessionKeys { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Tombstones of the photos removed from the sequence (owner review 2, R6), by SHA-256; null when there are none, so a
|
||||
/// sidecar without removals is written as before. A build that does not know the field keeps it in its
|
||||
/// <see cref="Extra"/> and writes it back unchanged.
|
||||
/// </summary>
|
||||
public IReadOnlyList<RemovedPhoto>? Removed { get; init; }
|
||||
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? Extra { get; set; }
|
||||
}
|
||||
@@ -127,6 +134,53 @@ public sealed record SidecarFrame
|
||||
/// <summary><see cref="FrameFlags"/> bits, stored as a number so bits of newer builds survive.</summary>
|
||||
public FrameFlags Flags { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The file this frame was converted from (reserved for the conversion of owner review 2, R7); null for an original.
|
||||
/// Read and written only: nothing acts on it yet.
|
||||
/// </summary>
|
||||
public FrameSource? Source { get; init; }
|
||||
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? Extra { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The tombstone of a photo removed from a sequence (owner review 2, R6): sync never offers that content back to the
|
||||
/// sequence, and an upload of it is answered as already there. <see cref="Replacement"/> names the converted file that took
|
||||
/// its place (<see cref="RemovalReason.Replaced"/>), which sync then counts as the same photo.
|
||||
/// </summary>
|
||||
public sealed record RemovedPhoto
|
||||
{
|
||||
/// <summary>Lower-case hex SHA-256 of the removed photo.</summary>
|
||||
public required string Sha256 { get; init; }
|
||||
|
||||
/// <summary>Lower-case hex SHA-256 of the file that replaced it; null for a photo deleted outright.</summary>
|
||||
public string? Replacement { get; init; }
|
||||
|
||||
[JsonConverter(typeof(TolerantEnumConverter<RemovalReason>))]
|
||||
public RemovalReason Reason { get; init; }
|
||||
|
||||
/// <summary>When it was removed (UTC).</summary>
|
||||
public DateTimeOffset At { get; init; }
|
||||
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? Extra { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The original a converted frame was made from (reserved for owner review 2, R7): its content, format, file and size.</summary>
|
||||
public sealed record FrameSource
|
||||
{
|
||||
/// <summary>Lower-case hex SHA-256 of the source file.</summary>
|
||||
public string? Sha256 { get; init; }
|
||||
|
||||
[JsonConverter(typeof(TolerantEnumConverter<ImageFileFormat>))]
|
||||
public ImageFileFormat Format { get; init; }
|
||||
|
||||
/// <summary>The source's path relative to the sequence folder (forward slashes) when it was converted.</summary>
|
||||
public string? File { get; init; }
|
||||
|
||||
public long Size { get; init; }
|
||||
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? Extra { get; set; }
|
||||
}
|
||||
@@ -346,6 +346,30 @@ public sealed class ThumbPackWriter : IDisposable
|
||||
_dirty = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves each thumbnail to the frame index <paramref name="indices"/> maps its own to (old → new) and drops those it
|
||||
/// does not map (frames removed), then commits: only a new index is written, the thumbnails stay where they are. Their
|
||||
/// entry headers keep the old index, so a pack whose index a crash cut off reads back under those, where each one's
|
||||
/// source fingerprint (<see cref="ThumbPack.IsFrom"/>) still tells it from the frame now at that index.
|
||||
/// </summary>
|
||||
public void Rekey(IReadOnlyDictionary<int, int> indices)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(indices);
|
||||
if (_entries.All(e => indices.TryGetValue(e.Key, out var to) && to == e.Key)) return;
|
||||
var moved = new List<ThumbEntry>(_entries.Count);
|
||||
foreach (var (index, entry) in _entries)
|
||||
{
|
||||
if (indices.TryGetValue(index, out var to)) moved.Add(entry with { FrameIndex = to });
|
||||
}
|
||||
_entries.Clear();
|
||||
foreach (var entry in moved) _entries[entry.FrameIndex] = entry;
|
||||
// The new index replaces the last committed one at the end of the pack.
|
||||
if (_indexOffset is { } offset) _stream.SetLength(offset);
|
||||
_indexOffset = null;
|
||||
_dirty = true;
|
||||
Commit();
|
||||
}
|
||||
|
||||
/// <summary>Writes the index and footer and flushes to disk.</summary>
|
||||
public void Commit()
|
||||
{
|
||||
|
||||
@@ -17,6 +17,13 @@ public sealed record Archive
|
||||
public int ProxyLongEdge { get; init; } = 1920;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The tombstone of a photo removed from a sequence (owner review 2, R6): its SHA-256, the replacement's when it was
|
||||
/// replaced by a converted file, why and when. Kept in the sidecar (<c>removed</c>) and the index (<c>frame_removals</c>), so
|
||||
/// sync never offers the photo back and an upload of that content into the sequence is answered as already there.
|
||||
/// </summary>
|
||||
public sealed record FrameRemoval(Guid SequenceId, string Sha256, string? ReplacementSha256, RemovalReason Reason, DateTimeOffset RemovedAt);
|
||||
|
||||
/// <summary>One shoot: a folder of frames that becomes one project (BRIEF §5).</summary>
|
||||
public sealed record Sequence
|
||||
{
|
||||
|
||||
@@ -87,6 +87,22 @@ public enum JobKind
|
||||
|
||||
/// <summary>Housekeeping steps: job history, audit log, trash report and the host's own (owner review 2, R10); stored as 17.</summary>
|
||||
Cleanup = 17,
|
||||
|
||||
/// <summary>
|
||||
/// Erases exactly the trash entries of a confirmed plan, refused when the trash changed since (owner review 2, R6); stored
|
||||
/// as 18.
|
||||
/// </summary>
|
||||
EmptyTrash = 18,
|
||||
}
|
||||
|
||||
/// <summary>Why a photo left a sequence (its tombstone, owner review 2, R6); stored as a number.</summary>
|
||||
public enum RemovalReason
|
||||
{
|
||||
/// <summary>Deleted by a user into the archive's trash.</summary>
|
||||
Deleted = 0,
|
||||
|
||||
/// <summary>Replaced by a converted file (a later phase): the tombstone names the replacement's SHA-256.</summary>
|
||||
Replaced = 1,
|
||||
}
|
||||
|
||||
public enum JobState
|
||||
|
||||
@@ -152,8 +152,11 @@ public sealed class ArchiveIndexer
|
||||
if (positions is not null) existing = positions.ApplyTo(existing);
|
||||
}
|
||||
var row = SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing);
|
||||
// A hero frame the sidecar no longer lists (a photo deleted) names nothing: the project's hero waits for its photo.
|
||||
if (row.HeroFrameId is { } hero && !manifest.Frames.Any(f => f.Id == hero)) row = row with { HeroFrameId = null };
|
||||
await tx.Sequences.UpsertAsync(row with { Status = row.Status & ~clear }, cancellationToken).ConfigureAwait(false);
|
||||
await tx.Frames.SyncSequenceAsync(manifest.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
|
||||
await tx.FrameRemovals.SyncSequenceAsync(manifest.Id, SequenceMapping.ToRemovals(manifest), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var key in manifest.SessionKeys)
|
||||
await tx.Sequences.MapSessionKeyAsync(archive.Id, key, manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
@@ -254,10 +257,19 @@ public sealed class ArchiveIndexer
|
||||
/// sidecar then tells every host, so the follow-ups make them again (the images on a server,
|
||||
/// <see cref="ArchiveServiceOptions.ImagesAfterScan"/>).
|
||||
/// </summary>
|
||||
private static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken) =>
|
||||
SequenceAdopter.Reconcile(sequence, manifest, cancellationToken) is { } reconciled
|
||||
private static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken)
|
||||
{
|
||||
// A restore from the trash that could not be settled yet (its entry busy) may have photos in the folder its sidecar
|
||||
// does not list: they are its own, not photos to adopt, until a later writer settles it.
|
||||
if (File.Exists(sequence.RestoreJournalPath))
|
||||
{
|
||||
Log.Info("archive", $"{sequence.RelativeFolder} is not reconciled while a restore from the trash into it waits");
|
||||
return null;
|
||||
}
|
||||
return SequenceAdopter.Reconcile(sequence, manifest, cancellationToken) is { } reconciled
|
||||
? reconciled with { Status = reconciled.Status & ~CoveringStatus }
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies <paramref name="edit"/> to the sidecar (null writes nothing) and indexes the result, both under the sequence
|
||||
@@ -324,7 +336,8 @@ public sealed class ArchiveIndexer
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
bytes = null;
|
||||
}
|
||||
if (reconcile || File.Exists(sequence.IngestJournalPath))
|
||||
// A journal of an ingest, a photo deletion or a restore a crash interrupted is settled under the lease first (ReadLocked).
|
||||
if (reconcile || File.Exists(sequence.IngestJournalPath) || File.Exists(sequence.RemovalJournalPath) || File.Exists(sequence.RestoreJournalPath))
|
||||
{
|
||||
// Photos added, gone or back clear what covered the frames, and the scan's follow-ups make it again.
|
||||
manifest = await UpdateAndSyncAsync(archive, paths, sequence, manifest.Id, m => Reconcile(sequence, m, cancellationToken), cancellationToken)
|
||||
@@ -411,12 +424,17 @@ public sealed class ArchiveIndexer
|
||||
return rows.Any(row => !listed.TryGetValue(row.Index, out var id) || id != row.FrameId);
|
||||
}
|
||||
|
||||
/// <summary>A sidecar for a folder that has none; ids of a sequence the index already knew at this folder are kept.</summary>
|
||||
/// <summary>
|
||||
/// A sidecar for a folder that has none; ids and tombstones of a sequence the index already knew at this folder are
|
||||
/// kept, so a photo deleted from it is not offered back once the index is synced from the new sidecar.
|
||||
/// </summary>
|
||||
private async Task<SequenceManifest> AdoptAsync(SequencePaths sequence, Locations locations, CancellationToken cancellationToken)
|
||||
{
|
||||
var known = locations.AtFolder(sequence.RelativeFolder);
|
||||
var manifest = await WithKnownFrameIdsAsync(SequenceAdopter.Build(known ?? Guid.CreateVersion7(), sequence, _writer.Options.Owner, cancellationToken),
|
||||
sequence, cancellationToken).ConfigureAwait(false);
|
||||
if (known is { } id && await _db.FrameRemovals.ListBySequenceAsync(id, cancellationToken).ConfigureAwait(false) is { Count: > 0 } removals)
|
||||
manifest = manifest with { Removed = SequenceMapping.ToTombstones(removals) };
|
||||
Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
// Another process may adopt the same folder at the same moment: the first sidecar wins.
|
||||
return ManifestStore.TryCreateSequence(sequence.ManifestPath, manifest) ? manifest : ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
|
||||
@@ -12,8 +12,9 @@ namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>A verified staged file and how to name it.</summary>
|
||||
/// <param name="PlannedName">Name chosen by an import plan; null = the archive's file template.</param>
|
||||
/// <param name="RefuseRemoved">See <see cref="IngestRequest.RefuseRemoved"/>.</param>
|
||||
internal sealed record StagedFrame(string StagedPath, string OriginalFileName, long Size, string Sha256, FrameMetadata Metadata,
|
||||
DateTime? ClientCapturedAt, string? PlannedName);
|
||||
DateTime? ClientCapturedAt, string? PlannedName, bool RefuseRemoved = false);
|
||||
|
||||
/// <summary>A sequence found or created by key (upload session, card session, or a new title).</summary>
|
||||
/// <param name="PreferredFolder">Folder of an import plan; null = the archive's folder template.</param>
|
||||
@@ -54,7 +55,7 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
if (!staged.Exists || staged.Length != request.Size)
|
||||
throw new FileNotFoundException("The staged file is missing or has another size.", request.StagedPath);
|
||||
var frame = new StagedFrame(request.StagedPath, request.OriginalFileName, request.Size, request.Sha256,
|
||||
MetadataReader.Read(request.StagedPath, cancellationToken), request.ClientCapturedAt, null);
|
||||
MetadataReader.Read(request.StagedPath, cancellationToken), request.ClientCapturedAt, null, request.RefuseRemoved);
|
||||
|
||||
Guid sequenceId;
|
||||
if (request.SequenceId is { } id)
|
||||
@@ -297,6 +298,7 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, sequence, cancellationToken).ConfigureAwait(false);
|
||||
var before = manifest.Frames.Count;
|
||||
var held = manifest.Frames.Where(f => f.Sha256 is not null).ToLookup(f => f.Sha256!, StringComparer.OrdinalIgnoreCase);
|
||||
var tombstoned = (manifest.Removed ?? []).Select(r => r.Sha256).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
// Content this batch files (new frames and repairs): another copy of it in the batch is a duplicate of that frame.
|
||||
var filed = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
@@ -305,6 +307,13 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
var duplicates = new List<(Pending Pending, Guid FrameId)>();
|
||||
foreach (var p in batch)
|
||||
{
|
||||
// Deleted from the sequence (its tombstone, and no frame holds the content) and not asked back: checked under the
|
||||
// lease a deletion takes, so none lands between this check and the commit (owner review 2, R6).
|
||||
if (p.Frame.RefuseRemoved && tombstoned.Contains(p.Frame.Sha256) && !held[p.Frame.Sha256].Any())
|
||||
{
|
||||
p.Completion.TrySetException(new PhotoRemovedException(sequenceId, p.Frame.Sha256));
|
||||
continue;
|
||||
}
|
||||
if (filed.TryGetValue(p.Frame.Sha256, out var same))
|
||||
{
|
||||
duplicates.Add((p, same));
|
||||
@@ -358,13 +367,17 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
updated = SequenceFrames.Update(updated, repaired.ToDictionary(id => id,
|
||||
_ => (Func<SidecarFrame, SidecarFrame>)(f => f with { Flags = f.Flags & ~(FrameFlags.Missing | FrameFlags.Corrupt) })));
|
||||
}
|
||||
// A photo deleted from the sequence and filed into it again (a card imported again, a sync download) is back: its
|
||||
// tombstone goes, so sync offers it like any other.
|
||||
var back = Readded(updated, moved);
|
||||
if (back) updated = updated with { Removed = Remaining(updated.Removed!, moved) };
|
||||
if (moved.Count > 0 || repaired.Count > 0) ManifestStore.WriteSequence(sequence.ManifestPath, updated);
|
||||
IngestJournal.Delete(sequence);
|
||||
|
||||
var byId = updated.Frames.ToDictionary(f => f.Id);
|
||||
if (moved.Count > 0 || repaired.Count > 0)
|
||||
{
|
||||
await IndexAsync(archive, sequence, updated, inStep, photosChanged, before, moved.ConvertAll(m => byId[m.Id]), repaired.Count > 0,
|
||||
await IndexAsync(archive, sequence, updated, inStep, photosChanged, before, moved.ConvertAll(m => byId[m.Id]), repaired.Count > 0 || back,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
foreach (var (p, frame) in accepted.Where(a => byId.ContainsKey(a.Frame.Id)))
|
||||
@@ -382,6 +395,22 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether a frame filed by the batch holds content the sequence's tombstones name.</summary>
|
||||
private static bool Readded(SequenceManifest manifest, List<SidecarFrame> moved)
|
||||
{
|
||||
if (manifest.Removed is not { Count: > 0 } removed || moved.Count == 0) return false;
|
||||
var tombstoned = removed.Select(r => r.Sha256).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
return moved.Any(f => f.Sha256 is { } sha && tombstoned.Contains(sha));
|
||||
}
|
||||
|
||||
/// <summary>The tombstones without those of the content filed again; null when none is left.</summary>
|
||||
private static IReadOnlyList<RemovedPhoto>? Remaining(IReadOnlyList<RemovedPhoto> removed, List<SidecarFrame> moved)
|
||||
{
|
||||
var filed = moved.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var left = removed.Where(r => !filed.Contains(r.Sha256)).ToList();
|
||||
return left.Count == 0 ? null : left;
|
||||
}
|
||||
|
||||
/// <summary>Final file names, in capture order: the plan's name or the template with <c>{n}</c> = index + 1, made unique.</summary>
|
||||
private static Dictionary<Guid, SidecarFrame> Name(Archive archive, SequencePaths sequence, SequenceManifest manifest,
|
||||
List<(Pending Pending, SidecarFrame Frame)> accepted)
|
||||
@@ -416,7 +445,7 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
}
|
||||
|
||||
/// <summary>The frame still holds its content: not flagged missing or corrupt, and its file is there with its size.</summary>
|
||||
private static bool IsIntact(SequencePaths sequence, SidecarFrame frame)
|
||||
internal static bool IsIntact(SequencePaths sequence, SidecarFrame frame)
|
||||
{
|
||||
if ((frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0) return false;
|
||||
var file = new FileInfo(sequence.File(frame.File));
|
||||
|
||||
@@ -40,6 +40,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
Images = new ArchiveImages(db, _writer, Indexer);
|
||||
Imports = new ImportService(db, Ingest);
|
||||
Trash = new SequenceTrash(db, _writer, Indexer);
|
||||
FrameTrash = new FrameTrash(db, _writer, Indexer, Ingest, Trash);
|
||||
var shared = Housekeeping.CleanupSteps.Shared(Trash);
|
||||
CleanupSteps = [.. shared, .. _writer.Options.CleanupSteps.Where(s => !shared.Any(o => o.Name == s.Name))];
|
||||
}
|
||||
@@ -55,9 +56,12 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
public ArchiveImages Images { get; }
|
||||
public ImportService Imports { get; }
|
||||
|
||||
/// <summary>Deletes sequences into the archive's trash and restores them.</summary>
|
||||
/// <summary>Deletes sequences into the archive's trash and restores them; lists and empties the trash.</summary>
|
||||
public SequenceTrash Trash { get; }
|
||||
|
||||
/// <summary>Deletes photos of a sequence into the archive's trash and restores them (owner review 2, R6).</summary>
|
||||
public FrameTrash FrameTrash { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The steps this host's <see cref="JobKind.Cleanup"/> jobs can run: the shared ones (<see cref="Housekeeping.CleanupSteps.Shared"/>),
|
||||
/// then the host's (<see cref="ArchiveServiceOptions.CleanupSteps"/>). A schedule host lists their names.
|
||||
@@ -69,7 +73,8 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
|
||||
/// <summary>
|
||||
/// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans
|
||||
/// reports, index backups and clean-ups (owner review 2, R10); register them on the <see cref="JobEngine"/>.
|
||||
/// reports, index backups and clean-ups (owner review 2, R10) and the emptying of the trash (R6); register them on the
|
||||
/// <see cref="JobEngine"/>.
|
||||
/// </summary>
|
||||
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
|
||||
[
|
||||
@@ -84,6 +89,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
new OrphansJobHandler(_db, Maintenance),
|
||||
new Housekeeping.BackupJobHandler(_db, _writer.Options.BackupDirectory),
|
||||
new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System),
|
||||
new EmptyTrashJobHandler(_db, Trash),
|
||||
];
|
||||
|
||||
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
|
||||
@@ -358,13 +364,37 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Trash.DeleteAsync(plan, deletedBy, progress, cancellationToken);
|
||||
|
||||
/// <summary>The sequences in an archive's trash, newest first.</summary>
|
||||
/// <summary>The entries of an archive's trash, newest first: deleted sequences and photos deleted from sequences (<see cref="SequenceTrash.ListAsync"/>).</summary>
|
||||
public async Task<IReadOnlyList<TrashEntry>> ListTrashAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
|
||||
await Trash.ListAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>Moves a sequence back from the trash and indexes it again.</summary>
|
||||
/// <summary>Moves a sequence back from the trash and indexes it again (an entry of deleted photos: see <see cref="RestoreEntryAsync"/>).</summary>
|
||||
public async Task<Sequence> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) =>
|
||||
await Trash.RestoreAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), entryName, cancellationToken).ConfigureAwait(false);
|
||||
(await RestoreEntryAsync(archiveId, entryName, null, cancellationToken).ConfigureAwait(false)).Sequence;
|
||||
|
||||
/// <summary>
|
||||
/// Brings a trash entry back: a sequence into its folder (<see cref="SequenceTrash.RestoreAsync"/>), or photos into
|
||||
/// their sequence (<see cref="Archiving.FrameTrash.RestoreAsync"/>, which queues on <paramref name="followUps"/> what the
|
||||
/// frames need again).
|
||||
/// </summary>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
/// <exception cref="SequenceInLibraryException">A sequence entry whose sequence is in the index already.</exception>
|
||||
/// <exception cref="TrashMismatchException">No file of a photo entry matches its record; nothing moved.</exception>
|
||||
/// <exception cref="InvalidDataException">A sidecar is damaged or another sequence's (the trashed folder's own, or that of
|
||||
/// the sequence the photos go back into); nothing moved.</exception>
|
||||
public async Task<TrashRestoreResult> RestoreEntryAsync(Guid archiveId, string entryName, JobEngine? followUps = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
|
||||
if (!Archiving.FrameTrash.IsPhotoEntry(entryName))
|
||||
return new TrashRestoreResult(TrashKind.Sequence, await Trash.RestoreAsync(archive, entryName, cancellationToken).ConfigureAwait(false), 0, [], false);
|
||||
var photos = await FrameTrash.RestoreAsync(archive, entryName, followUps, cancellationToken).ConfigureAwait(false);
|
||||
return new TrashRestoreResult(TrashKind.Photos, photos.Sequence, photos.Restored, photos.Kept, photos.NewSequence);
|
||||
}
|
||||
|
||||
/// <summary>The dry run of emptying an archive's trash: <paramref name="names"/> of the entries (null: all), measured, with the plan's fingerprint.</summary>
|
||||
public async Task<TrashEmptyPlan> PlanEmptyTrashAsync(Guid archiveId, IReadOnlyList<string>? names = null, CancellationToken cancellationToken = default) =>
|
||||
await Trash.PlanEmptyAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), names, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>Plans a card or folder import into an archive (nothing is copied).</summary>
|
||||
public async Task<ImportPlan> PlanImportAsync(Guid archiveId, string sourceRoot, ImportOptions options, Guid? cardId = null, IProgress<int>? progress = null,
|
||||
@@ -440,6 +470,12 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
private static ArgumentException Unknown(Guid sequenceId) => new($"Unknown sequence {sequenceId}.", nameof(sequenceId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a restore from the trash did: the kind of entry, the sequence restored (or the one the photos went back into),
|
||||
/// and for photos how many came back, the photos kept in the trash (each with why) and whether they went into a new sequence.
|
||||
/// </summary>
|
||||
public sealed record TrashRestoreResult(TrashKind Kind, Sequence Sequence, int Photos, IReadOnlyList<KeptPhoto> Kept, bool NewSequence);
|
||||
|
||||
/// <summary>The fields of a sequence the user describes it with (sidecar and index).</summary>
|
||||
public sealed record SequenceInfo(string? Title, IReadOnlyList<string> Tags, int Rating, string? Notes);
|
||||
|
||||
@@ -518,6 +554,19 @@ public static class ArchiveJobs
|
||||
new(JobKind.Cleanup, archive is null ? [] : [archive.Id], archive?.Name,
|
||||
Json(new CleanupParameters(steps, olderThanDays), ArchiveJobJson.Default.CleanupParameters), JobPriority.Normal);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.EmptyTrash"/>: erases exactly the entries of a confirmed <paramref name="plan"/>, refused when the
|
||||
/// trash no longer matches its fingerprint (owner review 2, R6).
|
||||
/// </summary>
|
||||
public static ArchiveJobRequest EmptyTrash(Archive archive, TrashEmptyPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
var items = plan.Entries.OrderBy(e => e.Name, StringComparer.Ordinal).Select(e => new EmptyTrashItem(e.Name, SequenceTrash.EntryFingerprint(e))).ToList();
|
||||
return new(JobKind.EmptyTrash, [archive.Id], archive.Name, Json(new EmptyTrashParameters(items, plan.Fingerprint), ArchiveJobJson.Default.EmptyTrashParameters),
|
||||
JobPriority.User);
|
||||
}
|
||||
|
||||
public static Task<Job> EnqueueAsync(this JobEngine engine, ArchiveJobRequest request, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
|
||||
engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, createdBy, cancellationToken);
|
||||
|
||||
|
||||
@@ -0,0 +1,638 @@
|
||||
using System.Globalization;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using SequenceFrames = Chronos.Core.Archiving.SequenceFrames;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
public sealed partial class FrameTrash
|
||||
{
|
||||
/// <summary>
|
||||
/// Folder inside a photo entry where a restore into a new sequence stages each original for the ingest: never a folder
|
||||
/// another restore shares, never swept by maintenance (it is not the archive's staging), and emptied back into the entry
|
||||
/// by the next restore of the entry when a crash left something there.
|
||||
/// </summary>
|
||||
private const string RestoringFolder = ".restoring";
|
||||
|
||||
/// <summary>Who takes an entry's lease while settling a restore another writer of its sequence finds (<see cref="Settle"/>).</summary>
|
||||
private static readonly string SettleOwner = "chronos@" + Environment.MachineName;
|
||||
|
||||
/// <summary>
|
||||
/// Brings the photos of a trash entry back. Each file is re-hashed against its record: a file that no longer matches
|
||||
/// (or is missing) stays in the trash with its photo, which is reported, as is a photo whose content an intact frame of
|
||||
/// the sequence holds again, and one whose files could not move. Each kept photo says why (<see cref="KeptReason"/>).
|
||||
/// The others move back to their places (a name taken since, or one of its companions', gets <c>_2</c>, <c>_3</c>…)
|
||||
/// with the same frame records, inserted by capture time, and their tombstones go; a journal
|
||||
/// (<see cref="FrameRestoreJournal"/>) settles a restore a crash interrupted, and once the first file moves the restore
|
||||
/// runs to its end whatever the caller cancels. When the sequence is gone (deleted, or never indexed in this archive),
|
||||
/// they go into a new sequence through the archive ingest, titled and placed as theirs was, the record rewritten after
|
||||
/// each photo filed; a cancel there stops before the next photo. The entry goes once nothing is left in it.
|
||||
/// </summary>
|
||||
/// <param name="name">The entry's <see cref="TrashEntry.Name"/> (<c>photos-…</c>).</param>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
/// <exception cref="TrashMismatchException">No file of the entry matches its record; nothing moved.</exception>
|
||||
/// <exception cref="InvalidDataException">The sequence's sidecar is damaged or belongs to another sequence; nothing moved.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">The entry or the sequence is busy, or the sequence holds a restore of another
|
||||
/// entry that is busy and not settled yet; nothing moved.</exception>
|
||||
public async Task<PhotoRestoreResult> RestoreAsync(Archive archive, string name, JobEngine? followUps = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(name);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var entryFolder = Path.Combine(Directory(paths), DiskName(name));
|
||||
var recordPath = entryFolder + RecordExtension;
|
||||
// The entry's lease by the name the trash lists it under, the one an emptying and a settle take.
|
||||
var lease = SequenceTrash.EntryLease(EntryPrefix + DiskName(name));
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, lease, _writer.Options.Owner, _writer.Options.LeaseWait, _writer.Options.LeaseDuration,
|
||||
cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (!System.IO.Directory.Exists(entryFolder) || ReadRecord(recordPath) is not { } listed)
|
||||
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
var sequence = await _db.Sequences.GetAsync(listed.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
var into = sequence is not null && sequence.ArchiveId == archive.Id ? sequence : null;
|
||||
// What an earlier restore a crash interrupted left half-way is settled first, so the record read next is true.
|
||||
Unstage(entryFolder);
|
||||
if (into is not null && File.Exists(paths.Sequence(into.Folder).RestoreJournalPath))
|
||||
{
|
||||
await using (await _writer.LockAsync(paths, into.Id, cancellationToken).ConfigureAwait(false))
|
||||
SequenceWriter.ReadLocked(paths.Sequence(into.Folder), into.Id, lease);
|
||||
}
|
||||
if (!System.IO.Directory.Exists(entryFolder) || ReadRecord(recordPath) is not { } record)
|
||||
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
var (intact, kept) = await CheckAsync(entryFolder, record, cancellationToken).ConfigureAwait(false);
|
||||
// Nothing that matches its record: the entry stays as it is.
|
||||
if (intact.Count == 0) throw new TrashMismatchException();
|
||||
var had = into?.Status ?? SequenceStatus.None;
|
||||
PhotoRestoreResult result;
|
||||
List<Stay> stays;
|
||||
var stopped = false;
|
||||
if (into is not null)
|
||||
{
|
||||
// The record is settled under the sequence's lease, with the sidecar.
|
||||
(result, var left) = await IntoSequenceAsync(archive, paths, into, recordPath, entryFolder, lease, intact, cancellationToken).ConfigureAwait(false);
|
||||
stays = [.. kept, .. left];
|
||||
}
|
||||
else
|
||||
{
|
||||
var restore = await IntoNewSequenceAsync(archive, paths, record, recordPath, entryFolder, intact, cancellationToken).ConfigureAwait(false);
|
||||
stays = [.. kept, .. restore.Left];
|
||||
Rewrite(recordPath, entryFolder, record with { Photos = [.. stays.Select(s => s.Photo)], Leftovers = Merge(record.Leftovers, restore.Leftovers) });
|
||||
restore.Failure?.Throw();
|
||||
stopped = restore.Stopped;
|
||||
if (stopped && restore.Restored == 0) throw new OperationCanceledException(cancellationToken);
|
||||
if (restore.SequenceId is not { } id)
|
||||
throw new IOException($"No photo of trash entry {Path.GetFileName(entryFolder)} could be filed into a new sequence; they stay in the trash.");
|
||||
var row = await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"The photos of {record.SequenceTitle} were restored but their sequence is not indexed.");
|
||||
result = new PhotoRestoreResult(row, restore.Restored, [], true);
|
||||
}
|
||||
Log.Info("archive", $"{record.SequenceTitle}: {result.Restored} photo(s) restored from the trash, {stays.Count} kept there");
|
||||
var all = result with { Kept = [.. stays.Select(s => new KeptPhoto(s.Photo.Frame.Original ?? Path.GetFileName(s.Photo.Frame.File), s.Reason))] };
|
||||
if (result.Restored > 0) await QueueAsync(followUps, archive, all.Sequence, had, CancellationToken.None).ConfigureAwait(false);
|
||||
// A cancel stopped a restore into a new sequence before its last photo: those not done stay in the trash, listed.
|
||||
if (stopped) throw new OperationCanceledException(cancellationToken);
|
||||
return all;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A photo a restore leaves in its entry, and why.</summary>
|
||||
private sealed record Stay(TrashedPhoto Photo, KeptReason Reason);
|
||||
|
||||
/// <summary>
|
||||
/// Each photo whose files all match their record (size and SHA-256), and those that stay in the trash: a file that does
|
||||
/// not match, or no file at all (its original was missing when it was deleted).
|
||||
/// </summary>
|
||||
private static async Task<(List<TrashedPhoto> Intact, List<Stay> Kept)> CheckAsync(string entryFolder, PhotoTrashRecord record,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var intact = new List<TrashedPhoto>();
|
||||
var kept = new List<Stay>();
|
||||
foreach (var photo in record.Photos)
|
||||
{
|
||||
if (photo.Files.Count == 0)
|
||||
{
|
||||
kept.Add(new Stay(photo, KeptReason.NoFile));
|
||||
continue;
|
||||
}
|
||||
var ok = true;
|
||||
foreach (var file in photo.Files)
|
||||
{
|
||||
var path = Path.Combine(entryFolder, file.Path);
|
||||
var info = new FileInfo(path);
|
||||
if (!info.Exists || info.Length != file.Size
|
||||
|| (file.Sha256 is { } sha && !string.Equals(sha, await ContentHash.Sha256Async(path, null, cancellationToken).ConfigureAwait(false),
|
||||
StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
Log.Warning("archive", $"{file.Path} of trash entry {Path.GetFileName(entryFolder)} does not match its record; it stays in the trash");
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ok) intact.Add(photo);
|
||||
else kept.Add(new Stay(photo, KeptReason.Mismatch));
|
||||
}
|
||||
return (intact, kept);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The photos back into their sequence, under its lease: the names chosen and the journal written before the first
|
||||
/// move, then every move to its end, the sidecar, and the record settled (<see cref="Settle"/>). Returns what came
|
||||
/// back and the photos left in the trash.
|
||||
/// </summary>
|
||||
/// <param name="lease">The entry's lease, which the caller holds.</param>
|
||||
private async Task<(PhotoRestoreResult, List<Stay>)> IntoSequenceAsync(Archive archive, ArchivePaths paths, Sequence sequence, string recordPath,
|
||||
string entryFolder, string lease, List<TrashedPhoto> intact, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
var left = new List<Stay>();
|
||||
int restored;
|
||||
SequenceManifest updated;
|
||||
var indexed = true;
|
||||
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id, lease);
|
||||
// A restore of another entry, busy now, is not settled yet: its journal is not written over.
|
||||
EnsureSettled(folder);
|
||||
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
|
||||
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, folder, cancellationToken).ConfigureAwait(false);
|
||||
var ids = manifest.Frames.Select(f => f.Id).ToHashSet();
|
||||
var holders = manifest.Frames.Where(f => f.Sha256 is not null).ToLookup(f => f.Sha256!, StringComparer.OrdinalIgnoreCase);
|
||||
var taken = manifest.Frames.Select(f => f.File).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var planned = new List<(TrashedPhoto Photo, SidecarFrame Frame, RestoredPhoto Moves)>();
|
||||
foreach (var photo in intact)
|
||||
{
|
||||
// In the sequence again (restored before, or filed again since): the trash keeps its copy. Only a frame that
|
||||
// still holds the content counts; a missing or damaged one leaves the trash's copy to come back.
|
||||
if (ids.Contains(photo.Frame.Id) || (photo.Frame.Sha256 is { } sha && holders[sha].Any(f => ArchiveIngest.IsIntact(folder, f))))
|
||||
{
|
||||
left.Add(new Stay(photo, KeptReason.InSequence));
|
||||
continue;
|
||||
}
|
||||
var original = photo.Files[0];
|
||||
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
|
||||
var file = FreeName(folder, original.From, tails, taken);
|
||||
var stem = file[..^Path.GetExtension(file).Length];
|
||||
taken.Add(file);
|
||||
// A companion follows its photo's name: IMG_0001_2.xmp beside IMG_0001_2.JPG.
|
||||
List<FrameRemovalMove> moves = [new(file, paths.ToRelative(Path.Combine(entryFolder, original.Path)))];
|
||||
for (var c = 0; c < tails.Count; c++)
|
||||
{
|
||||
taken.Add(stem + tails[c]);
|
||||
moves.Add(new FrameRemovalMove(stem + tails[c], paths.ToRelative(Path.Combine(entryFolder, photo.Files[c + 1].Path))));
|
||||
}
|
||||
planned.Add((photo, photo.Frame with { File = file, Flags = photo.Frame.Flags & ~FrameFlags.Missing }, new RestoredPhoto(photo.Frame.Id, moves)));
|
||||
}
|
||||
if (planned.Count == 0) return (new PhotoRestoreResult(sequence, 0, [], false), left);
|
||||
// Checked once: from the journal on, the restore runs to its end whatever the caller cancels meanwhile.
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var journal = new FrameRestoreJournal(paths.ToRelative(recordPath), paths.ToRelative(entryFolder), [.. planned.Select(p => p.Moves)]);
|
||||
journal.Write(folder);
|
||||
var back = new List<SidecarFrame>();
|
||||
foreach (var (photo, frame, moves) in planned)
|
||||
{
|
||||
if (MoveIn(paths, folder, moves.Moves)) back.Add(frame);
|
||||
else left.Add(new Stay(photo, KeptReason.NotMoved));
|
||||
}
|
||||
updated = manifest;
|
||||
if (back.Count > 0)
|
||||
{
|
||||
var returned = back.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var tombstones = manifest.Removed?.Where(r => !returned.Contains(r.Sha256)).ToList();
|
||||
updated = SequenceFrames.Insert(manifest, back) with
|
||||
{
|
||||
Status = manifest.Status & ~Uncovered,
|
||||
Removed = tombstones is { Count: > 0 } ? tombstones : null,
|
||||
};
|
||||
try
|
||||
{
|
||||
ManifestStore.WriteSequence(folder.ManifestPath, updated);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// The sidecar lists none of them: their files go back into the entry, whose record is as it was.
|
||||
Log.Warning("archive", $"{sequence.DisplayTitle}: the sidecar could not take the photos restored; they go back into the trash", ex);
|
||||
Settle(folder, manifest, journal, lease);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
Settle(folder, updated, journal, lease);
|
||||
restored = back.Count;
|
||||
if (restored > 0)
|
||||
{
|
||||
indexed = await IndexAsync(archive, folder, updated, photosChanged, sequence.DisplayTitle).ConfigureAwait(false);
|
||||
ShiftProxies(folder, manifest.Frames, updated.Frames, []);
|
||||
ShiftThumbnails(paths, folder, sequence.Id, manifest.Frames, updated.Frames);
|
||||
}
|
||||
}
|
||||
var row = restored > 0 ? await RowAsync(sequence, updated, indexed).ConfigureAwait(false) : sequence;
|
||||
return (new PhotoRestoreResult(row, restored, [], false), left);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves one photo's files from its entry into the sequence, the original first. When one cannot follow, those that
|
||||
/// moved go back, the companions first, so the photo stays whole in the trash; an original that cannot go back either
|
||||
/// stays restored, and its companions that are still in the entry then stay there (leftovers of its record). Returns
|
||||
/// whether the original is in the sequence.
|
||||
/// </summary>
|
||||
private static bool MoveIn(ArchivePaths paths, SequencePaths folder, IReadOnlyList<FrameRemovalMove> moves)
|
||||
{
|
||||
var done = 0;
|
||||
try
|
||||
{
|
||||
for (; done < moves.Count; done++) MoveFile(paths.FromRelative(moves[done].To), folder.File(moves[done].From));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"{moves[done].To} could not move back into {folder.RelativeFolder}; its photo stays in the trash", ex);
|
||||
for (var i = done - 1; i >= 0; i--)
|
||||
{
|
||||
try
|
||||
{
|
||||
MoveFile(folder.File(moves[i].From), paths.FromRelative(moves[i].To));
|
||||
}
|
||||
catch (Exception again) when (again is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Error("archive", $"{folder.ArchiveRelative(moves[i].From)} could not go back into the trash; its photo stays restored", again);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles a restore into a sequence (<see cref="FrameRestoreJournal"/>) as <paramref name="manifest"/>, the sidecar
|
||||
/// read or written under the sequence's lease, has it: each photo the sidecar lists again leaves the entry's record (a
|
||||
/// companion of it still in the entry stays there as one of the record's leftovers), and each file of the others that
|
||||
/// reached the sequence goes back into the entry, whose record still lists it (unless the entry was emptied since: the
|
||||
/// file then stays where it is, logged, for a scan to adopt). Then the journal goes. All of it under the entry's lease
|
||||
/// as well, which an emptying holds: an entry busy now (or a failure, logged) keeps the journal, and the next writer of
|
||||
/// the sequence settles it (<see cref="EnsureSettled"/> keeps writers that would add files from going on meanwhile).
|
||||
/// </summary>
|
||||
/// <param name="heldLease">The entry lease the caller holds already (its own restore), if any.</param>
|
||||
internal static void Settle(SequencePaths sequence, SequenceManifest manifest, FrameRestoreJournal journal, string? heldLease = null)
|
||||
{
|
||||
var archive = sequence.Archive;
|
||||
var recordPath = archive.FromRelative(journal.Record);
|
||||
var entryFolder = archive.FromRelative(journal.Folder);
|
||||
var listed = manifest.Frames.Select(f => f.Id).ToHashSet();
|
||||
var lease = EntryLease(entryFolder);
|
||||
LeaseFile? taken = null;
|
||||
if (lease != heldLease)
|
||||
{
|
||||
taken = LeaseFile.TryAcquire(archive.LocksDirectory, lease, SettleOwner);
|
||||
if (taken is null)
|
||||
{
|
||||
Log.Info("archive", $"A restore from the trash into {sequence.RelativeFolder} waits: its entry {Path.GetFileName(entryFolder)} is busy");
|
||||
return;
|
||||
}
|
||||
}
|
||||
using var held = taken;
|
||||
try
|
||||
{
|
||||
var record = ReadRecord(recordPath);
|
||||
var back = new HashSet<Guid>();
|
||||
var leftovers = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var photo in journal.Photos)
|
||||
{
|
||||
if (listed.Contains(photo.Frame))
|
||||
{
|
||||
back.Add(photo.Frame);
|
||||
leftovers.UnionWith(photo.Moves.Where(m => File.Exists(archive.FromRelative(m.To))).Select(m => m.To));
|
||||
continue;
|
||||
}
|
||||
foreach (var move in photo.Moves)
|
||||
{
|
||||
var place = sequence.File(move.From);
|
||||
var trashed = archive.FromRelative(move.To);
|
||||
if (!File.Exists(place) || File.Exists(trashed)) continue;
|
||||
if (record is null)
|
||||
{
|
||||
Log.Warning("archive", $"{sequence.ArchiveRelative(move.From)} stays in its sequence: its trash entry is gone");
|
||||
continue;
|
||||
}
|
||||
MoveFile(place, trashed);
|
||||
}
|
||||
}
|
||||
if (record is not null && back.Count > 0)
|
||||
{
|
||||
var extra = record.Photos.Where(p => back.Contains(p.Frame.Id)).SelectMany(p => p.Files)
|
||||
.Where(f => leftovers.Contains(archive.ToRelative(Path.Combine(entryFolder, f.Path))));
|
||||
Rewrite(recordPath, entryFolder, record with
|
||||
{
|
||||
Photos = [.. record.Photos.Where(p => !back.Contains(p.Frame.Id))],
|
||||
Leftovers = Merge(record.Leftovers, extra),
|
||||
});
|
||||
}
|
||||
FrameRestoreJournal.Delete(sequence);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"A restore from the trash into {sequence.RelativeFolder} is not settled yet; the next writer of the sequence settles it", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles the restore a crash interrupted (<see cref="Settle"/>), if any; the caller holds the sequence's lease, and
|
||||
/// <paramref name="heldLease"/> when it holds an entry's lease too.
|
||||
/// </summary>
|
||||
internal static void RecoverRestore(SequencePaths sequence, SequenceManifest manifest, string? heldLease = null)
|
||||
{
|
||||
if (!File.Exists(sequence.RestoreJournalPath)) return;
|
||||
if (FrameRestoreJournal.Read(sequence) is { } journal)
|
||||
{
|
||||
Log.Warning("archive", $"An interrupted restore from the trash into {sequence.RelativeFolder} is settled unless its entry is busy");
|
||||
Settle(sequence, manifest, journal, heldLease);
|
||||
}
|
||||
else
|
||||
{
|
||||
FrameRestoreJournal.Delete(sequence); // torn while being written: nothing was moved yet
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refuses to go on while a restore into <paramref name="sequence"/> is still not settled after
|
||||
/// <see cref="SequenceWriter.ReadLocked"/> (its entry was busy, or a file could not move): a writer that would write
|
||||
/// another journal over it, or move the sequence's folder away with it, waits until it is. The caller holds the
|
||||
/// sequence's lease.
|
||||
/// </summary>
|
||||
/// <exception cref="LeaseUnavailableException">The restore is not settled; nothing was changed.</exception>
|
||||
internal static void EnsureSettled(SequencePaths sequence)
|
||||
{
|
||||
if (!File.Exists(sequence.RestoreJournalPath)) return;
|
||||
var lease = FrameRestoreJournal.Read(sequence) is { } journal ? EntryLease(sequence.Archive.FromRelative(journal.Folder)) : "restore";
|
||||
throw new LeaseUnavailableException(lease, LeaseFile.Holder(sequence.Archive.LocksDirectory, lease));
|
||||
}
|
||||
|
||||
/// <summary>The lease of the photo entry in <paramref name="entryFolder"/>, as a restore and an emptying of it take it.</summary>
|
||||
private static string EntryLease(string entryFolder) => SequenceTrash.EntryLease(EntryPrefix + Path.GetFileName(entryFolder));
|
||||
|
||||
/// <summary>
|
||||
/// What a restore into a new sequence did: the photos left in the trash, the companions that did not follow theirs, and
|
||||
/// what stopped it before its last photo (a failure other than a file's, or a cancel).
|
||||
/// </summary>
|
||||
private sealed record NewSequenceRestore(Guid? SequenceId, int Restored, List<Stay> Left, List<TrashedFile> Leftovers, ExceptionDispatchInfo? Failure,
|
||||
bool Stopped);
|
||||
|
||||
/// <summary>
|
||||
/// The photos of a sequence that is gone into a new one, through the archive ingest (naming templates, a sidecar of its
|
||||
/// own), one photo at a time so one that fails stays in the trash alone: titled as theirs was, placed at its folder when
|
||||
/// that is free, and keyed by its id, so every entry of that sequence comes back into the same new one. Each original
|
||||
/// is staged inside its own entry (<see cref="RestoringFolder"/>); once it leaves the entry its commit runs to the end,
|
||||
/// and when it is not filed, whatever the failure, it goes back. Companions follow their photo under a name chosen so
|
||||
/// that theirs are free. The record is rewritten after each photo filed, so a crash or a failure later never leaves it
|
||||
/// listing one that is back. A cancel, or a failure other than a file's, stops before the next photo.
|
||||
/// </summary>
|
||||
private async Task<NewSequenceRestore> IntoNewSequenceAsync(Archive archive, ArchivePaths paths, PhotoTrashRecord record, string recordPath,
|
||||
string entryFolder, List<TrashedPhoto> intact, CancellationToken cancellationToken)
|
||||
{
|
||||
var left = new List<Stay>();
|
||||
var leftovers = new List<TrashedFile>();
|
||||
var filed = new HashSet<Guid>();
|
||||
var staging = Path.Combine(entryFolder, RestoringFolder);
|
||||
var key = $"trash:{record.SequenceId:N}";
|
||||
var target = new SequenceTarget(key, record.SequenceTitle, record.SequenceFolder.Length > 0 ? record.SequenceFolder : null, null);
|
||||
var sequenceId = await _db.Sequences.FindBySessionKeyAsync(archive.Id, key, cancellationToken).ConfigureAwait(false);
|
||||
SequencePaths? folder = null;
|
||||
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var restored = 0;
|
||||
ExceptionDispatchInfo? failure = null;
|
||||
var stopped = false;
|
||||
foreach (var photo in intact)
|
||||
{
|
||||
stopped |= failure is null && cancellationToken.IsCancellationRequested;
|
||||
if (failure is not null || stopped)
|
||||
{
|
||||
left.Add(new Stay(photo, KeptReason.NotMoved));
|
||||
continue;
|
||||
}
|
||||
if (folder is null && sequenceId is { } known && await _db.Sequences.GetAsync(known, CancellationToken.None).ConfigureAwait(false) is { } row)
|
||||
folder = paths.Sequence(row.Folder);
|
||||
var original = photo.Files[0];
|
||||
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
|
||||
var planned = FreeName(folder, ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(original.From), tails, names);
|
||||
var inEntry = Path.Combine(entryFolder, original.Path);
|
||||
var path = Path.Combine(staging, original.Path);
|
||||
try
|
||||
{
|
||||
MoveFile(inEntry, path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"{original.Path} could not be staged for a restore; it stays in the trash", ex);
|
||||
left.Add(new Stay(photo, KeptReason.NotMoved));
|
||||
continue;
|
||||
}
|
||||
IngestResult? result = null;
|
||||
try
|
||||
{
|
||||
var frame = new StagedFrame(path, photo.Frame.Original ?? Path.GetFileName(original.From), original.Size, photo.Frame.Sha256 ?? original.Sha256!,
|
||||
MetadataReader.Read(path, CancellationToken.None), photo.Frame.CapturedAt, Path.GetFileName(planned));
|
||||
// The original has left the entry: its commit runs to the end whatever the caller cancels meanwhile.
|
||||
result = (await _ingest.CommitSessionAsync(archive, target, [frame], CancellationToken.None).ConfigureAwait(false))[0];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("archive", $"{original.Path} could not be restored into a new sequence", ex);
|
||||
if (ex is not (IOException or UnauthorizedAccessException or InvalidDataException)) failure = ExceptionDispatchInfo.Capture(ex);
|
||||
}
|
||||
if (File.Exists(path))
|
||||
{
|
||||
// Not filed (a failure, or a duplicate of a photo the new sequence holds): it returns to the entry, or, when it
|
||||
// cannot, the next restore of the entry puts it back.
|
||||
try
|
||||
{
|
||||
MoveFile(path, inEntry);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Error("archive", $"{original.Path} stays staged in its trash entry; the next restore puts it back", ex);
|
||||
}
|
||||
left.Add(new Stay(photo, result is { Duplicate: true } ? KeptReason.InSequence : KeptReason.NotMoved));
|
||||
continue;
|
||||
}
|
||||
restored++;
|
||||
filed.Add(photo.Frame.Id);
|
||||
if (result is null)
|
||||
{
|
||||
// Filed although its commit failed afterwards (the ingest's journal completes it): where is not known, so its
|
||||
// companions stay in the trash.
|
||||
leftovers.AddRange(photo.Files.Skip(1));
|
||||
Follow();
|
||||
continue;
|
||||
}
|
||||
sequenceId ??= result.SequenceId;
|
||||
var placed = paths.FromRelative(result.RelativePath);
|
||||
var stem = placed[..^Path.GetExtension(placed).Length];
|
||||
names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(placed));
|
||||
foreach (var companion in photo.Files.Skip(1))
|
||||
{
|
||||
var beside = stem + CompanionTail(companion.From, original.From);
|
||||
names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(beside));
|
||||
try
|
||||
{
|
||||
MoveFile(Path.Combine(entryFolder, companion.Path), beside);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Taken there since its name was chosen, or not movable: it stays in the trash, counted in the record.
|
||||
Log.Warning("archive", $"{companion.Path} could not follow its photo to {result.RelativePath}; it stays in the trash", ex);
|
||||
leftovers.Add(companion);
|
||||
}
|
||||
}
|
||||
Follow();
|
||||
}
|
||||
// A photo filed by a commit that failed afterwards may be the first in the new sequence.
|
||||
if (sequenceId is null && restored > 0)
|
||||
sequenceId = await _db.Sequences.FindBySessionKeyAsync(archive.Id, key, CancellationToken.None).ConfigureAwait(false);
|
||||
return new NewSequenceRestore(sequenceId, restored, left, leftovers, failure, stopped);
|
||||
|
||||
// The record without the photos filed so far, and with the companions that did not follow; a record that cannot be
|
||||
// written now (logged) is written once more when the restore ends.
|
||||
void Follow()
|
||||
{
|
||||
try
|
||||
{
|
||||
Rewrite(recordPath, entryFolder, record with
|
||||
{
|
||||
Photos = [.. record.Photos.Where(p => !filed.Contains(p.Frame.Id))],
|
||||
Leftovers = Merge(record.Leftovers, leftovers),
|
||||
});
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"Trash record {recordPath} does not follow the photos restored yet; it is written again at the end", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Puts back into an entry what a restore into a new sequence left staged in it (a crash, or a file that could not move back).</summary>
|
||||
private static void Unstage(string entryFolder)
|
||||
{
|
||||
var staging = Path.Combine(entryFolder, RestoringFolder);
|
||||
if (!System.IO.Directory.Exists(staging)) return;
|
||||
foreach (var file in System.IO.Directory.EnumerateFiles(staging, "*", SearchOption.AllDirectories).ToList())
|
||||
{
|
||||
var place = Path.Combine(entryFolder, Path.GetRelativePath(staging, file));
|
||||
if (File.Exists(place))
|
||||
{
|
||||
Log.Warning("archive", $"{file} stays staged: {place} exists");
|
||||
continue;
|
||||
}
|
||||
MoveFile(file, place);
|
||||
Log.Warning("archive", $"{Path.GetRelativePath(entryFolder, place)} of trash entry {Path.GetFileName(entryFolder)} was staged by a restore that stopped; it is back");
|
||||
}
|
||||
FrameRemovalJournal.RemoveEmpty(staging);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rewrites an entry's record with what it still holds; when it lists nothing and nothing is left in its folder, the
|
||||
/// record goes too. While it lists a photo, its folder stays (empty when only photos without a file are left), so the
|
||||
/// entry stays listed and Empty can erase it.
|
||||
/// </summary>
|
||||
private static void Rewrite(string recordPath, string entryFolder, PhotoTrashRecord record)
|
||||
{
|
||||
var done = record.Photos.Count == 0 && record.Leftovers is not { Count: > 0 };
|
||||
if (done) FrameRemovalJournal.RemoveEmpty(entryFolder);
|
||||
else if (System.IO.Directory.Exists(entryFolder))
|
||||
foreach (var child in System.IO.Directory.EnumerateDirectories(entryFolder).ToList()) FrameRemovalJournal.RemoveEmpty(child);
|
||||
// Only an entry left without a file goes; anything still in its folder keeps it listed, never erased by a restore.
|
||||
if (done && !System.IO.Directory.Exists(entryFolder))
|
||||
{
|
||||
File.Delete(recordPath);
|
||||
return;
|
||||
}
|
||||
AtomicFile.WriteAllText(recordPath, JsonSerializer.Serialize(record with
|
||||
{
|
||||
Bytes = record.Photos.Sum(p => p.Files.Sum(f => f.Size)) + (record.Leftovers?.Sum(f => f.Size) ?? 0),
|
||||
}, TrashJson.Default.PhotoTrashRecord));
|
||||
}
|
||||
|
||||
/// <summary>The leftovers of a record with <paramref name="more"/>, each file once; null when there are none.</summary>
|
||||
private static List<TrashedFile>? Merge(IReadOnlyList<TrashedFile>? leftovers, IEnumerable<TrashedFile> more)
|
||||
{
|
||||
var all = (leftovers ?? []).Concat(more).DistinctBy(f => f.Path, StringComparer.OrdinalIgnoreCase).ToList();
|
||||
return all.Count > 0 ? all : null;
|
||||
}
|
||||
|
||||
/// <summary>What a companion's name adds to its photo's stem (<c>.xmp</c>, <c>.CR2.xmp</c>).</summary>
|
||||
private static string CompanionTail(string companion, string photo)
|
||||
{
|
||||
var stem = Path.GetFileNameWithoutExtension(Path.GetFileName(photo));
|
||||
var name = Path.GetFileName(companion);
|
||||
return name.StartsWith(stem, StringComparison.OrdinalIgnoreCase) ? name[stem.Length..] : Path.GetExtension(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="file"/> when it and its companions' names (<paramref name="tails"/> after its stem) are free in
|
||||
/// <paramref name="taken"/> and on disk in <paramref name="folder"/> (none yet: in <paramref name="taken"/> only), else
|
||||
/// <c>stem_2.ext</c>, <c>stem_3.ext</c>…
|
||||
/// </summary>
|
||||
private static string FreeName(SequencePaths? folder, string file, IReadOnlyList<string> tails, HashSet<string> taken)
|
||||
{
|
||||
var extension = Path.GetExtension(file);
|
||||
var stem = file[..^extension.Length];
|
||||
var candidate = file;
|
||||
for (var n = 2; Taken(candidate); n++)
|
||||
candidate = string.Create(CultureInfo.InvariantCulture, $"{stem}_{n}{extension}");
|
||||
return candidate;
|
||||
|
||||
bool Taken(string name)
|
||||
{
|
||||
var named = name[..^extension.Length];
|
||||
return Used(name) || tails.Any(t => Used(named + t));
|
||||
}
|
||||
|
||||
bool Used(string name) => taken.Contains(name) || (folder is not null && File.Exists(folder.File(name)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The files of one photo a restore moves from its trash entry into its sequence, the original first.</summary>
|
||||
/// <param name="Frame">The photo's frame id, which the sidecar lists once the photo is back.</param>
|
||||
/// <param name="Moves">Each file: <see cref="FrameRemovalMove.From"/> its place in the sequence folder, <see cref="FrameRemovalMove.To"/>
|
||||
/// the file in the entry (relative to the archive root).</param>
|
||||
internal sealed record RestoredPhoto(Guid Frame, IReadOnlyList<FrameRemovalMove> Moves);
|
||||
|
||||
/// <summary>
|
||||
/// Write-ahead record of photos restored from the trash into their sequence (<c>.chronos/restore.pending.json</c>, owner
|
||||
/// review 2, R6): the entry they come from and each photo's file moves. Written under the sequence's lease before the
|
||||
/// first move and removed once the restore is settled (<see cref="FrameTrash.Settle"/>: the record without the photos the
|
||||
/// sidecar lists, the files of the others back in the entry), so the next writer of the sequence settles a restore a crash
|
||||
/// interrupted (<see cref="SequenceWriter.ReadLocked"/>).
|
||||
/// </summary>
|
||||
/// <param name="Record">The entry's record, relative to the archive root.</param>
|
||||
/// <param name="Folder">The entry's folder, relative to the archive root.</param>
|
||||
internal sealed record FrameRestoreJournal(string Record, string Folder, IReadOnlyList<RestoredPhoto> Photos)
|
||||
{
|
||||
public void Write(SequencePaths sequence)
|
||||
{
|
||||
System.IO.Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
AtomicFile.WriteAllBytes(sequence.RestoreJournalPath, JsonSerializer.SerializeToUtf8Bytes(this, TrashJson.Default.FrameRestoreJournal));
|
||||
}
|
||||
|
||||
/// <summary>The journal of a sequence; null when it is torn (written by a process that died while writing it).</summary>
|
||||
public static FrameRestoreJournal? Read(SequencePaths sequence)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.RestoreJournalPath), TrashJson.Default.FrameRestoreJournal);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Delete(SequencePaths sequence)
|
||||
{
|
||||
if (File.Exists(sequence.RestoreJournalPath)) File.Delete(sequence.RestoreJournalPath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,717 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using ProcessingJobs = Chronos.Data.Processing.ProcessingJobs;
|
||||
using ProcessingFrames = Chronos.Data.Processing.SequenceFrames;
|
||||
using SequenceFrames = Chronos.Core.Archiving.SequenceFrames;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>Why photos cannot leave their sequence; nothing is touched.</summary>
|
||||
public enum FrameDeleteBlock
|
||||
{
|
||||
/// <summary>The archive is offline or read-only.</summary>
|
||||
Offline,
|
||||
|
||||
/// <summary>A running or paused job works on the sequence or its whole archive (<see cref="SequenceTrash"/>'s rule).</summary>
|
||||
Busy,
|
||||
|
||||
/// <summary>The sequence's frames changed since the caller read them (another version, or a frame named is gone).</summary>
|
||||
FramesChanged,
|
||||
|
||||
/// <summary>Every frame of the sequence would go: delete the sequence instead, which keeps its settings and renders.</summary>
|
||||
WouldEmpty,
|
||||
|
||||
/// <summary>
|
||||
/// A photo named was never hashed and its original is on disk but cannot be read (another program holds it, or no
|
||||
/// access; <see cref="FrameDeletePlan.Unhashable"/>): it is hashed as it goes, for the tombstone that tells sync it was
|
||||
/// deleted, so it waits until it can be read. One whose original is missing is not blocked: it goes without a file and
|
||||
/// without a tombstone, as there is no content left to name.
|
||||
/// </summary>
|
||||
Unhashable,
|
||||
}
|
||||
|
||||
/// <summary>The dry run of deleting photos of one sequence into the archive's trash (owner review 2, R6).</summary>
|
||||
/// <param name="Frames">The frames that go, in index order.</param>
|
||||
/// <param name="Bytes">Their originals' size.</param>
|
||||
/// <param name="Blocked">Why they cannot go; empty when they can.</param>
|
||||
public sealed record FrameDeletePlan(Sequence Sequence, IReadOnlyList<Frame> Frames, long Bytes, IReadOnlyList<FrameDeleteBlock> Blocked)
|
||||
{
|
||||
public bool CanDelete => Blocked.Count == 0 && Frames.Count > 0;
|
||||
|
||||
/// <summary>The frames named that block the plan as <see cref="FrameDeleteBlock.Unhashable"/>, in index order.</summary>
|
||||
public IReadOnlyList<Frame> Unhashable { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>What a photo deletion did: the trash entry made and the sequence as it is now.</summary>
|
||||
public sealed record FrameDeleteResult(TrashEntry Entry, Sequence Sequence);
|
||||
|
||||
/// <summary>Why a photo stayed in the trash when its entry was restored.</summary>
|
||||
public enum KeptReason
|
||||
{
|
||||
/// <summary>A file of it no longer matches its record (changed, or gone from the entry).</summary>
|
||||
Mismatch,
|
||||
|
||||
/// <summary>Its files match, but they could not be moved back (open elsewhere, no access, or the archive refused them).</summary>
|
||||
NotMoved,
|
||||
|
||||
/// <summary>The sequence holds its content again (restored before, or filed again since): the trash keeps its copy.</summary>
|
||||
InSequence,
|
||||
|
||||
/// <summary>Its original was already missing when it was deleted: the entry holds its record without a file.</summary>
|
||||
NoFile,
|
||||
}
|
||||
|
||||
/// <summary>A photo a restore left in the trash: its name (as on the card or upload source) and why.</summary>
|
||||
public sealed record KeptPhoto(string Name, KeptReason Reason)
|
||||
{
|
||||
/// <summary>"2 photos stayed in the trash: they no longer match their record." in <paramref name="culture"/>.</summary>
|
||||
public static string Sentence(KeptReason reason, int count, System.Globalization.CultureInfo culture) =>
|
||||
Core.Localization.Loc.Text(reason switch
|
||||
{
|
||||
KeptReason.Mismatch => "Archive.Trash.Kept.Mismatch",
|
||||
KeptReason.NotMoved => "Archive.Trash.Kept.NotMoved",
|
||||
KeptReason.InSequence => "Archive.Trash.Kept.InSequence",
|
||||
_ => "Archive.Trash.Kept.NoFile",
|
||||
}, [count], culture);
|
||||
|
||||
/// <summary>One sentence per reason, in the order of <see cref="KeptReason"/>, each counting its photos.</summary>
|
||||
public static IReadOnlyList<string> Sentences(IEnumerable<KeptPhoto> kept, System.Globalization.CultureInfo culture) =>
|
||||
[.. kept.GroupBy(k => k.Reason).OrderBy(g => g.Key).Select(g => Sentence(g.Key, g.Count(), culture))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a restore of photos did: the sequence they went back into (a new one when theirs is gone), how many came back, and
|
||||
/// the photos kept in the trash, each with why (<see cref="KeptReason"/>).
|
||||
/// </summary>
|
||||
public sealed record PhotoRestoreResult(Sequence Sequence, int Restored, IReadOnlyList<KeptPhoto> Kept, bool NewSequence);
|
||||
|
||||
/// <summary>
|
||||
/// Deleting photos of a sequence without erasing anything (owner review 2, R6; BRIEF §0.2 rule 8): <see cref="PlanDeleteAsync"/>
|
||||
/// is the dry run; <see cref="DeleteAsync"/> moves each original (and its XMP companion) under the sequence's lease into
|
||||
/// <c>.chronos/trash/photos/<sequence>-<time>/originals</c> next to a record of the frames, writes the sidecar
|
||||
/// without them (frames version + 1) and with a tombstone of each (a photo never hashed is hashed first), and indexes it:
|
||||
/// what covered the frames is cleared and queued again, the proxies and thumbnails of the frames that stay follow their
|
||||
/// new index, and the project's positions follow their photos (those on the photos that went wait as pending frames).
|
||||
/// A journal undoes a deletion a crash interrupted, whose entry the trash does not list meanwhile.
|
||||
/// <see cref="RestoreAsync"/> re-hashes each file against its record and moves the matching ones back with the same frame
|
||||
/// records, dropping their tombstones, under a journal of its own; into a new sequence through the archive ingest when
|
||||
/// theirs is gone.
|
||||
/// </summary>
|
||||
public sealed partial class FrameTrash
|
||||
{
|
||||
/// <summary>Folder of the photo entries inside the trash.</summary>
|
||||
public const string FolderName = "photos";
|
||||
|
||||
/// <summary>What <see cref="TrashEntry.Name"/> of a photo entry starts with (the folder name follows).</summary>
|
||||
public const string EntryPrefix = "photos-";
|
||||
|
||||
private const string RecordExtension = ".json";
|
||||
|
||||
/// <summary>Statuses the frames removed or put back no longer let stand: the passes make them again.</summary>
|
||||
private const SequenceStatus Uncovered = SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt;
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIndexer _indexer;
|
||||
private readonly ArchiveIngest _ingest;
|
||||
private readonly SequenceTrash _trash;
|
||||
|
||||
internal FrameTrash(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer indexer, ArchiveIngest ingest, SequenceTrash trash)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_indexer = indexer;
|
||||
_ingest = ingest;
|
||||
_trash = trash;
|
||||
}
|
||||
|
||||
/// <summary>The folder of the photo entries of an archive's trash.</summary>
|
||||
public static string Directory(ArchivePaths archive) => Path.Combine(SequenceTrash.TrashDirectory(archive), FolderName);
|
||||
|
||||
/// <summary>Whether <paramref name="name"/> names a photo entry (<see cref="EntryPrefix"/>).</summary>
|
||||
public static bool IsPhotoEntry(string name) => name.StartsWith(EntryPrefix, StringComparison.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// The dry run: the frames of <paramref name="frameIds"/> that go and their size, or why they cannot go. With
|
||||
/// <paramref name="expectedFramesVersion"/>, frames that changed since the caller read that version block the plan.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The sequence is not in the index, or no frame is named.</exception>
|
||||
public async Task<FrameDeletePlan> PlanDeleteAsync(Guid sequenceId, IReadOnlyList<Guid> frameIds, int? expectedFramesVersion = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frameIds);
|
||||
if (frameIds.Count == 0) throw new ArgumentException("No frame is named.", nameof(frameIds));
|
||||
var sequence = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ArgumentException($"Unknown sequence {sequenceId}.", nameof(sequenceId));
|
||||
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ArgumentException($"Unknown archive {sequence.ArchiveId}.", nameof(sequenceId));
|
||||
var all = await ProcessingFrames.ListAsync(_db, sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
var wanted = frameIds.ToHashSet();
|
||||
var frames = all.Where(f => wanted.Contains(f.Id)).ToList();
|
||||
var blocked = new List<FrameDeleteBlock>();
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var online = ArchiveVolume.Probe(paths) == ArchiveAvailability.Online;
|
||||
if (!online) blocked.Add(FrameDeleteBlock.Offline);
|
||||
var busy = await _trash.BusyAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (busy.Contains(sequence.Id) || busy.Contains(sequence.ArchiveId)) blocked.Add(FrameDeleteBlock.Busy);
|
||||
if (frames.Count != wanted.Count || (expectedFramesVersion is { } expected && expected != sequence.FramesVersion)) blocked.Add(FrameDeleteBlock.FramesChanged);
|
||||
if (frames.Count > 0 && frames.Count == all.Count) blocked.Add(FrameDeleteBlock.WouldEmpty);
|
||||
// A photo without a hash is hashed as it goes, for its tombstone: one whose original cannot be read waits.
|
||||
var unhashable = online ? Unreadable(paths, frames) : [];
|
||||
if (unhashable.Count > 0) blocked.Add(FrameDeleteBlock.Unhashable);
|
||||
return new FrameDeletePlan(sequence, frames, frames.Sum(f => f.Size), blocked) { Unhashable = unhashable };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frames never hashed whose original is on disk but cannot be opened for reading, in index order: the first
|
||||
/// <c>256</c> of them are opened (nothing is read), so a dry run of thousands stays quick on a share; one past those that
|
||||
/// cannot be read refuses the deletion itself, which hashes them (an <see cref="IOException"/>, nothing moved). A missing
|
||||
/// original is no reason: nothing is left to hash.
|
||||
/// </summary>
|
||||
private static List<Frame> Unreadable(ArchivePaths paths, IReadOnlyList<Frame> frames)
|
||||
{
|
||||
const int Probes = 256;
|
||||
return [.. frames.Where(f => f.Sha256 is null).OrderBy(f => f.Index).Take(Probes).Where(f => !CanRead(paths.FromRelative(f.RelativePath)))];
|
||||
}
|
||||
|
||||
/// <summary>Whether a file opens for reading; one that is not there counts as readable (there is nothing to read).</summary>
|
||||
private static bool CanRead(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves exactly the planned photos into the trash and takes them out of the sequence, then queues on
|
||||
/// <paramref name="followUps"/> (null: nothing) what the frames need again: the light analysis, a background deep analysis
|
||||
/// when the sequence had one, and the thumbnails and proxies the host keeps (always on a server; on a desktop those it
|
||||
/// had). A kind the engine does not run, or one already queued for the sequence, is left out. Once the sidecar is
|
||||
/// written the deletion stands: an index that cannot follow (logged) is resynced by the next scan.
|
||||
/// </summary>
|
||||
/// <param name="deletedBy">Who asked (user name or client), kept in the trash record.</param>
|
||||
/// <exception cref="StaleDeletePlanException">The plan is blocked, or the sequence changed since it was made; nothing moved.</exception>
|
||||
/// <exception cref="ArchiveOfflineException">The archive went offline; nothing moved.</exception>
|
||||
/// <exception cref="IOException">A file is open elsewhere, or the sidecar could not be written; nothing moved.</exception>
|
||||
public async Task<FrameDeleteResult> DeleteAsync(FrameDeletePlan plan, string? deletedBy = null, JobEngine? followUps = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
var id = plan.Sequence.Id;
|
||||
if (!plan.CanDelete) throw new StaleDeletePlanException(id);
|
||||
var revised = await PlanDeleteAsync(id, [.. plan.Frames.Select(f => f.Id)], plan.Sequence.FramesVersion, cancellationToken).ConfigureAwait(false);
|
||||
var archive = await ArchiveOfAsync(revised.Sequence, cancellationToken).ConfigureAwait(false);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
// Offline since the plan: said as such (ArchiveOfflineException), not as a stale plan.
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
if (!revised.CanDelete || revised.Sequence.Folder != plan.Sequence.Folder) throw new StaleDeletePlanException(id);
|
||||
var folder = paths.Sequence(revised.Sequence.Folder);
|
||||
var had = revised.Sequence.Status;
|
||||
|
||||
TrashEntry entry;
|
||||
SequenceManifest updated;
|
||||
bool indexed;
|
||||
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var manifest = SequenceWriter.ReadLocked(folder, id);
|
||||
var plannedPaths = plan.Frames.ToDictionary(f => f.Id, f => f.RelativePath);
|
||||
var planned = plannedPaths.Keys.ToHashSet();
|
||||
var removed = manifest.Frames.Where(f => planned.Contains(f.Id)).ToList();
|
||||
if (manifest.Versions.Frames != plan.Sequence.FramesVersion || removed.Count != planned.Count
|
||||
|| removed.Any(f => plannedPaths[f.Id] != folder.ArchiveRelative(f.File)))
|
||||
throw new StaleDeletePlanException(id);
|
||||
var kept = manifest.Frames.Where(f => !planned.Contains(f.Id)).ToList();
|
||||
if (kept.Count == 0) throw new StaleDeletePlanException(id);
|
||||
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
|
||||
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, folder, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var trash = Directory(paths);
|
||||
System.IO.Directory.CreateDirectory(trash);
|
||||
var name = EntryName(trash, id);
|
||||
var entryFolder = Path.Combine(trash, name);
|
||||
var recordPath = entryFolder + RecordExtension;
|
||||
var photos = await TrashedAsync(folder, removed, kept, cancellationToken).ConfigureAwait(false);
|
||||
var (held, hashed) = await HeldAsync(folder, kept, photos, cancellationToken).ConfigureAwait(false);
|
||||
// The hashes computed for frames that stay go into the sidecar with them: a later deletion does not read them again.
|
||||
if (hashed.Count > 0) kept = [.. kept.Select(f => hashed.TryGetValue(f.Id, out var sha) ? f with { Sha256 = sha } : f)];
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var record = new PhotoTrashRecord(TrashKind.Photos, id, revised.Sequence.DisplayTitle, revised.Sequence.Folder, photos,
|
||||
photos.Sum(p => p.Files.Sum(f => f.Size)), now, deletedBy);
|
||||
var moves = photos.SelectMany(p => p.Files).Select(f => new FrameRemovalMove(f.From, paths.ToRelative(Path.Combine(entryFolder, f.Path)))).ToList();
|
||||
updated = SequenceFrames.WithFrames(manifest, kept) with
|
||||
{
|
||||
Status = manifest.Status & ~Uncovered,
|
||||
Removed = WithTombstones(manifest.Removed, photos, held, now),
|
||||
};
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// The journal first: a crash from here until the sidecar is written puts every file back (ReadLocked).
|
||||
FrameRemovalJournal.Write(folder, new FrameRemovalJournal(paths.ToRelative(recordPath), paths.ToRelative(entryFolder), [.. planned], moves));
|
||||
// Under a name the trash does not list until the sidecar is written: half an entry is never restored or emptied.
|
||||
AtomicFile.WriteAllText(FrameRemovalJournal.PendingRecord(recordPath), JsonSerializer.Serialize(record, TrashJson.Default.PhotoTrashRecord));
|
||||
System.IO.Directory.CreateDirectory(entryFolder);
|
||||
var done = new List<FrameRemovalMove>();
|
||||
try
|
||||
{
|
||||
foreach (var move in moves)
|
||||
{
|
||||
MoveFile(folder.File(move.From), paths.FromRelative(move.To));
|
||||
done.Add(move);
|
||||
}
|
||||
ManifestStore.WriteSequence(folder.ManifestPath, updated);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// A file is open elsewhere, or the sidecar cannot be written: the ones that moved go back, and nothing changed.
|
||||
Log.Warning("archive", $"{revised.Sequence.DisplayTitle}: photos could not move to the trash; those that moved go back", ex);
|
||||
Undo(paths, folder, done, recordPath, entryFolder);
|
||||
throw;
|
||||
}
|
||||
Publish(folder, recordPath);
|
||||
Log.Info("archive", $"{revised.Sequence.DisplayTitle}: {removed.Count} photo(s) moved to the trash ({name}, {record.Bytes} bytes)");
|
||||
// The files have moved: the index follows to the end, whatever the caller cancels meanwhile.
|
||||
indexed = await IndexAsync(archive, folder, updated, photosChanged, revised.Sequence.DisplayTitle).ConfigureAwait(false);
|
||||
ShiftProxies(folder, manifest.Frames, updated.Frames, removed);
|
||||
ShiftThumbnails(paths, folder, id, manifest.Frames, updated.Frames);
|
||||
entry = Entry(archive.Id, name, record);
|
||||
}
|
||||
var sequence = await RowAsync(revised.Sequence, updated, indexed).ConfigureAwait(false);
|
||||
await QueueAsync(followUps, archive, sequence, had, CancellationToken.None).ConfigureAwait(false);
|
||||
return new FrameDeleteResult(entry, sequence);
|
||||
}
|
||||
|
||||
/// <summary>The photo entries of an archive's trash (records whose folder is gone, or of a deletion still under way, are left out).</summary>
|
||||
internal static IReadOnlyList<TrashEntry> List(Archive archive, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = Directory(new ArchivePaths(archive.RootPath));
|
||||
if (!System.IO.Directory.Exists(folder)) return [];
|
||||
var entries = new List<TrashEntry>();
|
||||
foreach (var path in System.IO.Directory.EnumerateFiles(folder, "*" + RecordExtension))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (!path.EndsWith(RecordExtension, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var name = Path.GetFileNameWithoutExtension(path);
|
||||
if (!System.IO.Directory.Exists(Path.Combine(folder, name)) || ReadRecord(path) is not { } record) continue;
|
||||
entries.Add(Entry(archive.Id, name, record));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>The record of a photo entry; null when it is not one or cannot be read.</summary>
|
||||
internal static PhotoTrashRecord? ReadEntry(ArchivePaths paths, string name) =>
|
||||
IsPhotoEntry(name) ? ReadRecord(Path.Combine(Directory(paths), DiskName(name)) + RecordExtension) : null;
|
||||
|
||||
/// <summary>A photo entry as the trash lists it, read from its record now; null when it is not one or cannot be read.</summary>
|
||||
internal static TrashEntry? ReadListed(ArchivePaths paths, Guid archiveId, string name) =>
|
||||
ReadEntry(paths, name) is { } record ? Entry(archiveId, DiskName(name), record) : null;
|
||||
|
||||
/// <summary>The entry's folder and record on disk.</summary>
|
||||
internal static (string Folder, string Record) Location(ArchivePaths paths, string name)
|
||||
{
|
||||
var folder = Path.Combine(Directory(paths), DiskName(name));
|
||||
return (folder, folder + RecordExtension);
|
||||
}
|
||||
|
||||
/// <summary>The folder name of an entry: its name without <see cref="EntryPrefix"/>, never a path.</summary>
|
||||
private static string DiskName(string name) => Path.GetFileName(IsPhotoEntry(name) ? name[EntryPrefix.Length..] : name);
|
||||
|
||||
private async Task<Archive> ArchiveOfAsync(Sequence sequence, CancellationToken cancellationToken) =>
|
||||
await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false) ?? throw new StaleDeletePlanException(sequence.Id);
|
||||
|
||||
/// <summary>
|
||||
/// The files of each frame that goes: its original (with the hash it was archived with, or one computed now for a frame
|
||||
/// never hashed) under the entry's <c>originals/</c>, and an XMP companion (<c>IMG_0001.xmp</c>, <c>IMG_0001.CR2.xmp</c>)
|
||||
/// no frame that stays shares. A frame whose original is missing goes without a file: its record stays in the entry,
|
||||
/// which cannot bring it back, and one never hashed leaves no tombstone either, so a copy of it elsewhere (another PC,
|
||||
/// a card) is not known to be deleted.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">An original never hashed cannot be read; nothing moved.</exception>
|
||||
private static async Task<List<TrashedPhoto>> TrashedAsync(SequencePaths folder, List<SidecarFrame> removed, List<SidecarFrame> kept,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var keptStems = kept.Select(f => Stem(f.File)).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var companions = new CompanionIndex(folder);
|
||||
var photos = new List<TrashedPhoto>(removed.Count);
|
||||
foreach (var frame in removed)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var files = new List<TrashedFile>();
|
||||
var original = new FileInfo(folder.File(frame.File));
|
||||
var sha = frame.Sha256;
|
||||
if (original.Exists)
|
||||
{
|
||||
sha ??= await ContentHash.Sha256Async(original.FullName, null, cancellationToken).ConfigureAwait(false);
|
||||
files.Add(new TrashedFile(frame.File, Unique(used, "originals/" + Inside(frame.File)), original.Length, sha));
|
||||
if (!keptStems.Contains(Stem(frame.File)))
|
||||
{
|
||||
foreach (var companion in companions.Of(frame.File).Where(claimed.Add))
|
||||
{
|
||||
var path = folder.File(companion);
|
||||
files.Add(new TrashedFile(companion, Unique(used, "originals/" + Inside(companion)), new FileInfo(path).Length,
|
||||
await ContentHash.Sha256Async(path, null, cancellationToken).ConfigureAwait(false)));
|
||||
}
|
||||
}
|
||||
}
|
||||
photos.Add(new TrashedPhoto(frame with { Sha256 = sha }, files, null));
|
||||
}
|
||||
return photos;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The SHA-256 the frames that stay hold, so a duplicate that stays keeps its content out of the tombstones: those of
|
||||
/// their sidecar, and that of each one never hashed that may hold a deleted photo's content, hashed now (returned by
|
||||
/// frame, for the sidecar). The work is bounded: only a frame with a deleted photo's size is looked at, and only one
|
||||
/// whose first and last 64 KiB match that photo's (<see cref="EdgesAsync"/>) is read whole, so a sequence of raw files of
|
||||
/// one size reads 128 KiB a frame, not every file.
|
||||
/// </summary>
|
||||
private static async Task<(HashSet<string> Held, Dictionary<Guid, string> Hashed)> HeldAsync(SequencePaths folder, List<SidecarFrame> kept,
|
||||
List<TrashedPhoto> photos, CancellationToken cancellationToken)
|
||||
{
|
||||
var held = kept.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var hashed = new Dictionary<Guid, string>();
|
||||
var deleted = photos.Where(p => p.Files.Count > 0).GroupBy(p => p.Files[0].Size).ToDictionary(g => g.Key, g => g.Select(p => p.Files[0].From).ToList());
|
||||
var edges = new Dictionary<long, HashSet<string>>();
|
||||
foreach (var frame in kept.Where(f => f.Sha256 is null && deleted.ContainsKey(f.Size)))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var file = new FileInfo(folder.File(frame.File));
|
||||
if (!file.Exists || file.Length != frame.Size) continue;
|
||||
if (!edges.TryGetValue(frame.Size, out var known))
|
||||
{
|
||||
// The deleted photos of that size are still in place: the moves come later.
|
||||
known = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var from in deleted[frame.Size]) known.Add(await EdgesAsync(folder.File(from), cancellationToken).ConfigureAwait(false));
|
||||
edges[frame.Size] = known;
|
||||
}
|
||||
if (!known.Contains(await EdgesAsync(file.FullName, cancellationToken).ConfigureAwait(false))) continue;
|
||||
var sha = await ContentHash.Sha256Async(file.FullName, null, cancellationToken).ConfigureAwait(false);
|
||||
hashed[frame.Id] = sha;
|
||||
held.Add(sha);
|
||||
}
|
||||
return (held, hashed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SHA-256 of a file's first and last 64 KiB (the whole file when smaller): two files of one size whose edges differ
|
||||
/// differ in content, so only those whose edges match need a full hash.
|
||||
/// </summary>
|
||||
private static async Task<string> EdgesAsync(string path, CancellationToken cancellationToken)
|
||||
{
|
||||
const int Edge = 64 * 1024;
|
||||
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 1,
|
||||
FileOptions.Asynchronous | FileOptions.RandomAccess);
|
||||
using var hash = System.Security.Cryptography.IncrementalHash.CreateHash(System.Security.Cryptography.HashAlgorithmName.SHA256);
|
||||
var buffer = new byte[Edge];
|
||||
var length = stream.Length;
|
||||
var read = await stream.ReadAtLeastAsync(buffer, (int)System.Math.Min(Edge, length), throwOnEndOfStream: false, cancellationToken).ConfigureAwait(false);
|
||||
hash.AppendData(buffer, 0, read);
|
||||
if (length > Edge)
|
||||
{
|
||||
stream.Position = System.Math.Max(Edge, length - Edge);
|
||||
read = await stream.ReadAtLeastAsync(buffer, (int)(length - stream.Position), throwOnEndOfStream: false, cancellationToken).ConfigureAwait(false);
|
||||
hash.AppendData(buffer, 0, read);
|
||||
}
|
||||
return Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The XMP files of a sequence's photo directories, each directory listed once (a deletion of thousands of photos does
|
||||
/// not list it again for each) and case-insensitively on every system (<c>IMG_0001.XMP</c> too).
|
||||
/// </summary>
|
||||
private sealed class CompanionIndex(SequencePaths folder)
|
||||
{
|
||||
private static readonly EnumerationOptions Listing = new() { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 };
|
||||
private readonly Dictionary<string, ILookup<string, string>> _directories = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The XMP files beside a photo that name it (<c>stem.xmp</c> or <c>file.xmp</c>), relative to the sequence folder.</summary>
|
||||
public IEnumerable<string> Of(string file)
|
||||
{
|
||||
var prefix = file.Contains('/') ? file[..(file.LastIndexOf('/') + 1)] : string.Empty;
|
||||
if (!_directories.TryGetValue(prefix, out var named))
|
||||
{
|
||||
var directory = Path.GetDirectoryName(folder.File(file))!;
|
||||
named = (System.IO.Directory.Exists(directory) ? System.IO.Directory.EnumerateFiles(directory, "*.xmp", Listing) : [])
|
||||
.Select(p => Path.GetFileName(p))
|
||||
.Where(n => Path.GetExtension(n).Equals(".xmp", StringComparison.OrdinalIgnoreCase))
|
||||
.ToLookup(n => Path.GetFileNameWithoutExtension(n), StringComparer.OrdinalIgnoreCase);
|
||||
_directories[prefix] = named;
|
||||
}
|
||||
var name = Path.GetFileName(file);
|
||||
var stem = Path.GetFileNameWithoutExtension(name);
|
||||
var matches = stem.Equals(name, StringComparison.OrdinalIgnoreCase) ? named[stem] : named[stem].Concat(named[name]);
|
||||
return matches.Select(n => prefix + n);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A photo's stem with its folder (<c>originals/IMG_0001</c>): its companions share it.</summary>
|
||||
private static string Stem(string file)
|
||||
{
|
||||
var slash = file.LastIndexOf('/');
|
||||
var name = file[(slash + 1)..];
|
||||
var dot = name.IndexOf('.', StringComparison.Ordinal);
|
||||
return file[..(slash + 1)] + (dot > 0 ? name[..dot] : name);
|
||||
}
|
||||
|
||||
/// <summary>A sequence-relative path without its leading <c>originals/</c>.</summary>
|
||||
private static string Inside(string file) =>
|
||||
file.StartsWith(ArchiveLayout.OriginalsFolder + "/", StringComparison.OrdinalIgnoreCase) ? file[(ArchiveLayout.OriginalsFolder.Length + 1)..] : file;
|
||||
|
||||
/// <summary><paramref name="path"/>, or with <c>_2</c>, <c>_3</c>… before its extension when another file of the entry has it.</summary>
|
||||
private static string Unique(HashSet<string> used, string path)
|
||||
{
|
||||
var candidate = path;
|
||||
for (var n = 2; !used.Add(candidate); n++)
|
||||
candidate = string.Create(CultureInfo.InvariantCulture, $"{Path.ChangeExtension(path, null)}_{n}{Path.GetExtension(path)}");
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The tombstones after a deletion: those of before, and one per SHA-256 of the photos that went (hashed as they went
|
||||
/// when the sidecar had none) that no frame staying holds (<paramref name="held"/>: a duplicate that stays keeps the
|
||||
/// content in the sequence).
|
||||
/// </summary>
|
||||
private static List<RemovedPhoto>? WithTombstones(IReadOnlyList<RemovedPhoto>? before, List<TrashedPhoto> photos, HashSet<string> held, DateTimeOffset at)
|
||||
{
|
||||
var tombstones = new Dictionary<string, RemovedPhoto>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var tombstone in before ?? []) tombstones[tombstone.Sha256] = tombstone;
|
||||
foreach (var sha in photos.Select(p => p.Frame.Sha256).OfType<string>())
|
||||
{
|
||||
if (!held.Contains(sha)) tombstones[sha] = new RemovedPhoto { Sha256 = sha.ToLowerInvariant(), Reason = RemovalReason.Deleted, At = at };
|
||||
}
|
||||
return tombstones.Count == 0 ? null : [.. tombstones.Values];
|
||||
}
|
||||
|
||||
/// <summary>Puts back the files of a deletion that failed half-way, and removes its record, folder and journal.</summary>
|
||||
private static void Undo(ArchivePaths paths, SequencePaths folder, List<FrameRemovalMove> done, string recordPath, string entryFolder)
|
||||
{
|
||||
foreach (var move in done)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(paths.FromRelative(move.To), folder.File(move.From), overwrite: false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Error("archive", $"{move.To} could not move back to {folder.ArchiveRelative(move.From)}; the journal puts it back later", ex);
|
||||
return;
|
||||
}
|
||||
}
|
||||
File.Delete(FrameRemovalJournal.PendingRecord(recordPath));
|
||||
FrameRemovalJournal.RemoveEmpty(entryFolder);
|
||||
FrameRemovalJournal.Delete(folder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lists a deletion whose sidecar is written: its record takes its own name and the journal goes. A failure (logged)
|
||||
/// keeps the journal, and the next writer of the sequence lists the entry (<see cref="FrameRemovalJournal.Recover"/>).
|
||||
/// </summary>
|
||||
private static void Publish(SequencePaths folder, string recordPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
FrameRemovalJournal.Publish(recordPath);
|
||||
FrameRemovalJournal.Delete(folder);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"Trash record {recordPath} keeps its pending name; the next writer of {folder.RelativeFolder} lists it", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indexes a sidecar this class wrote, to the end whatever the caller cancels. False (logged) when the index cannot
|
||||
/// follow: the files have moved and the sidecar says so, and the folder's stamps stay unrecorded, so the next scan
|
||||
/// resyncs the sequence from it.
|
||||
/// </summary>
|
||||
private async Task<bool> IndexAsync(Archive archive, SequencePaths folder, SequenceManifest manifest, bool photosChanged, string title)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _indexer.SyncAsync(archive, folder, manifest, null, Uncovered, photosChanged, CancellationToken.None).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"{title}: the index did not follow the photos moved; the next scan resyncs it", ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The sequence's row now; when the index did not follow (or cannot be read), the row as the sidecar has it.</summary>
|
||||
private async Task<Sequence> RowAsync(Sequence before, SequenceManifest manifest, bool indexed)
|
||||
{
|
||||
var fallback = before with { FramesVersion = manifest.Versions.Frames, FrameCount = manifest.Frames.Count };
|
||||
if (!indexed) return fallback;
|
||||
try
|
||||
{
|
||||
return await _db.Sequences.GetAsync(before.Id, CancellationToken.None).ConfigureAwait(false) ?? fallback;
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("archive", $"{before.DisplayTitle}: its row could not be read again", ex);
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renames the proxies of the frames whose index changed (BRIEF §8.5: proxies are named by frame index) so they stay
|
||||
/// theirs, and deletes those of the frames removed: the passes queued afterwards reuse them instead of making the
|
||||
/// sequence's proxies again. Proxies are regenerable and carry their frame's capture time, so one left in the wrong
|
||||
/// place (a failure here, logged) is made again.
|
||||
/// </summary>
|
||||
internal static void ShiftProxies(SequencePaths folder, IReadOnlyList<SidecarFrame> before, IReadOnlyList<SidecarFrame> after,
|
||||
IReadOnlyList<SidecarFrame> removed)
|
||||
{
|
||||
if (!System.IO.Directory.Exists(folder.Proxies)) return;
|
||||
try
|
||||
{
|
||||
foreach (var frame in removed)
|
||||
{
|
||||
var stale = folder.Proxy(frame.I);
|
||||
if (File.Exists(stale)) File.Delete(stale);
|
||||
}
|
||||
var now = after.ToDictionary(f => f.Id, f => f.I);
|
||||
var moves = before.Where(f => now.TryGetValue(f.Id, out var to) && to != f.I).Select(f => (From: f.I, To: now[f.Id])).ToList();
|
||||
if (moves.Count == 0) return;
|
||||
// Downwards from the lowest when frames left, upwards from the highest when frames came: each target is free by then.
|
||||
var ordered = moves[0].To < moves[0].From ? moves.OrderBy(m => m.From) : moves.OrderByDescending(m => m.From);
|
||||
foreach (var (from, to) in ordered)
|
||||
{
|
||||
var source = folder.Proxy(from);
|
||||
var target = folder.Proxy(to);
|
||||
if (File.Exists(source)) File.Move(source, target, overwrite: true);
|
||||
else if (File.Exists(target)) File.Delete(target);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"Proxies of {folder.RelativeFolder} did not follow their frames; the proxy pass makes them again", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the thumbnails of the frames whose index changed to their new index in <c>thumbs.pack</c> (BRIEF §8.5: the pack
|
||||
/// is keyed by frame index) and drops those of the frames removed, as <see cref="ShiftProxies"/> does for proxies, so the
|
||||
/// thumbnail pass queued afterwards reuses them instead of drawing the rest of the sequence again. Only the pack's index
|
||||
/// is rewritten. A thumbnail writer holding the pack meanwhile (its lease) leaves it as it is, and so does a failure
|
||||
/// (logged): each thumbnail carries its original's fingerprint, so one in the wrong place is drawn again.
|
||||
/// </summary>
|
||||
private void ShiftThumbnails(ArchivePaths paths, SequencePaths folder, Guid sequenceId, IReadOnlyList<SidecarFrame> before,
|
||||
IReadOnlyList<SidecarFrame> after)
|
||||
{
|
||||
if (!File.Exists(folder.ThumbsPackPath)) return;
|
||||
var now = after.ToDictionary(f => f.Id, f => f.I);
|
||||
var indices = before.Where(f => now.ContainsKey(f.Id)).ToDictionary(f => f.I, f => now[f.Id]);
|
||||
try
|
||||
{
|
||||
using var lease = LeaseFile.TryAcquire(paths.LocksDirectory, $"thumbs-{sequenceId:N}", _writer.Options.Owner, _writer.Options.LeaseDuration);
|
||||
if (lease is null)
|
||||
{
|
||||
Log.Info("archive", $"Thumbnails of {folder.RelativeFolder} are being written; the thumbnail pass draws those that moved again");
|
||||
return;
|
||||
}
|
||||
using var pack = ThumbPackWriter.Open(folder.ThumbsPackPath);
|
||||
pack.Rekey(indices);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"Thumbnails of {folder.RelativeFolder} did not follow their frames; the thumbnail pass draws them again", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Queues what the frames need again (see <see cref="DeleteAsync"/>), as an orphans fix does; an index that cannot take them is logged.</summary>
|
||||
private async Task QueueAsync(JobEngine? followUps, Archive archive, Sequence sequence, SequenceStatus had, CancellationToken cancellationToken)
|
||||
{
|
||||
if (followUps is null) return;
|
||||
var label = sequence.DisplayTitle;
|
||||
List<ArchiveJobRequest> requests = [ProcessingJobs.LightAnalysis([sequence.Id], label)];
|
||||
if ((had & SequenceStatus.AnalyzedDeep) != 0) requests.Add(ProcessingJobs.DeepAnalysis([sequence.Id], label) with { Priority = JobPriority.Background });
|
||||
var images = _writer.Options.ImagesAfterScan;
|
||||
if (images || (had & SequenceStatus.ThumbsBuilt) != 0) requests.Add(ArchiveJobs.Thumbnails([sequence.Id], label));
|
||||
if ((images || (had & SequenceStatus.ProxiesBuilt) != 0) && archive.ProxyLongEdge != ProxyPolicy.Disabled)
|
||||
requests.Add(ArchiveJobs.Proxies([sequence.Id], label));
|
||||
try
|
||||
{
|
||||
foreach (var request in requests)
|
||||
{
|
||||
if (!followUps.Runs(request.Kind) || await _db.Jobs.IsQueuedAsync(request.Kind, sequence.Id, cancellationToken).ConfigureAwait(false)) continue;
|
||||
await followUps.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("archive", $"{label}: the passes its frames need again were not queued; the next scan queues them", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Moves a file, making its folder first; never over another file.</summary>
|
||||
private static void MoveFile(string from, string to)
|
||||
{
|
||||
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(to)!);
|
||||
File.Move(from, to, overwrite: false);
|
||||
}
|
||||
|
||||
/// <summary>The sequence id and the time, with a number when an entry of that second exists already (or is being made).</summary>
|
||||
private static string EntryName(string trash, Guid sequenceId)
|
||||
{
|
||||
var stamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
|
||||
var name = $"{sequenceId:N}-{stamp}";
|
||||
for (var n = 2; Taken(Path.Combine(trash, name)); n++)
|
||||
name = string.Create(CultureInfo.InvariantCulture, $"{sequenceId:N}-{stamp}-{n}");
|
||||
return name;
|
||||
|
||||
static bool Taken(string entry) =>
|
||||
System.IO.Directory.Exists(entry) || File.Exists(entry + RecordExtension) || File.Exists(FrameRemovalJournal.PendingRecord(entry + RecordExtension));
|
||||
}
|
||||
|
||||
private static TrashEntry Entry(Guid archiveId, string folderName, PhotoTrashRecord record) =>
|
||||
new(archiveId, EntryPrefix + folderName, record.SequenceId, record.SequenceTitle, record.SequenceFolder, record.Photos.Count,
|
||||
record.Photos.Sum(p => p.Files.Count) + (record.Leftovers?.Count ?? 0), record.Bytes, record.DeletedAt, record.DeletedBy, record.Kind);
|
||||
|
||||
private static PhotoTrashRecord? ReadRecord(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), TrashJson.Default.PhotoTrashRecord) : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"Trash record {path} is unreadable", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the trash keeps next to deleted photos (owner review 2, R6): the frame records, where each file was and is, the
|
||||
/// sequence they came from. <see cref="TrashKind.Replaced"/> entries (a later conversion) name each photo's replacement.
|
||||
/// </summary>
|
||||
/// <param name="Leftovers">Files of the entry whose photo is back in a sequence without them (a companion whose name was
|
||||
/// taken there): counted and erased with the entry, never restored.</param>
|
||||
internal sealed record PhotoTrashRecord(TrashKind Kind, Guid SequenceId, string SequenceTitle, string SequenceFolder, IReadOnlyList<TrashedPhoto> Photos,
|
||||
long Bytes, DateTimeOffset DeletedAt, string? DeletedBy, IReadOnlyList<TrashedFile>? Leftovers = null);
|
||||
|
||||
/// <summary>One photo of a photo entry: its frame record, its files (the original first) and, when replaced, the replacement's SHA-256.</summary>
|
||||
internal sealed record TrashedPhoto(SidecarFrame Frame, IReadOnlyList<TrashedFile> Files, string? Replacement);
|
||||
|
||||
/// <param name="From">Where the file was, relative to the sequence folder.</param>
|
||||
/// <param name="Path">Where it is, relative to the entry's folder.</param>
|
||||
/// <param name="Sha256">Its SHA-256 when it left the sequence; a restore re-hashes the file against it.</param>
|
||||
internal sealed record TrashedFile(string From, string Path, long Size, string? Sha256);
|
||||
@@ -5,6 +5,10 @@ namespace Chronos.Data.Archiving;
|
||||
/// Exactly one of <see cref="SequenceId"/>, <see cref="NewSequenceTitle"/> or <see cref="SessionKey"/> selects the target:
|
||||
/// an existing sequence, a new one with that title, or the sequence grouped automatically by session.
|
||||
/// </summary>
|
||||
/// <param name="RefuseRemoved">Content the target sequence tombstoned (a photo deleted from it, none of its frames holding
|
||||
/// that content) is refused with <see cref="PhotoRemovedException"/>, checked under the sequence's lease with the commit, so
|
||||
/// no deletion lands in between: an upload that does not ask to bring the photo back. Otherwise filing it drops the
|
||||
/// tombstone (a card imported again, a sync download, an explicit upload again).</param>
|
||||
public sealed record IngestRequest(
|
||||
Guid ArchiveId,
|
||||
Guid? SequenceId,
|
||||
@@ -15,7 +19,18 @@ public sealed record IngestRequest(
|
||||
long Size,
|
||||
string Sha256,
|
||||
DateTime? ClientCapturedAt,
|
||||
Guid? UserId);
|
||||
Guid? UserId,
|
||||
bool RefuseRemoved = false);
|
||||
|
||||
/// <summary>
|
||||
/// The target sequence tombstoned the content of an <see cref="IngestRequest"/> that refuses it
|
||||
/// (<see cref="IngestRequest.RefuseRemoved"/>): the photo was deleted from it. Nothing was filed; the staged file stays.
|
||||
/// </summary>
|
||||
public sealed class PhotoRemovedException(Guid sequenceId, string sha256)
|
||||
: InvalidOperationException($"Sequence {sequenceId} tombstoned {sha256}: the photo was deleted from it and is not filed again.")
|
||||
{
|
||||
public Guid SequenceId { get; } = sequenceId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The committed frame; <see cref="Duplicate"/> when an intact frame of the sequence already held that SHA-256 (the file
|
||||
|
||||
@@ -31,6 +31,15 @@ public sealed record BackupParameters(int Keep);
|
||||
/// </summary>
|
||||
public sealed record CleanupParameters(IReadOnlyList<string> Steps, int OlderThanDays);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.EmptyTrash"/>: target = the archive; the entries of the confirmed plan, each with its own fingerprint
|
||||
/// (<see cref="SequenceTrash.EntryFingerprint"/>), and the plan's fingerprint (<see cref="TrashEmptyPlan.Fingerprint"/>).
|
||||
/// </summary>
|
||||
public sealed record EmptyTrashParameters(IReadOnlyList<EmptyTrashItem> Entries, string Fingerprint);
|
||||
|
||||
/// <summary>One entry of a confirmed emptying: its name and fingerprint when it was planned.</summary>
|
||||
public sealed record EmptyTrashItem(string Name, string Fingerprint);
|
||||
|
||||
/// <summary>A job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
|
||||
@@ -42,6 +51,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
|
||||
[JsonSerializable(typeof(ImportJobParameters))]
|
||||
[JsonSerializable(typeof(BackupParameters))]
|
||||
[JsonSerializable(typeof(CleanupParameters))]
|
||||
[JsonSerializable(typeof(EmptyTrashParameters))]
|
||||
[JsonSerializable(typeof(CardProfile))]
|
||||
internal sealed partial class ArchiveJobJson : JsonSerializerContext
|
||||
{
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.EmptyTrash"/> (owner review 2, R6): erases exactly the entries of a confirmed plan
|
||||
/// (<see cref="EmptyTrashParameters"/>) and fails, erasing nothing, when the trash no longer matches the plan's
|
||||
/// fingerprint (<see cref="StaleTrashPlanException"/>). Checkpoint: <c>done:<n></c>, the entries done; a resumed job
|
||||
/// checks each remaining entry against its own fingerprint. Entries kept (a replacement that no longer matches, an entry
|
||||
/// changed since) are logged and fail the job at the end, after the others are erased.
|
||||
/// </summary>
|
||||
internal sealed class EmptyTrashJobHandler(ChronosDatabase db, SequenceTrash trash) : IJobHandler
|
||||
{
|
||||
private const string Prefix = "done:";
|
||||
|
||||
public JobKind Kind => JobKind.EmptyTrash;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
|
||||
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.EmptyTrashParameters, new EmptyTrashParameters([], string.Empty));
|
||||
var start = context.Checkpoint is { } checkpoint && checkpoint.StartsWith(Prefix, StringComparison.Ordinal)
|
||||
&& int.TryParse(checkpoint.AsSpan(Prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var done)
|
||||
? Math.Min(done, parameters.Entries.Count)
|
||||
: 0;
|
||||
await context.ReportAsync(start, parameters.Entries.Count).ConfigureAwait(false);
|
||||
var result = await trash.EmptyAsync(archive, parameters, start,
|
||||
(n, total) => context.CheckpointAsync(Prefix + n.ToString(CultureInfo.InvariantCulture), n, total), context.Cancellation).ConfigureAwait(false);
|
||||
context.Log(Loc.L("Archive.Log.TrashEmptied", result.Erased, CleanupSteps.Megabytes(result.Bytes)));
|
||||
foreach (var title in result.Refused) context.Log(Loc.L("Archive.Log.TrashKept", title));
|
||||
if (result.Refused.Count > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.TrashKept", result.Refused.Count));
|
||||
}
|
||||
}
|
||||
@@ -12,15 +12,19 @@ namespace Chronos.Data.Archiving;
|
||||
/// Keeps a project's frame positions (exclusions, hero, virtual-camera keyframes; BRIEF §5, §7) on their frames when the
|
||||
/// index takes a sidecar in which frames were inserted before others: an upload or import of earlier photos, photos a
|
||||
/// scan found, a sync download, a journalled batch completed after a crash. Positions name the frames in the indexed
|
||||
/// order (what editors, renders and the API read), so the old order comes from the index rows. Only an insertion is
|
||||
/// followed: when an indexed frame is no longer in the sidecar, positions cannot be mapped and stay as they are. The move
|
||||
/// is part of the frames change, not a settings edit, so the settings version stays. Settings synced from another copy
|
||||
/// order (what editors, renders and the API read), so the old order comes from the index rows. An insertion moves them
|
||||
/// by position; when an indexed frame is no longer in the sidecar (photos deleted, owner review 2, R6) they are translated
|
||||
/// by photo, those on the photos that went waiting as pending frames. The move is part of the frames change, not a
|
||||
/// settings edit, so the settings version stays. Settings synced from another copy
|
||||
/// arrive translated to this copy's frames (<see cref="ProjectSettings.TranslateFramePositions"/>); their positions on
|
||||
/// photos that were not here yet (<see cref="ProjectSettings.PendingFrames"/>) take their place when the photos arrive,
|
||||
/// wherever they land.
|
||||
/// </summary>
|
||||
internal static class ProjectPositions
|
||||
{
|
||||
/// <summary>Index frames read at once when positions are translated by photo.</summary>
|
||||
private const int PageSize = 1000;
|
||||
|
||||
/// <summary>
|
||||
/// The index's copy of the project (the one in force) with its positions moved to the order of
|
||||
/// <paramref name="manifest"/> and its pending frames placed; null when nothing changes. A <c>project.json</c> the
|
||||
@@ -45,9 +49,35 @@ internal static class ProjectPositions
|
||||
}
|
||||
if (index != row.Index) moves[row.Index] = index;
|
||||
}
|
||||
return Placed(project, moves is null ? null : ProjectSettings.MoveFramePositions(project, moves), manifest);
|
||||
if (moves is null) return await RemovedAsync(db, indexed.Id, project, manifest, cancellationToken).ConfigureAwait(false);
|
||||
return Placed(project, ProjectSettings.MoveFramePositions(project, moves), manifest);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indexed frames are no longer in the sidecar (photos deleted into the trash, here or by another process sharing the
|
||||
/// archive, owner review 2, R6): the positions are translated by photo from the index's frames to the sidecar's
|
||||
/// (<see cref="ProjectSettings.TranslateFramePositions"/>), so those on the photos that went wait as pending frames
|
||||
/// and take their place again when the photos come back (a restore), and the others follow their photos.
|
||||
/// </summary>
|
||||
private static async Task<PositionMove?> RemovedAsync(ChronosRepositories db, Guid sequenceId, string project, SequenceManifest manifest,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var before = new List<(int, FramePhoto)>();
|
||||
for (var after = -1; ;)
|
||||
{
|
||||
var page = await db.Frames.ListBySequenceAsync(sequenceId, after, PageSize, cancellationToken).ConfigureAwait(false);
|
||||
before.AddRange(page.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
|
||||
if (page.Count < PageSize) break;
|
||||
after = page[^1].Index;
|
||||
}
|
||||
var to = new FramePhotos(manifest.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
|
||||
var translated = ProjectSettings.TranslateFramePositions(project, new FramePhotos(before), to);
|
||||
if (translated is null) return null;
|
||||
var hero = HeroOf(project) is null && HeroOf(translated) is { } index ? manifest.Frames.FirstOrDefault(f => f.I == index)?.Id : null;
|
||||
return new PositionMove(project, translated, hero);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// The index's copy of the project with the pending frames whose photos <paramref name="manifest"/> now holds put in
|
||||
/// place: frames appended in step with the index, which moves no position. Null when nothing changes.
|
||||
|
||||
@@ -41,6 +41,22 @@ internal static class SequenceMapping
|
||||
public static List<Frame> ToFrames(SequenceManifest manifest, SequencePaths sequence) =>
|
||||
manifest.Frames.Select(f => ToFrame(f, manifest.Id, sequence)).ToList();
|
||||
|
||||
/// <summary>
|
||||
/// The sidecar's tombstones as index rows (owner review 2, R6), without those whose content a frame of the sidecar
|
||||
/// holds: that photo is in the sequence again (adopted back by a scan, say), and sync offers it like any other.
|
||||
/// </summary>
|
||||
public static List<FrameRemoval> ToRemovals(SequenceManifest manifest)
|
||||
{
|
||||
if (manifest.Removed is not { Count: > 0 } removed) return [];
|
||||
var held = manifest.Frames.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
return removed.Where(r => !string.IsNullOrEmpty(r.Sha256) && !held.Contains(r.Sha256))
|
||||
.Select(r => new FrameRemoval(manifest.Id, r.Sha256.ToLowerInvariant(), r.Replacement?.ToLowerInvariant(), r.Reason, r.At)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>Index rows of tombstones as a sidecar carries them: a sidecar rebuilt from the photos takes them back.</summary>
|
||||
public static List<RemovedPhoto> ToTombstones(IEnumerable<FrameRemoval> removals) =>
|
||||
removals.Select(r => new RemovedPhoto { Sha256 = r.Sha256, Replacement = r.ReplacementSha256, Reason = r.Reason, At = r.RemovedAt }).ToList();
|
||||
|
||||
/// <param name="existing">The current row; its render, analysis, sync and ownership fields are kept, and so are its
|
||||
/// title, tags, rating and notes when its settings version is ahead of the sidecar's (edited in the index only).</param>
|
||||
public static Sequence ToSequence(SequenceManifest m, Guid archiveId, SequencePaths sequence, Sequence? existing)
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of emptying an archive's trash (owner review 2, R6; BRIEF §0.2 rule 8): the entries that would be erased,
|
||||
/// with the files and bytes their folders hold now, and a fingerprint of exactly those entries. Erasing
|
||||
/// (<see cref="JobKind.EmptyTrash"/>) refuses a plan whose fingerprint no longer matches the trash.
|
||||
/// </summary>
|
||||
/// <param name="Unknown">Names asked for that the trash does not hold.</param>
|
||||
public sealed record TrashEmptyPlan(Guid ArchiveId, IReadOnlyList<TrashEntry> Entries, long Bytes, string Fingerprint, IReadOnlyList<string> Unknown)
|
||||
{
|
||||
public int Files => Entries.Sum(e => e.Files);
|
||||
public int Photos => Entries.Sum(e => e.Frames);
|
||||
}
|
||||
|
||||
/// <summary>What an emptying erased, and the entries it kept (a replacement that no longer matches, an entry changed since the plan).</summary>
|
||||
public sealed record TrashEmptyResult(int Erased, long Bytes, IReadOnlyList<string> Refused);
|
||||
|
||||
/// <summary>The trash changed after the emptying was planned (an entry came, went or changed); nothing was erased.</summary>
|
||||
public sealed class StaleTrashPlanException() : InvalidOperationException(Loc.L("Archive.Error.TrashChanged"));
|
||||
|
||||
public sealed partial class SequenceTrash
|
||||
{
|
||||
/// <summary>Folder inside the trash that entries move into before they are erased, so a listing never sees half an entry.</summary>
|
||||
private const string ErasingFolder = ".erasing";
|
||||
|
||||
/// <summary>The lease that keeps a restore and an erasing of one entry apart.</summary>
|
||||
internal static string EntryLease(string name) => "trash-" + name;
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of emptying the trash: <paramref name="names"/> of the entries to erase (null: every entry), each
|
||||
/// measured on disk, and the plan's fingerprint (<see cref="Fingerprint"/>). Reads only.
|
||||
/// </summary>
|
||||
public async Task<TrashEmptyPlan> PlanEmptyAsync(Archive archive, IReadOnlyList<string>? names = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var listed = await ListAsync(archive, cancellationToken).ConfigureAwait(false);
|
||||
var wanted = names?.ToHashSet(StringComparer.Ordinal);
|
||||
var chosen = wanted is null ? listed : [.. listed.Where(e => wanted.Contains(e.Name))];
|
||||
var measured = await Task.Run(() => chosen.Select(e =>
|
||||
{
|
||||
var (folder, _) = Location(paths, e);
|
||||
var (files, bytes) = Directory.Exists(folder) ? Measure(folder, cancellationToken) : (0, 0L);
|
||||
return e with { Files = files, Bytes = bytes };
|
||||
}).ToList(), cancellationToken).ConfigureAwait(false);
|
||||
var unknown = names?.Where(n => !listed.Any(e => e.Name == n)).Distinct(StringComparer.Ordinal).ToList() ?? [];
|
||||
return new TrashEmptyPlan(archive.Id, measured, measured.Sum(e => e.Bytes), Fingerprint(measured), unknown);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fingerprint of a set of entries: SHA-256 of each one's <see cref="EntryFingerprint"/> in name order. The same
|
||||
/// entries with the same files on disk give the same fingerprint whatever order they were listed in.
|
||||
/// </summary>
|
||||
public static string Fingerprint(IEnumerable<TrashEntry> entries)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entries);
|
||||
var text = new StringBuilder();
|
||||
foreach (var entry in entries.OrderBy(e => e.Name, StringComparer.Ordinal)) text.Append(EntryFingerprint(entry)).Append('\n');
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
|
||||
}
|
||||
|
||||
/// <summary>What identifies one entry as planned: its kind, name, files and bytes on disk, and when it was deleted.</summary>
|
||||
public static string EntryFingerprint(TrashEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
return string.Create(CultureInfo.InvariantCulture, $"{entry.Kind}|{entry.Name}|{entry.Files}|{entry.Bytes}|{entry.DeletedAt.UtcTicks}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Erases the entries of <paramref name="parameters"/> from <paramref name="start"/> on, one at a time under its lease,
|
||||
/// each moved aside whole and then deleted (a listing never shows half an entry). From the start, the trash must still
|
||||
/// hold exactly the planned entries (<see cref="EmptyTrashParameters.Fingerprint"/>), else nothing is erased; a run
|
||||
/// resumed after a stop checks each remaining entry against its own fingerprint, keeps one that changed and skips one
|
||||
/// that is gone, and each entry is checked against its fingerprint once more under its lease, just before it goes. A
|
||||
/// <see cref="TrashKind.Replaced"/> entry is erased only while every replacement still matches its
|
||||
/// SHA-256 in the sequence (re-hashed now); otherwise it is kept. Leftovers of an interrupted erase are deleted first.
|
||||
/// </summary>
|
||||
/// <param name="progress">Entries done so far (the resume point) and their number.</param>
|
||||
/// <exception cref="StaleTrashPlanException">The trash no longer holds exactly the planned entries; nothing was erased.</exception>
|
||||
internal async Task<TrashEmptyResult> EmptyAsync(Archive archive, EmptyTrashParameters parameters, int start, Func<int, int, ValueTask> progress,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
SweepErasing(paths);
|
||||
var items = parameters.Entries;
|
||||
var current = await PlanEmptyAsync(archive, [.. items.Skip(start).Select(i => i.Name)], cancellationToken).ConfigureAwait(false);
|
||||
if (start == 0 && (current.Fingerprint != parameters.Fingerprint || current.Unknown.Count > 0)) throw new StaleTrashPlanException();
|
||||
var refused = new List<string>();
|
||||
int erased = 0;
|
||||
long bytes = 0;
|
||||
for (var i = start; i < items.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var item = items[i];
|
||||
if (current.Entries.FirstOrDefault(e => e.Name == item.Name) is { } entry)
|
||||
{
|
||||
if (EntryFingerprint(entry) != item.Fingerprint)
|
||||
{
|
||||
refused.Add(entry.Title);
|
||||
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
|
||||
}
|
||||
else if (await EraseAsync(paths, entry, item.Fingerprint, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
erased++;
|
||||
bytes += entry.Bytes;
|
||||
}
|
||||
else
|
||||
{
|
||||
refused.Add(entry.Title);
|
||||
}
|
||||
}
|
||||
await progress(i + 1, items.Count).ConfigureAwait(false);
|
||||
}
|
||||
return new TrashEmptyResult(erased, bytes, refused);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Erases one entry under its lease, once its record read and its folder measured again under it still give the
|
||||
/// planned <paramref name="fingerprint"/> (another host sharing the archive may have restored the entry and deleted the
|
||||
/// same sequence again since); false (logged) when it changed, or a replaced entry's replacements no longer match.
|
||||
/// </summary>
|
||||
private async Task<bool> EraseAsync(ArchivePaths paths, TrashEntry entry, string fingerprint, CancellationToken cancellationToken)
|
||||
{
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, EntryLease(entry.Name), _writer.Options.Owner, _writer.Options.LeaseWait,
|
||||
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var (folder, record) = Location(paths, entry);
|
||||
if (!Directory.Exists(folder) || !File.Exists(record)) return false;
|
||||
if (Reread(paths, entry, cancellationToken) is not { } now || EntryFingerprint(now) != fingerprint)
|
||||
{
|
||||
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
|
||||
return false;
|
||||
}
|
||||
if (entry.Kind == TrashKind.Replaced && !await ReplacementsHoldAsync(paths, entry, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
Log.Warning("archive", $"Trash entry {entry.Name} is kept: a replacement of its originals no longer matches");
|
||||
return false;
|
||||
}
|
||||
var aside = Path.Combine(TrashDirectory(paths), ErasingFolder, Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(aside)!);
|
||||
Directory.Move(folder, aside);
|
||||
File.Delete(record);
|
||||
Erase(aside);
|
||||
Log.Info("archive", $"Trash entry {entry.Name} ({entry.Title}, {entry.Files} files, {entry.Bytes} bytes) erased");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether every photo of a replaced entry still has its replacement in the sequence: a frame holding the replacement's
|
||||
/// SHA-256 whose file hashes to it now. The originals are erased only then (a later phase's conversion).
|
||||
/// </summary>
|
||||
private async Task<bool> ReplacementsHoldAsync(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
|
||||
{
|
||||
if (FrameTrash.ReadEntry(paths, entry.Name) is not { } record) return false;
|
||||
foreach (var photo in record.Photos)
|
||||
{
|
||||
if (photo.Replacement is not { } replacement) return false;
|
||||
var holders = (await _db.Frames.FindBySha256Async(replacement.ToLowerInvariant(), cancellationToken).ConfigureAwait(false))
|
||||
.Where(f => f.SequenceId == record.SequenceId).ToList();
|
||||
var verified = false;
|
||||
foreach (var frame in holders)
|
||||
{
|
||||
var file = paths.FromRelative(frame.RelativePath);
|
||||
if (!File.Exists(file)) continue;
|
||||
if (string.Equals(await ContentHash.Sha256Async(file, null, cancellationToken).ConfigureAwait(false), replacement, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
verified = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!verified) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>An entry as the trash lists it, from its record and folder as they are now; null when its record cannot be read.</summary>
|
||||
private static TrashEntry? Reread(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
|
||||
{
|
||||
var (folder, recordPath) = Location(paths, entry);
|
||||
var now = FrameTrash.IsPhotoEntry(entry.Name)
|
||||
? FrameTrash.ReadListed(paths, entry.ArchiveId, entry.Name)
|
||||
: ReadRecord(recordPath) is { } record ? Entry(entry.ArchiveId, Path.GetFileName(entry.Name), record) : null;
|
||||
if (now is null) return null;
|
||||
var (files, bytes) = Measure(folder, cancellationToken);
|
||||
return now with { Files = files, Bytes = bytes };
|
||||
}
|
||||
|
||||
/// <summary>The folder and record of an entry of either kind.</summary>
|
||||
private static (string Folder, string Record) Location(ArchivePaths paths, TrashEntry entry)
|
||||
{
|
||||
if (FrameTrash.IsPhotoEntry(entry.Name)) return FrameTrash.Location(paths, entry.Name);
|
||||
var folder = Path.Combine(TrashDirectory(paths), Path.GetFileName(entry.Name));
|
||||
return (folder, folder + RecordExtension);
|
||||
}
|
||||
|
||||
/// <summary>Deletes what an interrupted erase left aside: those entries were confirmed and had left the listing already.</summary>
|
||||
private static void SweepErasing(ArchivePaths paths)
|
||||
{
|
||||
var erasing = Path.Combine(TrashDirectory(paths), ErasingFolder);
|
||||
if (!Directory.Exists(erasing)) return;
|
||||
foreach (var leftover in Directory.EnumerateDirectories(erasing)) Erase(leftover);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a folder and everything in it, read-only files included; one that is gone already is fine.</summary>
|
||||
internal static void Erase(string folder)
|
||||
{
|
||||
if (!Directory.Exists(folder)) return;
|
||||
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0 }))
|
||||
{
|
||||
if ((file.Attributes & FileAttributes.ReadOnly) != 0) file.Attributes &= ~FileAttributes.ReadOnly;
|
||||
}
|
||||
Directory.Delete(folder, recursive: true);
|
||||
}
|
||||
}
|
||||
@@ -48,11 +48,27 @@ public sealed record DeletePlan(IReadOnlyList<DeleteStep> Steps, IReadOnlyList<B
|
||||
public int Renders => Steps.Sum(s => s.Sequence.RenderedCount);
|
||||
}
|
||||
|
||||
/// <summary>A deleted sequence kept in an archive's trash, as <see cref="SequenceTrash.ListAsync"/> lists it.</summary>
|
||||
/// <param name="Name">Folder name inside the trash; pass it to <see cref="SequenceTrash.RestoreAsync"/>.</param>
|
||||
/// <summary>What a trash entry holds (owner review 2, R6).</summary>
|
||||
public enum TrashKind
|
||||
{
|
||||
/// <summary>A whole sequence folder (<see cref="SequenceTrash"/>).</summary>
|
||||
Sequence,
|
||||
|
||||
/// <summary>Photos deleted from a sequence (<see cref="FrameTrash"/>).</summary>
|
||||
Photos,
|
||||
|
||||
/// <summary>Originals a conversion replaced (a later phase): erased only while their replacements still match.</summary>
|
||||
Replaced,
|
||||
}
|
||||
|
||||
/// <summary>An entry of an archive's trash, as <see cref="SequenceTrash.ListAsync"/> lists it: a deleted sequence or deleted photos.</summary>
|
||||
/// <param name="Name">The entry's name: the folder name inside the trash for a sequence, <c>photos-</c> and the folder name for
|
||||
/// photos; pass it to <see cref="ArchiveService.RestoreEntryAsync"/>.</param>
|
||||
/// <param name="Title">The sequence's title (the one the photos came from).</param>
|
||||
/// <param name="Folder">Archive-relative folder the sequence came from (and returns to when it is free).</param>
|
||||
/// <param name="Frames">Photos the entry holds.</param>
|
||||
public sealed record TrashEntry(Guid ArchiveId, string Name, Guid SequenceId, string Title, string Folder, int Frames, int Files, long Bytes,
|
||||
DateTimeOffset DeletedAt, string? DeletedBy);
|
||||
DateTimeOffset DeletedAt, string? DeletedBy, TrashKind Kind = TrashKind.Sequence);
|
||||
|
||||
/// <summary>The plan no longer matches the index or the jobs (a sequence moved, vanished or got busy since it was made); nothing was deleted.</summary>
|
||||
public sealed class StaleDeletePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
|
||||
@@ -66,6 +82,12 @@ public sealed class SequenceInLibraryException(Guid sequenceId, string title) :
|
||||
public Guid SequenceId { get; } = sequenceId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// No file of a photo entry matches its record any more (each one re-hashed); the entry stays as it is and nothing moved.
|
||||
/// A restore's <see cref="InvalidDataException"/> is about a sidecar instead (damaged, or another sequence's).
|
||||
/// </summary>
|
||||
public sealed class TrashMismatchException() : IOException(Loc.L("Archive.Error.TrashMismatch"));
|
||||
|
||||
/// <summary>
|
||||
/// Deleting sequences without erasing anything (BRIEF §0.2 rule 8, §12.2, §12.5): <see cref="PlanAsync"/> is the dry
|
||||
/// run; <see cref="DeleteAsync"/> moves each sequence folder whole — originals, proxies, exports and its sidecars — into
|
||||
@@ -75,7 +97,7 @@ public sealed class SequenceInLibraryException(Guid sequenceId, string title) :
|
||||
/// moved, its index step runs to the end whatever the caller cancels; when that step fails, the folder moves back, so
|
||||
/// the trash and the index never disagree.
|
||||
/// </summary>
|
||||
public sealed class SequenceTrash
|
||||
public sealed partial class SequenceTrash
|
||||
{
|
||||
/// <summary>Folder of the trash inside the archive's <c>.chronos</c>.</summary>
|
||||
public const string FolderName = "trash";
|
||||
@@ -153,6 +175,10 @@ public sealed class SequenceTrash
|
||||
/// <param name="progress">Sequences moved so far.</param>
|
||||
/// <exception cref="StaleDeletePlanException">A sequence moved, vanished or got busy since the plan; nothing was deleted.</exception>
|
||||
/// <exception cref="ArchiveOfflineException">An archive is offline; sequences before it are in the trash.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">A sequence, or the trash entry of a restore into it a crash interrupted, is
|
||||
/// busy; sequences before it are in the trash.</exception>
|
||||
/// <exception cref="InvalidDataException">The sidecar of a sequence with an interrupted journal is damaged; sequences
|
||||
/// before it are in the trash.</exception>
|
||||
public async Task<IReadOnlyList<TrashEntry>> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -168,7 +194,10 @@ public sealed class SequenceTrash
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>The sequences in an archive's trash, newest first; records whose folder is gone are left out.</summary>
|
||||
/// <summary>
|
||||
/// The entries of an archive's trash, newest first: deleted sequences (<c>trash/*.json</c>) and deleted photos
|
||||
/// (<c>trash/photos/*.json</c>); records whose folder is gone are left out.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<TrashEntry>> ListAsync(Archive archive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
@@ -184,7 +213,8 @@ public sealed class SequenceTrash
|
||||
if (!Directory.Exists(Path.Combine(trash, name)) || ReadRecord(path) is not { } record) continue;
|
||||
entries.Add(Entry(archive.Id, name, record));
|
||||
}
|
||||
return entries.OrderByDescending(e => e.DeletedAt).ToList();
|
||||
entries.AddRange(FrameTrash.List(archive, cancellationToken));
|
||||
return entries.OrderByDescending(e => e.DeletedAt).ThenBy(e => e.Name, StringComparer.Ordinal).ToList();
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -215,14 +245,18 @@ public sealed class SequenceTrash
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var folder = FreeFolder(paths, record.Sequence.Folder, locations);
|
||||
var sequence = paths.Sequence(folder);
|
||||
// The entry's lease keeps an emptying of the trash out meanwhile.
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, EntryLease(Path.GetFileName(name)), _writer.Options.Owner, _writer.Options.LeaseWait,
|
||||
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (!Directory.Exists(source)) throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(sequence.Folder)!);
|
||||
Directory.Move(source, sequence.Folder);
|
||||
try
|
||||
{
|
||||
var manifest = File.Exists(sequence.ManifestPath) ? SequenceWriter.ReadLocked(sequence, id) : Adopt(sequence, record.Sequence, cancellationToken);
|
||||
var manifest = File.Exists(sequence.ManifestPath) ? SequenceWriter.ReadLocked(sequence, id) : Adopt(sequence, record, cancellationToken);
|
||||
// The index step runs to the end once it starts: a cancel cannot leave half the rows written.
|
||||
await IndexAsync(archive, sequence, manifest, record, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
@@ -242,10 +276,12 @@ public sealed class SequenceTrash
|
||||
|
||||
/// <summary>
|
||||
/// A sidecar for a restored folder that lost its own, built as a scan adopts a folder: its frames get new ids, the
|
||||
/// sequence keeps its id, and the title, tags, rating and notes of the record go into it so sidecar and index agree.
|
||||
/// sequence keeps its id, and the title, tags, rating, notes and tombstones of the record go into it so sidecar and
|
||||
/// index agree, and a photo deleted before stays deleted.
|
||||
/// </summary>
|
||||
private SequenceManifest Adopt(SequencePaths sequence, Sequence kept, CancellationToken cancellationToken)
|
||||
private SequenceManifest Adopt(SequencePaths sequence, TrashRecord record, CancellationToken cancellationToken)
|
||||
{
|
||||
var kept = record.Sequence;
|
||||
var built = SequenceAdopter.Build(kept.Id, sequence, _writer.Options.Owner, cancellationToken);
|
||||
var manifest = built with
|
||||
{
|
||||
@@ -254,6 +290,7 @@ public sealed class SequenceTrash
|
||||
Rating = kept.Rating,
|
||||
Notes = kept.Notes,
|
||||
Versions = built.Versions with { Settings = System.Math.Max(built.Versions.Settings, kept.SettingsVersion) },
|
||||
Removed = record.Removed is { Count: > 0 } removed ? removed : null,
|
||||
};
|
||||
Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
@@ -269,6 +306,7 @@ public sealed class SequenceTrash
|
||||
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, kept), cancellationToken).ConfigureAwait(false);
|
||||
await tx.Frames.SyncSequenceAsync(deleted.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
|
||||
await tx.FrameRemovals.SyncSequenceAsync(deleted.Id, SequenceMapping.ToRemovals(manifest), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var key in manifest.SessionKeys) await tx.Sequences.MapSessionKeyAsync(archive.Id, key, deleted.Id, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var render in record.Renders)
|
||||
{
|
||||
@@ -335,12 +373,25 @@ public sealed class SequenceTrash
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
if (!Directory.Exists(folder.Folder) || (File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id))
|
||||
throw new StaleDeletePlanException(sequence.Id);
|
||||
// A photo deletion, a restore from the trash or an ingest a crash interrupted is settled first, as any writer does
|
||||
// (SequenceWriter.ReadLocked): neither its journal nor the files it moved travel into this entry, where emptying it
|
||||
// would erase them while their own entry still lists them. A restore whose entry is busy keeps the folder here.
|
||||
var (files, bytes) = (step.Files, step.Bytes);
|
||||
if (File.Exists(folder.ManifestPath) && (File.Exists(folder.RemovalJournalPath) || File.Exists(folder.RestoreJournalPath)
|
||||
|| File.Exists(folder.IngestJournalPath)))
|
||||
{
|
||||
SequenceWriter.ReadLocked(folder, sequence.Id);
|
||||
FrameTrash.EnsureSettled(folder);
|
||||
// Files came back into the folder, or left it: the record counts what moves.
|
||||
(files, bytes) = Measure(folder.Folder, cancellationToken);
|
||||
}
|
||||
var trash = TrashDirectory(paths);
|
||||
Directory.CreateDirectory(trash);
|
||||
var name = EntryName(paths, sequence.Id, new HashSet<string>());
|
||||
var target = Path.Combine(trash, name);
|
||||
var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), step.Files,
|
||||
step.Bytes, DateTimeOffset.UtcNow, deletedBy);
|
||||
var tombstones = await _db.FrameRemovals.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
|
||||
var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), files,
|
||||
bytes, DateTimeOffset.UtcNow, deletedBy, tombstones.Count > 0 ? SequenceMapping.ToTombstones(tombstones) : null);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// The record first: a crash before the move leaves a record without a folder, which the listing ignores.
|
||||
var recordPath = target + RecordExtension;
|
||||
@@ -366,7 +417,7 @@ public sealed class SequenceTrash
|
||||
if (MoveBack(target, folder.Folder)) File.Delete(recordPath);
|
||||
throw;
|
||||
}
|
||||
Log.Info("archive", $"{row.DisplayTitle} moved to the trash: {row.Folder} → {name} ({step.Files} files, {step.Bytes} bytes)");
|
||||
Log.Info("archive", $"{row.DisplayTitle} moved to the trash: {row.Folder} → {name} ({files} files, {bytes} bytes)");
|
||||
return Entry(archive.Id, name, record);
|
||||
}
|
||||
}
|
||||
@@ -426,7 +477,7 @@ public sealed class SequenceTrash
|
||||
/// archives of archive-wide ones (scan, rebuild, import, maintenance, a verify of everything). An import's folders
|
||||
/// are known only to its plan, so it holds its whole archive; a verify of named sequences holds only those.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlySet<Guid>> BusyAsync(CancellationToken cancellationToken)
|
||||
internal async Task<IReadOnlySet<Guid>> BusyAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var busy = new HashSet<Guid>();
|
||||
foreach (var state in new[] { JobState.Running, JobState.Paused })
|
||||
@@ -545,10 +596,16 @@ public sealed class SequenceTrash
|
||||
private sealed record ArchiveContext(ArchivePaths Paths, ArchiveAvailability Availability, IReadOnlyList<Repositories.SequenceLocation> Locations);
|
||||
}
|
||||
|
||||
/// <summary>What the trash keeps next to a deleted folder: the index row and renders the sidecar does not carry.</summary>
|
||||
internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList<Render> Renders, int Files, long Bytes, DateTimeOffset DeletedAt, string? DeletedBy);
|
||||
/// <summary>
|
||||
/// What the trash keeps next to a deleted folder: the index row and renders the sidecar does not carry, and the
|
||||
/// sequence's tombstones, which a sidecar rebuilt from the photos on restore takes back.
|
||||
/// </summary>
|
||||
internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList<Render> Renders, int Files, long Bytes, DateTimeOffset DeletedAt, string? DeletedBy,
|
||||
IReadOnlyList<RemovedPhoto>? Removed = null);
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
UseStringEnumConverter = true, IgnoreReadOnlyProperties = true)]
|
||||
[JsonSerializable(typeof(TrashRecord))]
|
||||
[JsonSerializable(typeof(PhotoTrashRecord))]
|
||||
[JsonSerializable(typeof(FrameRestoreJournal))]
|
||||
internal sealed partial class TrashJson : JsonSerializerContext;
|
||||
@@ -88,14 +88,19 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the sidecar of a locked sequence, completing an interrupted ingest batch first.
|
||||
/// Reads the sidecar of a locked sequence, undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>),
|
||||
/// settling an interrupted restore from the trash (<see cref="FrameRestoreJournal"/>; left for later while its trash
|
||||
/// entry is busy) and completing an interrupted ingest batch first.
|
||||
/// </summary>
|
||||
/// <param name="heldEntryLease">The trash entry lease the caller holds already (a restore of that entry), if any.</param>
|
||||
/// <exception cref="InvalidDataException">The sidecar in the folder belongs to another sequence.</exception>
|
||||
public static SequenceManifest ReadLocked(SequencePaths sequence, Guid sequenceId)
|
||||
public static SequenceManifest ReadLocked(SequencePaths sequence, Guid sequenceId, string? heldEntryLease = null)
|
||||
{
|
||||
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
if (manifest.Id != sequenceId)
|
||||
throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}.");
|
||||
FrameRemovalJournal.Recover(sequence, manifest);
|
||||
FrameTrash.RecoverRestore(sequence, manifest, heldEntryLease);
|
||||
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
|
||||
{
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, recovered);
|
||||
|
||||
@@ -23,6 +23,7 @@ public abstract class ChronosRepositories
|
||||
Audit = new AuditRepository(access);
|
||||
Uploads = new UploadRepository(access);
|
||||
Schedules = new ScheduleRepository(access);
|
||||
FrameRemovals = new FrameRemovalRepository(access);
|
||||
}
|
||||
|
||||
public ArchiveRepository Archives { get; }
|
||||
@@ -41,6 +42,9 @@ public abstract class ChronosRepositories
|
||||
|
||||
/// <summary>Scheduled jobs (owner review 2, R10).</summary>
|
||||
public ScheduleRepository Schedules { get; }
|
||||
|
||||
/// <summary>Tombstones of the photos removed from sequences (owner review 2, R6).</summary>
|
||||
public FrameRemovalRepository FrameRemovals { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Tombstones of photos removed from sequences (owner review 2, R6): a photo deleted into the archive's trash (reason 0)
|
||||
-- or replaced by a converted file (reason 1, with the replacement's SHA-256). The sidecar's "removed" list is the truth;
|
||||
-- the index writes these rows from it, so a rebuild keeps them. Sync never offers a tombstoned photo back, and an upload
|
||||
-- of that content into the sequence is answered as already there. Mirrors sqlite/0008_frame_removals.sql.
|
||||
|
||||
CREATE TABLE frame_removals (
|
||||
sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
|
||||
sha256 text NOT NULL,
|
||||
replacement_sha256 text,
|
||||
reason integer NOT NULL DEFAULT 0,
|
||||
removed_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (sequence_id, sha256)
|
||||
);
|
||||
CREATE INDEX ix_frame_removals_sha256 ON frame_removals (sha256);
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Tombstones of photos removed from sequences (owner review 2, R6): a photo deleted into the archive's trash (reason 0)
|
||||
-- or replaced by a converted file (reason 1, with the replacement's SHA-256). The sidecar's "removed" list is the truth;
|
||||
-- the index writes these rows from it, so a rebuild keeps them. Sync never offers a tombstoned photo back, and an upload
|
||||
-- of that content into the sequence is answered as already there. Mirrors postgres/0008_frame_removals.sql.
|
||||
|
||||
CREATE TABLE frame_removals (
|
||||
sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
|
||||
sha256 TEXT NOT NULL,
|
||||
replacement_sha256 TEXT,
|
||||
reason INTEGER NOT NULL DEFAULT 0,
|
||||
removed_at TEXT NOT NULL,
|
||||
PRIMARY KEY (sequence_id, sha256)
|
||||
);
|
||||
CREATE INDEX ix_frame_removals_sha256 ON frame_removals (sha256);
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Data.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// Tombstones of the photos removed from sequences (owner review 2, R6; <c>frame_removals</c>), by sequence and SHA-256.
|
||||
/// The sidecar's <c>removed</c> list is the truth: the index writes a sequence's rows from it whenever it takes the
|
||||
/// sidecar (<see cref="SyncSequenceAsync"/>), so a rebuild keeps them, and they go with the sequence's row.
|
||||
/// </summary>
|
||||
public sealed class FrameRemovalRepository
|
||||
{
|
||||
private const string Columns = "sequence_id, sha256, replacement_sha256, reason, removed_at";
|
||||
|
||||
/// <summary>Rows one INSERT writes (five parameters each, well inside both engines' limits).</summary>
|
||||
private const int InsertRows = 200;
|
||||
|
||||
private readonly DbAccess _db;
|
||||
|
||||
internal FrameRemovalRepository(DbAccess db) => _db = db;
|
||||
|
||||
/// <summary>The tombstones of a sequence, oldest first.</summary>
|
||||
public Task<IReadOnlyList<FrameRemoval>> ListBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
|
||||
_db.ListAsync($"SELECT {Columns} FROM frame_removals WHERE sequence_id = $1 ORDER BY removed_at, sha256", [sequenceId], Map, cancellationToken);
|
||||
|
||||
/// <summary>Whether <paramref name="sha256"/> was removed from the sequence (any reason).</summary>
|
||||
public async Task<bool> IsRemovedAsync(Guid sequenceId, string sha256, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(sha256);
|
||||
return await _db.ScalarAsync<long>("SELECT count(*) FROM frame_removals WHERE sequence_id = $1 AND sha256 = $2",
|
||||
[sequenceId, sha256.ToLowerInvariant()], cancellationToken).ConfigureAwait(false) > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the tombstones of a sequence with <paramref name="removals"/> (the sidecar's list; one per SHA-256, the
|
||||
/// last one given wins). Returns how many rows the sequence has now.
|
||||
/// </summary>
|
||||
public Task<int> SyncSequenceAsync(Guid sequenceId, IReadOnlyList<FrameRemoval> removals, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(removals);
|
||||
var rows = removals.Where(r => !string.IsNullOrEmpty(r.Sha256)).GroupBy(r => r.Sha256.ToLowerInvariant(), StringComparer.Ordinal)
|
||||
.Select(g => g.Last() with { Sha256 = g.Key, SequenceId = sequenceId }).ToList();
|
||||
return _db.InTransactionAsync(async session =>
|
||||
{
|
||||
await session.ExecuteAsync("DELETE FROM frame_removals WHERE sequence_id = $1", [sequenceId], cancellationToken).ConfigureAwait(false);
|
||||
for (var start = 0; start < rows.Count; start += InsertRows)
|
||||
{
|
||||
var count = Math.Min(InsertRows, rows.Count - start);
|
||||
var sql = new StringBuilder($"INSERT INTO frame_removals ({Columns}) VALUES ");
|
||||
var args = new DbParam[count * 5];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var row = rows[start + i];
|
||||
sql.Append(i > 0 ? ", (" : "(").Append(string.Join(", ", Enumerable.Range(i * 5 + 1, 5).Select(n => "$" + n.ToString(CultureInfo.InvariantCulture))))
|
||||
.Append(')');
|
||||
args[i * 5] = row.SequenceId;
|
||||
args[i * 5 + 1] = row.Sha256;
|
||||
args[i * 5 + 2] = row.ReplacementSha256?.ToLowerInvariant();
|
||||
args[i * 5 + 3] = (int)row.Reason;
|
||||
args[i * 5 + 4] = row.RemovedAt;
|
||||
}
|
||||
await session.ExecuteAsync(sql.ToString(), args, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return rows.Count;
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
private static FrameRemoval Map(DbRow r) =>
|
||||
new(r.GetGuid(0), r.GetString(1), r.GetStringOrNull(2), (RemovalReason)r.GetInt32(3), r.GetDateTimeOffset(4));
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
|
||||
@@ -103,6 +104,15 @@ public sealed record CameraBucket(string? Make, string? Model, int Sequences, lo
|
||||
|
||||
public sealed record FormatBucket(ImageFileFormat Format, long Photos, long Bytes);
|
||||
|
||||
/// <summary>
|
||||
/// A value a Library filter offers, as <see cref="SequenceQuery"/> takes it (a year, an exact camera model, a tag), and
|
||||
/// how many sequences have it; <see cref="Make"/> is a camera model's make, for its label.
|
||||
/// </summary>
|
||||
public sealed record ArchiveFacet(string Value, int Sequences, string? Make = null);
|
||||
|
||||
/// <summary>The years of first capture, camera models and tags of an archive's sequences (owner review 2, R6: the panel's filters).</summary>
|
||||
public sealed record ArchiveFacets(IReadOnlyList<ArchiveFacet> Years, IReadOnlyList<ArchiveFacet> Cameras, IReadOnlyList<ArchiveFacet> Tags);
|
||||
|
||||
/// <summary>Health counters: sequences needing attention and flagged frames.</summary>
|
||||
public sealed record ArchiveHealth(
|
||||
int Unverified,
|
||||
@@ -389,6 +399,32 @@ public sealed class SequenceRepository
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the Library's filters offer for <paramref name="archiveId"/>: years of first capture (newest first), camera
|
||||
/// models (most sequences first; one entry per model, as the camera filter matches the model alone) and the tags in use
|
||||
/// (by name). Only sequence rows are read, never frames.
|
||||
/// </summary>
|
||||
public Task<ArchiveFacets> GetFacetsAsync(Guid archiveId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
DbParam[] args = [archiveId];
|
||||
var year = _db.Sql.Year("s.first_capture");
|
||||
return _db.RunAsync(async session =>
|
||||
{
|
||||
var years = await session.QueryListAsync(
|
||||
$"SELECT {year}, count(*) FROM sequences s WHERE s.archive_id = $1 AND s.first_capture IS NOT NULL GROUP BY 1 ORDER BY 1 DESC", args,
|
||||
r => new ArchiveFacet(r.GetInt32(0).ToString(CultureInfo.InvariantCulture), r.GetInt32(1)), cancellationToken).ConfigureAwait(false);
|
||||
var cameras = await session.QueryListAsync(
|
||||
"SELECT s.camera_model, MIN(s.camera_make), count(*) FROM sequences s " +
|
||||
"WHERE s.archive_id = $1 AND s.camera_model IS NOT NULL AND s.camera_model <> '' GROUP BY s.camera_model ORDER BY 3 DESC, 1", args,
|
||||
r => new ArchiveFacet(r.GetString(0), r.GetInt32(2), r.GetStringOrNull(1)), cancellationToken).ConfigureAwait(false);
|
||||
var tags = await session.QueryListAsync(
|
||||
"SELECT MIN(t.name), count(*) FROM sequence_tags st JOIN tags t ON t.id = st.tag_id JOIN sequences s ON s.id = st.sequence_id " +
|
||||
"WHERE s.archive_id = $1 GROUP BY t.name_key ORDER BY t.name_key", args,
|
||||
r => new ArchiveFacet(r.GetString(0), r.GetInt32(1)), cancellationToken).ConfigureAwait(false);
|
||||
return new ArchiveFacets(years, cameras, tags);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequences of <paramref name="archiveId"/> a rolling verification checks next (owner review 2, R10): those never
|
||||
/// verified first, then the longest unverified, at most <paramref name="limit"/>. With <paramref name="verifiedBefore"/>
|
||||
|
||||
@@ -24,6 +24,9 @@ internal sealed class SyncPositions(ChronosDatabase db, ISyncRemote remote, Guid
|
||||
/// <summary>The manifest's frames by hash, and with their capture times once fetched.</summary>
|
||||
private FramePhotos? _hashed, _timed;
|
||||
|
||||
/// <summary>The photos either copy removed: a replaced photo is translated as its replacement (owner review 2, R6).</summary>
|
||||
private SyncTombstones? _tombstones;
|
||||
|
||||
/// <summary>The server's frames version the translation to the server's frames is made against.</summary>
|
||||
public int ServerFrames => manifest.FramesVersion;
|
||||
|
||||
@@ -73,7 +76,10 @@ internal sealed class SyncPositions(ChronosDatabase db, ISyncRemote remote, Guid
|
||||
var frames = await SequenceFrames.ListAsync(db, localId, cancellationToken).ConfigureAwait(false);
|
||||
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } after) return null;
|
||||
if (after.FramesVersion == before.FramesVersion)
|
||||
return new LocalState(after, new FramePhotos(frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))));
|
||||
{
|
||||
var tombstones = await TombstonesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new LocalState(after, new FramePhotos(frames.Select(f => (f.Index, tombstones.Canonical(new FramePhoto(f.Sha256, f.Size, f.CapturedAt))))));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -87,20 +93,25 @@ internal sealed class SyncPositions(ChronosDatabase db, ISyncRemote remote, Guid
|
||||
/// </summary>
|
||||
private async Task<FramePhotos?> ServerAsync(FramePhotos local, CancellationToken cancellationToken)
|
||||
{
|
||||
var tombstones = await TombstonesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (_hashed is null)
|
||||
{
|
||||
if (!OneList(manifest.Frames)) return null;
|
||||
_hashed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, null))));
|
||||
_hashed = new FramePhotos(manifest.Frames.Select(f => (f.Index, tombstones.Canonical(new FramePhoto(f.Sha256, f.Size, null)))));
|
||||
}
|
||||
if (_hashed.SameAs(local)) return _hashed;
|
||||
if (_timed is null)
|
||||
{
|
||||
var captured = (await remote.ListFramesAsync(manifest.SequenceId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
|
||||
_timed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, captured.GetValueOrDefault(f.Id)))));
|
||||
_timed = new FramePhotos(manifest.Frames.Select(f => (f.Index, tombstones.Canonical(new FramePhoto(f.Sha256, f.Size, captured.GetValueOrDefault(f.Id))))));
|
||||
}
|
||||
return _timed;
|
||||
}
|
||||
|
||||
/// <summary>This copy's tombstones and the server's, read once.</summary>
|
||||
private async Task<SyncTombstones> TombstonesAsync(CancellationToken cancellationToken) =>
|
||||
_tombstones ??= new SyncTombstones(await db.FrameRemovals.ListBySequenceAsync(localId, cancellationToken).ConfigureAwait(false), manifest.Removed);
|
||||
|
||||
/// <summary>Each frame once, at the indices 0…n-1 a sequence's frames always take.</summary>
|
||||
private static bool OneList(IReadOnlyList<ManifestFrame> frames)
|
||||
{
|
||||
|
||||
@@ -164,6 +164,28 @@ public static class SyncRules
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="CompareOriginals(IReadOnlyCollection{FramePhoto}, IReadOnlyCollection{FramePhoto})"/> honouring the photos
|
||||
/// either side removed (owner review 2, R6): a photo the server deleted is not missing there, one this PC deleted is not
|
||||
/// missing here, and a photo replaced by a converted file on either side is compared as its replacement. A tombstone
|
||||
/// leaves out only a photo its side no longer holds: one left beside a frame of the same content (the other copy of a
|
||||
/// duplicate, a file put back by hand) would otherwise keep the other side's copy missing for good.
|
||||
/// </summary>
|
||||
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<FramePhoto> local, IReadOnlyCollection<FramePhoto> remote,
|
||||
SyncTombstones tombstones)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(local);
|
||||
ArgumentNullException.ThrowIfNull(remote);
|
||||
ArgumentNullException.ThrowIfNull(tombstones);
|
||||
if (tombstones.IsEmpty) return CompareOriginals(local, remote);
|
||||
var mine = local.Select(p => (p.Sha256, Photo: tombstones.Canonical(p))).ToList();
|
||||
var theirs = remote.Select(p => (p.Sha256, Photo: tombstones.Canonical(p))).ToList();
|
||||
var minePhotos = new FramePhotos(mine.Select((p, i) => (i, p.Photo)));
|
||||
var theirPhotos = new FramePhotos(theirs.Select((p, i) => (i, p.Photo)));
|
||||
return CompareOriginals([.. mine.Where(p => !tombstones.DeletedRemotely(p.Sha256) || theirPhotos.IndexOf(p.Photo) is not null).Select(p => p.Photo)],
|
||||
[.. theirs.Where(p => !tombstones.DeletedLocally(p.Sha256) || minePhotos.IndexOf(p.Photo) is not null).Select(p => p.Photo)]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Frames whose proxy the server asks for (it cannot decode their originals, BRIEF §2.3) that this PC holds and its
|
||||
/// <paramref name="decoder"/> reads: an upload makes and sends them. A local original not hashed yet (a folder adopted
|
||||
|
||||
@@ -528,8 +528,10 @@ public sealed class SyncService
|
||||
var captured = manifest.Frames.Any(f => f.Sha256.Length == 0) || present.Any(f => f.Sha256 is null)
|
||||
? (await remote.ListFramesAsync(link.RemoteId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt)
|
||||
: null;
|
||||
// Photos either side removed are not offered back; one replaced by a converted file counts as its replacement (owner review 2, R6).
|
||||
var tombstones = new SyncTombstones(await _db.FrameRemovals.ListBySequenceAsync(local.Id, cancellationToken).ConfigureAwait(false), manifest.Removed);
|
||||
var (missingRemote, missingLocal) = SyncRules.CompareOriginals([.. present.Select(f => new FramePhoto(f.Sha256, f.Size, f.CapturedAt))],
|
||||
[.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))]);
|
||||
[.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))], tombstones);
|
||||
// Proxies the server asks for that this PC can make from its originals travel with an upload too (BRIEF §2.3).
|
||||
var proxies = policy.CanEdit && manifest.Proxies is not null ? SyncRules.ProxiesToSend(manifest, present, Options.Archive.Decoder, captured) : 0;
|
||||
// Those change without the server's frame counters moving: while some may be made here, the server's next
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Sync;
|
||||
|
||||
/// <summary>
|
||||
/// The photos each copy of a linked pair removed (owner review 2, R6; BRIEF §14.5): a photo one side deleted is not
|
||||
/// offered to it again (no upload of what the server deleted, no download of what this PC deleted; local files are never
|
||||
/// deleted by sync), and a photo one side replaced by a converted file is the same photo as its replacement on either side
|
||||
/// (an alias: both are compared, matched and translated as the replacement). No I/O.
|
||||
/// </summary>
|
||||
public sealed class SyncTombstones
|
||||
{
|
||||
/// <summary>Links a replacement chain may have at most (a conversion of a conversion…); longer ones stop there.</summary>
|
||||
private const int MaxAliasSteps = 8;
|
||||
|
||||
private readonly HashSet<string> _deletedLocally;
|
||||
private readonly HashSet<string> _deletedRemotely;
|
||||
private readonly Dictionary<string, string> _aliases;
|
||||
|
||||
public SyncTombstones(IEnumerable<FrameRemoval> local, IEnumerable<RemovedPhotoDto>? remote)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(local);
|
||||
_deletedLocally = new HashSet<string>(StringComparer.Ordinal);
|
||||
_deletedRemotely = new HashSet<string>(StringComparer.Ordinal);
|
||||
_aliases = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var removal in local) Add(removal.Sha256, removal.ReplacementSha256, removal.Reason == RemovalReason.Replaced, _deletedLocally);
|
||||
foreach (var removal in remote ?? [])
|
||||
Add(removal.Sha256, removal.Replacement, string.Equals(removal.Reason, Wire(RemovalReason.Replaced), StringComparison.OrdinalIgnoreCase), _deletedRemotely);
|
||||
}
|
||||
|
||||
/// <summary>No photo removed on either side.</summary>
|
||||
public static SyncTombstones None { get; } = new([], null);
|
||||
|
||||
/// <summary>Whether either side removed or replaced anything.</summary>
|
||||
public bool IsEmpty => _deletedLocally.Count == 0 && _deletedRemotely.Count == 0 && _aliases.Count == 0;
|
||||
|
||||
/// <summary>The wire name of a removal reason (<c>deleted</c>, <c>replaced</c>).</summary>
|
||||
public static string Wire(RemovalReason reason) => reason.ToString().ToLowerInvariant();
|
||||
|
||||
/// <summary>The tombstones of a sequence as the manifest carries them.</summary>
|
||||
public static IReadOnlyList<RemovedPhotoDto> ToDto(IEnumerable<FrameRemoval> removals) =>
|
||||
[.. removals.Select(r => new RemovedPhotoDto(r.Sha256, r.ReplacementSha256, Wire(r.Reason), r.RemovedAt))];
|
||||
|
||||
/// <summary>
|
||||
/// The SHA-256 a photo is compared as: the end of its replacement chain on either side, lower-case; null or empty
|
||||
/// (not hashed yet) stays as it is.
|
||||
/// </summary>
|
||||
public string? Canonical(string? sha256)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sha256)) return sha256;
|
||||
var current = sha256.ToLowerInvariant();
|
||||
for (var step = 0; step < MaxAliasSteps && _aliases.TryGetValue(current, out var next); step++) current = next;
|
||||
return current;
|
||||
}
|
||||
|
||||
/// <summary>The photo as it is compared (<see cref="Canonical(string?)"/>).</summary>
|
||||
public FramePhoto Canonical(FramePhoto photo)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(photo);
|
||||
return photo.IsHashed && _aliases.Count > 0 ? photo with { Sha256 = Canonical(photo.Sha256) } : photo;
|
||||
}
|
||||
|
||||
/// <summary>This PC deleted the photo (or what replaced it): the server's copy is not downloaded.</summary>
|
||||
public bool DeletedLocally(string? sha256) => Deleted(sha256, _deletedLocally);
|
||||
|
||||
/// <summary>The server deleted the photo (or what replaced it): this PC's copy is not uploaded.</summary>
|
||||
public bool DeletedRemotely(string? sha256) => Deleted(sha256, _deletedRemotely);
|
||||
|
||||
private bool Deleted(string? sha256, HashSet<string> deleted) =>
|
||||
!string.IsNullOrEmpty(sha256) && deleted.Count > 0 && (deleted.Contains(sha256.ToLowerInvariant()) || deleted.Contains(Canonical(sha256)!));
|
||||
|
||||
private void Add(string sha256, string? replacement, bool replaced, HashSet<string> deleted)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sha256)) return;
|
||||
var sha = sha256.ToLowerInvariant();
|
||||
if (replaced && !string.IsNullOrEmpty(replacement)) _aliases[sha] = replacement.ToLowerInvariant();
|
||||
else deleted.Add(sha);
|
||||
}
|
||||
}
|
||||
@@ -48,13 +48,15 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
|
||||
var frames = (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
|
||||
var manifest = remoteId is { } known ? await remote.GetManifestAsync(known, ct).ConfigureAwait(false) : null;
|
||||
var present = manifest?.Frames.Where(f => f.Sha256.Length > 0).Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal) ?? [];
|
||||
// A photo the server deleted is not sent back; one it replaced by a converted file is there as its replacement (owner review 2, R6).
|
||||
var tombstones = new SyncTombstones(await db.FrameRemovals.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false), manifest?.Removed);
|
||||
var present = manifest?.Frames.Where(f => f.Sha256.Length > 0).Select(f => tombstones.Canonical(f.Sha256)!).ToHashSet(StringComparer.Ordinal) ?? [];
|
||||
// Originals the server holds without a hash (adopted there, not verified) are the ones of their size and capture
|
||||
// time: the server could not recognise them by content, so they are not sent again.
|
||||
var adopted = manifest is not null && manifest.Frames.Any(f => f.Sha256.Length == 0)
|
||||
? await UnhashedAsync(remote, manifest, ct).ConfigureAwait(false)
|
||||
: new FramePhotos([]);
|
||||
var pending = new Queue<Frame>(frames.Where(f => (f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant()))
|
||||
var pending = new Queue<Frame>(frames.Where(f => (f.Sha256 is null || (!present.Contains(tombstones.Canonical(f.Sha256)!) && !tombstones.DeletedRemotely(f.Sha256)))
|
||||
&& adopted.IndexOf(new FramePhoto(f.Sha256, f.Size, f.CapturedAt)) is null));
|
||||
var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count);
|
||||
await progress.ReportAsync().ConfigureAwait(false);
|
||||
@@ -68,8 +70,8 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
// server has filed one, which creates the sequence (an original it already holds elsewhere creates nothing).
|
||||
while (remoteId is null && pending.TryDequeue(out var first))
|
||||
{
|
||||
var sent = await UploadFrameAsync(context, remote, null, SyncService.SessionKey(local.Id), paths.FromRelative(first.RelativePath), first, hashes, ct)
|
||||
.ConfigureAwait(false);
|
||||
var sent = await UploadFrameAsync(context, remote, null, SyncService.SessionKey(local.Id), paths.FromRelative(first.RelativePath), first, tombstones,
|
||||
hashes, ct).ConfigureAwait(false);
|
||||
if (sent is null) skipped++;
|
||||
else if (sent.SequenceId != Guid.Empty)
|
||||
{
|
||||
@@ -83,11 +85,15 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
|
||||
await Parallel.ForEachAsync(pending, Workers(sync.Options.Uploads, ct), async (frame, token) =>
|
||||
{
|
||||
if (await UploadFrameAsync(context, remote, target, null, paths.FromRelative(frame.RelativePath), frame, hashes, token).ConfigureAwait(false) is null)
|
||||
Interlocked.Increment(ref skipped);
|
||||
var sent = await UploadFrameAsync(context, remote, target, null, paths.FromRelative(frame.RelativePath), frame, tombstones, hashes, token)
|
||||
.ConfigureAwait(false);
|
||||
if (sent is null) Interlocked.Increment(ref skipped);
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
}).ConfigureAwait(false);
|
||||
await SendProxiesAsync(context, remote, target, local, paths, frames, hashes).ConfigureAwait(false);
|
||||
// An original the index has no hash for turned out to be a photo the server deleted: the verify gives the index
|
||||
// the hashes (as before a download), so the comparison leaves it out instead of offering its upload again and again.
|
||||
if (hashes.Values.Any(tombstones.DeletedRemotely)) await VerifyAsync(archive, local.Id, ct).ConfigureAwait(false);
|
||||
|
||||
if (created) await sync.PushAllAsync(remote, target, ct).ConfigureAwait(false);
|
||||
await sync.RecompareAsync(remote, target, ct).ConfigureAwait(false);
|
||||
@@ -205,12 +211,16 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
|
||||
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
|
||||
var (have, restore, photos) = local is null ? ([], [], new FramePhotos([])) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
|
||||
// A photo this PC deleted is not fetched again; one replaced here by a converted file is here as its replacement (owner review 2, R6).
|
||||
var tombstones = local is null ? SyncTombstones.None
|
||||
: new SyncTombstones(await db.FrameRemovals.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false), manifest.Removed);
|
||||
if (!tombstones.IsEmpty) have = [.. have.Select(h => tombstones.Canonical(h)!)];
|
||||
// An original the server has not hashed yet (adopted there, not verified) is here when an original of its size and
|
||||
// capture time is; each one is fetched on its own and hashed here.
|
||||
var wanted = manifest.Frames
|
||||
.Where(f => f.Sha256.Length == 0
|
||||
? photos.IndexOf(new FramePhoto(null, f.Size, captured.GetValueOrDefault(f.Id))) is null
|
||||
: !have.Contains(f.Sha256.ToLowerInvariant()))
|
||||
: !have.Contains(tombstones.Canonical(f.Sha256)!) && !tombstones.DeletedLocally(f.Sha256))
|
||||
.DistinctBy(f => f.Sha256.Length == 0 ? f.Id.ToString("N") : f.Sha256.ToLowerInvariant()).ToList();
|
||||
EnsureSpace(paths.Root, wanted.Sum(f => f.Size));
|
||||
|
||||
@@ -234,7 +244,7 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
}
|
||||
var sequenceId = local?.Id;
|
||||
var restored = 0;
|
||||
int restored = 0, refused = 0;
|
||||
await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
|
||||
{
|
||||
var (staged, sha) = await FetchOriginalAsync(remote, frame, staging, token).ConfigureAwait(false);
|
||||
@@ -243,6 +253,14 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
Restore(staged, place);
|
||||
Interlocked.Increment(ref restored);
|
||||
}
|
||||
else if (frame.Sha256.Length == 0 && (tombstones.DeletedLocally(sha) || have.Contains(tombstones.Canonical(sha)!)))
|
||||
{
|
||||
// An original the server has not hashed is known by content only now: one this PC deleted (or holds as
|
||||
// the converted file that replaced it) is not filed again, which would also drop its tombstone.
|
||||
File.Delete(staged);
|
||||
Interlocked.Increment(ref refused);
|
||||
if (tombstones.DeletedLocally(sha)) context.Log($"{frame.FileName}: deleted on this PC, not downloaded");
|
||||
}
|
||||
else
|
||||
{
|
||||
await CommitAsync(remoteId, archive.Id, sequenceId, frame, staged, sha, captured, token).ConfigureAwait(false);
|
||||
@@ -255,7 +273,7 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
|
||||
if (created) await sync.TakeAllAsync(remote, remoteId, ct).ConfigureAwait(false);
|
||||
await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false);
|
||||
if (sequenceId is { } downloaded && wanted.Count > restored)
|
||||
if (sequenceId is { } downloaded && wanted.Count > restored + refused)
|
||||
{
|
||||
var label = local!.DisplayTitle;
|
||||
await EnqueueFollowUpAsync(context, ArchiveJobs.Thumbnails([downloaded], label)).ConfigureAwait(false);
|
||||
@@ -491,10 +509,11 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
/// <summary>
|
||||
/// Hashes the original again and sends it into <paramref name="sequenceId"/> (or the sequence of
|
||||
/// <paramref name="sessionKey"/>); null (logged) when it is gone or no longer the archived file. The hash of an
|
||||
/// original the index has none for goes into <paramref name="hashes"/>.
|
||||
/// original the index has none for goes into <paramref name="hashes"/>; known by content only now, such an original
|
||||
/// the server deleted (<paramref name="tombstones"/>) is not sent back.
|
||||
/// </summary>
|
||||
private static async Task<CompleteUploadResponse?> UploadFrameAsync(JobContext context, ISyncRemote remote, Guid? sequenceId, string? sessionKey, string path,
|
||||
Frame frame, ConcurrentDictionary<Guid, string> hashes, CancellationToken cancellationToken)
|
||||
Frame frame, SyncTombstones tombstones, ConcurrentDictionary<Guid, string> hashes, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
@@ -502,14 +521,22 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
return null;
|
||||
}
|
||||
var sha = await ChronosClient.HashFileAsync(path, cancellationToken).ConfigureAwait(false);
|
||||
if (frame.Sha256 is null) hashes[frame.Id] = sha;
|
||||
var notSent = new CompleteUploadResponse(Guid.Empty, sequenceId ?? Guid.Empty, -1);
|
||||
if (frame.Sha256 is null)
|
||||
{
|
||||
hashes[frame.Id] = sha;
|
||||
if (tombstones.DeletedRemotely(sha))
|
||||
{
|
||||
context.Log($"{frame.FileName}: deleted on the server, not uploaded");
|
||||
return notSent;
|
||||
}
|
||||
}
|
||||
if (frame.Sha256 is { } archived && !archived.Equals(sha, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
context.Log($"{frame.FileName}: changed since it was archived, not uploaded");
|
||||
return null;
|
||||
}
|
||||
return await remote.UploadFileAsync(path, sequenceId, sessionKey, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false)
|
||||
?? new CompleteUploadResponse(Guid.Empty, sequenceId ?? Guid.Empty, -1);
|
||||
return await remote.UploadFileAsync(path, sequenceId, sessionKey, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false) ?? notSent;
|
||||
}
|
||||
|
||||
/// <summary>Commits one original from staging into the local sequence (created from the server id when null).</summary>
|
||||
|
||||
@@ -165,7 +165,9 @@ public sealed class ChronosClient : IDisposable
|
||||
|
||||
/// <summary>
|
||||
/// Uploads one file with resumable, idempotent chunks; the server verifies the SHA-256 before committing it
|
||||
/// (BRIEF §14.4). Returns the committed frame id. Transient failures retry with exponential backoff.
|
||||
/// (BRIEF §14.4). Returns the committed frame id; null when the server holds the photo without a frame to name: it was
|
||||
/// deleted from the target sequence, before the upload or while it was on its way (owner review 2, R6). Transient
|
||||
/// failures retry with exponential backoff.
|
||||
/// </summary>
|
||||
public async Task<CompleteUploadResponse?> UploadFileAsync(
|
||||
string path,
|
||||
@@ -189,7 +191,15 @@ public sealed class ChronosClient : IDisposable
|
||||
|
||||
var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id.");
|
||||
await SendChunksAsync(path, info.Length, uploadId, start.ChunkSize, start.Received, progress, ct).ConfigureAwait(false);
|
||||
return await RetryAsync(() => SendAsync<CompleteUploadResponse>(HttpMethod.Post, $"api/v1/uploads/{uploadId}/complete", ProtocolJson.Default.CompleteUploadResponse, ct), ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return await RetryAsync(() => SendAsync<CompleteUploadResponse>(HttpMethod.Post, $"api/v1/uploads/{uploadId}/complete", ProtocolJson.Default.CompleteUploadResponse, ct), ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex is { Status: HttpStatusCode.Conflict, Error.Code: UploadErrors.PhotoRemoved })
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -9,6 +9,10 @@ public sealed record ApiError(string Code, string Message, string? Details = nul
|
||||
public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes, int PasswordMinLength = 10);
|
||||
|
||||
/// <summary><c>GET /api/v1/server/info</c>.</summary>
|
||||
/// <param name="Extensions">
|
||||
/// File extensions the archive files as photos (lower case, no dot): the admin panel's upload dialog offers and sends only
|
||||
/// these (owner review 2, R3). Null from servers that do not announce them.
|
||||
/// </param>
|
||||
public sealed record ServerInfo(
|
||||
string Name,
|
||||
string Version,
|
||||
@@ -16,7 +20,8 @@ public sealed record ServerInfo(
|
||||
IReadOnlyList<string> Capabilities,
|
||||
string? TlsFingerprint,
|
||||
IReadOnlyList<string> Formats,
|
||||
ServerLimits Limits);
|
||||
ServerLimits Limits,
|
||||
IReadOnlyList<string>? Extensions = null);
|
||||
|
||||
/// <summary><c>GET /health</c>.</summary>
|
||||
public sealed record HealthStatus(string Status, string Version, IReadOnlyDictionary<string, string> Checks);
|
||||
@@ -0,0 +1,83 @@
|
||||
namespace Chronos.Protocol;
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/sequences/{id}/frames/delete</c> (owner review 2, R6): the photos to move into the archive's trash.
|
||||
/// <see cref="ExpectedFramesVersion"/> is the frames version the ids were read at: a sequence whose frames changed since
|
||||
/// answers 409 <c>frames_conflict</c>. <see cref="DryRun"/> only reports what would happen.
|
||||
/// </summary>
|
||||
public sealed record FrameDeleteRequest(IReadOnlyList<Guid> FrameIds, int? ExpectedFramesVersion, bool DryRun);
|
||||
|
||||
/// <summary>
|
||||
/// What a photo deletion does (dry run) or did: the photos and bytes that go, the sequence's frames version (as it is on a
|
||||
/// dry run, after the deletion otherwise) and the trash entry made (null on a dry run).
|
||||
/// </summary>
|
||||
public sealed record FrameDeleteResultDto(Guid SequenceId, int Photos, long Bytes, int FramesVersion, int FrameCount, string? TrashEntry, bool DryRun);
|
||||
|
||||
/// <summary>
|
||||
/// An entry of the archive's trash (<c>GET /api/v1/archive/trash</c>): a deleted sequence (<see cref="Kind"/> <c>sequence</c>)
|
||||
/// or photos deleted from one (<c>photos</c>; <c>replaced</c> for originals a conversion replaced). <see cref="Name"/>
|
||||
/// identifies it in restore and empty requests.
|
||||
/// </summary>
|
||||
public sealed record TrashEntryDto(string Name, string Kind, Guid SequenceId, string Title, string Folder, int Photos, int Files, long Bytes,
|
||||
string? DeletedBy, DateTimeOffset DeletedAt);
|
||||
|
||||
/// <summary><c>GET /api/v1/archive/trash</c>: the entries, newest first, and their total size.</summary>
|
||||
public sealed record TrashListDto(IReadOnlyList<TrashEntryDto> Entries, long Bytes);
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/archive/trash/{name}/restore</c>: the sequence the entry went back into (a new one when the photos'
|
||||
/// sequence is gone: <see cref="NewSequence"/>), how many photos came back, and the photos kept in the trash: their names
|
||||
/// (<see cref="Kept"/>), why each stayed (<see cref="KeptReasons"/>, in the same order: <c>mismatch</c>, its files no
|
||||
/// longer match their record; <c>not_moved</c>, they could not be moved back; <c>in_sequence</c>, the sequence holds it
|
||||
/// already; <c>no_file</c>, its original was missing when it was deleted) and one sentence per reason in the request's
|
||||
/// language (<see cref="Message"/>; null when none stayed).
|
||||
/// </summary>
|
||||
public sealed record TrashRestoreDto(string Name, string Kind, Guid SequenceId, int Photos, IReadOnlyList<string> Kept, bool NewSequence,
|
||||
IReadOnlyList<string>? KeptReasons = null, string? Message = null);
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/archive/trash/empty</c>: erase the entries <see cref="Names"/> (null: every entry). A dry run answers the
|
||||
/// plan with its <see cref="TrashEmptyPlanDto.Fingerprint"/>; the erase itself must send that fingerprint back (409
|
||||
/// <c>trash_changed</c> when the trash changed since) and runs as an <c>empty-trash</c> job (202).
|
||||
/// </summary>
|
||||
public sealed record TrashEmptyRequest(IReadOnlyList<string>? Names, bool DryRun, string? Fingerprint);
|
||||
|
||||
/// <summary>The dry run of emptying the trash: the entries measured on disk, their totals, the fingerprint, and names not in the trash.</summary>
|
||||
public sealed record TrashEmptyPlanDto(IReadOnlyList<TrashEntryDto> Entries, int Photos, int Files, long Bytes, string Fingerprint, IReadOnlyList<string> Unknown);
|
||||
|
||||
/// <summary><c>POST /api/v1/sequences/bulk/delete</c>: move these sequences into the trash (or, with <see cref="DryRun"/>, say what would).</summary>
|
||||
public sealed record BulkDeleteRequest(IReadOnlyList<Guid> Ids, bool DryRun);
|
||||
|
||||
/// <summary><c>POST /api/v1/sequences/bulk/retag</c>: add and remove tags on these sequences (the same edit as a PATCH of their tags).</summary>
|
||||
public sealed record BulkRetagRequest(IReadOnlyList<Guid> Ids, IReadOnlyList<string>? Add, IReadOnlyList<string>? Remove);
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/sequences/bulk/jobs</c>: queue one job of <see cref="Kind"/> (<c>analyse</c>, <c>deep</c>, <c>proxies</c>,
|
||||
/// <c>thumbnails</c>, <c>verify</c>) over these sequences.
|
||||
/// </summary>
|
||||
public sealed record BulkJobsRequest(IReadOnlyList<Guid> Ids, string Kind);
|
||||
|
||||
/// <summary>
|
||||
/// One sequence of a bulk operation: <see cref="Outcome"/> <c>ok</c>, or <c>skipped</c> with the error code that says why
|
||||
/// (<see cref="Reason"/>, e.g. <c>not_found</c>, <c>forbidden</c>, <c>sequence_busy</c>) and its localised sentence.
|
||||
/// </summary>
|
||||
/// <param name="TrashFolder">For a delete: where the folder goes (or went) in the trash; null when it has no folder.</param>
|
||||
public sealed record BulkItemResult(Guid Id, string Outcome, string? Reason = null, string? Message = null, string? TrashFolder = null);
|
||||
|
||||
/// <summary>
|
||||
/// The result of a bulk operation: one item per id asked for, the counts, the photos and bytes a delete moves (or moved),
|
||||
/// and the job a bulk job request queued (null when nothing was queued).
|
||||
/// </summary>
|
||||
public sealed record BulkResultDto(IReadOnlyList<BulkItemResult> Items, int Ok, int Skipped, bool DryRun, int Photos = 0, long Bytes = 0, JobDto? Job = null);
|
||||
|
||||
/// <summary>
|
||||
/// A value a Library filter offers: <see cref="Value"/> as <c>GET /api/v1/sequences</c> takes it (<c>year</c>, <c>camera</c>,
|
||||
/// <c>tag</c>), the sequences that have it, and the label a menu shows when it differs (a camera model with its make).
|
||||
/// </summary>
|
||||
public sealed record FacetDto(string Value, int Sequences, string? Label = null);
|
||||
|
||||
/// <summary>
|
||||
/// <c>GET /api/v1/sequences/facets</c> (owner review 2, R6): the years of first capture (newest first), camera models (most
|
||||
/// sequences first) and tags in use (by name) of the archive's sequences, for the admin panel's Library filters.
|
||||
/// </summary>
|
||||
public sealed record LibraryFacetsDto(IReadOnlyList<FacetDto> Years, IReadOnlyList<FacetDto> Cameras, IReadOnlyList<FacetDto> Tags);
|
||||
@@ -73,4 +73,18 @@ namespace Chronos.Protocol;
|
||||
[JsonSerializable(typeof(CreateScheduleRequest))]
|
||||
[JsonSerializable(typeof(UpdateScheduleRequest))]
|
||||
[JsonSerializable(typeof(ScheduleRunDto))]
|
||||
[JsonSerializable(typeof(RemovedPhotoDto))]
|
||||
[JsonSerializable(typeof(FrameDeleteRequest))]
|
||||
[JsonSerializable(typeof(FrameDeleteResultDto))]
|
||||
[JsonSerializable(typeof(TrashEntryDto))]
|
||||
[JsonSerializable(typeof(TrashListDto))]
|
||||
[JsonSerializable(typeof(TrashRestoreDto))]
|
||||
[JsonSerializable(typeof(TrashEmptyRequest))]
|
||||
[JsonSerializable(typeof(TrashEmptyPlanDto))]
|
||||
[JsonSerializable(typeof(BulkDeleteRequest))]
|
||||
[JsonSerializable(typeof(BulkRetagRequest))]
|
||||
[JsonSerializable(typeof(BulkJobsRequest))]
|
||||
[JsonSerializable(typeof(BulkItemResult))]
|
||||
[JsonSerializable(typeof(BulkResultDto))]
|
||||
[JsonSerializable(typeof(LibraryFacetsDto))]
|
||||
public sealed partial class ProtocolJson : JsonSerializerContext;
|
||||
@@ -75,6 +75,10 @@ public sealed record FrameDto(
|
||||
|
||||
/// <summary><c>GET /api/v1/sequences/{id}/manifest</c>: what a client needs to diff a sequence (BRIEF §14.5).</summary>
|
||||
/// <param name="Proxies">How to make the proxies the server asks for (<see cref="ManifestFrame.WantsProxy"/>); null when it makes none.</param>
|
||||
/// <param name="Removed">
|
||||
/// Tombstones of the photos removed from the sequence (owner review 2, R6): a client never offers them back, and counts a
|
||||
/// replaced photo and its replacement as one; null from servers before owner review 2 and when there are none.
|
||||
/// </param>
|
||||
public sealed record SequenceManifest(
|
||||
Guid SequenceId,
|
||||
int FramesVersion,
|
||||
@@ -83,7 +87,14 @@ public sealed record SequenceManifest(
|
||||
IReadOnlyList<string> Tags,
|
||||
IReadOnlyList<ManifestFrame> Frames,
|
||||
IReadOnlyList<RenderDto> Renders,
|
||||
ProxySpec? Proxies = null);
|
||||
ProxySpec? Proxies = null,
|
||||
IReadOnlyList<RemovedPhotoDto>? Removed = null);
|
||||
|
||||
/// <summary>
|
||||
/// A photo removed from a sequence (owner review 2, R6): its lower-case hex SHA-256, the replacement's when a conversion
|
||||
/// replaced it, why (<c>deleted</c>, <c>replaced</c>) and when.
|
||||
/// </summary>
|
||||
public sealed record RemovedPhotoDto(string Sha256, string? Replacement, string Reason, DateTimeOffset At);
|
||||
|
||||
/// <summary>One frame of a manifest: its content, whether the server has a proxy and thumbnail of it, and its flags.</summary>
|
||||
/// <param name="Sha256">Lower-case hex SHA-256; empty while the server has not hashed it (a folder adopted and not verified yet).</param>
|
||||
|
||||
@@ -2,12 +2,26 @@ namespace Chronos.Protocol;
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/uploads</c> (BRIEF §14.4). The client hashes the file first; when the server already holds that
|
||||
/// SHA-256 it answers 200 with <see cref="StartUploadResponse.AlreadyExists"/> and no upload is needed.
|
||||
/// SHA-256 it answers 200 with <see cref="StartUploadResponse.AlreadyExists"/> and no upload is needed. A photo deleted
|
||||
/// from the target sequence is answered the same way, without a frame (owner review 2, R6), unless <see cref="Restore"/>
|
||||
/// asks to file it there again: only an explicit user action sends it (the admin panel's "Upload again"), never sync or a
|
||||
/// watch folder, and the completion repeats it (<c>complete?restore=true</c>). Filing it drops the photo's tombstone.
|
||||
/// </summary>
|
||||
public sealed record StartUploadRequest(Guid? SequenceId, string FileName, long Size, string Sha256, DateTime? CapturedAt, string? SessionKey);
|
||||
public sealed record StartUploadRequest(Guid? SequenceId, string FileName, long Size, string Sha256, DateTime? CapturedAt, string? SessionKey,
|
||||
bool Restore = false);
|
||||
|
||||
public sealed record StartUploadResponse(Guid? UploadId, int ChunkSize, IReadOnlyList<int> Received, bool AlreadyExists, Guid? FrameId);
|
||||
|
||||
/// <summary>Error codes of the frame upload calls that clients act on.</summary>
|
||||
public static class UploadErrors
|
||||
{
|
||||
/// <summary>
|
||||
/// 409 from <c>POST /api/v1/uploads/{id}/complete</c>: the photo was deleted from the target sequence while it was on its
|
||||
/// way and the completion did not ask to restore it, so it was not filed and the upload is cancelled (owner review 2, R6).
|
||||
/// </summary>
|
||||
public const string PhotoRemoved = "photo_removed";
|
||||
}
|
||||
|
||||
/// <summary><c>PUT /api/v1/uploads/{id}/chunks/{n}</c> response.</summary>
|
||||
public sealed record ChunkReceived(int Index, IReadOnlyList<int> Received);
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
--error: light-dark(#c42b1c, #f0625d);
|
||||
--shadow: light-dark(rgba(0, 0, 0, .18), rgba(0, 0, 0, .4));
|
||||
--scrim: light-dark(rgba(0, 0, 0, .25), rgba(0, 0, 0, .6));
|
||||
/* Badges drawn over photos (counts, numbers, the cover mark) read the same on light and dark pages. */
|
||||
--on-photo: rgba(0, 0, 0, .6);
|
||||
--radius: 6px;
|
||||
--radius-card: 8px;
|
||||
--font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Noto Sans", sans-serif;
|
||||
@@ -293,6 +295,133 @@ dialog.dialog p { margin: 0; color: var(--text-muted); }
|
||||
.toast { width: 420px; max-width: calc(100vw - 48px); padding: 12px 14px; color: var(--text); background: var(--card); border: 1px solid var(--stroke); border-inline-start: 3px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px var(--shadow); }
|
||||
.toast.error { border-inline-start-color: var(--error); }
|
||||
|
||||
/* Directional glyphs (icons.js) point along the reading direction; inside a left-to-right island (photos, time) they do not turn. */
|
||||
svg.directional:dir(rtl) { transform: scaleX(-1); }
|
||||
.btn svg, .tag svg { flex: none; }
|
||||
dialog.dialog .dialog-list { margin: 0; padding-block: 8px; padding-inline: 28px 12px; max-height: 200px; overflow: auto; border: 1px solid var(--stroke);
|
||||
border-radius: var(--radius); background: var(--bg); font-size: 12px; overflow-wrap: anywhere; }
|
||||
dialog.dialog .dialog-list:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
dialog.dialog .field-label strong { color: var(--text); }
|
||||
|
||||
/* Library (owner review 2, R6): toolbar, cards (DESIGN §4: 16:9 thumbnail, count badge, check box on hover or selection,
|
||||
selected = accent border and glow), list rows, the selection's bar, a sequence's photos and the photo viewer. */
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.toolbar .input.small { height: 32px; max-width: 200px; }
|
||||
.toolbar select.active { border-color: var(--accent); color: var(--accent); }
|
||||
.seq-items { min-width: 0; }
|
||||
.seq-items.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 1fr)); gap: 16px; padding: 16px; }
|
||||
.seq-items > .empty { grid-column: 1 / -1; }
|
||||
/* Shift+click picks a range: it selects no text. */
|
||||
.seq-card, .seq-row, .frame { position: relative; cursor: pointer; outline: none; user-select: none; }
|
||||
.seq-card { display: flex; flex-direction: column; min-width: 0; background: var(--card); border: 1px solid var(--stroke); border-radius: var(--radius-card); overflow: hidden; }
|
||||
.seq-card:hover { border-color: var(--stroke-strong); }
|
||||
.seq-card:focus-visible, .seq-row:focus-visible, .frame:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.seq-card[aria-selected="true"], .frame[aria-selected="true"] { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-selected); }
|
||||
.thumb { position: relative; display: block; aspect-ratio: 16 / 9; background: var(--card-pressed); overflow: hidden; }
|
||||
.thumb .placeholder { position: absolute; inset: 0; display: grid; place-items: center; color: var(--text-faint); }
|
||||
.thumb .placeholder svg { width: 28px; height: 28px; }
|
||||
.thumb img { position: relative; display: block; width: 100%; height: 100%; object-fit: cover; }
|
||||
.thumb img.failed { visibility: hidden; }
|
||||
.seq-check { position: absolute; top: 8px; inset-inline-start: 8px; width: 18px; height: 18px; z-index: 1; opacity: 0; cursor: pointer; }
|
||||
.seq-card:hover .seq-check, .seq-card:focus-visible .seq-check, .frame:hover .seq-check, .frame:focus-visible .seq-check,
|
||||
.selecting .seq-check, [aria-selected="true"] > .seq-check { opacity: 1; }
|
||||
.seq-card .count { position: absolute; top: 8px; inset-inline-end: 8px; padding: 0 6px; border-radius: 8px; background: var(--on-photo); color: #fff; font-size: 11px; }
|
||||
.seq-card .info { display: flex; flex-direction: column; gap: 4px; padding: 8px 10px 10px; min-width: 0; }
|
||||
.seq-card .facts { font-size: 12px; color: var(--text-muted); }
|
||||
.chips-row { display: flex; flex-wrap: wrap; gap: 4px 8px; font-size: 11px; color: var(--text-muted); }
|
||||
.st { white-space: nowrap; }
|
||||
.st.ok { color: var(--success); }
|
||||
.st.off { color: var(--text-faint); }
|
||||
.st.warn { color: var(--warning); }
|
||||
.st.err { color: var(--error); }
|
||||
/* List: the rows are one grid's subgrids, so every column fits its widest cell (as .table). */
|
||||
.seq-items.rows { display: grid; grid-template-columns: max-content 64px minmax(160px, 2fr) minmax(80px, 1fr) max-content max-content max-content; column-gap: 12px; }
|
||||
.seq-items.rows > .seq-head, .seq-items.rows > .seq-row { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; align-items: center; padding: 0 18px; }
|
||||
.seq-items.rows > .seq-head { font-size: 11px; color: var(--text-muted); padding-block: 10px; border-bottom: 1px solid var(--stroke); white-space: nowrap; }
|
||||
.seq-items.rows > .empty { grid-column: 1 / -1; }
|
||||
.seq-row { min-height: 52px; border-bottom: 1px solid var(--stroke); }
|
||||
.seq-row:hover { background: var(--card-hover); }
|
||||
.seq-row[aria-selected="true"] { background: var(--accent-selected); }
|
||||
.seq-row .seq-check { position: static; opacity: 1; }
|
||||
.seq-row .thumb { width: 64px; border-radius: 4px; }
|
||||
.seq-row .thumb .placeholder svg { width: 16px; height: 16px; }
|
||||
@media (max-width: 900px) {
|
||||
.seq-items.rows { grid-template-columns: max-content 64px minmax(120px, 1fr) max-content; }
|
||||
.seq-items.rows .col-camera, .seq-items.rows .col-size, .seq-items.rows .col-date { display: none; }
|
||||
}
|
||||
/* The selection's actions stay in view at the foot of the window while the list scrolls. */
|
||||
.mass-bar { position: sticky; bottom: 16px; z-index: 4; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px;
|
||||
background: var(--surface); border: 1px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px var(--shadow); }
|
||||
/* A sequence: cover, editable fields and facts side by side, stacked on narrow screens. */
|
||||
.seq-detail { grid-template-columns: minmax(180px, 280px) minmax(0, 1fr) minmax(220px, 320px); gap: 20px; align-items: start; }
|
||||
.seq-cover .thumb { border-radius: var(--radius); }
|
||||
.input.heading { height: 38px; font-size: 18px; font-weight: 600; border-color: transparent; background: transparent; padding-inline: 8px; margin-inline-start: -8px; }
|
||||
.input.heading:hover { border-color: var(--stroke); }
|
||||
.input.heading:focus { background: var(--card); }
|
||||
textarea.input.notes { height: auto; min-height: 64px; padding: 6px 10px; resize: vertical; font: inherit; }
|
||||
.tag-editor { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
|
||||
.tag-list { display: contents; }
|
||||
.tag { display: inline-flex; align-items: center; gap: 2px; height: 24px; padding-inline: 10px 2px; border: 1px solid var(--stroke); border-radius: 12px; background: var(--card); color: var(--text); font-size: 12px; }
|
||||
.tag-editor .input.small { width: 140px; }
|
||||
.btn.tiny { width: 20px; min-width: 20px; height: 20px; border-radius: 10px; }
|
||||
.btn.tiny svg { width: 12px; height: 12px; }
|
||||
.stars { display: flex; gap: 2px; }
|
||||
.btn.star { color: var(--text-faint); }
|
||||
.btn.star[aria-pressed="true"] { color: var(--sun); border-color: transparent; box-shadow: none; }
|
||||
.seq-facts, .viewer-meta { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 14px; margin: 0; font-size: 12px; }
|
||||
.seq-facts > div, .viewer-meta > div { display: contents; }
|
||||
.seq-facts dt, .viewer-meta dt { color: var(--text-muted); }
|
||||
.seq-facts dd, .viewer-meta dd { margin: 0; overflow-wrap: anywhere; min-width: 0; }
|
||||
.panel-head.wrap { flex-wrap: wrap; }
|
||||
.frame-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 8px; padding: 12px 18px; }
|
||||
.frame-grid > .frame-empty { grid-column: 1 / -1; }
|
||||
/* Thousands of photos: the browser lays out and paints only those near the view. */
|
||||
.frame { content-visibility: auto; contain-intrinsic-size: auto 90px; border: 1px solid var(--stroke); border-radius: var(--radius); overflow: hidden; background: var(--card); }
|
||||
.frame .thumb { aspect-ratio: 3 / 2; }
|
||||
.frame-no { position: absolute; bottom: 4px; inset-inline-end: 4px; padding: 0 5px; border-radius: 6px; background: var(--on-photo); color: #fff; font-size: 10px; }
|
||||
.frame-badge { position: absolute; top: 4px; inset-inline-end: 4px; display: grid; place-items: center; width: 22px; height: 22px; border-radius: 11px; background: var(--on-photo); color: #fff; }
|
||||
.frame-badge.hero { color: var(--sun); }
|
||||
.frame-badge.warn { top: auto; bottom: 4px; inset-inline: 4px auto; color: var(--warning); }
|
||||
.table.renders { grid-template-columns: minmax(100px, 1.4fr) max-content max-content max-content max-content max-content; }
|
||||
.table.trash { grid-template-columns: max-content minmax(140px, 2fr) max-content max-content minmax(60px, 1fr) max-content max-content; }
|
||||
.table.trash.fit-1 { grid-template-columns: max-content minmax(120px, 2fr) max-content max-content max-content max-content; }
|
||||
.table.trash.fit-1 .col-by { display: none; }
|
||||
dialog.viewer { width: min(1100px, calc(100vw - 32px)); padding: 16px 18px; }
|
||||
dialog.viewer[open] { display: grid; grid-template-columns: minmax(0, 1fr) 240px; grid-template-rows: auto minmax(0, 1fr) auto; gap: 12px 16px; }
|
||||
.viewer-head { grid-column: 1 / -1; display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||
.viewer-stage { position: relative; display: grid; place-items: center; min-height: 240px; max-height: 72vh; background: #000; border-radius: var(--radius); overflow: hidden; }
|
||||
.viewer-stage img { max-width: 100%; max-height: 72vh; object-fit: contain; display: block; }
|
||||
.viewer-stage img.failed { display: none; }
|
||||
.viewer-stage .placeholder { position: absolute; color: var(--text-faint); }
|
||||
.viewer-stage img:not(.failed) + .placeholder { display: none; }
|
||||
.viewer-meta { align-content: start; }
|
||||
dialog.viewer .buttons { grid-column: 1 / -1; }
|
||||
@media (max-width: 900px) {
|
||||
.seq-detail { grid-template-columns: minmax(0, 1fr); }
|
||||
dialog.viewer[open] { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
@media (forced-colors: active) {
|
||||
.seq-card[aria-selected="true"], .frame[aria-selected="true"], .seq-row[aria-selected="true"] { outline: 3px solid Highlight; }
|
||||
}
|
||||
|
||||
/* Upload dialog (owner review 2, R3, upload.js): the target, a drop zone, the photos with their state, the total. */
|
||||
dialog.dialog.upload { width: 640px; }
|
||||
.upload-choice { border: 0; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px 20px; }
|
||||
.upload-choice legend { color: var(--text-muted); padding: 0; margin-block-end: 8px; }
|
||||
.upload-existing { display: grid; gap: 8px; margin-block-start: 10px; }
|
||||
.upload-new { display: grid; gap: 6px; margin-block-start: 10px; color: var(--text-muted); }
|
||||
.input.list { height: auto; padding: 4px 0; }
|
||||
.input.list option { padding: 3px 10px; }
|
||||
.drop { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; padding: 14px; border: 1px dashed var(--stroke-strong); border-radius: var(--radius-card); color: var(--text-muted); }
|
||||
dialog.upload.dragging .drop { border-color: var(--accent); background: var(--accent-selected); color: var(--text); }
|
||||
.upload-files { list-style: none; margin: 0; padding: 0; max-height: 40vh; overflow-y: auto; display: grid; grid-template-columns: minmax(0, 1fr) max-content minmax(110px, 170px) 28px; column-gap: 12px; align-content: start; }
|
||||
.upload-file { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; align-items: center; min-height: 36px; border-bottom: 1px solid var(--stroke); }
|
||||
.upload-file .status { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: 12px; }
|
||||
.upload-file .status svg.bar { flex: 1 1 0; min-width: 24px; }
|
||||
.upload-file .btn.icon.small { width: 28px; min-width: 28px; }
|
||||
.upload-total { display: flex; align-items: center; gap: 12px; font-size: 12px; }
|
||||
.upload-total .progress-cell { flex: 1 1 0; }
|
||||
|
||||
/* About: the last group of Settings (owner review 2); #/about scrolls to it below the sticky header and focuses its heading. */
|
||||
.about { scroll-margin-block-start: 84px; }
|
||||
.about h2:focus { outline: none; }
|
||||
|
||||
@@ -17,14 +17,19 @@ function csrfToken() {
|
||||
return m ? decodeURIComponent(m[1]) : "";
|
||||
}
|
||||
|
||||
async function request(method, url, body) {
|
||||
/**
|
||||
* One API call: a JSON body, or with raw the bytes of a Blob (upload chunks, sent as octet-stream). An abort through
|
||||
* signal rejects with the browser's AbortError; any other failure to reach the server with ApiFailure status 0.
|
||||
*/
|
||||
async function request(method, url, body, { raw = false, signal } = {}) {
|
||||
const headers = { Accept: "application/json", "Accept-Language": culture() };
|
||||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||
if (body !== undefined) headers["Content-Type"] = raw ? "application/octet-stream" : "application/json";
|
||||
if (method !== "GET") headers["X-CSRF-Token"] = csrfToken();
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
} catch {
|
||||
res = await fetch(url, { method, headers, credentials: "same-origin", signal, body: body === undefined ? undefined : raw ? body : JSON.stringify(body) });
|
||||
} catch (err) {
|
||||
if (signal?.aborted) throw err;
|
||||
throw new ApiFailure(0, "unreachable", "");
|
||||
}
|
||||
if (res.status === 401 && url !== "/api/v1/auth/login") {
|
||||
@@ -49,6 +54,8 @@ export const api = {
|
||||
put: (url, body) => request("PUT", url, body),
|
||||
patch: (url, body) => request("PATCH", url, body),
|
||||
del: (url) => request("DELETE", url),
|
||||
/** PUT of a Blob's bytes (an upload chunk) with the session's headers: the parsed JSON answer; failures as the calls above. */
|
||||
putBytes: (url, blob, signal) => request("PUT", url, blob, { raw: true, signal }),
|
||||
user: () => currentUser,
|
||||
|
||||
/** Restores the session from the cookie; null when signed out. */
|
||||
@@ -81,16 +88,29 @@ export const api = {
|
||||
currentUser = null;
|
||||
},
|
||||
|
||||
/** Server events over WebSocket (cookie session), reconnecting with back-off until stop() is called. */
|
||||
/**
|
||||
* Server events over WebSocket (cookie session), reconnecting with back-off until stop() is called. The events sent
|
||||
* while it was not connected are lost, so once it is connected again onEvent gets { type: "reconnected" } (the
|
||||
* panel's own, never the server's): a page then reads again what it follows.
|
||||
*/
|
||||
events(onEvent) {
|
||||
let socket = null;
|
||||
let stopped = false;
|
||||
let opened = false;
|
||||
let delay = 1000;
|
||||
const connect = () => {
|
||||
if (stopped) return;
|
||||
socket = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/v1/events`);
|
||||
socket.onopen = () => {
|
||||
delay = 1000;
|
||||
if (opened) {
|
||||
try {
|
||||
onEvent({ type: "reconnected" });
|
||||
} catch {
|
||||
// A listener that throws does not stop the events.
|
||||
}
|
||||
}
|
||||
opened = true;
|
||||
};
|
||||
socket.onmessage = (m) => {
|
||||
try {
|
||||
|
||||
@@ -5,8 +5,9 @@ import { icons } from "./icons.js";
|
||||
import { escapeHtml, attr, errorText, nativeName, formatNumber, fitColumns } from "./ui.js";
|
||||
|
||||
const app = document.getElementById("app");
|
||||
// The menu: its pages from the top, then the ones docked at its foot above the account (owner review 2).
|
||||
const topPages = ["dashboard", "users", "archive", "jobs", "logs"];
|
||||
// The menu: its pages from the top, then the ones docked at its foot above the account (owner review 2). The Library
|
||||
// manages sequences and photos without editing them (owner review 2, R6).
|
||||
const topPages = ["dashboard", "library", "users", "archive", "jobs", "logs"];
|
||||
const bottomPages = ["settings"];
|
||||
const pages = [...topPages, ...bottomPages];
|
||||
/** Routes of old bookmarks and where they open now: About is the last group of Settings (owner review 2). */
|
||||
|
||||
@@ -61,6 +61,19 @@ export function detailText(entry) {
|
||||
const shown = [scheduleNameIn(parts), scheduleAction(action), recurrence ? recurrenceText(recurrence) : code];
|
||||
return (off ? [...shown, t("Admin.Schedules.Off")] : shown).join(" · ");
|
||||
}
|
||||
// Owner review 2, R6: "3 · photos-<entry>", "<entry> · Harbour sunset", "2 · 1048576 · <entries>".
|
||||
case "frames_deleted": {
|
||||
const [count] = details.split(" · ");
|
||||
return /^\d+$/.test(count) ? plural("Admin.Dashboard.PhotoCount", Number(count)) : details;
|
||||
}
|
||||
case "trash_restored": {
|
||||
const [, ...title] = details.split(" · ");
|
||||
return title.length > 0 ? title.join(" · ") : details;
|
||||
}
|
||||
case "trash_empty_requested": {
|
||||
const [count, size] = details.split(" · ");
|
||||
return /^\d+$/.test(count) && /^\d+$/.test(size ?? "") ? `${plural("Admin.Trash.EntryCount", Number(count))} · ${formatBytes(Number(size))}` : details;
|
||||
}
|
||||
default:
|
||||
return details;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// The capture time the upload dialog sends with a photo (owner review 2, R3), as local wall time without an offset
|
||||
// ("2025-05-01T06:30:00", the way the desktop clients send it): the Exif DateTimeOriginal of a JPEG or of a TIFF-based file
|
||||
// (TIFF, DNG and most RAW formats), else the file's modification time. The server keeps the time a photo records itself
|
||||
// and uses this one only for a photo that records none (a PNG, an export stripped of its Exif data), so such photos keep
|
||||
// their order instead of taking the moment they arrived. The reader is minimal: it follows one IFD pointer, checks every
|
||||
// offset against the bytes it read and gives up (null) on anything it does not expect.
|
||||
|
||||
/** Bytes read from the start of a file: every camera writes the Exif block within them. */
|
||||
const READ = 256 * 1024;
|
||||
|
||||
/** The capture time of a picked File; null when neither the photo nor the file gives a usable one. */
|
||||
export async function captureTime(file) {
|
||||
try {
|
||||
const taken = exifCaptureTime(new Uint8Array(await file.slice(0, READ).arrayBuffer()));
|
||||
if (taken) return taken;
|
||||
} catch {
|
||||
// Unreadable here: the file's own time stands in, and the server reads the photo again anyway.
|
||||
}
|
||||
const modified = file.lastModified;
|
||||
return Number.isFinite(modified) && modified > 0 ? localIso(new Date(modified)) : null;
|
||||
}
|
||||
|
||||
/** The Exif DateTimeOriginal of the JPEG or TIFF whose first bytes are given, as "yyyy-MM-ddTHH:mm:ss"; null when there is none. */
|
||||
export function exifCaptureTime(bytes) {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const size = view.byteLength;
|
||||
let tiff = -1;
|
||||
if (size >= 4 && view.getUint16(0) === 0xffd8) {
|
||||
// JPEG: the segments before the image data, up to the APP1 that starts with "Exif\0\0".
|
||||
for (let at = 2; at + 4 <= size;) {
|
||||
const marker = view.getUint16(at);
|
||||
if ((marker & 0xff00) !== 0xff00 || marker === 0xffda) break;
|
||||
const length = view.getUint16(at + 2);
|
||||
if (marker === 0xffe1 && length >= 16 && at + 10 <= size && view.getUint32(at + 4) === 0x45786966 && view.getUint16(at + 8) === 0) {
|
||||
tiff = at + 10;
|
||||
break;
|
||||
}
|
||||
if (length < 2) break;
|
||||
at += 2 + length;
|
||||
}
|
||||
} else {
|
||||
tiff = 0;
|
||||
}
|
||||
if (tiff < 0 || tiff + 8 > size) return null;
|
||||
const order = view.getUint16(tiff);
|
||||
if (order !== 0x4949 && order !== 0x4d4d) return null;
|
||||
const little = order === 0x4949;
|
||||
const u16 = (at) => view.getUint16(at, little);
|
||||
const u32 = (at) => view.getUint32(at, little);
|
||||
if (u16(tiff + 2) !== 42) return null;
|
||||
|
||||
// The 12-byte entry of a tag in the IFD at an offset from the TIFF header; -1 when it is not within reach.
|
||||
const entry = (ifd, tag) => {
|
||||
const at = tiff + ifd;
|
||||
if (ifd < 8 || at + 2 > size) return -1;
|
||||
const count = u16(at);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const e = at + 2 + i * 12;
|
||||
if (e + 12 > size) return -1;
|
||||
if (u16(e) === tag) return e;
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
const exif = entry(u32(tiff + 4), 0x8769);
|
||||
if (exif < 0) return null;
|
||||
const original = entry(u32(exif + 8), 0x9003);
|
||||
// ASCII "YYYY:MM:DD HH:MM:SS" and its terminator, stored after the IFD.
|
||||
if (original < 0 || u16(original + 2) !== 2 || u32(original + 4) < 19) return null;
|
||||
const text = tiff + u32(original + 8);
|
||||
if (text + 19 > size) return null;
|
||||
let value = "";
|
||||
for (let i = 0; i < 19; i++) value += String.fromCharCode(view.getUint8(text + i));
|
||||
const m = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/.exec(value);
|
||||
if (!m) return null;
|
||||
const [year, month, day, hour, minute, second] = m.slice(1).map(Number);
|
||||
// A real date and time only ("0000:00:00 00:00:00" is what cameras write without a clock): checked in UTC, where every
|
||||
// wall time exists.
|
||||
const check = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
|
||||
if (year < 1900 || check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day ||
|
||||
check.getUTCHours() !== hour || check.getUTCMinutes() !== minute || check.getUTCSeconds() !== second) return null;
|
||||
return `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}`;
|
||||
}
|
||||
|
||||
/** Local wall time with milliseconds and no offset; null outside the years a server date takes. */
|
||||
export function localIso(date) {
|
||||
const year = date.getFullYear();
|
||||
if (!(year >= 1 && year <= 9999)) return null;
|
||||
const p = (n, width = 2) => String(n).padStart(width, "0");
|
||||
return `${p(year, 4)}-${p(date.getMonth() + 1)}-${p(date.getDate())}T${p(date.getHours())}:${p(date.getMinutes())}:${p(date.getSeconds())}` +
|
||||
`.${p(date.getMilliseconds(), 3)}`;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Module worker of the upload dialog (owner review 2, R3): hashes a picked photo off the page's thread, reading it in
|
||||
// 8 MiB blocks so a large RAW never sits in memory whole. Before its first hash it runs the SHA-256 self-test and, if
|
||||
// any check fails, refuses every request (fail closed): the dialog then uploads nothing.
|
||||
//
|
||||
// Messages in: { id, file } a File or Blob to hash; requests are answered one after the other
|
||||
// Messages out: { id, type: "progress", done, total }
|
||||
// { id, type: "done", sha256 } lower-case hex
|
||||
// { id, type: "error", reason: "self_test" | "read", detail }
|
||||
import { Sha256, toHex, selfTest } from "./sha256.js";
|
||||
|
||||
const BLOCK = 8 * 1024 * 1024;
|
||||
let verdict = null;
|
||||
let queue = Promise.resolve();
|
||||
|
||||
self.addEventListener("message", (e) => {
|
||||
const { id, file } = e.data ?? {};
|
||||
queue = queue.then(() => hash(id, file));
|
||||
});
|
||||
|
||||
async function hash(id, file) {
|
||||
try {
|
||||
verdict ??= selfTest().catch(() => "self_test_error");
|
||||
const failed = await verdict;
|
||||
if (failed) {
|
||||
self.postMessage({ id, type: "error", reason: "self_test", detail: failed });
|
||||
return;
|
||||
}
|
||||
const sha = new Sha256();
|
||||
const total = file.size;
|
||||
for (let done = 0; done < total;) {
|
||||
const bytes = new Uint8Array(await file.slice(done, Math.min(done + BLOCK, total)).arrayBuffer());
|
||||
// A file that shrank while it was read must not end with a digest of part of it.
|
||||
if (bytes.length === 0) throw new Error("short read");
|
||||
sha.update(bytes);
|
||||
done += bytes.length;
|
||||
self.postMessage({ id, type: "progress", done, total });
|
||||
}
|
||||
self.postMessage({ id, type: "done", sha256: toHex(sha.digest()) });
|
||||
} catch (err) {
|
||||
self.postMessage({ id, type: "error", reason: "read", detail: String(err?.name ?? err) });
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
// Generated by branding/ui-icons/icons.py (same 16-px set as the desktop apps). Do not edit by hand.
|
||||
// Glyphs that point along the reading direction carry class="directional" (mirrored in right-to-left pages, admin.css).
|
||||
export const icons = {
|
||||
dashboard: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
library: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.600000000000001 5.6 A1.2 1.2 0 1 0 12.0 5.6 A1.2 1.2 0 1 0 9.600000000000001 5.6 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
users: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5 5 A3 3 0 1 0 11 5 A3 3 0 1 0 5 5 Z M2.5 14 A5.5 5.5 0 0 1 13.5 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
archive: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 4.5 H14 V13.5 H2 Z M2 2 H14 V4.5 H2 Z M6 8 H10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
jobs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 8 H13 M3 4 H13 M3 12 H9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
jobs: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 8 H13 M3 4 H13 M3 12 H9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
settings: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M7.15 3.48 L7.4 1.53 A6.5 6.5 0 0 1 8.6 1.53 L8.85 3.48 A4.6 4.6 0 0 1 10.6 4.2 L12.15 3 A6.5 6.5 0 0 1 13 3.85 L11.8 5.4 A4.6 4.6 0 0 1 12.52 7.15 L14.47 7.4 A6.5 6.5 0 0 1 14.47 8.6 L12.52 8.85 A4.6 4.6 0 0 1 11.8 10.6 L13 12.15 A6.5 6.5 0 0 1 12.15 13 L10.6 11.8 A4.6 4.6 0 0 1 8.85 12.52 L8.6 14.47 A6.5 6.5 0 0 1 7.4 14.47 L7.15 12.52 A4.6 4.6 0 0 1 5.4 11.8 L3.85 13 A6.5 6.5 0 0 1 3 12.15 L4.2 10.6 A4.6 4.6 0 0 1 3.48 8.85 L1.53 8.6 A6.5 6.5 0 0 1 1.53 7.4 L3.48 7.15 A4.6 4.6 0 0 1 4.2 5.4 L3 3.85 A6.5 6.5 0 0 1 3.85 3 L5.4 4.2 A4.6 4.6 0 0 1 7.15 3.48 Z M6.3 8 A1.7 1.7 0 1 0 9.7 8 A1.7 1.7 0 1 0 6.3 8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
logs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
logs: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
menu: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 4 H13.5 M2.5 8 H13.5 M2.5 12 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
power: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 V7.5 M11.54 4.59 A5.5 5.5 0 1 1 4.46 4.59" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
moon: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.5 1.8 A6.5 6.5 0 1 0 14.2 11.2 A5.5 5.5 0 0 1 9.5 1.8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
@@ -14,4 +16,17 @@ export const icons = {
|
||||
plus: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 3 V13 M3 8 H13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
copy: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M6.5 5 H13.0 A1.5 1.5 0 0 1 14.5 6.5 V13.0 A1.5 1.5 0 0 1 13.0 14.5 H6.5 A1.5 1.5 0 0 1 5 13.0 V6.5 A1.5 1.5 0 0 1 6.5 5 Z M11 5 V2.5 A1 1 0 0 0 10 1.5 H2.5 A1 1 0 0 0 1.5 2.5 V10 A1 1 0 0 0 2.5 11 H5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
search: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 7 A4.5 4.5 0 1 0 11.5 7 A4.5 4.5 0 1 0 2.5 7 Z M10.4 10.4 L14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
grid: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
list: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5.5 4 H13.5 M5.5 8 H13.5 M5.5 12 H13.5 M2.5 4 H2.6 M2.5 8 H2.6 M2.5 12 H2.6" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
trash: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 4 H13.5 M6 4 V2.5 H10 V4 M3.8 4 L4.6 14 H11.4 L12.2 4 M6.6 6.8 V11.2 M9.4 6.8 V11.2" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
upload: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 10.5 V2.5 M4.5 6 L8 2.5 L11.5 6 M2.5 13.5 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
download: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 2 V10 M4.5 6.5 L8 10 L11.5 6.5 M2.5 13.5 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
back: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M13 8 H3 M7 4 L3 8 L7 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
previous: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M10 4 L6 8 L10 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
next: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M6 4 L10 8 L6 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
star: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
starFilled: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z" fill="currentColor"/></svg>`,
|
||||
hero: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 4.8 L8.9 6.9 L11.1 7.1 L9.4 8.5 L9.9 10.7 L8 9.5 L6.1 10.7 L6.6 8.5 L4.9 7.1 L7.1 6.9 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
image: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.600000000000001 5.6 A1.2 1.2 0 1 0 12.0 5.6 A1.2 1.2 0 1 0 9.600000000000001 5.6 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
warning: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L14.8 13.8 H1.2 Z M8 6.2 V9.6 M8 11.7 V11.8" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics.
|
||||
// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics, and the way to the
|
||||
// archive's trash (the Library's trash view, owner review 2, R6).
|
||||
import { t, plural, applyStrings } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, bar, storageTip, writeVolumeLine, columns, toast, errorText, emptyState, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js";
|
||||
|
||||
@@ -46,7 +47,8 @@ export async function render(root, { api, setMeta }) {
|
||||
</form>
|
||||
<section class="panel" aria-labelledby="maintenance-title">
|
||||
<h2 id="maintenance-title" data-i18n="Admin.Archive.Maintenance"></h2>
|
||||
<div class="button-row">${ACTIONS.map((a) => `<button class="btn" data-action="${a}" data-i18n="Admin.Archive.${cap(a)}" data-i18n-title="Admin.Archive.${cap(a)}.Tip"></button>`).join("")}</div>
|
||||
<div class="button-row">${ACTIONS.map((a) => `<button class="btn" data-action="${a}" data-i18n="Admin.Archive.${cap(a)}" data-i18n-title="Admin.Archive.${cap(a)}.Tip"></button>`).join("")}
|
||||
<a class="btn" href="#/library?view=trash" data-i18n="Admin.Archive.Trash" data-i18n-title="Admin.Archive.Trash.Tip"></a></div>
|
||||
<h2 id="cameras-title" data-i18n="Admin.Archive.ByCamera"></h2>
|
||||
${statsTable(stats.byCamera.slice(0, 8).map((c) => ({ label: c.key || "—", count: c.count, bytes: c.bytes })), "cameras-title")
|
||||
|| `<p class="muted" data-i18n="Admin.Dashboard.NoData"></p>`}
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
// Library (owner review 2, R6; BRIEF §14.8): the panel browses, views and deletes sequences and photos and runs mass
|
||||
// operations on them, but never edits a video (no settings, no render). #/library lists the sequences with filters in the
|
||||
// address, #/library?id=<sequence> opens one (library/sequence.js), #/library?view=trash the archive's trash (library/trash.js).
|
||||
import { t, plural, applyStrings } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, toast, errorText, confirmDialog, formDialog, markInvalid, emptyState, routeParams, redraw } from "../ui.js";
|
||||
import { icons } from "../icons.js";
|
||||
import { BULK_LIMIT, factsLine, captureText, cameraLabel, statusChips, lazyImage, watchImages, Selection, selectableGrid, chunks, saveFile, sequencesCsv, today, tagList, coverUrl, listed, JOB_ENDED } from "./library/shared.js";
|
||||
import { renderSequence } from "./library/sequence.js";
|
||||
import { renderTrash } from "./library/trash.js";
|
||||
|
||||
const VIEW_KEY = "chronos.admin.library.view";
|
||||
const PAGE = 100;
|
||||
/** The Status menu: its value in the address and the listing's query parameters. */
|
||||
const STATUS_FILTERS = {
|
||||
analysed: "status=analyzedLight",
|
||||
"not-analysed": "status=-analyzedLight",
|
||||
proxies: "status=proxiesBuilt",
|
||||
"no-proxies": "status=-proxiesBuilt",
|
||||
rendered: "rendered=true",
|
||||
"not-rendered": "rendered=false",
|
||||
verified: "status=verified",
|
||||
"not-verified": "status=-verified",
|
||||
warnings: "status=hasWarnings",
|
||||
errors: "status=hasErrors",
|
||||
};
|
||||
const SORTS = ["newest", "oldest", "title", "frameCount", "size"];
|
||||
const JOBS = ["analyse", "proxies", "thumbnails", "verify"];
|
||||
const FILTERS = ["q", "year", "camera", "status", "tag", "sort"];
|
||||
|
||||
/** The list's address the last time it was shown, so a sequence's Back returns to the same filters. */
|
||||
let listHash = "#/library";
|
||||
/** upload.js of the web upload, once asked for: the module, or null when this server has none. */
|
||||
let uploadModule;
|
||||
|
||||
/**
|
||||
* The web upload (owner review 2, R3) lives in its own module; the Library offers it only when that module loads, so
|
||||
* the page works on a panel without it.
|
||||
*/
|
||||
export async function loadUpload() {
|
||||
if (uploadModule === undefined) {
|
||||
try {
|
||||
const m = await import("../upload.js");
|
||||
uploadModule = typeof m.openUpload === "function" ? m : null;
|
||||
} catch {
|
||||
uploadModule = null;
|
||||
}
|
||||
}
|
||||
return uploadModule;
|
||||
}
|
||||
|
||||
export async function render(root, context) {
|
||||
const params = routeParams();
|
||||
if (params.get("view") === "trash") return renderTrash(root, context, { back: listHash });
|
||||
const id = params.get("id");
|
||||
if (id) return renderSequence(root, context, id, { back: listHash, loadUpload });
|
||||
listHash = location.hash || "#/library";
|
||||
return renderList(root, context, params);
|
||||
}
|
||||
|
||||
async function renderList(root, { api, setMeta, actions, onEvent }, params) {
|
||||
const filters = Object.fromEntries(FILTERS.map((f) => [f, params.get(f) ?? ""]));
|
||||
if (!SORTS.includes(filters.sort)) filters.sort = "newest";
|
||||
if (!Object.hasOwn(STATUS_FILTERS, filters.status)) filters.status = "";
|
||||
let view = storedView();
|
||||
let rows = [];
|
||||
let cursor = null;
|
||||
let total = 0;
|
||||
let facets = { years: [], cameras: [], tags: [] };
|
||||
/** Every sequence of the filter, once "Select all" fetched them; null otherwise. */
|
||||
let matching = null;
|
||||
let generation = 0;
|
||||
const selection = new Selection();
|
||||
let refreshTimer = null;
|
||||
|
||||
actions.innerHTML = `
|
||||
<button class="btn" id="upload" hidden>${icons.upload}<span data-i18n="Admin.Library.Upload"></span></button>
|
||||
<a class="btn" href="#/library?view=trash" data-i18n-title="Admin.Library.Trash.Tip">${icons.trash}<span data-i18n="Admin.Library.Trash"></span></a>
|
||||
<button class="btn icon" id="refresh" data-i18n-title="Admin.Library.Refresh.Tip">${icons.refresh}</button>`;
|
||||
applyStrings(actions);
|
||||
actions.querySelector("#refresh").addEventListener("click", () => load());
|
||||
loadUpload().then((upload) => {
|
||||
const button = actions.querySelector("#upload");
|
||||
if (!upload || !button.isConnected) return;
|
||||
button.hidden = false;
|
||||
button.title = t("Admin.Library.Upload.Tip");
|
||||
button.addEventListener("click", () => upload.openUpload({ api, onDone: () => load() }));
|
||||
});
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="toolbar" role="search">
|
||||
<input class="input search" type="search" id="q" dir="auto" value="${attr(filters.q)}" data-i18n-placeholder="Admin.Library.Search"
|
||||
data-i18n-title="Admin.Library.Search.Tip" aria-label="${attr(t("Admin.Library.Search"))}">
|
||||
<select class="input small" id="year" data-i18n-title="Admin.Library.Year.Tip"></select>
|
||||
<select class="input small" id="camera" data-i18n-title="Admin.Library.Camera.Tip"></select>
|
||||
<select class="input small" id="status" data-i18n-title="Admin.Library.Status.Tip"></select>
|
||||
<select class="input small" id="tag" data-i18n-title="Admin.Library.Tag.Tip"></select>
|
||||
<select class="input small" id="sort" data-i18n-title="Admin.Library.Sort.Tip">${SORTS.map((s) =>
|
||||
`<option value="${s}" ${s === filters.sort ? "selected" : ""}>${escapeHtml(t(`Admin.Library.Sort.${cap(s)}`))}</option>`).join("")}</select>
|
||||
<span class="spacer"></span>
|
||||
<div class="segmented" role="group" aria-label="${attr(t("Admin.Library.View"))}">
|
||||
<button class="btn icon" data-view="grid" aria-pressed="${view === "grid"}" data-i18n-title="Admin.Library.View.Grid.Tip">${icons.grid}</button>
|
||||
<button class="btn icon" data-view="list" aria-pressed="${view === "list"}" data-i18n-title="Admin.Library.View.List.Tip">${icons.list}</button>
|
||||
</div>
|
||||
</div>
|
||||
<section class="panel flush library" aria-label="${attr(t("Admin.Nav.Library"))}">
|
||||
<div id="items"></div>
|
||||
<div class="table-foot" id="foot" hidden><span class="muted" id="shown"></span><span class="spacer"></span>
|
||||
<button class="btn small" id="more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>
|
||||
</section>
|
||||
<div class="mass-bar" id="mass" role="toolbar" aria-label="${attr(t("Admin.Library.Selection"))}" hidden></div>`;
|
||||
applyStrings(root);
|
||||
const itemsHost = root.querySelector("#items");
|
||||
const mass = root.querySelector("#mass");
|
||||
|
||||
let searchTimer = null;
|
||||
root.querySelector("#q").addEventListener("input", (e) => {
|
||||
clearTimeout(searchTimer);
|
||||
searchTimer = setTimeout(() => setFilter("q", e.target.value.trim()), 300);
|
||||
});
|
||||
for (const f of ["year", "camera", "status", "tag", "sort"]) root.querySelector(`#${f}`).addEventListener("change", (e) => setFilter(f, e.target.value));
|
||||
root.querySelectorAll("[data-view]").forEach((b) => b.addEventListener("click", () => {
|
||||
view = b.dataset.view;
|
||||
root.querySelectorAll("[data-view]").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
|
||||
try {
|
||||
localStorage.setItem(VIEW_KEY, view);
|
||||
} catch {
|
||||
// Only this page keeps the view then.
|
||||
}
|
||||
draw();
|
||||
}));
|
||||
root.querySelector("#more").addEventListener("click", () => load(true));
|
||||
|
||||
// One grid object for the page: the host stays, its items are redrawn.
|
||||
const grid = selectableGrid(itemsHost, {
|
||||
selection,
|
||||
order: () => rows.map((r) => r.id),
|
||||
open: (key) => {
|
||||
location.hash = `#/library?id=${encodeURIComponent(key)}`;
|
||||
},
|
||||
onChange: () => {
|
||||
// "Select all" holds while sequences beyond the loaded rows stay selected (unticking cards keeps those); once none
|
||||
// does (Esc, Ctrl+A) the selection is the loaded rows' again: Select all comes back and a refresh drops sequences gone.
|
||||
if (matching) {
|
||||
const loaded = new Set(rows.map((r) => r.id));
|
||||
if ([...selection.ids].every((id) => loaded.has(id))) matching = null;
|
||||
}
|
||||
syncSelection();
|
||||
},
|
||||
});
|
||||
|
||||
function setFilter(name, value) {
|
||||
if (filters[name] === value) return;
|
||||
filters[name] = value;
|
||||
// The address keeps the filters (no hashchange: the page stays), so Back from a sequence finds them again.
|
||||
const query = new URLSearchParams(Object.entries(filters).filter(([k, v]) => v && !(k === "sort" && v === "newest")));
|
||||
listHash = `#/library${query.size ? `?${query}` : ""}`;
|
||||
history.replaceState(null, "", listHash);
|
||||
selection.clear();
|
||||
matching = null;
|
||||
load();
|
||||
}
|
||||
|
||||
function listQuery(limit, after) {
|
||||
const p = new URLSearchParams({ limit: String(limit), sort: filters.sort });
|
||||
for (const f of ["q", "year", "camera", "tag"]) if (filters[f]) p.set(f, filters[f]);
|
||||
if (after) p.set("cursor", after);
|
||||
const status = STATUS_FILTERS[filters.status];
|
||||
return `/api/v1/sequences?${p}${status ? `&${status}` : ""}`;
|
||||
}
|
||||
|
||||
async function load(more = false) {
|
||||
const mine = ++generation;
|
||||
try {
|
||||
const [page, f] = await Promise.all([
|
||||
api.get(listQuery(PAGE, more ? cursor : null)),
|
||||
more ? Promise.resolve(facets) : api.get("/api/v1/sequences/facets").catch(() => facets),
|
||||
]);
|
||||
if (mine !== generation || !root.isConnected) return;
|
||||
facets = f;
|
||||
if (!more) total = page.total ?? page.items.length;
|
||||
cursor = page.nextCursor;
|
||||
if (more) {
|
||||
rows = rows.concat(page.items);
|
||||
appendItems(page.items);
|
||||
} else {
|
||||
rows = page.items;
|
||||
drawFilters();
|
||||
draw();
|
||||
}
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
setMeta(plural("Admin.Library.Count", total));
|
||||
drawFoot();
|
||||
}
|
||||
|
||||
/**
|
||||
* The loaded rows again, as many as are shown (live updates), a thousand per request; the selection and the keyboard
|
||||
* place stay.
|
||||
*/
|
||||
async function refreshVisible() {
|
||||
const mine = ++generation;
|
||||
const wanted = Math.max(rows.length, PAGE);
|
||||
try {
|
||||
const facetsRead = api.get("/api/v1/sequences/facets").catch(() => facets);
|
||||
const first = await api.get(listQuery(Math.min(wanted, BULK_LIMIT), null));
|
||||
let items = first.items;
|
||||
let after = first.nextCursor;
|
||||
while (after && items.length < wanted) {
|
||||
if (mine !== generation || !root.isConnected) return;
|
||||
const page = await api.get(listQuery(Math.min(wanted - items.length, BULK_LIMIT), after));
|
||||
items = items.concat(page.items);
|
||||
after = page.nextCursor;
|
||||
}
|
||||
const f = await facetsRead;
|
||||
if (mine !== generation || !root.isConnected) return;
|
||||
total = first.total ?? total;
|
||||
facets = f;
|
||||
drawFilters();
|
||||
rows = items;
|
||||
cursor = after;
|
||||
const known = new Set(rows.map((r) => r.id));
|
||||
if (!matching) selection.set([...selection.ids].filter((id) => known.has(id)));
|
||||
const focused = itemsHost.contains(document.activeElement);
|
||||
draw();
|
||||
grid.restore(focused);
|
||||
setMeta(plural("Admin.Library.Count", total));
|
||||
drawFoot();
|
||||
} catch {
|
||||
// The next event or Refresh tries again.
|
||||
}
|
||||
}
|
||||
|
||||
function drawFilters() {
|
||||
const option = (value, label, chosen) => `<option value="${attr(value)}" ${value === chosen ? "selected" : ""}>${escapeHtml(label)}</option>`;
|
||||
// A value of the address the archive no longer has stays in its menu, so the filter shows what the list does.
|
||||
const withChosen = (list, chosen) => (chosen && !list.some((f) => f.value === chosen) ? [{ value: chosen, sequences: 0 }, ...list] : list);
|
||||
const counted = (f, label) => `${label ?? f.label ?? f.value} (${formatNumber(f.sequences)})`;
|
||||
root.querySelector("#year").innerHTML = option("", t("Admin.Library.AnyYear"), filters.year) +
|
||||
withChosen(facets.years, filters.year).map((f) => option(f.value, counted(f), filters.year)).join("");
|
||||
root.querySelector("#camera").innerHTML = option("", t("Admin.Library.AnyCamera"), filters.camera) +
|
||||
withChosen(facets.cameras, filters.camera).map((f) => option(f.value, counted(f), filters.camera)).join("");
|
||||
root.querySelector("#tag").innerHTML = option("", t("Admin.Library.AnyTag"), filters.tag) +
|
||||
withChosen(facets.tags, filters.tag).map((f) => option(f.value, counted(f), filters.tag)).join("");
|
||||
root.querySelector("#status").innerHTML = option("", t("Admin.Library.AnyStatus"), filters.status) +
|
||||
Object.keys(STATUS_FILTERS).map((s) => option(s, t(`Admin.Library.Filter.${pascal(s)}`), filters.status)).join("");
|
||||
root.querySelectorAll(".toolbar select").forEach((s) => s.classList.toggle("active", s.id !== "sort" && s.value !== ""));
|
||||
}
|
||||
|
||||
function draw() {
|
||||
itemsHost.className = `seq-items ${view === "list" ? "rows" : "cards"}`;
|
||||
itemsHost.setAttribute("role", "listbox");
|
||||
itemsHost.setAttribute("aria-multiselectable", "true");
|
||||
itemsHost.setAttribute("aria-label", t("Admin.Library.Sequences"));
|
||||
if (rows.length === 0) {
|
||||
itemsHost.removeAttribute("role");
|
||||
itemsHost.removeAttribute("aria-multiselectable");
|
||||
const filtered = FILTERS.some((f) => f !== "sort" && filters[f]);
|
||||
itemsHost.innerHTML = filtered
|
||||
? emptyState("Admin.Library.NoMatch", `<button class="btn small" id="clear" data-i18n="Admin.Library.ClearFilters" data-i18n-title="Admin.Library.ClearFilters.Tip"></button>`)
|
||||
: emptyState("Admin.Library.Empty", `<button class="btn small" id="scan" data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`);
|
||||
applyStrings(itemsHost);
|
||||
itemsHost.querySelector("#clear")?.addEventListener("click", clearFilters);
|
||||
itemsHost.querySelector("#scan")?.addEventListener("click", scan);
|
||||
syncSelection();
|
||||
return;
|
||||
}
|
||||
const head = view === "list" ? `<div class="seq-head" aria-hidden="true"><span></span><span></span>
|
||||
<span data-i18n="Admin.Library.Column.Sequence"></span><span class="col-camera" data-i18n="Admin.Library.Column.Camera"></span>
|
||||
<span class="end" data-i18n="Admin.Library.Column.Photos"></span><span class="end col-size" data-i18n="Admin.Library.Column.Size"></span>
|
||||
<span class="col-date" data-i18n="Admin.Library.Column.Date"></span></div>` : "";
|
||||
itemsHost.innerHTML = head + rows.map(itemHtml).join("");
|
||||
applyStrings(itemsHost);
|
||||
watchImages(itemsHost);
|
||||
grid.restore();
|
||||
syncSelection();
|
||||
}
|
||||
|
||||
function appendItems(items) {
|
||||
if (rows.length === items.length) return draw();
|
||||
itemsHost.insertAdjacentHTML("beforeend", items.map(itemHtml).join(""));
|
||||
watchImages(itemsHost);
|
||||
grid.restore();
|
||||
syncSelection();
|
||||
}
|
||||
|
||||
function itemHtml(s) {
|
||||
const facts = factsLine(s);
|
||||
const thumb = lazyImage(coverUrl(s));
|
||||
const label = [s.displayTitle, facts].filter(Boolean).join(" · ");
|
||||
const check = `<input type="checkbox" class="seq-check" data-check tabindex="-1" aria-hidden="true" title="${attr(t("Admin.Library.Select.Tip"))}">`;
|
||||
if (view === "list") {
|
||||
return `<div class="seq-row" role="option" data-key="${attr(s.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Library.Open.Tip"))}">
|
||||
${check}${thumb}
|
||||
<span class="stack"><strong class="ellipsis" dir="auto">${escapeHtml(s.displayTitle)}</strong><span class="chips-row">${statusChips(s)}</span></span>
|
||||
<span class="ellipsis col-camera" dir="auto">${escapeHtml(cameraLabel(s.cameraMake, s.cameraModel) || "—")}</span>
|
||||
<span class="num end">${formatNumber(s.frameCount)}</span>
|
||||
<span class="num end col-size">${escapeHtml(formatBytes(s.totalBytes))}</span>
|
||||
<span class="muted nowrap col-date">${escapeHtml(captureText(s.firstCapture, false))}</span>
|
||||
</div>`;
|
||||
}
|
||||
return `<div class="seq-card" role="option" data-key="${attr(s.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Library.Open.Tip"))}">
|
||||
${thumb}${check}
|
||||
<span class="count num" aria-hidden="true">${formatNumber(s.frameCount)}</span>
|
||||
<span class="info"><strong class="ellipsis" dir="auto">${escapeHtml(s.displayTitle)}</strong>
|
||||
<span class="facts ellipsis" dir="auto">${escapeHtml(facts || "—")}</span>
|
||||
<span class="chips-row">${statusChips(s)}</span></span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function drawFoot() {
|
||||
root.querySelector("#foot").hidden = rows.length === 0 || (!cursor && rows.length >= total);
|
||||
root.querySelector("#more").hidden = !cursor;
|
||||
root.querySelector("#shown").textContent = t("Admin.Library.Shown", formatNumber(rows.length), formatNumber(total));
|
||||
}
|
||||
|
||||
/** Check boxes, item states and the mass bar for the selection; the items themselves are not drawn again. */
|
||||
function syncSelection() {
|
||||
itemsHost.querySelectorAll('[role="option"]').forEach((el) => {
|
||||
const on = selection.has(el.dataset.key);
|
||||
el.setAttribute("aria-selected", String(on));
|
||||
const box = el.querySelector("[data-check]");
|
||||
if (box) box.checked = on;
|
||||
});
|
||||
itemsHost.classList.toggle("selecting", selection.size > 0);
|
||||
drawMass();
|
||||
}
|
||||
|
||||
function drawMass() {
|
||||
if (selection.size === 0) {
|
||||
mass.hidden = true;
|
||||
mass.innerHTML = "";
|
||||
return;
|
||||
}
|
||||
const selectAll = !matching && total > selection.size
|
||||
? `<button class="btn small subtle" id="mass-all" data-mass="all" data-i18n-title="Admin.Library.SelectAll.Tip">${escapeHtml(t("Admin.Library.SelectAll", formatNumber(total)))}</button>` : "";
|
||||
const job = (kind) => `<button class="btn small" id="mass-${kind}" data-mass="job" data-kind="${kind}" data-i18n="Admin.Library.Job.${cap(kind)}" data-i18n-title="Admin.Library.Job.${cap(kind)}.Tip"></button>`;
|
||||
mass.hidden = false;
|
||||
// Drawn again at every change of the selection: the keyboard focus stays on its button.
|
||||
redraw(mass, () => {
|
||||
mass.innerHTML = `
|
||||
<strong class="nowrap" role="status">${escapeHtml(plural("Admin.Library.Selected", selection.size))}</strong>${selectAll}
|
||||
<span class="spacer"></span>
|
||||
${JOBS.map(job).join("")}
|
||||
<button class="btn small" id="mass-retag" data-mass="retag" data-i18n="Admin.Library.Retag" data-i18n-title="Admin.Library.Retag.Tip"></button>
|
||||
<button class="btn small" id="mass-csv" data-mass="csv" data-i18n="Admin.Library.ExportCsv" data-i18n-title="Admin.Library.ExportCsv.Tip"></button>
|
||||
<button class="btn small destructive" id="mass-delete" data-mass="delete" data-i18n="Admin.Library.Delete" data-i18n-title="Admin.Library.Delete.Tip"></button>
|
||||
<button class="btn small icon subtle" id="mass-clear" data-mass="clear" data-i18n-title="Admin.Library.ClearSelection.Tip">${icons.close}</button>`;
|
||||
applyStrings(mass);
|
||||
});
|
||||
mass.querySelectorAll("[data-mass]").forEach((b) => b.addEventListener("click", () => massAction(b.dataset.mass, b)));
|
||||
}
|
||||
|
||||
async function massAction(action, button) {
|
||||
if (action === "clear") {
|
||||
selection.clear();
|
||||
matching = null;
|
||||
syncSelection();
|
||||
grid.restore(true);
|
||||
return;
|
||||
}
|
||||
if (action === "all") return selectAll();
|
||||
if (action === "csv") return exportCsv();
|
||||
button.disabled = true;
|
||||
try {
|
||||
if (action === "job") await queueJobs(button.dataset.kind);
|
||||
else if (action === "retag") await retag();
|
||||
else if (action === "delete") await deleteSequences();
|
||||
} finally {
|
||||
if (button.isConnected) button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Every sequence of the filter, a thousand per request: they all count as selected. */
|
||||
async function selectAll() {
|
||||
const all = [];
|
||||
let after = null;
|
||||
try {
|
||||
do {
|
||||
const page = await api.get(listQuery(BULK_LIMIT, after));
|
||||
all.push(...page.items);
|
||||
after = page.nextCursor;
|
||||
} while (after);
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
matching = all;
|
||||
selection.set(all.map((s) => s.id));
|
||||
syncSelection();
|
||||
}
|
||||
|
||||
/** The selected sequences as far as this page knows them (all of them after Select all). */
|
||||
function selectedRows() {
|
||||
const known = new Map([...(matching ?? []), ...rows].map((s) => [s.id, s]));
|
||||
return [...selection.ids].map((id) => known.get(id)).filter(Boolean);
|
||||
}
|
||||
|
||||
/** One job per thousand sequences (a bulk request's limit); the toast counts them, and says those queued before a failure. */
|
||||
async function queueJobs(kind) {
|
||||
let queued = 0;
|
||||
let skipped = 0;
|
||||
let failure = null;
|
||||
try {
|
||||
for (const ids of chunks([...selection.ids])) {
|
||||
const result = await api.post("/api/v1/sequences/bulk/jobs", { ids, kind });
|
||||
if (result.job) queued++;
|
||||
skipped += result.skipped;
|
||||
}
|
||||
} catch (err) {
|
||||
failure = errorText(err);
|
||||
}
|
||||
const done = queued > 0 ? plural("Admin.Library.JobsQueued", queued) : failure ? "" : t("Admin.Library.NothingQueued");
|
||||
toast([done, skipped > 0 ? plural("Admin.Library.Skipped", skipped) : "", failure ?? ""].filter(Boolean).join(" · "), failure !== null);
|
||||
}
|
||||
|
||||
async function retag() {
|
||||
const datalist = facets.tags.map((f) => `<option value="${attr(f.value)}"></option>`).join("");
|
||||
const data = await formDialog({
|
||||
title: plural("Admin.Library.RetagTitle", selection.size),
|
||||
fields: `
|
||||
<label><span data-i18n="Admin.Library.AddTags"></span><input class="input" name="add" dir="auto" list="retag-tags" autocomplete="off" data-i18n-title="Admin.Library.AddTags.Tip"></label>
|
||||
<label><span data-i18n="Admin.Library.RemoveTags"></span><input class="input" name="remove" dir="auto" list="retag-tags" autocomplete="off" data-i18n-title="Admin.Library.RemoveTags.Tip"></label>
|
||||
<datalist id="retag-tags">${datalist}</datalist>`,
|
||||
confirm: t("Admin.Library.Apply"),
|
||||
confirmTip: t("Admin.Library.Apply.Tip"),
|
||||
cancel: t("Admin.Common.Cancel"),
|
||||
cancelTip: t("Admin.Common.Cancel.Tip"),
|
||||
check: (form) => {
|
||||
const add = tagList(form.elements.add.value);
|
||||
const remove = tagList(form.elements.remove.value);
|
||||
const long = [form.elements.add, form.elements.remove].find((f) => tagList(f.value).some((tag) => tag.length > 64));
|
||||
if (long) {
|
||||
markInvalid(long, t("Admin.Library.TagTooLong"));
|
||||
long.focus();
|
||||
return false;
|
||||
}
|
||||
if (add.length + remove.length === 0) {
|
||||
markInvalid(form.elements.add, t("Admin.Library.NoTags"));
|
||||
form.elements.add.focus();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
});
|
||||
if (!data) return;
|
||||
const add = tagList(String(data.get("add")));
|
||||
const remove = tagList(String(data.get("remove")));
|
||||
let ok = 0;
|
||||
const skipped = [];
|
||||
try {
|
||||
for (const ids of chunks([...selection.ids])) {
|
||||
const result = await api.post("/api/v1/sequences/bulk/retag", { ids, add, remove });
|
||||
ok += result.ok;
|
||||
skipped.push(...result.items.filter((i) => i.outcome !== "ok"));
|
||||
}
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
toast([plural("Admin.Library.Retagged", ok), skipped.length > 0 ? plural("Admin.Library.Skipped", skipped.length) : ""].filter(Boolean).join(" · "),
|
||||
skipped.length > 0 && ok === 0);
|
||||
refreshSoon();
|
||||
}
|
||||
|
||||
/** Dry run, the list of what moves to the trash, then the move; each sequence goes whole or not at all. */
|
||||
async function deleteSequences() {
|
||||
const ids = [...selection.ids];
|
||||
const plan = { items: [], ok: 0, photos: 0, bytes: 0 };
|
||||
try {
|
||||
for (const part of chunks(ids)) {
|
||||
const result = await api.post("/api/v1/sequences/bulk/delete", { ids: part, dryRun: true });
|
||||
plan.items.push(...result.items);
|
||||
plan.ok += result.ok;
|
||||
plan.photos += result.photos;
|
||||
plan.bytes += result.bytes;
|
||||
}
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
const titles = new Map(selectedRows().map((s) => [s.id, s.displayTitle]));
|
||||
const going = plan.items.filter((i) => i.outcome === "ok");
|
||||
const blocked = plan.items.filter((i) => i.outcome !== "ok");
|
||||
if (going.length === 0) {
|
||||
toast(blocked[0]?.message || t("Admin.Library.NothingToDelete"), true);
|
||||
return;
|
||||
}
|
||||
const body = [plural("Admin.Library.DeleteBody", going.length, plural("Admin.Dashboard.PhotoCount", plan.photos), formatBytes(plan.bytes)),
|
||||
blocked.length > 0 ? plural("Admin.Library.DeleteBlocked", blocked.length) : ""].filter(Boolean).join(" ");
|
||||
// Those that stay first, with their reasons; the title and the body count them all.
|
||||
const confirmed = await confirmDialog({
|
||||
title: plural("Admin.Library.DeleteTitle", going.length),
|
||||
body,
|
||||
list: listed([...blocked.map((i) => t("Admin.Library.BlockedItem", titles.get(i.id) ?? i.id, i.message ?? i.reason)), ...going.map((i) => titles.get(i.id) ?? i.id)]),
|
||||
confirm: t("Admin.Library.DeleteConfirm"),
|
||||
confirmTip: t("Admin.Library.DeleteConfirm.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
let moved = 0;
|
||||
let photos = 0;
|
||||
const failed = [];
|
||||
try {
|
||||
for (const part of chunks(going.map((i) => i.id))) {
|
||||
const result = await api.post("/api/v1/sequences/bulk/delete", { ids: part, dryRun: false });
|
||||
moved += result.ok;
|
||||
photos += result.photos;
|
||||
failed.push(...result.items.filter((i) => i.outcome !== "ok"));
|
||||
}
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
}
|
||||
toast([plural("Admin.Library.Deleted", moved, plural("Admin.Dashboard.PhotoCount", photos)), failed.length > 0 ? plural("Admin.Library.Skipped", failed.length) : ""]
|
||||
.filter(Boolean).join(" · "), moved === 0);
|
||||
selection.clear();
|
||||
matching = null;
|
||||
await load();
|
||||
}
|
||||
|
||||
function exportCsv() {
|
||||
const chosen = selectedRows();
|
||||
saveFile(`chronos-library-${today()}.csv`, sequencesCsv(chosen));
|
||||
toast(plural("Admin.Library.Exported", chosen.length));
|
||||
}
|
||||
|
||||
function clearFilters() {
|
||||
for (const f of FILTERS) filters[f] = f === "sort" ? filters.sort : "";
|
||||
root.querySelector("#q").value = "";
|
||||
listHash = filters.sort === "newest" ? "#/library" : `#/library?sort=${filters.sort}`;
|
||||
history.replaceState(null, "", listHash);
|
||||
selection.clear();
|
||||
matching = null;
|
||||
load();
|
||||
root.querySelector("#q").focus();
|
||||
}
|
||||
|
||||
async function scan() {
|
||||
try {
|
||||
await api.post("/api/v1/archive/scan");
|
||||
toast(t("Admin.Archive.Queued"));
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
}
|
||||
}
|
||||
|
||||
function refreshSoon(delay = 800) {
|
||||
clearTimeout(refreshTimer);
|
||||
refreshTimer = setTimeout(() => {
|
||||
if (root.isConnected) refreshVisible();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
// Sequences that change (a job finished, an upload landed, someone deleted or retagged) show their new state.
|
||||
onEvent((e) => {
|
||||
if (e.type === "sequenceChanged") refreshSoon(800);
|
||||
else if (e.type === "jobState" && JOB_ENDED.has(e.state)) refreshSoon(1500);
|
||||
});
|
||||
await load();
|
||||
}
|
||||
|
||||
function storedView() {
|
||||
try {
|
||||
return localStorage.getItem(VIEW_KEY) === "list" ? "list" : "grid";
|
||||
} catch {
|
||||
return "grid";
|
||||
}
|
||||
}
|
||||
|
||||
function cap(s) {
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
}
|
||||
|
||||
function pascal(s) {
|
||||
return s.split("-").map(cap).join("");
|
||||
}
|
||||
@@ -0,0 +1,613 @@
|
||||
// A sequence on the panel (owner review 2, R6): its title, tags, rating and notes, its facts, its photos in pages of 500
|
||||
// with lazy thumbnails, a photo viewer, deleting photos into the archive's trash, the cover, the originals and the renders
|
||||
// to download. Nothing here edits the video: its settings and its renders are the desktop editor's.
|
||||
import { t, plural, applyStrings } from "../../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, escapeReverts, redraw } from "../../ui.js";
|
||||
import { icons } from "../../icons.js";
|
||||
import { captureText, cameraLabel, spanText, statusChips, lazyImage, watchImages, retryImages, Selection, selectableGrid, tagList, coverUrl, listed, JOB_ENDED } from "./shared.js";
|
||||
|
||||
const FRAME_PAGE = 500;
|
||||
/** Deleting more photos than this asks for their number to be typed. */
|
||||
const TYPED_ABOVE = 20;
|
||||
/** How long after a job ended the page reads the sequence again; one read covers every job that ended meanwhile. */
|
||||
const AFTER_JOB_MS = 1500;
|
||||
/** FrameFlags bits the viewer and the tiles name. */
|
||||
const FLAGS = [[1, "Missing"], [2, "Corrupt"], [4, "Duplicate"], [8, "Excluded"]];
|
||||
const MAX_TAGS = 50;
|
||||
|
||||
export async function renderSequence(root, { api, setMeta, actions, onEvent }, id, { back, loadUpload }) {
|
||||
let seq;
|
||||
let frames = [];
|
||||
let cursor = null;
|
||||
let renders = [];
|
||||
/** The renders' list as last drawn (JSON), null before the first draw. */
|
||||
let rendersShown = null;
|
||||
let generation = 0;
|
||||
let timer = null;
|
||||
let jobTimer = null;
|
||||
/** Set once this page deleted the sequence, or saw it go: its deletion event then says nothing more. */
|
||||
let leaving = false;
|
||||
const selection = new Selection();
|
||||
|
||||
actions.innerHTML = `
|
||||
<a class="btn" href="${attr(back)}" data-i18n-title="Admin.Sequence.Back.Tip">${icons.back}<span data-i18n="Admin.Sequence.Back"></span></a>`;
|
||||
applyStrings(actions);
|
||||
|
||||
try {
|
||||
seq = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}`);
|
||||
} catch (err) {
|
||||
root.innerHTML = err.status === 404
|
||||
? `<section class="panel">${emptyState("Admin.Sequence.Gone", `<a class="btn small" href="${attr(back)}" data-i18n="Admin.Sequence.Back" data-i18n-title="Admin.Sequence.Back.Tip"></a>`)}</section>`
|
||||
: `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
|
||||
applyStrings(root);
|
||||
return;
|
||||
}
|
||||
|
||||
actions.insertAdjacentHTML("beforeend", `
|
||||
<button class="btn" id="add" hidden>${icons.upload}<span data-i18n="Admin.Sequence.AddPhotos"></span></button>
|
||||
<button class="btn destructive" id="delete-sequence" data-i18n="Admin.Sequence.Delete" data-i18n-title="Admin.Sequence.Delete.Tip"></button>`);
|
||||
applyStrings(actions);
|
||||
actions.querySelector("#delete-sequence").addEventListener("click", deleteSequence);
|
||||
loadUpload().then((upload) => {
|
||||
const button = actions.querySelector("#add");
|
||||
if (!upload || !button?.isConnected) return;
|
||||
button.hidden = false;
|
||||
button.title = t("Admin.Sequence.AddPhotos.Tip");
|
||||
button.addEventListener("click", () => upload.openUpload({ api, sequence: seq, onDone: () => reload(true) }));
|
||||
});
|
||||
|
||||
root.innerHTML = `
|
||||
<section class="panel seq-detail" aria-label="${attr(t("Admin.Sequence.Details"))}">
|
||||
<div class="seq-cover" id="cover"></div>
|
||||
<form class="form seq-fields" novalidate>
|
||||
<input class="input heading" name="title" id="seq-title" dir="auto" maxlength="200" autocomplete="off"
|
||||
aria-label="${attr(t("Admin.Sequence.Title"))}" data-i18n-title="Admin.Sequence.Title.Tip">
|
||||
<div class="field-label"><span id="tags-label" data-i18n="Admin.Sequence.Tags"></span>
|
||||
<div class="tag-editor" role="group" aria-labelledby="tags-label"><span class="tag-list" id="tags"></span>
|
||||
<input class="input small" id="tag-add" dir="auto" autocomplete="off" data-i18n-placeholder="Admin.Sequence.AddTag" data-i18n-title="Admin.Sequence.AddTag.Tip"
|
||||
aria-label="${attr(t("Admin.Sequence.AddTag"))}"></div></div>
|
||||
<div class="field-label"><span id="rating-label" data-i18n="Admin.Sequence.Rating"></span>
|
||||
<div class="stars" role="group" aria-labelledby="rating-label" id="rating"></div></div>
|
||||
<label><span data-i18n="Admin.Sequence.Notes"></span>
|
||||
<textarea class="input notes" name="notes" dir="auto" rows="3" maxlength="2000" data-i18n-title="Admin.Sequence.Notes.Tip"></textarea></label>
|
||||
</form>
|
||||
<dl class="seq-facts" id="facts"></dl>
|
||||
</section>
|
||||
<section class="panel flush" aria-labelledby="photos-title">
|
||||
<div class="panel-head padded wrap"><h2 id="photos-title" data-i18n="Admin.Sequence.Photos"></h2><span class="muted ellipsis" id="photos-meta"></span>
|
||||
<span class="spacer"></span><span class="button-row" id="frame-actions"></span></div>
|
||||
<div class="frame-grid" id="frames" dir="ltr" role="listbox" aria-multiselectable="true" aria-labelledby="photos-title"></div>
|
||||
<div class="table-foot" id="frames-foot" hidden><span class="muted" id="frames-shown"></span><span class="spacer"></span>
|
||||
<button class="btn small" id="frames-more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Sequence.MorePhotos.Tip"></button></div>
|
||||
</section>
|
||||
<section class="panel flush" aria-labelledby="renders-title">
|
||||
<div class="panel-head padded"><h2 id="renders-title" data-i18n="Admin.Sequence.Renders"></h2></div>
|
||||
<div id="renders"></div>
|
||||
</section>`;
|
||||
applyStrings(root);
|
||||
const form = root.querySelector("form");
|
||||
const framesHost = root.querySelector("#frames");
|
||||
escapeReverts(form);
|
||||
|
||||
form.addEventListener("submit", (e) => e.preventDefault());
|
||||
form.elements.title.addEventListener("change", () => {
|
||||
const title = form.elements.title.value.trim();
|
||||
if (title !== (seq.title ?? "")) patch({ title });
|
||||
});
|
||||
form.elements.title.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") form.elements.title.blur();
|
||||
});
|
||||
form.elements.notes.addEventListener("change", () => {
|
||||
const notes = form.elements.notes.value;
|
||||
if (notes !== (seq.notes ?? "")) patch({ notes });
|
||||
});
|
||||
const tagInput = root.querySelector("#tag-add");
|
||||
tagInput.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
e.preventDefault();
|
||||
const added = tagList(tagInput.value).filter((tag) => !seq.tags.some((s) => s.toLocaleLowerCase() === tag.toLocaleLowerCase()));
|
||||
if (added.some((tag) => tag.length > 64)) return toast(t("Admin.Library.TagTooLong"), true);
|
||||
if (seq.tags.length + added.length > MAX_TAGS) return toast(t("Admin.Sequence.TooManyTags"), true);
|
||||
tagInput.value = "";
|
||||
if (added.length > 0) patch({ tags: [...seq.tags, ...added] }, "tag-add");
|
||||
});
|
||||
root.querySelector("#frames-more").addEventListener("click", () => loadFrames(true));
|
||||
|
||||
const grid = selectableGrid(framesHost, {
|
||||
selection,
|
||||
order: () => frames.map((f) => f.id),
|
||||
open: (key) => openViewer(key),
|
||||
onChange: syncSelection,
|
||||
});
|
||||
|
||||
function drawHeader() {
|
||||
setMeta(seq.displayTitle);
|
||||
document.title = `${seq.displayTitle} · Chronos Server`;
|
||||
const titleField = form.elements.title;
|
||||
if (document.activeElement !== titleField) titleField.value = titleField.defaultValue = seq.title ?? "";
|
||||
titleField.placeholder = seq.displayTitle;
|
||||
const notes = form.elements.notes;
|
||||
if (document.activeElement !== notes) notes.value = notes.defaultValue = seq.notes ?? "";
|
||||
|
||||
// The cover is drawn again only when it changes (another photo, other photos), not at every edit.
|
||||
const cover = root.querySelector("#cover");
|
||||
if (cover.dataset.src !== coverUrl(seq)) {
|
||||
cover.dataset.src = coverUrl(seq);
|
||||
cover.innerHTML = lazyImage(coverUrl(seq), "cover");
|
||||
watchImages(cover);
|
||||
}
|
||||
|
||||
// Tags and stars are buttons: a redraw keeps the keyboard focus on the same one (a star by its id, a tag by its place).
|
||||
const tags = root.querySelector("#tags");
|
||||
redraw(tags, () => {
|
||||
tags.innerHTML = seq.tags.map((tag, i) => `<span class="tag" dir="auto">${escapeHtml(tag)}<button class="btn icon subtle tiny" type="button" data-remove="${i}"
|
||||
title="${attr(t("Admin.Sequence.RemoveTag.Tip", tag))}" aria-label="${attr(t("Admin.Sequence.RemoveTag.Tip", tag))}">${icons.close}</button></span>`).join("");
|
||||
});
|
||||
tags.querySelectorAll("[data-remove]").forEach((b) => b.addEventListener("click", () =>
|
||||
patch({ tags: seq.tags.filter((_, i) => i !== Number(b.dataset.remove)) }, "tag-add")));
|
||||
|
||||
const rating = root.querySelector("#rating");
|
||||
redraw(rating, () => {
|
||||
rating.innerHTML = [1, 2, 3, 4, 5].map((n) => `<button class="btn icon subtle star" type="button" id="star-${n}" data-star="${n}" aria-pressed="${n <= seq.rating}"
|
||||
aria-label="${attr(plural("Admin.Sequence.Stars", n))}" title="${attr(t(n === seq.rating ? "Admin.Sequence.Unrate.Tip" : "Admin.Sequence.Rate.Tip", n))}">${n <= seq.rating ? icons.starFilled : icons.star}</button>`).join("");
|
||||
});
|
||||
rating.querySelectorAll("[data-star]").forEach((b) => b.addEventListener("click", () => {
|
||||
const n = Number(b.dataset.star);
|
||||
patch({ rating: n === seq.rating ? 0 : n }, `star-${n}`);
|
||||
}));
|
||||
|
||||
const fact = (key, value, { ltr = false, html = false } = {}) => value === null || value === undefined || value === ""
|
||||
? "" : `<div><dt data-i18n="Admin.Sequence.Fact.${key}"></dt><dd ${ltr ? 'dir="ltr" class="mono"' : 'dir="auto"'}>${html ? value : escapeHtml(value)}</dd></div>`;
|
||||
const captured = seq.firstCapture ? `${captureText(seq.firstCapture)} – ${captureText(seq.lastCapture)}` : "";
|
||||
root.querySelector("#facts").innerHTML = [
|
||||
fact("Camera", cameraLabel(seq.cameraMake, seq.cameraModel)),
|
||||
fact("Lens", seq.lens),
|
||||
fact("Captured", captured),
|
||||
fact("Span", spanText(seq)),
|
||||
fact("Photos", formatNumber(seq.frameCount)),
|
||||
fact("Size", formatBytes(seq.totalBytes)),
|
||||
fact("Interval", seq.medianInterval ? t("Common.Duration.Seconds", formatNumber(Math.round(seq.medianInterval * 10) / 10)) : ""),
|
||||
fact("Folder", seq.folder, { ltr: true }),
|
||||
fact("Status", `<span class="chips-row">${statusChips(seq)}</span>`, { html: true }),
|
||||
fact("Updated", formatDateTime(seq.updatedAt)),
|
||||
].join("");
|
||||
applyStrings(root.querySelector("#facts"));
|
||||
}
|
||||
|
||||
/** One field of the sequence changed (the same edit as the desktop's Library makes); a conflict reloads it. */
|
||||
async function patch(change, focusId = null) {
|
||||
const hero = seq.heroFrameId;
|
||||
try {
|
||||
seq = await api.patch(`/api/v1/sequences/${encodeURIComponent(id)}`, { ...change, expectedSettingsVersion: seq.settingsVersion });
|
||||
toast(t("Admin.Common.Saved"));
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
if (err.status === 409) await reloadSequence();
|
||||
}
|
||||
drawHeader();
|
||||
// The cover's mark moves to its new photo.
|
||||
if (seq.heroFrameId !== hero) drawFrames();
|
||||
if (focusId) root.querySelector(`#${focusId}`)?.focus();
|
||||
}
|
||||
|
||||
async function reloadSequence() {
|
||||
try {
|
||||
seq = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}`);
|
||||
} catch (err) {
|
||||
if (err.status === 404) gone();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFrames(more = false) {
|
||||
const mine = ++generation;
|
||||
try {
|
||||
const page = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/frames?limit=${FRAME_PAGE}${more && cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
|
||||
if (mine !== generation || !root.isConnected) return;
|
||||
cursor = page.nextCursor;
|
||||
if (more) {
|
||||
frames = frames.concat(page.items);
|
||||
framesHost.insertAdjacentHTML("beforeend", page.items.map(frameHtml).join(""));
|
||||
watchImages(framesHost);
|
||||
grid.restore();
|
||||
syncSelection();
|
||||
} else {
|
||||
frames = page.items;
|
||||
drawFrames();
|
||||
}
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
}
|
||||
drawFramesFoot();
|
||||
}
|
||||
|
||||
/** The photos again after they changed, as many as were shown; the selection keeps the photos still there. */
|
||||
async function reloadFrames() {
|
||||
const want = Math.max(frames.length, FRAME_PAGE);
|
||||
const mine = ++generation;
|
||||
let list = [];
|
||||
let after = null;
|
||||
try {
|
||||
do {
|
||||
const page = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/frames?limit=${FRAME_PAGE}${after ? `&cursor=${encodeURIComponent(after)}` : ""}`);
|
||||
list = list.concat(page.items);
|
||||
after = page.nextCursor;
|
||||
} while (after && list.length < want);
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
if (mine !== generation || !root.isConnected) return;
|
||||
frames = list;
|
||||
cursor = after;
|
||||
const known = new Set(frames.map((f) => f.id));
|
||||
selection.set([...selection.ids].filter((f) => known.has(f)));
|
||||
const focused = framesHost.contains(document.activeElement);
|
||||
drawFrames();
|
||||
grid.restore(focused);
|
||||
drawFramesFoot();
|
||||
}
|
||||
|
||||
function drawFrames() {
|
||||
framesHost.innerHTML = frames.map(frameHtml).join("") ||
|
||||
`<div class="frame-empty">${emptyState("Admin.Sequence.NoPhotos")}</div>`;
|
||||
applyStrings(framesHost);
|
||||
watchImages(framesHost);
|
||||
grid.restore();
|
||||
syncSelection();
|
||||
}
|
||||
|
||||
function frameHtml(f) {
|
||||
const flags = FLAGS.filter(([bit]) => (f.flags & bit) !== 0).map(([, name]) => t(`Admin.Sequence.Flag.${name}`));
|
||||
const label = [f.fileName, captureText(f.capturedAt), ...flags].join(" · ");
|
||||
const hero = f.id === seq.heroFrameId ? `<span class="frame-badge hero" title="${attr(t("Admin.Sequence.Cover.Tip"))}">${icons.hero}</span>` : "";
|
||||
const flagged = flags.length > 0 ? `<span class="frame-badge warn" title="${attr(flags.join(" · "))}">${icons.warning}</span>` : "";
|
||||
return `<div class="frame" role="option" data-key="${attr(f.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Sequence.Photo.Tip", f.fileName))}">
|
||||
${lazyImage(`/api/v1/frames/${encodeURIComponent(f.id)}/thumb`)}
|
||||
<input type="checkbox" class="seq-check" data-check tabindex="-1" aria-hidden="true" title="${attr(t("Admin.Sequence.SelectPhoto.Tip"))}">
|
||||
<span class="frame-no num" aria-hidden="true">${formatNumber(f.index + 1)}</span>${hero}${flagged}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function drawFramesFoot() {
|
||||
root.querySelector("#photos-meta").textContent = plural("Admin.Dashboard.PhotoCount", seq.frameCount);
|
||||
root.querySelector("#frames-foot").hidden = !cursor;
|
||||
root.querySelector("#frames-shown").textContent = t("Admin.Library.Shown", formatNumber(frames.length), formatNumber(seq.frameCount));
|
||||
}
|
||||
|
||||
function syncSelection() {
|
||||
framesHost.querySelectorAll('[role="option"]').forEach((el) => {
|
||||
const on = selection.has(el.dataset.key);
|
||||
el.setAttribute("aria-selected", String(on));
|
||||
const box = el.querySelector("[data-check]");
|
||||
if (box) box.checked = on;
|
||||
});
|
||||
framesHost.classList.toggle("selecting", selection.size > 0);
|
||||
drawFrameActions();
|
||||
}
|
||||
|
||||
function drawFrameActions() {
|
||||
const host = root.querySelector("#frame-actions");
|
||||
const n = selection.size;
|
||||
const one = n === 1;
|
||||
const tip = (key, enabled, why) => attr(t(enabled ? key : why));
|
||||
redraw(host, () => {
|
||||
host.innerHTML = `
|
||||
${n > 0 ? `<span class="muted nowrap" role="status">${escapeHtml(plural("Admin.Library.Selected", n))}</span>` : ""}
|
||||
<button class="btn small" id="frames-all" data-frames="all" data-i18n="Admin.Sequence.SelectAll" data-i18n-title="Admin.Sequence.SelectAll.Tip" ${frames.length === 0 ? "disabled" : ""}></button>
|
||||
${n > 0 ? `<button class="btn small" id="frames-clear" data-frames="clear" data-i18n="Admin.Sequence.ClearSelection" data-i18n-title="Admin.Sequence.ClearSelection.Tip"></button>` : ""}
|
||||
<button class="btn small" id="frames-cover" data-frames="cover" title="${tip("Admin.Sequence.SetCover.Tip", one, "Admin.Sequence.OnePhoto.Tip")}" ${one ? "" : "disabled"}>${icons.hero}<span data-i18n="Admin.Sequence.SetCover"></span></button>
|
||||
<button class="btn small" id="frames-download" data-frames="download" title="${tip("Admin.Sequence.Download.Tip", one, "Admin.Sequence.OnePhoto.Tip")}" ${one ? "" : "disabled"}>${icons.download}<span data-i18n="Admin.Sequence.Download"></span></button>
|
||||
<button class="btn small destructive" id="frames-delete" data-frames="delete" title="${tip("Admin.Sequence.DeletePhotos.Tip", n > 0, "Admin.Sequence.SomePhotos.Tip")}" ${n > 0 ? "" : "disabled"}
|
||||
data-i18n="Admin.Sequence.DeletePhotos"></button>`;
|
||||
applyStrings(host);
|
||||
});
|
||||
host.querySelectorAll("[data-frames]").forEach((b) => b.addEventListener("click", () => frameAction(b.dataset.frames)));
|
||||
}
|
||||
|
||||
function frameAction(action) {
|
||||
const [only] = selection.ids;
|
||||
switch (action) {
|
||||
case "all":
|
||||
selection.set(frames.map((f) => f.id));
|
||||
return syncSelection();
|
||||
case "clear":
|
||||
selection.clear();
|
||||
syncSelection();
|
||||
return grid.restore(true);
|
||||
case "cover":
|
||||
return setCover(only);
|
||||
case "download":
|
||||
return download(only);
|
||||
case "delete":
|
||||
return deletePhotos();
|
||||
}
|
||||
}
|
||||
|
||||
function setCover(frameId) {
|
||||
return patch({ heroFrameId: frameId });
|
||||
}
|
||||
|
||||
function download(frameId) {
|
||||
const frame = frames.find((f) => f.id === frameId);
|
||||
const a = document.createElement("a");
|
||||
a.href = `/api/v1/frames/${encodeURIComponent(frameId)}/original`;
|
||||
a.download = frame?.fileName ?? "";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
}
|
||||
|
||||
/** Dry run, the confirmation (typing the count when many go), then the move into the archive's trash. */
|
||||
async function deletePhotos() {
|
||||
const ids = [...selection.ids];
|
||||
const url = `/api/v1/sequences/${encodeURIComponent(id)}/frames/delete`;
|
||||
let plan;
|
||||
try {
|
||||
plan = await api.post(url, { frameIds: ids, expectedFramesVersion: seq.framesVersion, dryRun: true });
|
||||
} catch (err) {
|
||||
return refused(err);
|
||||
}
|
||||
const names = frames.filter((f) => selection.has(f.id)).map((f) => f.fileName);
|
||||
const confirmed = await confirmDialog({
|
||||
title: plural("Admin.Sequence.DeletePhotosTitle", plan.photos),
|
||||
body: plural("Admin.Sequence.DeletePhotosBody", plan.photos, formatBytes(plan.bytes)),
|
||||
list: listed(names),
|
||||
confirm: t("Admin.Sequence.DeletePhotosConfirm"),
|
||||
confirmTip: t("Admin.Sequence.DeletePhotosConfirm.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
typed: plan.photos > TYPED_ABOVE ? String(plan.photos) : undefined,
|
||||
typedKind: "count",
|
||||
});
|
||||
if (!confirmed) return;
|
||||
let result;
|
||||
try {
|
||||
result = await api.post(url, { frameIds: ids, expectedFramesVersion: plan.framesVersion, dryRun: false });
|
||||
} catch (err) {
|
||||
return refused(err);
|
||||
}
|
||||
toast(plural("Admin.Sequence.PhotosDeleted", result.photos));
|
||||
selection.clear();
|
||||
await reload(true);
|
||||
}
|
||||
|
||||
/** A deletion the server refused: its sentence; photos that changed meanwhile are shown again. */
|
||||
async function refused(err) {
|
||||
toast(errorText(err), true);
|
||||
if (err.code === "frames_conflict") await reload(true);
|
||||
if (err.status === 404) gone();
|
||||
}
|
||||
|
||||
async function deleteSequence() {
|
||||
const url = `/api/v1/sequences/${encodeURIComponent(id)}`;
|
||||
let plan;
|
||||
try {
|
||||
plan = await api.del(`${url}?dryRun=true`);
|
||||
} catch (err) {
|
||||
return toast(errorText(err), true);
|
||||
}
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("Admin.Sequence.DeleteTitle", seq.displayTitle),
|
||||
body: plural("Admin.Sequence.DeleteBody", plan.frameCount, formatBytes(plan.totalBytes)),
|
||||
confirm: t("Admin.Library.DeleteConfirm"),
|
||||
confirmTip: t("Admin.Sequence.DeleteConfirm.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
leaving = true;
|
||||
try {
|
||||
await api.del(url);
|
||||
} catch (err) {
|
||||
leaving = false;
|
||||
return toast(errorText(err), true);
|
||||
}
|
||||
toast(t("Admin.Sequence.Deleted", seq.displayTitle));
|
||||
location.hash = back;
|
||||
}
|
||||
|
||||
/** The renders, drawn again only when their list changed (a refresh after every job must not move the focus). */
|
||||
async function loadRenders() {
|
||||
let list;
|
||||
try {
|
||||
list = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/renders`);
|
||||
} catch {
|
||||
// A failed refresh leaves the list shown; a first read that failed shows none.
|
||||
if (rendersShown !== null) return;
|
||||
list = [];
|
||||
}
|
||||
const key = JSON.stringify(list);
|
||||
if (key === rendersShown || !root.isConnected) return;
|
||||
rendersShown = key;
|
||||
renders = list;
|
||||
const host = root.querySelector("#renders");
|
||||
redraw(host, () => drawRenders(host));
|
||||
}
|
||||
|
||||
function drawRenders(host) {
|
||||
host.innerHTML = renders.length === 0 ? emptyState("Admin.Sequence.NoRenders") : `
|
||||
<div class="table renders" role="table" aria-labelledby="renders-title">
|
||||
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Sequence.Render.Preset"></span>
|
||||
<span role="columnheader" data-i18n="Admin.Sequence.Render.Video"></span><span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Length"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Size"></span><span role="columnheader" data-i18n="Admin.Sequence.Render.Created"></span>
|
||||
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
|
||||
<div role="rowgroup">${renders.map((r) => `
|
||||
<div class="row" role="row" data-key="${attr(r.id)}">
|
||||
<span class="ellipsis" role="cell" dir="auto" title="${attr(r.producedBy ?? "")}">${escapeHtml(r.presetName)}</span>
|
||||
<span class="num nowrap" role="cell" dir="ltr">${escapeHtml(`${r.width} × ${r.height} · ${formatNumber(r.fps)} fps${r.codec ? ` · ${r.codec.toUpperCase()}` : ""}`)}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(clock(r.durationSeconds))}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(formatBytes(r.bytes))}</span>
|
||||
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(r.created))}</span>
|
||||
<span class="row-actions" role="cell"><a class="btn small" href="/api/v1/renders/${encodeURIComponent(r.id)}/file" download
|
||||
data-i18n-title="Admin.Sequence.Render.Download.Tip">${icons.download}<span data-i18n="Admin.Sequence.Render.Download"></span></a></span>
|
||||
</div>`).join("")}</div>
|
||||
</div>`;
|
||||
applyStrings(host);
|
||||
}
|
||||
|
||||
/** The photo viewer: the proxy (the thumbnail when there is none), its facts, ← and → through the photos, Esc closes. */
|
||||
function openViewer(frameId) {
|
||||
let index = frames.findIndex((f) => f.id === frameId);
|
||||
if (index < 0) return;
|
||||
const opener = document.activeElement;
|
||||
const dialog = document.createElement("dialog");
|
||||
dialog.className = "dialog viewer";
|
||||
dialog.setAttribute("aria-labelledby", "viewer-title");
|
||||
dialog.innerHTML = `
|
||||
<div class="viewer-head"><h2 id="viewer-title" class="ellipsis" dir="ltr"></h2><span class="muted num nowrap" id="viewer-position"></span>
|
||||
<span class="spacer"></span>
|
||||
<span class="inline" dir="ltr"><button class="btn icon" type="button" data-go="-1" data-i18n-title="Admin.Sequence.Previous.Tip">${icons.previous}</button>
|
||||
<button class="btn icon" type="button" data-go="1" data-i18n-title="Admin.Sequence.Next.Tip">${icons.next}</button></span>
|
||||
<button class="btn icon" type="button" data-close data-i18n-title="Admin.Sequence.CloseViewer.Tip">${icons.close}</button></div>
|
||||
<div class="viewer-stage" dir="ltr"><img alt=""><span class="placeholder" aria-hidden="true">${icons.image}</span></div>
|
||||
<dl class="viewer-meta" id="viewer-meta"></dl>
|
||||
<div class="buttons">
|
||||
<button class="btn" type="button" data-cover data-i18n-title="Admin.Sequence.SetCover.Tip">${icons.hero}<span data-i18n="Admin.Sequence.SetCover"></span></button>
|
||||
<button class="btn" type="button" data-download data-i18n-title="Admin.Sequence.Download.Tip">${icons.download}<span data-i18n="Admin.Sequence.Download"></span></button>
|
||||
</div>`;
|
||||
applyStrings(dialog);
|
||||
document.body.appendChild(dialog);
|
||||
const img = dialog.querySelector("img");
|
||||
img.addEventListener("error", () => {
|
||||
// No proxy (proxies off, or not built yet): the thumbnail, then the placeholder.
|
||||
const thumb = `/api/v1/frames/${encodeURIComponent(frames[index].id)}/thumb`;
|
||||
if (!img.src.endsWith(thumb)) img.src = thumb;
|
||||
else img.classList.add("failed");
|
||||
});
|
||||
img.addEventListener("load", () => img.classList.remove("failed"));
|
||||
|
||||
const show = async (to) => {
|
||||
if (to >= frames.length && cursor) await loadFrames(true);
|
||||
if (to < 0 || to >= frames.length) return;
|
||||
index = to;
|
||||
const f = frames[index];
|
||||
img.classList.remove("failed");
|
||||
img.src = `/api/v1/frames/${encodeURIComponent(f.id)}/proxy`;
|
||||
dialog.querySelector("#viewer-title").textContent = f.fileName;
|
||||
dialog.querySelector("#viewer-position").textContent = t("Admin.Sequence.Position", formatNumber(f.index + 1), formatNumber(seq.frameCount));
|
||||
dialog.querySelector("#viewer-meta").innerHTML = frameFacts(f);
|
||||
applyStrings(dialog.querySelector("#viewer-meta"));
|
||||
dialog.querySelector('[data-go="-1"]').disabled = index === 0;
|
||||
dialog.querySelector('[data-go="1"]').disabled = index === frames.length - 1 && !cursor;
|
||||
dialog.querySelector("[data-cover]").disabled = f.id === seq.heroFrameId;
|
||||
};
|
||||
dialog.addEventListener("keydown", (e) => {
|
||||
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
|
||||
e.preventDefault();
|
||||
show(index + (e.key === "ArrowRight" ? 1 : -1));
|
||||
}
|
||||
});
|
||||
dialog.querySelectorAll("[data-go]").forEach((b) => b.addEventListener("click", () => show(index + Number(b.dataset.go))));
|
||||
dialog.querySelector("[data-close]").addEventListener("click", () => dialog.close());
|
||||
dialog.querySelector("[data-cover]").addEventListener("click", async () => {
|
||||
await setCover(frames[index].id);
|
||||
show(index);
|
||||
});
|
||||
dialog.querySelector("[data-download]").addEventListener("click", () => download(frames[index].id));
|
||||
dialog.addEventListener("close", () => {
|
||||
const at = frames[index]?.id;
|
||||
dialog.remove();
|
||||
// Back on the photo the viewer ended on.
|
||||
const tile = at && framesHost.querySelector(`[data-key="${CSS.escape(at)}"]`);
|
||||
(tile ?? opener)?.focus?.();
|
||||
});
|
||||
dialog.showModal();
|
||||
show(index);
|
||||
}
|
||||
|
||||
function frameFacts(f) {
|
||||
const fact = (key, value, ltr = false) => value === null || value === undefined || value === ""
|
||||
? "" : `<div><dt data-i18n="Admin.Sequence.Fact.${key}"></dt><dd ${ltr ? 'dir="ltr"' : 'dir="auto"'}>${escapeHtml(value)}</dd></div>`;
|
||||
const swapped = f.orientation >= 5 && f.orientation <= 8;
|
||||
const [w, h] = swapped ? [f.height, f.width] : [f.width, f.height];
|
||||
const offset = f.utcOffsetMinutes == null ? "" : ` UTC${f.utcOffsetMinutes < 0 ? "−" : "+"}${String(Math.floor(Math.abs(f.utcOffsetMinutes) / 60)).padStart(2, "0")}:${String(Math.abs(f.utcOffsetMinutes) % 60).padStart(2, "0")}`;
|
||||
const flags = FLAGS.filter(([bit]) => (f.flags & bit) !== 0).map(([, name]) => t(`Admin.Sequence.Flag.${name}`)).join(" · ");
|
||||
return [
|
||||
fact("Time", f.capturedAt ? captureText(f.capturedAt) + offset : ""),
|
||||
fact("Exposure", exposure(f.exposureTime), true),
|
||||
fact("Aperture", f.fNumber ? `f/${formatNumber(f.fNumber)}` : "", true),
|
||||
fact("Iso", f.iso ? formatNumber(f.iso) : "", true),
|
||||
fact("Focal", f.focalLength ? `${formatNumber(f.focalLength)} mm` : "", true),
|
||||
fact("Dimensions", w > 0 && h > 0 ? `${w} × ${h}` : "", true),
|
||||
fact("Size", formatBytes(f.size)),
|
||||
fact("Format", f.format.toUpperCase(), true),
|
||||
fact("Flags", flags),
|
||||
fact("Sha256", f.sha256 ?? "", true),
|
||||
].join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything again after a change elsewhere; with frames, the photos too. Only what changed is drawn again (the header
|
||||
* when the sequence read differs from the one shown), so a refresh that finds nothing new leaves the page and the
|
||||
* keyboard focus as they were. True when the sequence changed.
|
||||
*/
|
||||
async function reload(withFrames) {
|
||||
const shown = seq;
|
||||
await reloadSequence();
|
||||
if (!root.isConnected || leaving) return false;
|
||||
const changed = JSON.stringify(seq) !== JSON.stringify(shown);
|
||||
if (changed) drawHeader();
|
||||
if (withFrames || seq.framesVersion !== shown.framesVersion) await reloadFrames();
|
||||
else if (seq.heroFrameId !== shown.heroFrameId) drawFrames();
|
||||
await loadRenders();
|
||||
return changed;
|
||||
}
|
||||
|
||||
function gone() {
|
||||
if (leaving) return;
|
||||
leaving = true;
|
||||
toast(t("Admin.Sequence.Gone"), true);
|
||||
location.hash = back;
|
||||
}
|
||||
|
||||
/**
|
||||
* After a job ended: thumbnail, proxy, verify and analysis jobs send no sequenceChanged, so the facts and status chips
|
||||
* are read again and the cover and photos that had no thumbnail yet are asked for again, each less often and up to a
|
||||
* limit, from the start again once the sequence changed.
|
||||
*/
|
||||
async function afterJob() {
|
||||
jobTimer = null;
|
||||
if (!root.isConnected || leaving) return;
|
||||
const changed = await reload(false);
|
||||
if (root.isConnected && !leaving) retryImages(root, changed);
|
||||
}
|
||||
|
||||
onEvent((e) => {
|
||||
if (e.type === "jobState") {
|
||||
// The event names neither the job's kind nor its targets: any job that ended may have worked on this one. The timer
|
||||
// is not pushed back by the next one, so a busy queue still refreshes the page every AFTER_JOB_MS; a refresh that
|
||||
// finds the sequence and its renders as shown draws nothing.
|
||||
if (JOB_ENDED.has(e.state) && jobTimer === null) jobTimer = setTimeout(afterJob, AFTER_JOB_MS);
|
||||
return;
|
||||
}
|
||||
if (e.type !== "sequenceChanged" || e.sequenceId !== id) return;
|
||||
if (e.change === "deleted") {
|
||||
gone();
|
||||
return;
|
||||
}
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
if (root.isConnected) reload(false);
|
||||
}, 800);
|
||||
});
|
||||
|
||||
drawHeader();
|
||||
await Promise.all([loadFrames(), loadRenders()]);
|
||||
drawFrameActions();
|
||||
}
|
||||
|
||||
/** 1/250 s, 0.5 s, 30 s. */
|
||||
function exposure(seconds) {
|
||||
if (!seconds || seconds <= 0) return "";
|
||||
if (seconds < 0.5) return `1/${Math.round(1 / seconds)} s`;
|
||||
return `${Math.round(seconds * 10) / 10} s`;
|
||||
}
|
||||
|
||||
/** A video length as 1:05 or 1:02:05. */
|
||||
function clock(seconds) {
|
||||
const s = Math.max(0, Math.round(seconds ?? 0));
|
||||
const hh = Math.floor(s / 3600);
|
||||
const mm = Math.floor((s % 3600) / 60);
|
||||
const ss = String(s % 60).padStart(2, "0");
|
||||
return hh > 0 ? `${hh}:${String(mm).padStart(2, "0")}:${ss}` : `${mm}:${ss}`;
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
// What the Library's views share (owner review 2, R6): sequence facts and status chips as the desktop cards show them,
|
||||
// thumbnails and their retries after a job ended, the job states that end a job, delete lists cut to LISTED names, a
|
||||
// selection with Shift ranges, the keyboard of a grid of selectable items, chunked bulk calls and file downloads.
|
||||
import { t, plural, culture } from "../../i18n.js";
|
||||
import { escapeHtml, attr, formatNumber, formatDuration } from "../../ui.js";
|
||||
import { icons } from "../../icons.js";
|
||||
|
||||
/** SequenceStatus bits (Chronos.Core.Model). */
|
||||
export const STATUS = { analysed: 1, deep: 2, proxies: 4, thumbs: 8, verified: 16, warnings: 32, errors: 64 };
|
||||
|
||||
/** Ids one bulk request may name (LibraryEndpoints.MaxBulkIds). */
|
||||
export const BULK_LIMIT = 1000;
|
||||
|
||||
/** Names a delete dialog lists; the count in its title says how many there are in all. */
|
||||
export const LISTED = 500;
|
||||
|
||||
/** The jobState states after which a job does nothing more. */
|
||||
export const JOB_ENDED = new Set(["done", "failed", "cancelled"]);
|
||||
|
||||
/** A dialog's list cut to LISTED lines and "…", so a delete of thousands never builds thousands of nodes. */
|
||||
export function listed(lines) {
|
||||
return lines.length > LISTED ? [...lines.slice(0, LISTED), "…"] : lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* A camera's name as the desktop and the server's facets give it (PathTemplate.CameraName): the make's brand once,
|
||||
* "Canon EOS R5" (Canon + Canon EOS R5), "Nikon Z 8" (NIKON CORPORATION + NIKON Z 8), "SONY ILCE-7M4".
|
||||
*/
|
||||
export function cameraLabel(make, model) {
|
||||
make = make?.trim();
|
||||
model = model?.trim();
|
||||
if (!model) return make ?? "";
|
||||
if (!make) return model;
|
||||
let brand = make.split(" ").find(Boolean);
|
||||
if (brand.toUpperCase() === "NIKON") brand = "Nikon";
|
||||
return model.toLowerCase().startsWith(brand.toLowerCase()) ? brand + model.slice(brand.length) : `${brand} ${model}`;
|
||||
}
|
||||
|
||||
/** How long the sequence lasts, from its first capture to its last ("2 h 0 m"); "" without captures. */
|
||||
export function spanText(s) {
|
||||
if (!s.firstCapture || !s.lastCapture) return "";
|
||||
return formatDuration((new Date(s.lastCapture) - new Date(s.firstCapture)) / 1000);
|
||||
}
|
||||
|
||||
/** A capture time as the camera recorded it (stored without zone, so read and shown as it was taken). */
|
||||
export function captureText(iso, withTime = true) {
|
||||
if (!iso) return "—";
|
||||
const options = withTime ? { dateStyle: "medium", timeStyle: "short" } : { dateStyle: "medium" };
|
||||
return new Intl.DateTimeFormat(culture(), options).format(new Date(iso));
|
||||
}
|
||||
|
||||
/** The line under a card's title: "3,600 · Canon EOS R5 · 2 h 0 m". */
|
||||
export function factsLine(s) {
|
||||
return [formatNumber(s.frameCount), cameraLabel(s.cameraMake, s.cameraModel), spanText(s)].filter(Boolean).join(" · ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Status glyphs as DESIGN §4 draws them: ● analysed (○ not yet), ● proxies (○ none), ▶ n renders, ▲ n warnings, ✕ errors,
|
||||
* ✓ verified. Each chip has its words for screen readers and its tooltip; the glyph alone is decoration.
|
||||
*/
|
||||
export function statusChips(s) {
|
||||
const chip = (cls, glyph, key, text, tipKey) =>
|
||||
`<span class="st ${cls}" title="${attr(t(tipKey))}"><span aria-hidden="true">${glyph}</span> ${escapeHtml(text ?? t(key))}</span>`;
|
||||
const on = (bit) => (s.status & bit) !== 0;
|
||||
const chips = [
|
||||
on(STATUS.analysed) ? chip("ok", "●", "Admin.Library.Status.Analysed", null, "Admin.Library.Status.Analysed.Tip")
|
||||
: chip("off", "○", "Admin.Library.Status.NotAnalysed", null, "Admin.Library.Status.NotAnalysed.Tip"),
|
||||
on(STATUS.proxies) ? chip("", "●", "Admin.Library.Status.Proxies", null, "Admin.Library.Status.Proxies.Tip")
|
||||
: chip("off", "○", "Admin.Library.Status.NoProxies", null, "Admin.Library.Status.NoProxies.Tip"),
|
||||
];
|
||||
if (on(STATUS.verified)) chips.push(chip("ok", "✓", "Admin.Library.Status.Verified", null, "Admin.Library.Status.Verified.Tip"));
|
||||
if (s.renderedCount > 0) chips.push(chip("", "▶", null, plural("Admin.Library.Status.Renders", s.renderedCount), "Admin.Library.Status.Renders.Tip"));
|
||||
if (s.warningCount > 0 || on(STATUS.warnings))
|
||||
chips.push(chip("warn", "▲", null, plural("Admin.Library.Status.Warnings", Math.max(1, s.warningCount)), "Admin.Library.Status.Warnings.Tip"));
|
||||
if (on(STATUS.errors)) chips.push(chip("err", "✕", "Admin.Library.Status.Errors", null, "Admin.Library.Status.Errors.Tip"));
|
||||
return chips.join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* An image the browser loads when it nears the view, with the photo icon in its place while it has none: before it
|
||||
* arrives, when the thumbnail is not built yet (404) or cannot be read. watchImages() hooks the error up (no inline
|
||||
* handlers under the panel's policy).
|
||||
*/
|
||||
export function lazyImage(src, cls = "") {
|
||||
return `<span class="thumb ${cls}"><span class="placeholder" aria-hidden="true">${icons.image}</span>` +
|
||||
`<img loading="lazy" decoding="async" alt="" src="${attr(src)}" data-fallback></span>`;
|
||||
}
|
||||
|
||||
export function watchImages(root) {
|
||||
root.querySelectorAll("img[data-fallback]").forEach((img) => {
|
||||
img.removeAttribute("data-fallback");
|
||||
img.addEventListener("error", () => img.classList.add("failed"), { once: true });
|
||||
img.addEventListener("load", () => img.classList.add("loaded"), { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
/** Retries of an image that had nothing to show, the first after RETRY_FIRST_MS and each next one after twice the wait, up to RETRY_LONGEST_MS. */
|
||||
const RETRY_TRIES = 8;
|
||||
const RETRY_FIRST_MS = 2000;
|
||||
const RETRY_LONGEST_MS = 60000;
|
||||
|
||||
/**
|
||||
* The images under root that had nothing to show (a thumbnail not built yet) asked for again, once a job that may have
|
||||
* built them ended: under an address the browser has not tried, so its first answer is not reused. Each image waits
|
||||
* longer before every retry and stops after RETRY_TRIES, since some never get one (a photo whose original is missing);
|
||||
* fresh (the sequence itself changed, a pass may have built them) starts every image's count again.
|
||||
*/
|
||||
export function retryImages(root, fresh = false) {
|
||||
const now = Date.now();
|
||||
root.querySelectorAll("img.failed").forEach((img) => {
|
||||
const tries = fresh ? 0 : Number(img.dataset.tries ?? 0);
|
||||
if (tries >= RETRY_TRIES || (!fresh && now < Number(img.dataset.retryAt ?? 0))) return;
|
||||
img.dataset.tries = String(tries + 1);
|
||||
img.dataset.retryAt = String(now + Math.min(RETRY_FIRST_MS * 2 ** tries, RETRY_LONGEST_MS));
|
||||
const url = new URL(img.getAttribute("src"), location.href);
|
||||
url.searchParams.set("retry", String(now));
|
||||
img.classList.remove("failed");
|
||||
img.setAttribute("data-fallback", "");
|
||||
img.src = url.pathname + url.search;
|
||||
});
|
||||
watchImages(root);
|
||||
}
|
||||
|
||||
/** A sequence's cover thumbnail; its address changes with the cover and the photos, so a browser's copy never shows an old one. */
|
||||
export function coverUrl(s) {
|
||||
return `/api/v1/sequences/${encodeURIComponent(s.id)}/thumb?v=${s.heroFrameId ?? "first"}-${s.framesVersion}`;
|
||||
}
|
||||
|
||||
/** Items picked by click, Space and Shift ranges over the order shown; the anchor is where the next range starts. */
|
||||
export class Selection {
|
||||
constructor() {
|
||||
this.ids = new Set();
|
||||
this.anchor = null;
|
||||
}
|
||||
|
||||
get size() {
|
||||
return this.ids.size;
|
||||
}
|
||||
|
||||
has(id) {
|
||||
return this.ids.has(id);
|
||||
}
|
||||
|
||||
toggle(id) {
|
||||
if (!this.ids.delete(id)) this.ids.add(id);
|
||||
this.anchor = id;
|
||||
}
|
||||
|
||||
/** Selects every item from the anchor to id in order (the anchor stays), or id alone without an anchor in view. */
|
||||
range(id, order) {
|
||||
const from = order.indexOf(this.anchor);
|
||||
const to = order.indexOf(id);
|
||||
if (from < 0 || to < 0) return this.toggle(id);
|
||||
const [a, b] = from < to ? [from, to] : [to, from];
|
||||
for (let i = a; i <= b; i++) this.ids.add(order[i]);
|
||||
}
|
||||
|
||||
set(ids) {
|
||||
this.ids = new Set(ids);
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.ids.clear();
|
||||
this.anchor = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The keyboard and pointer of a grid of selectable items (role="option" with data-key, in a role="listbox"): one tab
|
||||
* stop (the current item), arrows move along the reading direction and between rows, Home and End, Space selects
|
||||
* (Shift+Space: the range from the last one picked), Enter opens, Ctrl+A selects everything shown, Esc clears the
|
||||
* selection. A click on an item's check box selects (with Shift, a range), Ctrl+click too; a plain click opens.
|
||||
* The caller redraws through onChange after the selection changed.
|
||||
*/
|
||||
export function selectableGrid(host, { selection, order, open, onChange }) {
|
||||
let current = null;
|
||||
|
||||
const items = () => [...host.querySelectorAll('[role="option"]')];
|
||||
const focusItem = (el) => {
|
||||
if (!el) return;
|
||||
items().forEach((i) => (i.tabIndex = i === el ? 0 : -1));
|
||||
current = el.dataset.key;
|
||||
el.focus();
|
||||
};
|
||||
const pick = (key, shift) => {
|
||||
if (shift) selection.range(key, order());
|
||||
else selection.toggle(key);
|
||||
onChange();
|
||||
};
|
||||
|
||||
host.addEventListener("focusin", (e) => {
|
||||
const el = e.target.closest?.('[role="option"]');
|
||||
if (el && host.contains(el)) {
|
||||
current = el.dataset.key;
|
||||
items().forEach((i) => (i.tabIndex = i === el ? 0 : -1));
|
||||
}
|
||||
});
|
||||
host.addEventListener("click", (e) => {
|
||||
const el = e.target.closest('[role="option"]');
|
||||
if (!el || !host.contains(el)) return;
|
||||
if (e.target.closest("[data-check]") || e.ctrlKey || e.metaKey || e.shiftKey) {
|
||||
// A check box keeps its own click (a cancelled one would put its old state back after onChange drew the new one).
|
||||
if (!e.target.matches("input[data-check]")) e.preventDefault();
|
||||
pick(el.dataset.key, e.shiftKey);
|
||||
return;
|
||||
}
|
||||
if (e.target.closest("a, button")) return;
|
||||
open(el.dataset.key);
|
||||
});
|
||||
host.addEventListener("keydown", (e) => {
|
||||
const el = e.target.closest?.('[role="option"]');
|
||||
if (!el || e.altKey) return;
|
||||
const list = items();
|
||||
const index = list.indexOf(el);
|
||||
const rtl = getComputedStyle(host).direction === "rtl";
|
||||
let next = null;
|
||||
switch (e.key) {
|
||||
case "ArrowRight": next = list[index + (rtl ? -1 : 1)]; break;
|
||||
case "ArrowLeft": next = list[index + (rtl ? 1 : -1)]; break;
|
||||
case "ArrowDown": next = list[index + columns(list)]; break;
|
||||
case "ArrowUp": next = list[index - columns(list)]; break;
|
||||
case "Home": next = list[0]; break;
|
||||
case "End": next = list[list.length - 1]; break;
|
||||
case " ":
|
||||
e.preventDefault();
|
||||
pick(el.dataset.key, e.shiftKey);
|
||||
return;
|
||||
case "Enter":
|
||||
e.preventDefault();
|
||||
open(el.dataset.key);
|
||||
return;
|
||||
case "Escape":
|
||||
if (selection.size === 0) return;
|
||||
e.preventDefault();
|
||||
selection.clear();
|
||||
onChange();
|
||||
return;
|
||||
case "a":
|
||||
case "A":
|
||||
if (!(e.ctrlKey || e.metaKey)) return;
|
||||
e.preventDefault();
|
||||
selection.set(list.map((i) => i.dataset.key));
|
||||
onChange();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
focusItem(next);
|
||||
});
|
||||
|
||||
return {
|
||||
/** After a redraw: the current item keeps the tab stop (the first one when it is gone). */
|
||||
restore(focus = false) {
|
||||
const list = items();
|
||||
const el = list.find((i) => i.dataset.key === current) ?? list[0];
|
||||
list.forEach((i) => (i.tabIndex = i === el ? 0 : -1));
|
||||
if (focus && el) el.focus();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Items per row of a wrapping grid: those on the first item's line. */
|
||||
function columns(list) {
|
||||
const top = list[0]?.offsetTop;
|
||||
const n = list.findIndex((i) => i.offsetTop !== top);
|
||||
return n < 0 ? list.length || 1 : n;
|
||||
}
|
||||
|
||||
/** Tags typed as "night, roof; sky": trimmed, once each (case-insensitive), none empty. */
|
||||
export function tagList(text) {
|
||||
const seen = new Set();
|
||||
return String(text ?? "").split(/[,;]/).map((s) => s.trim()).filter((s) => {
|
||||
const key = s.toLocaleLowerCase();
|
||||
if (!s || seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/** The ids in requests of at most BULK_LIMIT, in their order. */
|
||||
export function chunks(ids, size = BULK_LIMIT) {
|
||||
const out = [];
|
||||
for (let i = 0; i < ids.length; i += size) out.push(ids.slice(i, i + size));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Hands the browser a file to save (a Blob made here; nothing leaves the page). */
|
||||
export function saveFile(name, blob) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sequences as CSV (comma separated, UTF-8 with a byte-order mark for spreadsheets): title, camera, photos, size in
|
||||
* bytes, first and last capture (ISO, as the camera recorded them) and tags. A cell a spreadsheet would run as a formula
|
||||
* starts with an apostrophe.
|
||||
*/
|
||||
export function sequencesCsv(sequences) {
|
||||
const cell = (value) => {
|
||||
let text = String(value ?? "");
|
||||
if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`;
|
||||
return /[",\n\r]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
|
||||
};
|
||||
const head = ["Admin.Library.Csv.Title", "Admin.Library.Csv.Camera", "Admin.Library.Csv.Photos", "Admin.Library.Csv.Bytes",
|
||||
"Admin.Library.Csv.First", "Admin.Library.Csv.Last", "Admin.Library.Csv.Tags"].map((key) => cell(t(key)));
|
||||
const rows = sequences.map((s) => [s.displayTitle, cameraLabel(s.cameraMake, s.cameraModel), s.frameCount, s.totalBytes,
|
||||
s.firstCapture ?? "", s.lastCapture ?? "", (s.tags ?? []).join("; ")].map(cell).join(","));
|
||||
return new Blob(["" + [head.join(","), ...rows].join("\r\n") + "\r\n"], { type: "text/csv;charset=utf-8" });
|
||||
}
|
||||
|
||||
/** "2026-10-27" in the file names of exports. */
|
||||
export function today() {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
// The archive's trash on the panel (owner review 2, R6; #/library?view=trash, reached from the Library and the Archive):
|
||||
// deleted sequences and photos deleted from sequences, each restorable; emptying it is the panel's only erase of user
|
||||
// files, so it measures the trash first (dry run), names what goes, asks for the word "empty" to be typed and sends the
|
||||
// plan's fingerprint, which the server's job checks again before it erases anything.
|
||||
import { t, plural, applyStrings } from "../../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, fitColumns } from "../../ui.js";
|
||||
import { icons } from "../../icons.js";
|
||||
import { JOB_ENDED } from "./shared.js";
|
||||
|
||||
/** Ended jobs the page remembers (their ids and last states), oldest dropped first. */
|
||||
const ENDED_KEPT = 100;
|
||||
|
||||
export async function renderTrash(root, { api, setMeta, actions, onEvent }, { back }) {
|
||||
let entries = [];
|
||||
let bytes = 0;
|
||||
/** The empty-trash job this page queued, followed until it ends. */
|
||||
let emptyJob = null;
|
||||
/**
|
||||
* The last jobState of jobs that ended while the page was open: the worker can claim the emptying and end it before
|
||||
* the POST that queued it has answered, so the page looks the job up here once it has its id.
|
||||
*/
|
||||
const ended = new Map();
|
||||
/** Entries whose restore was sent and has not answered: their buttons stay disabled through every redraw. */
|
||||
const restoring = new Set();
|
||||
let timer = null;
|
||||
let jobTimer = null;
|
||||
|
||||
actions.innerHTML = `
|
||||
<a class="btn" href="${attr(back)}" data-i18n-title="Admin.Trash.Back.Tip">${icons.back}<span data-i18n="Admin.Trash.Back"></span></a>
|
||||
<button class="btn destructive" id="empty" data-i18n="Admin.Trash.Empty" data-i18n-title="Admin.Trash.Empty.Tip"></button>`;
|
||||
applyStrings(actions);
|
||||
const emptyButton = actions.querySelector("#empty");
|
||||
emptyButton.addEventListener("click", emptyTrash);
|
||||
|
||||
root.innerHTML = `
|
||||
<section class="panel flush" aria-labelledby="trash-title">
|
||||
<div class="panel-head padded"><h2 id="trash-title" data-i18n="Admin.Trash.Title"></h2><span class="muted ellipsis" id="trash-meta"></span></div>
|
||||
<div class="table trash" data-levels="1" role="table" aria-labelledby="trash-title">
|
||||
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Trash.Kind"></span><span role="columnheader" data-i18n="Admin.Trash.Sequence"></span>
|
||||
<span role="columnheader" class="end" data-i18n="Admin.Trash.Photos"></span><span role="columnheader" class="end" data-i18n="Admin.Trash.Size"></span>
|
||||
<span role="columnheader" class="col-by" data-i18n="Admin.Trash.DeletedBy"></span><span role="columnheader" data-i18n="Admin.Trash.DeletedAt"></span>
|
||||
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
|
||||
<div id="rows" role="rowgroup"></div>
|
||||
</div>
|
||||
</section>`;
|
||||
applyStrings(root);
|
||||
const table = root.querySelector(".table");
|
||||
|
||||
async function load() {
|
||||
if (emptyJob !== null) await checkEmptyJob();
|
||||
try {
|
||||
const list = await api.get("/api/v1/archive/trash");
|
||||
entries = list.entries;
|
||||
bytes = list.bytes;
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
if (!root.isConnected) return;
|
||||
const summary = entries.length === 0 ? "" : `${plural("Admin.Trash.EntryCount", entries.length)} · ${formatBytes(bytes)}`;
|
||||
setMeta(t("Admin.Trash.Title"));
|
||||
root.querySelector("#trash-meta").textContent = summary;
|
||||
emptyButton.disabled = entries.length === 0 || emptyJob !== null;
|
||||
emptyButton.title = t(entries.length === 0 ? "Admin.Trash.NothingToEmpty.Tip" : emptyJob ? "Admin.Trash.Emptying.Tip" : "Admin.Trash.Empty.Tip");
|
||||
draw();
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const host = root.querySelector("#rows");
|
||||
redraw(host, () => {
|
||||
host.innerHTML = entries.map((e) => `
|
||||
<div class="row" role="row" data-key="${attr(e.name)}">
|
||||
<span class="nowrap" role="cell">${escapeHtml(kindLabel(e.kind))}</span>
|
||||
<span class="stack" role="cell"><strong class="ellipsis" dir="auto" title="${attr(e.title)}">${escapeHtml(e.title)}</strong>
|
||||
<small dir="ltr" class="mono" title="${attr(e.folder)}">${escapeHtml(e.folder)}</small></span>
|
||||
<span class="num end" role="cell">${formatNumber(e.photos)}</span>
|
||||
<span class="num end nowrap" role="cell">${escapeHtml(formatBytes(e.bytes))}</span>
|
||||
<span class="col-by ellipsis" role="cell" dir="auto">${escapeHtml(e.deletedBy ?? "—")}</span>
|
||||
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(e.deletedAt))}</span>
|
||||
<span class="row-actions" role="cell"><button class="btn small" data-restore="${attr(e.name)}" data-i18n="Admin.Trash.Restore"
|
||||
data-i18n-title="${e.kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : "Admin.Trash.RestorePhotos.Tip"}" ${restoring.has(e.name) ? "disabled" : ""}></button></span>
|
||||
</div>`).join("")
|
||||
|| `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Trash.IsEmpty",
|
||||
`<a class="btn small" href="${attr(back)}" data-i18n="Admin.Trash.Back" data-i18n-title="Admin.Trash.Back.Tip"></a>`)}</div></div>`;
|
||||
applyStrings(host);
|
||||
});
|
||||
host.querySelectorAll("[data-restore]").forEach((b) => b.addEventListener("click", () => restore(entries.find((e) => e.name === b.dataset.restore), b)));
|
||||
fitColumns(table);
|
||||
}
|
||||
|
||||
async function restore(entry, button) {
|
||||
if (!entry || restoring.has(entry.name)) return;
|
||||
restoring.add(entry.name);
|
||||
button.disabled = true;
|
||||
let result;
|
||||
try {
|
||||
result = await api.post(`/api/v1/archive/trash/${encodeURIComponent(entry.name)}/restore`);
|
||||
} catch (err) {
|
||||
restoring.delete(entry.name);
|
||||
toast(errorText(err), true);
|
||||
// The entry is gone (emptied or restored elsewhere): the list shows the trash as it is now; else its button, maybe
|
||||
// drawn again meanwhile, can be used again.
|
||||
if (err.status === 404) await load();
|
||||
else draw();
|
||||
return;
|
||||
}
|
||||
const lines = [result.kind === "sequence" ? t("Admin.Trash.RestoredSequence", entry.title)
|
||||
: result.newSequence ? plural("Admin.Trash.RestoredNew", result.photos) : plural("Admin.Trash.RestoredPhotos", result.photos, entry.title)];
|
||||
// The server says, in the page's language, how many photos stayed in the trash and why (one sentence per reason).
|
||||
if (result.kept.length > 0 && result.message) lines.push(result.message);
|
||||
toast(lines.join(" "), result.kept.length > 0);
|
||||
// Until the list without the entry is drawn: a read that started before the restore answered still shows it.
|
||||
await load();
|
||||
restoring.delete(entry.name);
|
||||
}
|
||||
|
||||
/** Measure (dry run), name what goes, have "empty" typed, then queue the erase with the plan's fingerprint. */
|
||||
async function emptyTrash() {
|
||||
emptyButton.disabled = true;
|
||||
try {
|
||||
let plan;
|
||||
try {
|
||||
plan = await api.post("/api/v1/archive/trash/empty", { names: null, dryRun: true, fingerprint: null });
|
||||
} catch (err) {
|
||||
toast(errorText(err), true);
|
||||
return;
|
||||
}
|
||||
if (plan.entries.length === 0) {
|
||||
toast(t("Admin.Trash.IsEmpty"));
|
||||
await load();
|
||||
return;
|
||||
}
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("Admin.Trash.EmptyTitle"),
|
||||
body: [plural("Admin.Trash.EmptyBody", plan.files, formatBytes(plan.bytes)), t("Admin.Trash.EmptyFinal")].join(" "),
|
||||
list: plan.entries.map((e) => t("Admin.Trash.PlanItem", kindLabel(e.kind), e.title, formatBytes(e.bytes))),
|
||||
confirm: t("Admin.Trash.EmptyConfirm"),
|
||||
confirmTip: t("Admin.Trash.EmptyConfirm.Tip"),
|
||||
cancel: t("Admin.Common.Keep"),
|
||||
cancelTip: t("Admin.Common.Keep.Tip"),
|
||||
typed: t("Admin.Trash.EmptyWord"),
|
||||
typedKind: "word",
|
||||
});
|
||||
if (!confirmed) return;
|
||||
try {
|
||||
const job = await api.post("/api/v1/archive/trash/empty", { names: null, dryRun: false, fingerprint: plan.fingerprint });
|
||||
// Its end may have come over the events before this answer did.
|
||||
const end = ended.get(job.id);
|
||||
if (end) emptyEnded(end);
|
||||
else {
|
||||
emptyJob = job.id;
|
||||
toast(t("Admin.Trash.EmptyQueued"));
|
||||
}
|
||||
} catch (err) {
|
||||
// trash_changed: something entered or left the trash since it was measured; it is shown as it is now.
|
||||
toast(errorText(err), true);
|
||||
}
|
||||
} finally {
|
||||
await load();
|
||||
}
|
||||
}
|
||||
|
||||
/** The emptying this page queued ended (its jobState event, or the job read): its toast; the caller shows the trash again. */
|
||||
function emptyEnded(e) {
|
||||
emptyJob = null;
|
||||
if (e.state === "done") toast(t("Admin.Trash.Emptied"));
|
||||
else toast(e.error || t("Admin.Trash.EmptyFailed"), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* The emptying this page follows, read from the queue: its end may have come while the events were not connected,
|
||||
* and nothing sends it again. A job no longer listed is followed no more, so Empty never stays disabled.
|
||||
*/
|
||||
async function checkEmptyJob() {
|
||||
const id = emptyJob;
|
||||
let job;
|
||||
try {
|
||||
job = await api.get(`/api/v1/jobs/${encodeURIComponent(id)}`);
|
||||
} catch (err) {
|
||||
if (err.status === 404 && emptyJob === id) emptyJob = null;
|
||||
return;
|
||||
}
|
||||
if (emptyJob === id && JOB_ENDED.has(job.state)) emptyEnded(job);
|
||||
}
|
||||
|
||||
onEvent((e) => {
|
||||
if (e.type === "jobState" && JOB_ENDED.has(e.state)) {
|
||||
ended.set(e.jobId, e);
|
||||
if (ended.size > ENDED_KEPT) ended.delete(ended.keys().next().value);
|
||||
if (e.jobId === emptyJob) {
|
||||
emptyEnded(e);
|
||||
load();
|
||||
} else if (jobTimer === null) {
|
||||
// An emptying started elsewhere (another tab, the desktop) sends no sequenceChanged. The timer is not pushed
|
||||
// back by the next job, so a busy queue still shows the trash again.
|
||||
jobTimer = setTimeout(() => {
|
||||
jobTimer = null;
|
||||
if (root.isConnected) load();
|
||||
}, 1500);
|
||||
}
|
||||
} else if (e.type === "sequenceChanged") {
|
||||
// A deletion or a restore elsewhere changes what the trash holds.
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
if (root.isConnected) load();
|
||||
}, 800);
|
||||
} else if (e.type === "reconnected") {
|
||||
// Events sent while the socket was down are lost: the trash, and the emptying it follows, are read again.
|
||||
if (root.isConnected) load();
|
||||
}
|
||||
});
|
||||
await load();
|
||||
}
|
||||
|
||||
function kindLabel(kind) {
|
||||
return t(kind === "sequence" ? "Admin.Trash.Kind.Sequence" : kind === "replaced" ? "Admin.Trash.Kind.Replaced" : "Admin.Trash.Kind.Photos");
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// Incremental SHA-256 (FIPS 180-4) for the upload dialog (owner review 2, R3): photos are hashed while they are read in
|
||||
// blocks, which crypto.subtle cannot do (it digests one buffer). In-house like everything else; the hash worker checks it
|
||||
// against known answers and crypto.subtle before using it (selfTest), and the server verifies every upload again.
|
||||
|
||||
const K = new Int32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
]);
|
||||
|
||||
const INITIAL = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
|
||||
|
||||
/** Hashes the whole 64-byte blocks of bytes[pos, end) into state h; returns where the first unprocessed byte is. */
|
||||
function blocks(h, w, bytes, pos, end) {
|
||||
let h0 = h[0], h1 = h[1], h2 = h[2], h3 = h[3], h4 = h[4], h5 = h[5], h6 = h[6], h7 = h[7];
|
||||
while (end - pos >= 64) {
|
||||
for (let i = 0; i < 16; i++, pos += 4) w[i] = (bytes[pos] << 24) | (bytes[pos + 1] << 16) | (bytes[pos + 2] << 8) | bytes[pos + 3];
|
||||
for (let i = 16; i < 64; i++) {
|
||||
const x = w[i - 15];
|
||||
const y = w[i - 2];
|
||||
const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
|
||||
const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
|
||||
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
|
||||
}
|
||||
let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, k = h7;
|
||||
for (let i = 0; i < 64; i++) {
|
||||
const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
|
||||
const t1 = (k + s1 + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0;
|
||||
const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
|
||||
const t2 = (s0 + ((a & b) ^ (a & c) ^ (b & c))) | 0;
|
||||
k = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = (d + t1) | 0;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = (t1 + t2) | 0;
|
||||
}
|
||||
h0 = (h0 + a) | 0;
|
||||
h1 = (h1 + b) | 0;
|
||||
h2 = (h2 + c) | 0;
|
||||
h3 = (h3 + d) | 0;
|
||||
h4 = (h4 + e) | 0;
|
||||
h5 = (h5 + f) | 0;
|
||||
h6 = (h6 + g) | 0;
|
||||
h7 = (h7 + k) | 0;
|
||||
}
|
||||
h[0] = h0; h[1] = h1; h[2] = h2; h[3] = h3; h[4] = h4; h[5] = h5; h[6] = h6; h[7] = h7;
|
||||
return pos;
|
||||
}
|
||||
|
||||
function asBytes(data) {
|
||||
if (data instanceof Uint8Array) return data;
|
||||
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
||||
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
||||
throw new TypeError("SHA-256 hashes bytes");
|
||||
}
|
||||
|
||||
/** SHA-256 fed in pieces of any size: update(bytes) as often as needed, then digest() once. */
|
||||
export class Sha256 {
|
||||
constructor() {
|
||||
this.h = new Int32Array(INITIAL);
|
||||
this.w = new Int32Array(64);
|
||||
this.buffer = new Uint8Array(64);
|
||||
this.buffered = 0;
|
||||
this.length = 0;
|
||||
this.finished = false;
|
||||
}
|
||||
|
||||
/** Adds bytes (Uint8Array, another typed array or an ArrayBuffer) to the message. */
|
||||
update(data) {
|
||||
if (this.finished) throw new Error("SHA-256 already digested");
|
||||
const bytes = asBytes(data);
|
||||
this.length += bytes.length;
|
||||
let pos = 0;
|
||||
if (this.buffered > 0) {
|
||||
const take = Math.min(64 - this.buffered, bytes.length);
|
||||
this.buffer.set(bytes.subarray(0, take), this.buffered);
|
||||
this.buffered += take;
|
||||
pos = take;
|
||||
if (this.buffered < 64) return this;
|
||||
blocks(this.h, this.w, this.buffer, 0, 64);
|
||||
this.buffered = 0;
|
||||
}
|
||||
pos = blocks(this.h, this.w, bytes, pos, bytes.length);
|
||||
if (pos < bytes.length) {
|
||||
this.buffer.set(bytes.subarray(pos), 0);
|
||||
this.buffered = bytes.length - pos;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The 32-byte digest; the hash takes no more input afterwards. */
|
||||
digest() {
|
||||
if (this.finished) throw new Error("SHA-256 already digested");
|
||||
this.finished = true;
|
||||
const tail = new Uint8Array(this.buffered < 56 ? 64 : 128);
|
||||
tail.set(this.buffer.subarray(0, this.buffered));
|
||||
tail[this.buffered] = 0x80;
|
||||
// The message length in bits as a 64-bit big-endian number, split without losing precision above 2^32.
|
||||
const high = Math.floor(this.length / 0x20000000);
|
||||
const low = (this.length % 0x20000000) * 8;
|
||||
const view = new DataView(tail.buffer);
|
||||
view.setUint32(tail.length - 8, high);
|
||||
view.setUint32(tail.length - 4, low);
|
||||
blocks(this.h, this.w, tail, 0, tail.length);
|
||||
const out = new Uint8Array(32);
|
||||
const result = new DataView(out.buffer);
|
||||
for (let i = 0; i < 8; i++) result.setUint32(i * 4, this.h[i] >>> 0);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/** Lower-case hexadecimal, as the upload API takes a SHA-256. */
|
||||
export function toHex(bytes) {
|
||||
let hex = "";
|
||||
for (const b of bytes) hex += (b < 16 ? "0" : "") + b.toString(16);
|
||||
return hex;
|
||||
}
|
||||
|
||||
/** The hex SHA-256 of one buffer. */
|
||||
export function sha256Hex(data) {
|
||||
return toHex(new Sha256().update(data).digest());
|
||||
}
|
||||
|
||||
const ascii = (text) => new TextEncoder().encode(text);
|
||||
|
||||
/** FIPS 180-4 examples (and the NIST long-message test): message and expected digest. */
|
||||
const KNOWN_ANSWERS = [
|
||||
["", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
|
||||
["abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"],
|
||||
["abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"],
|
||||
[
|
||||
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
|
||||
"cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1",
|
||||
],
|
||||
];
|
||||
const MILLION_A = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0";
|
||||
|
||||
/** Feeds bytes in pieces of uneven sizes, so the partial-block buffer is exercised at every offset. */
|
||||
function piecewise(bytes) {
|
||||
const hash = new Sha256();
|
||||
const sizes = [1, 63, 64, 65, 0, 127, 128, 129, 1000, 4096, 55, 56, 57];
|
||||
let pos = 0;
|
||||
for (let i = 0; pos < bytes.length; i++) {
|
||||
const size = Math.min(sizes[i % sizes.length], bytes.length - pos);
|
||||
hash.update(bytes.subarray(pos, pos + size));
|
||||
pos += size;
|
||||
}
|
||||
return toHex(hash.digest());
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the known-answer tests (whole and piece by piece) and, where crypto.subtle exists (secure pages), compares a 1 MiB
|
||||
* random buffer with it. Resolves to null when every check passes, else to the name of the first one that failed: the
|
||||
* caller refuses to hash then (fail closed).
|
||||
*/
|
||||
export async function selfTest() {
|
||||
for (const [message, expected] of KNOWN_ANSWERS) {
|
||||
const bytes = ascii(message);
|
||||
if (sha256Hex(bytes) !== expected || piecewise(bytes) !== expected) return `kat:${message.length}`;
|
||||
}
|
||||
const million = new Uint8Array(1_000_000).fill(0x61);
|
||||
if (sha256Hex(million) !== MILLION_A || piecewise(million) !== MILLION_A) return "kat:million";
|
||||
const subtle = globalThis.crypto?.subtle;
|
||||
if (subtle) {
|
||||
const random = new Uint8Array(1 << 20);
|
||||
// getRandomValues fills at most 64 KiB per call.
|
||||
for (let pos = 0; pos < random.length; pos += 65536) globalThis.crypto.getRandomValues(random.subarray(pos, pos + 65536));
|
||||
let reference;
|
||||
try {
|
||||
reference = toHex(new Uint8Array(await subtle.digest("SHA-256", random)));
|
||||
} catch {
|
||||
reference = null;
|
||||
}
|
||||
if (reference !== null && (sha256Hex(random) !== reference || piecewise(random) !== reference)) return "subtle";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Small DOM and formatting helpers shared by the admin pages. No inline styles: the panel runs under a strict CSP.
|
||||
import { t, culture } from "./i18n.js";
|
||||
import { t, culture, applyStrings } from "./i18n.js";
|
||||
|
||||
export function escapeHtml(s) {
|
||||
return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||||
@@ -145,33 +145,53 @@ export function toast(message, isError = false) {
|
||||
|
||||
let dialogs = 0;
|
||||
|
||||
/** What a typed confirmation asks for: its field's tooltip, the confirm button's while it waits, and how a value matches. */
|
||||
const TYPED = {
|
||||
// A name (an account), exactly as shown.
|
||||
name: { tip: "Admin.Common.TypeToConfirm.Tip", first: "Admin.Common.TypeFirst.Tip", matches: (value, typed) => value === typed },
|
||||
// A word of the interface (the localised "empty"), whatever its case.
|
||||
word: { tip: "Admin.Common.TypeWord.Tip", first: "Admin.Common.TypeWordFirst.Tip",
|
||||
matches: (value, typed) => value.trim().toLocaleLowerCase() === typed.toLocaleLowerCase() },
|
||||
// A count (the photos a deletion moves), its digits whatever the separators typed between them.
|
||||
count: { tip: "Admin.Common.TypeCount.Tip", first: "Admin.Common.TypeCountFirst.Tip",
|
||||
matches: (value, typed) => value.replace(/[\s.,'’ ]/g, "") === typed },
|
||||
};
|
||||
|
||||
/**
|
||||
* Two-button confirmation dialog (safe action left and default, Esc keeps). Resolves true when the destructive action
|
||||
* is chosen; with `typed`, that button stays disabled until the text is typed into the labelled field.
|
||||
* is chosen; with `typed`, that button stays disabled until the text is typed into the labelled field, as `typedKind`
|
||||
* says: a name exactly, a word whatever its case, or a count. `list` adds the items the action concerns (titles,
|
||||
* entries) under the body, in a scrolling box; user text, so each keeps its own direction.
|
||||
*/
|
||||
export function confirmDialog({ title, body, confirm, confirmTip, cancel, cancelTip, typed }) {
|
||||
export function confirmDialog({ title, body, list, confirm, confirmTip, cancel, cancelTip, typed, typedKind = "name" }) {
|
||||
return new Promise((resolve) => {
|
||||
const id = `dialog-${++dialogs}`;
|
||||
const dialog = document.createElement("dialog");
|
||||
dialog.className = "dialog";
|
||||
dialog.setAttribute("aria-labelledby", `${id}-title`);
|
||||
if (body) dialog.setAttribute("aria-describedby", `${id}-body`);
|
||||
const kind = TYPED[typedKind] ?? TYPED.name;
|
||||
const firstTip = t(kind.first);
|
||||
const matches = (value) => kind.matches(value, String(typed));
|
||||
// The text to type stands out of its sentence, and keeps its own direction.
|
||||
const typedLabel = typed ? escapeHtml(t("Admin.Common.TypeToConfirm", "\u0001")).replace("\u0001", `<strong dir="auto">${escapeHtml(typed)}</strong>`) : "";
|
||||
dialog.innerHTML = `
|
||||
<form method="dialog">
|
||||
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
|
||||
${body ? `<p id="${id}-body">${escapeHtml(body)}</p>` : ""}
|
||||
${typed ? `<label class="field-label"><span>${escapeHtml(t("Admin.Common.TypeToConfirm", typed))}</span>
|
||||
<input class="input" name="typed" autocomplete="off" spellcheck="false" dir="auto" title="${attr(t("Admin.Common.TypeToConfirm.Tip"))}"></label>` : ""}
|
||||
${list?.length ? `<ul class="dialog-list" tabindex="0" aria-label="${attr(title)}">${list.map((item) => `<li dir="auto">${escapeHtml(item)}</li>`).join("")}</ul>` : ""}
|
||||
${typed ? `<label class="field-label"><span>${typedLabel}</span>
|
||||
<input class="input" name="typed" autocomplete="off" spellcheck="false" dir="auto" ${typedKind === "count" ? 'inputmode="numeric"' : ""} title="${attr(t(kind.tip))}"></label>` : ""}
|
||||
<div class="buttons">
|
||||
<button class="btn" value="cancel" title="${attr(cancelTip)}" autofocus>${escapeHtml(cancel)}</button>
|
||||
<button class="btn destructive" value="ok" title="${attr(typed ? t("Admin.Common.TypeFirst.Tip") : confirmTip)}" ${typed ? "disabled" : ""}>${escapeHtml(confirm)}</button>
|
||||
<button class="btn destructive" value="ok" title="${attr(typed ? firstTip : confirmTip)}" ${typed ? "disabled" : ""}>${escapeHtml(confirm)}</button>
|
||||
</div>
|
||||
</form>`;
|
||||
document.body.appendChild(dialog);
|
||||
const ok = dialog.querySelector('button[value="ok"]');
|
||||
dialog.querySelector('input[name="typed"]')?.addEventListener("input", (e) => {
|
||||
ok.disabled = e.target.value !== typed;
|
||||
ok.title = ok.disabled ? t("Admin.Common.TypeFirst.Tip") : confirmTip;
|
||||
ok.disabled = !matches(e.target.value);
|
||||
ok.title = ok.disabled ? firstTip : confirmTip;
|
||||
});
|
||||
dialog.addEventListener("close", () => {
|
||||
resolve(dialog.returnValue === "ok");
|
||||
@@ -181,6 +201,47 @@ export function confirmDialog({ title, body, confirm, confirmTip, cancel, cancel
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A dialog of form fields (fields: HTML whose data-i18n attributes are filled here) with the action on the right, which
|
||||
* Enter in a field chooses too; Esc or the safe button cancels. Resolves the FormData once confirmed, null when cancelled.
|
||||
* check(form) may refuse the values: it marks the field (markInvalid) and returns false, and the dialog stays open.
|
||||
*/
|
||||
export function formDialog({ title, fields, confirm, confirmTip, cancel, cancelTip, check }) {
|
||||
return new Promise((resolve) => {
|
||||
const id = `dialog-${++dialogs}`;
|
||||
const dialog = document.createElement("dialog");
|
||||
dialog.className = "dialog";
|
||||
dialog.setAttribute("aria-labelledby", `${id}-title`);
|
||||
dialog.innerHTML = `
|
||||
<form method="dialog" class="form" novalidate>
|
||||
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
|
||||
${fields}
|
||||
<div class="buttons">
|
||||
<button class="btn" type="button" value="cancel" title="${attr(cancelTip)}">${escapeHtml(cancel)}</button>
|
||||
<button class="btn primary" value="ok" title="${attr(confirmTip)}">${escapeHtml(confirm)}</button>
|
||||
</div>
|
||||
</form>`;
|
||||
applyStrings(dialog);
|
||||
document.body.appendChild(dialog);
|
||||
const form = dialog.querySelector("form");
|
||||
let result = null;
|
||||
form.addEventListener("submit", (e) => {
|
||||
if (check && !check(form)) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
result = new FormData(form);
|
||||
});
|
||||
dialog.querySelector('button[value="cancel"]').addEventListener("click", () => dialog.close());
|
||||
dialog.addEventListener("close", () => {
|
||||
resolve(result);
|
||||
dialog.remove();
|
||||
});
|
||||
dialog.showModal();
|
||||
form.querySelector("input, select, textarea")?.focus();
|
||||
});
|
||||
}
|
||||
|
||||
/** The localised message of an API failure, or the generic one when the server was not reached. */
|
||||
export function errorText(err) {
|
||||
return err?.message && err.status ? err.message : t("Admin.Error.Unreachable");
|
||||
@@ -246,7 +307,8 @@ export function focusPlace(root) {
|
||||
|
||||
/**
|
||||
* Focuses the same control after a re-render, else the control at the same place in the same (or same-position) row,
|
||||
* else the first control left (an empty state's button).
|
||||
* else the first control left (an empty state's button). A control without a name (a tag's remove button) is found by
|
||||
* its place alone: matching its empty name would pick the first unnamed control instead.
|
||||
*/
|
||||
export function restoreFocus(root, place) {
|
||||
if (!place) return;
|
||||
@@ -259,7 +321,8 @@ export function restoreFocus(root, place) {
|
||||
else index = 0;
|
||||
}
|
||||
const controls = [...scope.querySelectorAll(FOCUSABLE)];
|
||||
(controls.find((c) => controlKey(c) === place.control) ?? controls[Math.min(Math.max(index, 0), controls.length - 1)])?.focus();
|
||||
const same = place.control ? controls.find((c) => controlKey(c) === place.control) : undefined;
|
||||
(same ?? controls[Math.min(Math.max(index, 0), controls.length - 1)])?.focus();
|
||||
}
|
||||
|
||||
/** Redraws with draw() and puts the keyboard focus back where it was. */
|
||||
|
||||
@@ -0,0 +1,795 @@
|
||||
// Upload dialog of the admin panel (owner review 2, R3; BRIEF §14.4, §14.8): photos from this computer into an existing
|
||||
// or a new sequence, chosen with the file picker or dropped on the dialog. Folders are not taken: importing a whole folder
|
||||
// stays a feature of the desktop app. Each photo is hashed in a module worker (hash-worker.js, which self-tests its
|
||||
// SHA-256 first and refuses to hash when a check fails), started with its capture time (capture-time.js), sent in the
|
||||
// chunks the server does not have yet and completed; the server verifies the hash again before it files the photo. A
|
||||
// photo deleted from the sequence before is not filed again unless the user asks for it on its row (Upload again).
|
||||
import { ApiFailure } from "./api.js";
|
||||
import { t, plural, applyStrings, culture } from "./i18n.js";
|
||||
import { escapeHtml, attr, bar, formatBytes, formatNumber, errorText } from "./ui.js";
|
||||
import { icons } from "./icons.js";
|
||||
import { captureTime } from "./capture-time.js";
|
||||
|
||||
/** Photos sent at once, and chunks in flight for each: four requests, half of what the server takes from one account. */
|
||||
const FILES_AT_ONCE = 2;
|
||||
const CHUNKS_AT_ONCE = 2;
|
||||
/** Retries of a call that failed for a passing reason (no answer, 429, 503), after 1, 2 and 4 seconds. */
|
||||
const RETRIES = 3;
|
||||
/** Checks of an upload another completion is filing, after 1, 2, 4 and then every 8 seconds: about a minute in all. */
|
||||
const SETTLE_CHECKS = 10;
|
||||
const SEARCH_DELAY = 250;
|
||||
const LIST_LIMIT = 50;
|
||||
/** States of a photo already on the server: a later run leaves it alone. */
|
||||
const FINISHED = new Set(["done", "exists", "deleted"]);
|
||||
/** States of a photo a run is sending. */
|
||||
const ACTIVE = new Set(["hashing", "starting", "uploading", "verifying"]);
|
||||
|
||||
/** A failure of the hash worker: kind self_test (its SHA-256 failed a check), worker (it did not run), read or stopped. */
|
||||
class HashError extends Error {
|
||||
constructor(kind, detail = "") {
|
||||
super(`${kind} ${detail}`.trim());
|
||||
this.kind = kind;
|
||||
}
|
||||
}
|
||||
|
||||
let dialogs = 0;
|
||||
|
||||
/**
|
||||
* Opens the upload dialog. With sequence ({ id, title } or a SequenceDto) the photos go into it; without, the dialog
|
||||
* lets the user pick an existing sequence or name a new one. onDone() runs after every run that changed the library
|
||||
* (photos uploaded or a sequence created), so the page can refresh. Resolves when the dialog closes.
|
||||
*/
|
||||
export function openUpload({ api, sequence, onDone } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const id = `upload-${++dialogs}`;
|
||||
let target = sequence?.id ? { id: sequence.id, title: sequence.displayTitle ?? sequence.title ?? "" } : null;
|
||||
let extensions = null;
|
||||
let maxBytes = 0;
|
||||
let running = false;
|
||||
let controller = null;
|
||||
let broken = null;
|
||||
let hasher = null;
|
||||
let searchTimer = null;
|
||||
let searchToken = 0;
|
||||
let frame = 0;
|
||||
// Per run: by SHA-256, the send of the last photo of that content, which the next copy waits for.
|
||||
let sameContent = new Map();
|
||||
const items = [];
|
||||
const skipped = { folders: 0, formats: 0, size: 0 };
|
||||
const titles = new Map();
|
||||
|
||||
const dialog = document.createElement("dialog");
|
||||
dialog.className = "dialog upload";
|
||||
dialog.setAttribute("aria-labelledby", `${id}-title`);
|
||||
dialog.innerHTML = `
|
||||
<form novalidate>
|
||||
<h2 id="${id}-title" data-i18n="Admin.Upload.Title"></h2>
|
||||
<div class="upload-target" id="${id}-target"></div>
|
||||
<div class="drop">
|
||||
<button class="btn" type="button" data-act="add" data-i18n="Admin.Upload.Add" data-i18n-title="Admin.Upload.Add.Tip"></button>
|
||||
<span data-i18n="Admin.Upload.Drop"></span>
|
||||
<input type="file" multiple hidden tabindex="-1">
|
||||
</div>
|
||||
<div class="chips upload-notes" hidden></div>
|
||||
<ul class="upload-files" aria-label="${attr(t("Admin.Upload.Photos"))}" hidden></ul>
|
||||
<div class="upload-total" hidden></div>
|
||||
<div class="error" role="alert"></div>
|
||||
<div class="buttons">
|
||||
<button class="btn" type="button" data-act="close" data-i18n="Admin.Upload.Close" data-i18n-title="Admin.Upload.Close.Tip"></button>
|
||||
<button class="btn primary" type="submit" data-act="start" data-i18n="Admin.Upload.Start" data-i18n-title="Admin.Upload.Start.Tip"></button>
|
||||
</div>
|
||||
</form>`;
|
||||
document.body.appendChild(dialog);
|
||||
applyStrings(dialog);
|
||||
const form = dialog.querySelector("form");
|
||||
const targetHost = dialog.querySelector(`#${id}-target`);
|
||||
const input = dialog.querySelector('input[type="file"]');
|
||||
const addButton = dialog.querySelector('[data-act="add"]');
|
||||
const closeButton = dialog.querySelector('[data-act="close"]');
|
||||
const startButton = dialog.querySelector('[data-act="start"]');
|
||||
const notes = dialog.querySelector(".upload-notes");
|
||||
const list = dialog.querySelector(".upload-files");
|
||||
const total = dialog.querySelector(".upload-total");
|
||||
const errorLine = dialog.querySelector(".error");
|
||||
|
||||
drawTarget();
|
||||
drawButtons();
|
||||
|
||||
addButton.addEventListener("click", () => input.click());
|
||||
input.addEventListener("change", () => {
|
||||
take([...input.files], 0);
|
||||
input.value = "";
|
||||
});
|
||||
form.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
run();
|
||||
});
|
||||
closeButton.addEventListener("click", () => {
|
||||
if (running) cancel();
|
||||
else dialog.close();
|
||||
});
|
||||
list.addEventListener("click", (e) => {
|
||||
// Upload again: a photo deleted from the sequence before goes back into it with the next run, on the user's word.
|
||||
const again = e.target.closest('[data-act="again"]');
|
||||
if (again && !running) {
|
||||
const item = items.find((i) => i.key === again.closest("[data-key]").dataset.key);
|
||||
if (item?.state !== "deleted") return;
|
||||
item.restore = true;
|
||||
setState(item, "waiting");
|
||||
drawButtons();
|
||||
startButton.focus();
|
||||
return;
|
||||
}
|
||||
const button = e.target.closest('[data-act="remove"]');
|
||||
if (!button || running) return;
|
||||
const index = items.findIndex((i) => i.key === button.closest("[data-key]").dataset.key);
|
||||
if (index < 0) return;
|
||||
const [item] = items.splice(index, 1);
|
||||
const next = item.row.nextElementSibling ?? item.row.previousElementSibling;
|
||||
item.row.remove();
|
||||
(next?.querySelector('[data-act="remove"]:not([hidden])') ?? addButton).focus();
|
||||
drawList();
|
||||
});
|
||||
|
||||
// Drops: photos are taken, folders only counted (BRIEF §14.8: no folder upload on the web).
|
||||
const hasFiles = (e) => [...(e.dataTransfer?.types ?? [])].includes("Files");
|
||||
dialog.addEventListener("dragover", (e) => {
|
||||
if (!hasFiles(e)) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = running || extensions === null ? "none" : "copy";
|
||||
dialog.classList.add("dragging");
|
||||
});
|
||||
dialog.addEventListener("dragleave", (e) => {
|
||||
if (!dialog.contains(e.relatedTarget)) dialog.classList.remove("dragging");
|
||||
});
|
||||
dialog.addEventListener("drop", (e) => {
|
||||
if (!hasFiles(e)) return;
|
||||
e.preventDefault();
|
||||
dialog.classList.remove("dragging");
|
||||
if (running || extensions === null) return;
|
||||
const { files, folders } = dropped(e.dataTransfer);
|
||||
take(files, folders);
|
||||
});
|
||||
|
||||
// Esc closes only while nothing is being sent; Cancel stops a run. Chromium lets a dialog's cancel be prevented only
|
||||
// once per user activation, so during a run Esc is stopped at its keydown, on the document in the capture phase: a
|
||||
// click on the dialog's text moves the focus to the body, and Esc from there would pass the dialog by. The cancel
|
||||
// handler stays for close requests that do not come from the keyboard (a back gesture).
|
||||
const stopEscape = (e) => {
|
||||
if (e.key === "Escape") e.preventDefault();
|
||||
};
|
||||
dialog.addEventListener("cancel", (e) => {
|
||||
if (running) e.preventDefault();
|
||||
});
|
||||
// Leaving the page while photos are sent asks first (returnValue for browsers before preventDefault counted).
|
||||
const guard = (e) => {
|
||||
e.preventDefault();
|
||||
e.returnValue = true;
|
||||
};
|
||||
const signedOut = () => {
|
||||
controller?.abort();
|
||||
dialog.close();
|
||||
};
|
||||
window.addEventListener("chronos:signed-out", signedOut);
|
||||
dialog.addEventListener("close", () => {
|
||||
controller?.abort();
|
||||
hasher?.stop();
|
||||
clearTimeout(searchTimer);
|
||||
cancelAnimationFrame(frame);
|
||||
window.removeEventListener("beforeunload", guard);
|
||||
document.removeEventListener("keydown", stopEscape, true);
|
||||
window.removeEventListener("chronos:signed-out", signedOut);
|
||||
dialog.remove();
|
||||
resolve();
|
||||
});
|
||||
dialog.showModal();
|
||||
targetHost.querySelector('input[type="search"]')?.focus();
|
||||
const firstFocus = document.activeElement;
|
||||
|
||||
// The photo extensions and the size limit the server announces: only those are offered and sent.
|
||||
api.get("/api/v1/server/info").then((info) => {
|
||||
extensions = new Set((info?.extensions ?? []).map((e) => String(e).toLowerCase()));
|
||||
maxBytes = info?.limits?.maxUploadBytes ?? 0;
|
||||
input.accept = [...extensions].map((e) => `.${e}`).join(",");
|
||||
drawButtons();
|
||||
// Into a given sequence the first step is adding photos, once the button can be used.
|
||||
if (target && document.activeElement === firstFocus) addButton.focus();
|
||||
}).catch((err) => showError(errorText(err)));
|
||||
|
||||
/** The target: fixed (given, or chosen when the first run started), else the choice of an existing or a new sequence. */
|
||||
function drawTarget() {
|
||||
if (target) {
|
||||
targetHost.innerHTML = `<div class="field-label"><span data-i18n="Admin.Upload.Target"></span>
|
||||
<strong class="ellipsis" dir="auto" title="${attr(target.title)}">${escapeHtml(target.title)}</strong></div>`;
|
||||
applyStrings(targetHost);
|
||||
return;
|
||||
}
|
||||
targetHost.innerHTML = `
|
||||
<fieldset class="upload-choice"><legend data-i18n="Admin.Upload.Target"></legend>
|
||||
<label class="check"><input type="radio" name="mode" value="existing" checked data-i18n-title="Admin.Upload.Existing.Tip"><span data-i18n="Admin.Upload.Existing"></span></label>
|
||||
<label class="check"><input type="radio" name="mode" value="new" data-i18n-title="Admin.Upload.New.Tip"><span data-i18n="Admin.Upload.New"></span></label>
|
||||
</fieldset>
|
||||
<div class="upload-existing">
|
||||
<input class="input" type="search" name="q" autocomplete="off" dir="auto" aria-label="${attr(t("Admin.Upload.Search"))}"
|
||||
data-i18n-placeholder="Admin.Upload.Search" data-i18n-title="Admin.Upload.Search.Tip">
|
||||
<select class="input list" name="sequence" size="5" aria-label="${attr(t("Admin.Upload.Sequences"))}" data-i18n-title="Admin.Upload.Sequences.Tip"></select>
|
||||
</div>
|
||||
<label class="upload-new" hidden><span data-i18n="Admin.Upload.NewTitle"></span>
|
||||
<input class="input" name="title" maxlength="200" autocomplete="off" dir="auto" data-i18n-title="Admin.Upload.NewTitle.Tip"></label>`;
|
||||
applyStrings(targetHost);
|
||||
const existing = targetHost.querySelector(".upload-existing");
|
||||
const fresh = targetHost.querySelector(".upload-new");
|
||||
targetHost.querySelectorAll('input[name="mode"]').forEach((radio) => radio.addEventListener("change", () => {
|
||||
const isNew = form.elements.mode.value === "new";
|
||||
existing.hidden = isNew;
|
||||
fresh.hidden = !isNew;
|
||||
showError("");
|
||||
}));
|
||||
const search = targetHost.querySelector('input[name="q"]');
|
||||
search.addEventListener("input", () => {
|
||||
clearTimeout(searchTimer);
|
||||
searchTimer = setTimeout(() => loadSequences(search.value.trim()), SEARCH_DELAY);
|
||||
});
|
||||
// Enter in the search box picks nothing and sends nothing.
|
||||
search.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") e.preventDefault();
|
||||
});
|
||||
targetHost.querySelector("select").addEventListener("change", () => showError(""));
|
||||
loadSequences("");
|
||||
}
|
||||
|
||||
async function loadSequences(q) {
|
||||
const token = ++searchToken;
|
||||
const query = new URLSearchParams({ limit: String(LIST_LIMIT) });
|
||||
if (q) query.set("q", q);
|
||||
let page;
|
||||
try {
|
||||
page = await api.get(`/api/v1/sequences?${query}`);
|
||||
} catch (err) {
|
||||
if (token === searchToken) showError(errorText(err));
|
||||
return;
|
||||
}
|
||||
const select = targetHost.querySelector("select");
|
||||
if (token !== searchToken || !select) return;
|
||||
const chosen = select.value;
|
||||
for (const s of page.items) titles.set(s.id, s.displayTitle);
|
||||
select.innerHTML = page.items.map((s) => `<option value="${attr(s.id)}" dir="auto" ${s.id === chosen ? "selected" : ""}>` +
|
||||
`${escapeHtml(s.displayTitle)} · ${escapeHtml(plural("Admin.Upload.PhotoCount", s.frameCount))}</option>`).join("") ||
|
||||
`<option disabled>${escapeHtml(t("Admin.Upload.NoMatch"))}</option>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds picked or dropped files: photos once each; folders, other files and files above the limit are counted. Hidden
|
||||
* dot files (the AppleDouble "._" companions a Mac leaves on cards among them) are left out like the archive scanner
|
||||
* leaves them out, and the server refuses them too.
|
||||
*/
|
||||
function take(files, folders) {
|
||||
skipped.folders += folders;
|
||||
for (const file of files) {
|
||||
const dot = file.name.lastIndexOf(".");
|
||||
const extension = dot < 0 ? "" : file.name.slice(dot + 1).toLowerCase();
|
||||
if (file.size === 0 || file.name.startsWith(".") || !extensions?.has(extension)) {
|
||||
skipped.formats++;
|
||||
continue;
|
||||
}
|
||||
if (maxBytes > 0 && file.size > maxBytes) {
|
||||
skipped.size++;
|
||||
continue;
|
||||
}
|
||||
const key = `${file.name}\u0000${file.size}\u0000${file.lastModified}`;
|
||||
if (items.some((i) => i.key === key)) continue;
|
||||
const item = { key, file, state: "waiting", hashed: 0, sent: 0, uploadId: null, restore: false, message: "", row: null };
|
||||
item.row = document.createElement("li");
|
||||
item.row.className = "upload-file";
|
||||
item.row.dataset.key = key;
|
||||
item.row.innerHTML = `<span class="name ellipsis" dir="auto" title="${attr(file.name)}">${escapeHtml(file.name)}</span>
|
||||
<span class="size num muted">${escapeHtml(formatBytes(file.size))}</span><span class="status"></span>
|
||||
<button class="btn icon small subtle" type="button" data-act="remove" title="${attr(t("Admin.Upload.Remove.Tip"))}"
|
||||
aria-label="${attr(t("Admin.Upload.Remove", file.name))}">${icons.close}</button>
|
||||
<button class="btn icon small subtle" type="button" data-act="again" hidden title="${attr(t("Admin.Upload.Again.Tip"))}"
|
||||
aria-label="${attr(t("Admin.Upload.Again", file.name))}">${icons.upload}</button>`;
|
||||
list.appendChild(item.row);
|
||||
items.push(item);
|
||||
drawItem(item);
|
||||
}
|
||||
drawNotes();
|
||||
drawList();
|
||||
}
|
||||
|
||||
function drawNotes() {
|
||||
const chip = (count, key, tip) => count === 0 ? "" : `<span class="chip warn" title="${attr(tip)}">${escapeHtml(t(key, formatNumber(count)))}</span>`;
|
||||
notes.innerHTML = chip(skipped.folders, "Admin.Upload.Skipped.Folders", t("Admin.Upload.Skipped.Folders.Tip")) +
|
||||
chip(skipped.formats, "Admin.Upload.Skipped.Formats", t("Admin.Upload.Skipped.Formats.Tip")) +
|
||||
chip(skipped.size, "Admin.Upload.Skipped.Size", t("Admin.Upload.Skipped.Size.Tip", formatBytes(maxBytes)));
|
||||
notes.hidden = notes.innerHTML === "";
|
||||
}
|
||||
|
||||
function drawList() {
|
||||
list.hidden = items.length === 0;
|
||||
drawTotal();
|
||||
drawButtons();
|
||||
}
|
||||
|
||||
/** One photo's row: its state, a bar while it is hashed or sent, and the reason of a failure as the tooltip. */
|
||||
function drawItem(item) {
|
||||
const status = item.row.querySelector(".status");
|
||||
const percent = (fraction) => new Intl.NumberFormat(culture(), { style: "percent", maximumFractionDigits: 0 }).format(fraction);
|
||||
let text;
|
||||
let tip = "";
|
||||
let tone = "queued";
|
||||
let fraction = null;
|
||||
switch (item.state) {
|
||||
case "hashing":
|
||||
text = t("Admin.Upload.State.Hashing", percent(item.hashed));
|
||||
fraction = item.hashed;
|
||||
tone = "running";
|
||||
break;
|
||||
case "starting":
|
||||
text = t("Admin.Upload.State.Starting");
|
||||
tone = "running";
|
||||
break;
|
||||
case "uploading":
|
||||
fraction = item.file.size > 0 ? item.sent / item.file.size : 1;
|
||||
text = t("Admin.Upload.State.Uploading", percent(fraction));
|
||||
tone = "running";
|
||||
break;
|
||||
case "verifying":
|
||||
text = t("Admin.Upload.State.Verifying");
|
||||
tone = "running";
|
||||
break;
|
||||
case "done":
|
||||
text = t("Admin.Upload.State.Done");
|
||||
tip = t("Admin.Upload.State.Done.Tip");
|
||||
tone = "done";
|
||||
break;
|
||||
case "exists":
|
||||
text = t("Admin.Upload.State.Exists");
|
||||
tip = t("Admin.Upload.State.Exists.Tip");
|
||||
tone = "done";
|
||||
break;
|
||||
case "deleted":
|
||||
text = t("Admin.Upload.State.Deleted");
|
||||
tip = t("Admin.Upload.State.Deleted.Tip");
|
||||
tone = "paused";
|
||||
break;
|
||||
case "failed":
|
||||
text = t("Admin.Upload.State.Failed");
|
||||
tip = item.message;
|
||||
tone = "failed";
|
||||
break;
|
||||
case "cancelled":
|
||||
text = t("Admin.Upload.State.Cancelled");
|
||||
tone = "cancelled";
|
||||
break;
|
||||
case "notSent":
|
||||
text = t("Admin.Upload.State.NotSent");
|
||||
tip = t("Admin.Upload.State.NotSent.Tip");
|
||||
tone = "cancelled";
|
||||
break;
|
||||
default:
|
||||
text = t("Admin.Upload.State.Waiting");
|
||||
}
|
||||
status.innerHTML = (fraction === null ? "" : bar(fraction)) +
|
||||
`<span class="state ${tone} ellipsis"${tip ? ` title="${attr(tip)}"` : ""}>${escapeHtml(text)}</span>`;
|
||||
drawRowButtons(item);
|
||||
}
|
||||
|
||||
/** A photo comes off the list only between runs, and only while it is not on the server. */
|
||||
function removable(item) {
|
||||
return !running && !FINISHED.has(item.state) && !ACTIVE.has(item.state);
|
||||
}
|
||||
|
||||
/** Remove, or for a photo deleted from the sequence before, Upload again; both only between runs. */
|
||||
function drawRowButtons(item) {
|
||||
item.row.querySelector('[data-act="remove"]').hidden = !removable(item);
|
||||
item.row.querySelector('[data-act="again"]').hidden = running || item.state !== "deleted";
|
||||
}
|
||||
|
||||
/** Progress redraws at most once a frame: the worker reports every 8 MiB, chunks finish four at a time. */
|
||||
function update(item) {
|
||||
item.dirty = true;
|
||||
if (frame) return;
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
for (const i of items) {
|
||||
if (!i.dirty) continue;
|
||||
i.dirty = false;
|
||||
drawItem(i);
|
||||
}
|
||||
drawTotal();
|
||||
});
|
||||
}
|
||||
|
||||
function setState(item, state, message = "") {
|
||||
item.state = state;
|
||||
item.message = message;
|
||||
drawItem(item);
|
||||
drawTotal();
|
||||
}
|
||||
|
||||
function drawTotal() {
|
||||
total.hidden = items.length === 0;
|
||||
if (items.length === 0) return;
|
||||
let bytes = 0;
|
||||
let done = 0;
|
||||
let sent = 0;
|
||||
let failed = 0;
|
||||
for (const item of items) {
|
||||
bytes += item.file.size;
|
||||
if (FINISHED.has(item.state)) {
|
||||
done++;
|
||||
sent += item.file.size;
|
||||
} else if (item.state === "uploading" || item.state === "verifying") {
|
||||
sent += item.sent;
|
||||
} else if (item.state === "failed") {
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
const text = `${t("Admin.Upload.Count", formatNumber(done), formatNumber(items.length))} · ${t("Admin.Upload.Bytes", formatBytes(sent), formatBytes(bytes))}`;
|
||||
total.innerHTML = `<div class="progress-cell">${bar(bytes > 0 ? sent / bytes : 0)}<span class="num" title="${attr(text)}">${escapeHtml(text)}</span></div>` +
|
||||
(failed > 0 ? `<span class="state failed nowrap">${escapeHtml(t("Admin.Upload.Failed", formatNumber(failed)))}</span>` : "");
|
||||
}
|
||||
|
||||
function drawButtons() {
|
||||
const pending = items.some((i) => !FINISHED.has(i.state));
|
||||
startButton.disabled = running || !pending || broken !== null || extensions === null;
|
||||
addButton.disabled = running || extensions === null;
|
||||
closeButton.textContent = t(running ? "Admin.Upload.Cancel" : "Admin.Upload.Close");
|
||||
closeButton.title = t(running ? "Admin.Upload.Cancel.Tip" : "Admin.Upload.Close.Tip");
|
||||
for (const item of items) drawRowButtons(item);
|
||||
targetHost.querySelectorAll("input, select").forEach((field) => {
|
||||
field.disabled = running;
|
||||
});
|
||||
}
|
||||
|
||||
function showError(text) {
|
||||
errorLine.textContent = text;
|
||||
}
|
||||
|
||||
/** Sends every photo not on the server yet, two at a time; a quota, space or permission refusal stops the rest. */
|
||||
async function run() {
|
||||
if (running) return;
|
||||
const todo = items.filter((i) => !FINISHED.has(i.state));
|
||||
if (todo.length === 0 || extensions === null) return;
|
||||
if (broken) return showError(broken);
|
||||
showError("");
|
||||
running = true;
|
||||
controller = new AbortController();
|
||||
sameContent = new Map();
|
||||
const signal = controller.signal;
|
||||
window.addEventListener("beforeunload", guard);
|
||||
document.addEventListener("keydown", stopEscape, true);
|
||||
drawButtons();
|
||||
let changed = false;
|
||||
try {
|
||||
const into = await resolveTarget();
|
||||
if (!into) return;
|
||||
changed = into.created;
|
||||
if (signal.aborted) return;
|
||||
todo.forEach((i) => setState(i, "waiting"));
|
||||
let next = 0;
|
||||
let stop = null;
|
||||
const lane = async () => {
|
||||
while (stop === null && !signal.aborted && next < todo.length) {
|
||||
const item = todo[next++];
|
||||
try {
|
||||
changed = (await send(item, into.id, signal)) || changed;
|
||||
} catch (err) {
|
||||
// A completion cut short may still have filed the photo: the page refreshes to find out.
|
||||
if (item.state === "verifying") changed = true;
|
||||
if (signal.aborted) {
|
||||
setState(item, "cancelled");
|
||||
continue;
|
||||
}
|
||||
setState(item, "failed", messageOf(err));
|
||||
if (stops(err)) stop = err;
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: FILES_AT_ONCE }, lane));
|
||||
if (signal.aborted) {
|
||||
await discard(todo);
|
||||
todo.filter((i) => i.state === "waiting").forEach((i) => setState(i, "cancelled"));
|
||||
} else if (stop !== null) {
|
||||
if (stop instanceof HashError) broken = messageOf(stop);
|
||||
showError(messageOf(stop));
|
||||
todo.filter((i) => i.state === "waiting").forEach((i) => setState(i, "notSent"));
|
||||
}
|
||||
} finally {
|
||||
running = false;
|
||||
controller = null;
|
||||
window.removeEventListener("beforeunload", guard);
|
||||
document.removeEventListener("keydown", stopEscape, true);
|
||||
todo.filter((i) => ACTIVE.has(i.state)).forEach((i) => setState(i, "cancelled"));
|
||||
drawButtons();
|
||||
drawTotal();
|
||||
if (changed) onDone?.();
|
||||
}
|
||||
}
|
||||
|
||||
/** Stops the run: requests are aborted, the hash worker stopped and the server's unfinished uploads discarded. */
|
||||
function cancel() {
|
||||
controller?.abort();
|
||||
hasher?.stop();
|
||||
hasher = null;
|
||||
}
|
||||
|
||||
/** DELETE of the uploads a cancelled run started and did not complete, so the server frees their space now. */
|
||||
async function discard(todo) {
|
||||
await Promise.all(todo.filter((i) => i.uploadId !== null && !FINISHED.has(i.state)).map(async (item) => {
|
||||
try {
|
||||
await api.del(`/api/v1/uploads/${item.uploadId}`);
|
||||
} catch {
|
||||
// Committed meanwhile, or already gone: nothing left to free.
|
||||
}
|
||||
item.uploadId = null;
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* The sequence the run fills: the fixed one, the one picked, or a new one created now; from then on it is the
|
||||
* dialog's fixed target, also when the run was cancelled meanwhile. Null (with the reason shown) when there is none.
|
||||
*/
|
||||
async function resolveTarget() {
|
||||
if (target) return { id: target.id, created: false };
|
||||
const mode = form.elements.mode.value;
|
||||
if (mode === "existing") {
|
||||
const select = targetHost.querySelector("select");
|
||||
if (!select.value) {
|
||||
showError(t("Admin.Upload.PickFirst"));
|
||||
select.focus();
|
||||
return null;
|
||||
}
|
||||
target = { id: select.value, title: titles.get(select.value) ?? "" };
|
||||
drawTarget();
|
||||
return { id: target.id, created: false };
|
||||
}
|
||||
const title = form.elements.title.value.trim();
|
||||
try {
|
||||
// Not retried: a lost answer must not create the sequence twice.
|
||||
const created = await api.post("/api/v1/sequences", { title: title || null, cameraHint: null });
|
||||
target = { id: created.id, title: created.displayTitle };
|
||||
} catch (err) {
|
||||
showError(errorText(err));
|
||||
return null;
|
||||
}
|
||||
drawTarget();
|
||||
return { id: target.id, created: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* One photo: hashed, started (the server may already have it, or have had it before it was deleted), the missing
|
||||
* chunks sent two at a time, completed. True when the library changed. The same photo picked under another name
|
||||
* waits for the first copy, which settles it for both: two lanes would otherwise complete the one upload the server
|
||||
* gives them and refuse each other.
|
||||
*/
|
||||
async function send(item, sequenceId, signal) {
|
||||
const file = item.file;
|
||||
item.hashed = 0;
|
||||
setState(item, "hashing");
|
||||
hasher ??= createHasher();
|
||||
const sha256 = await hasher.hash(file, (done, size) => {
|
||||
item.hashed = size > 0 ? done / size : 1;
|
||||
update(item);
|
||||
});
|
||||
if (signal.aborted) throw signal.reason;
|
||||
setState(item, "starting");
|
||||
const earlier = sameContent.get(sha256);
|
||||
let settle;
|
||||
sameContent.set(sha256, new Promise((resolve) => {
|
||||
settle = resolve;
|
||||
}));
|
||||
try {
|
||||
await earlier;
|
||||
if (signal.aborted) throw signal.reason;
|
||||
return await sendHashed(item, sha256, sequenceId, signal);
|
||||
} finally {
|
||||
settle();
|
||||
}
|
||||
}
|
||||
|
||||
/** A hashed photo: started (asking to bring it back when the user chose Upload again), its chunks sent, completed. */
|
||||
async function sendHashed(item, sha256, sequenceId, signal) {
|
||||
const file = item.file;
|
||||
const restore = item.restore;
|
||||
const capturedAt = await captureTime(file);
|
||||
const start = await retry(() => api.post("/api/v1/uploads", {
|
||||
sequenceId, fileName: file.name, size: file.size, sha256, capturedAt, sessionKey: null, restore,
|
||||
}), signal);
|
||||
if (start.alreadyExists) {
|
||||
// No frame: the photo was deleted from this sequence; a restore from the trash brings it back while the trash
|
||||
// holds it, or Upload again on its row (R6).
|
||||
finish(item, start.frameId ? "exists" : "deleted");
|
||||
return false;
|
||||
}
|
||||
item.uploadId = start.uploadId;
|
||||
const chunk = start.chunkSize;
|
||||
const count = Math.ceil(file.size / chunk);
|
||||
const received = new Set(start.received ?? []);
|
||||
const length = (index) => Math.min(chunk, file.size - index * chunk);
|
||||
item.sent = [...received].reduce((sum, index) => sum + length(index), 0);
|
||||
const missing = [];
|
||||
for (let index = 0; index < count; index++) if (!received.has(index)) missing.push(index);
|
||||
setState(item, "uploading");
|
||||
let cursor = 0;
|
||||
let failure = null;
|
||||
const lane = async () => {
|
||||
while (failure === null && cursor < missing.length) {
|
||||
const index = missing[cursor++];
|
||||
const blob = file.slice(index * chunk, index * chunk + length(index));
|
||||
try {
|
||||
await retry(() => api.putBytes(`/api/v1/uploads/${item.uploadId}/chunks/${index}`, blob, signal), signal);
|
||||
} catch (err) {
|
||||
failure ??= err;
|
||||
return;
|
||||
}
|
||||
item.sent += blob.size;
|
||||
update(item);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(CHUNKS_AT_ONCE, missing.length) }, lane));
|
||||
// A chunk refused because the upload is no longer receiving: another completion of it is filing it (or it ended),
|
||||
// which the completion below waits for and reports.
|
||||
if (failure !== null && !filing(failure)) throw failure;
|
||||
setState(item, "verifying");
|
||||
try {
|
||||
await complete(api, item.uploadId, restore, signal);
|
||||
} catch (err) {
|
||||
if (!(err instanceof ApiFailure && err.status === 409 && err.code === "photo_removed")) throw err;
|
||||
// Deleted from the sequence while it was on its way: not filed, and the server dropped the upload (R6).
|
||||
item.uploadId = null;
|
||||
finish(item, "deleted");
|
||||
return false;
|
||||
}
|
||||
item.uploadId = null;
|
||||
finish(item, "done");
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A photo is settled on the server: a later run leaves it alone, until Upload again asks to bring it back. */
|
||||
function finish(item, state) {
|
||||
item.restore = false;
|
||||
setState(item, state);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 409 upload_state: the upload is not receiving now, because a completion is filing it or it ended. */
|
||||
function filing(err) {
|
||||
return err instanceof ApiFailure && err.status === 409 && err.code === "upload_state";
|
||||
}
|
||||
|
||||
/**
|
||||
* Completes an upload through api, the dialog's (with restore, a photo deleted from the sequence meanwhile is filed
|
||||
* anyway). A completion refused while another one is filing the upload (the same photo started twice, a retry after a
|
||||
* lost answer) waits for it: once the upload is committed, completing again answers its frame. Only an upload that
|
||||
* failed or was cancelled, or one that stays busy for about a minute, fails the photo.
|
||||
*/
|
||||
async function complete(api, uploadId, restore, signal) {
|
||||
const url = `/api/v1/uploads/${uploadId}/complete${restore ? "?restore=true" : ""}`;
|
||||
for (let check = 0; ; check++) {
|
||||
try {
|
||||
return await retry(() => api.post(url), signal);
|
||||
} catch (err) {
|
||||
if (signal.aborted || !filing(err) || check >= SETTLE_CHECKS) throw err;
|
||||
await sleep(1000 * Math.min(2 ** check, 8), signal);
|
||||
const upload = await retry(() => api.get(`/api/v1/uploads/${uploadId}`), signal);
|
||||
if (upload?.state === "failed" || upload?.state === "cancelled") throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What dropped: the files, and how many folders were left out (the entries API tells them apart where it exists). */
|
||||
function dropped(transfer) {
|
||||
const files = [];
|
||||
let folders = 0;
|
||||
const entries = [...(transfer.items ?? [])].filter((i) => i.kind === "file");
|
||||
if (entries.length > 0) {
|
||||
for (const item of entries) {
|
||||
if (item.webkitGetAsEntry?.()?.isDirectory) {
|
||||
folders++;
|
||||
continue;
|
||||
}
|
||||
const file = item.getAsFile();
|
||||
if (file) files.push(file);
|
||||
}
|
||||
} else {
|
||||
files.push(...(transfer.files ?? []));
|
||||
}
|
||||
return { files, folders };
|
||||
}
|
||||
|
||||
/** Refusals that would refuse the next photos as well: quota, space, permission, a target gone, a broken hash. */
|
||||
function stops(err) {
|
||||
if (err instanceof HashError) return err.kind === "self_test" || err.kind === "worker";
|
||||
if (!(err instanceof ApiFailure)) return false;
|
||||
return err.status === 401 || err.status === 403 || err.status === 507 || (err.status === 404 && err.details === "sequence");
|
||||
}
|
||||
|
||||
function messageOf(err) {
|
||||
if (err instanceof HashError) {
|
||||
if (err.kind === "self_test") return t("Admin.Upload.SelfTestFailed");
|
||||
if (err.kind === "read") return t("Admin.Upload.ReadFailed");
|
||||
return t("Admin.Upload.HashFailed");
|
||||
}
|
||||
return errorText(err);
|
||||
}
|
||||
|
||||
/** Calls again after 1, 2 and 4 seconds when the server was not reached, was busy (429) or unavailable (503). */
|
||||
async function retry(call, signal) {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
return await call();
|
||||
} catch (err) {
|
||||
const passing = err instanceof ApiFailure && (err.status === 0 || err.status === 429 || err.status === 503);
|
||||
if (signal.aborted || !passing || attempt >= RETRIES) throw err;
|
||||
await sleep(1000 * 2 ** attempt, signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms, signal) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(resolve, ms);
|
||||
signal.addEventListener("abort", () => {
|
||||
clearTimeout(timer);
|
||||
reject(signal.reason);
|
||||
}, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The hash worker behind a promise per file. A worker that fails to load or run rejects every request (worker); its
|
||||
* refusal after a failed self-test is self_test. stop() ends the worker and rejects what it still had (stopped).
|
||||
*/
|
||||
function createHasher() {
|
||||
let worker = null;
|
||||
let failure = null;
|
||||
let next = 0;
|
||||
const pending = new Map();
|
||||
const fail = (error) => {
|
||||
for (const request of pending.values()) request.reject(error);
|
||||
pending.clear();
|
||||
};
|
||||
const start = () => {
|
||||
try {
|
||||
worker = new Worker(new URL("./hash-worker.js", import.meta.url), { type: "module" });
|
||||
} catch (err) {
|
||||
failure = new HashError("worker", String(err?.name ?? err));
|
||||
return;
|
||||
}
|
||||
worker.addEventListener("message", (e) => {
|
||||
const message = e.data ?? {};
|
||||
const request = pending.get(message.id);
|
||||
if (!request) return;
|
||||
if (message.type === "progress") {
|
||||
request.progress(message.done, message.total);
|
||||
return;
|
||||
}
|
||||
pending.delete(message.id);
|
||||
if (message.type === "done" && /^[0-9a-f]{64}$/.test(message.sha256 ?? "")) request.resolve(message.sha256);
|
||||
else request.reject(new HashError(message.reason === "self_test" ? "self_test" : message.reason === "read" ? "read" : "worker", message.detail));
|
||||
});
|
||||
worker.addEventListener("error", (e) => {
|
||||
e.preventDefault();
|
||||
failure = new HashError("worker", e.message ?? "");
|
||||
fail(failure);
|
||||
});
|
||||
};
|
||||
return {
|
||||
hash(file, progress) {
|
||||
if (!worker && !failure) start();
|
||||
if (failure) return Promise.reject(failure);
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = ++next;
|
||||
pending.set(id, { resolve, reject, progress });
|
||||
worker.postMessage({ id, file });
|
||||
});
|
||||
},
|
||||
stop() {
|
||||
worker?.terminate();
|
||||
worker = null;
|
||||
fail(new HashError("stopped"));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -114,6 +114,14 @@ public static class JobEndpoints
|
||||
return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
|
||||
}
|
||||
|
||||
if (kind == JobKind.Verify)
|
||||
{
|
||||
// A verify of sequences targets their archive and names them in its parameters, as its handler reads it.
|
||||
var verify = LibraryEndpoints.SequenceJob(kind, archive.Current, targets, label);
|
||||
targets = verify.Targets;
|
||||
queue = [(label, verify.ParametersJson)];
|
||||
}
|
||||
|
||||
Job? first = null;
|
||||
foreach (var (jobLabel, parameters) in queue)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Http.Metadata;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// The library the admin panel manages without editing (owner review 2, R6): a sequence's cover thumbnail, deleting photos
|
||||
/// of a sequence into the archive's trash (<see cref="FrameTrash"/>), and mass operations on many sequences at once —
|
||||
/// delete into the trash, retag, queue analysis, proxies, thumbnails or a verify — each answering per sequence whether it
|
||||
/// was done or skipped, and why.
|
||||
/// </summary>
|
||||
public static class LibraryEndpoints
|
||||
{
|
||||
/// <summary>Sequences one bulk request may name.</summary>
|
||||
public const int MaxBulkIds = 1000;
|
||||
|
||||
/// <summary>Photos one delete request may name.</summary>
|
||||
public const int MaxFrameIds = 100_000;
|
||||
|
||||
/// <summary>
|
||||
/// The body a delete request of <see cref="MaxFrameIds"/> photos may take: 48 bytes an id (36 characters, quotes, a
|
||||
/// comma and some indentation) and 4 KiB for the rest, about 4.8 MB, above the server's 1 MiB for other JSON bodies.
|
||||
/// </summary>
|
||||
public const long FrameDeleteBodyLimit = MaxFrameIds * 48L + 4096;
|
||||
|
||||
private const string Ok = "ok";
|
||||
private const string Skipped = "skipped";
|
||||
private const string Regenerable = "private, max-age=3600";
|
||||
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var sequences = api.MapGroup("/sequences");
|
||||
sequences.MapGet("/facets", FacetsAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/thumb", ThumbAsync).Requires(Permissions.Read);
|
||||
sequences.MapPost("/{id:guid}/frames/delete", DeleteFramesAsync).Requires(Permissions.Delete).WithMetadata(new FrameDeleteBodyLimitMetadata());
|
||||
sequences.MapPost("/bulk/delete", BulkDeleteAsync).Requires(Permissions.Delete);
|
||||
sequences.MapPost("/bulk/retag", BulkRetagAsync).Requires(Permissions.Edit);
|
||||
sequences.MapPost("/bulk/jobs", BulkJobsAsync).Requires(Permissions.Edit);
|
||||
}
|
||||
|
||||
/// <summary>The archive engine behind these operations: the host's, or one of its own (a test host that replaces the archive module).</summary>
|
||||
internal static ArchiveService Engine(ArchiveService? archives, ChronosDatabase db) =>
|
||||
archives ?? new ArchiveService(db, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, ImagesAfterScan = true });
|
||||
|
||||
/// <summary>
|
||||
/// What the Library's filters offer (the panel's Year, Camera and Tag menus): the years of first capture, the camera
|
||||
/// models and the tags of this archive's sequences, each with its count. A camera's label is the name the desktop
|
||||
/// shows (<see cref="PathTemplate.CameraName"/>: brand and model, the brand once).
|
||||
/// </summary>
|
||||
private static async Task<IResult> FacetsAsync(HttpContext context, ChronosDatabase db, ServerArchive archive)
|
||||
{
|
||||
var facets = await db.Sequences.GetFacetsAsync(archive.Id, context.RequestAborted);
|
||||
return Results.Json(new LibraryFacetsDto(
|
||||
[.. facets.Years.Select(y => new FacetDto(y.Value, y.Sequences))],
|
||||
[.. facets.Cameras.Select(c => new FacetDto(c.Value, c.Sequences, PathTemplate.CameraName(c.Make, c.Value)))],
|
||||
[.. facets.Tags.Select(t => new FacetDto(t.Value, t.Sequences))]), ProtocolJson.Default.LibraryFacetsDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The thumbnail of the sequence's hero frame, else of its first frame, streamed like <c>/frames/{id}/thumb</c> with an
|
||||
/// ETag (304 when unchanged); 404 <c>not_found</c> (<c>thumbnail</c>) when the sequence has no frame or that thumbnail
|
||||
/// is not built yet.
|
||||
/// </summary>
|
||||
private static async Task<IResult> ThumbAsync(HttpContext context, Guid id, ChronosDatabase db, ServerArchive archive, IFrameAssetLocator locator)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
var frame = sequence.HeroFrameId is { } hero && await db.Frames.GetAsync(hero, ct) is { } chosen && chosen.SequenceId == id
|
||||
? chosen
|
||||
: (await db.Frames.ListBySequenceAsync(id, limit: 1, cancellationToken: ct)).FirstOrDefault();
|
||||
if (frame is null) return ApiErrors.NotFound(context, "thumbnail");
|
||||
var location = await locator.LocateAsync(archive.Current, sequence, frame, FrameAsset.Thumbnail, ct);
|
||||
if (location is null || !ArchivePathGuard.IsInside(archive.Root, location.Path)) return ApiErrors.NotFound(context, "thumbnail");
|
||||
var file = new FileInfo(location.Path);
|
||||
if (!file.Exists || file.LinkTarget is not null) return ApiErrors.NotFound(context, "thumbnail");
|
||||
var etag = string.Create(CultureInfo.InvariantCulture, $"s-{frame.Id:N}-{file.LastWriteTimeUtc.Ticks}-{location.Offset}");
|
||||
return FileResponses.Serve(context, file, location.Offset, location.Length, location.ContentType, Regenerable, etag)
|
||||
?? ApiErrors.NotFound(context, "thumbnail");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves photos of a sequence into the archive's trash (<see cref="FrameTrash"/>; BRIEF §0.2 rule 8: nothing is erased),
|
||||
/// or with <c>dryRun</c> says what would go. Owners and admins only, like deleting the sequence. 400 <c>bad_request</c>
|
||||
/// (<c>frameIds</c>: none, or more than <see cref="MaxFrameIds"/>); 404 <c>not_found</c> (<c>sequence</c>, also when it
|
||||
/// left the index meanwhile); 409 <c>frames_conflict</c> (the frames changed since <c>expectedFramesVersion</c>, or a
|
||||
/// photo named is not the sequence's; details: the frames version now), <c>sequence_busy</c>, <c>would_empty</c> (every
|
||||
/// photo would go: delete the sequence instead), <c>photo_unreadable</c> (a photo never hashed cannot be read, so its
|
||||
/// deletion could leave no tombstone; one whose original is missing goes without one), <c>sidecar_mismatch</c> (the
|
||||
/// sidecar in its folder is damaged or another sequence's), <c>folder_in_use</c>; 413 <c>too_large</c> (a body above
|
||||
/// <see cref="FrameDeleteBodyLimit"/>); 503 <c>archive_offline</c>. Publishes <c>sequenceChanged</c> <c>frames</c>; the
|
||||
/// thumbnails, proxies and analyses follow as jobs.
|
||||
/// </summary>
|
||||
private static async Task<IResult> DeleteFramesAsync(HttpContext context, Caller caller, Guid id, FrameDeleteRequest request, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (request.FrameIds is not { Count: > 0 and <= MaxFrameIds } ids) return ApiErrors.BadRequest(context, "bad_request", "frameIds");
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context);
|
||||
var engine = Engine(archives, db).FrameTrash;
|
||||
FrameDeletePlan plan;
|
||||
try
|
||||
{
|
||||
plan = await engine.PlanDeleteAsync(id, ids, request.ExpectedFramesVersion, ct);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
}
|
||||
if (plan.Blocked.Count > 0) return Refused(context, plan);
|
||||
if (request.DryRun)
|
||||
return Results.Json(new FrameDeleteResultDto(id, plan.Frames.Count, plan.Bytes, plan.Sequence.FramesVersion, plan.Sequence.FrameCount, null, true),
|
||||
ProtocolJson.Default.FrameDeleteResultDto);
|
||||
|
||||
FrameDeleteResult result;
|
||||
try
|
||||
{
|
||||
// Once confirmed the deletion runs to the end even if the client goes away meanwhile.
|
||||
result = await engine.DeleteAsync(plan, caller.User.Username, host.Engine, lifetime.ApplicationStopping);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return Refused(context, plan with { Blocked = [FrameDeleteBlock.Offline] });
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// The sequence left the index since the plan.
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
}
|
||||
catch (Exception ex) when (ex is StaleDeletePlanException or LeaseUnavailableException)
|
||||
{
|
||||
return await RefusedAgainAsync(context, engine, id, ids, plan.Sequence.FramesVersion,
|
||||
ex is LeaseUnavailableException ? FrameDeleteBlock.Busy : FrameDeleteBlock.FramesChanged, ct);
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// The sidecar in the sequence's folder is damaged or another sequence's: nothing moved.
|
||||
return ApiErrors.Conflict(context, "sidecar_mismatch");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A photo is open in another program: nothing moved.
|
||||
return ApiErrors.Conflict(context, "folder_in_use");
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "frames_deleted", "sequence", id.ToString(), $"{plan.Frames.Count} · {result.Entry.Name}");
|
||||
events.Publish(new SequenceChangedEvent(id, "frames", result.Sequence.FramesVersion, result.Sequence.SettingsVersion));
|
||||
return Results.Json(new FrameDeleteResultDto(id, plan.Frames.Count, plan.Bytes, result.Sequence.FramesVersion, result.Sequence.FrameCount,
|
||||
result.Entry.Name, false), ProtocolJson.Default.FrameDeleteResultDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A plan's first block, each with its own code: 503 <c>archive_offline</c>; 409 <c>sequence_busy</c>,
|
||||
/// <c>frames_conflict</c> (details: the frames version now), <c>would_empty</c>, <c>photo_unreadable</c> (a photo never
|
||||
/// hashed cannot be read, so it could leave no tombstone; the message names the first, details: how many).
|
||||
/// </summary>
|
||||
private static IResult Refused(HttpContext context, FrameDeletePlan plan) => plan.Blocked[0] switch
|
||||
{
|
||||
FrameDeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"),
|
||||
FrameDeleteBlock.Busy => ApiErrors.Conflict(context, "sequence_busy"),
|
||||
FrameDeleteBlock.FramesChanged => ApiErrors.Conflict(context, "frames_conflict", plan.Sequence.FramesVersion.ToString(CultureInfo.InvariantCulture)),
|
||||
FrameDeleteBlock.WouldEmpty => ApiErrors.Conflict(context, "would_empty"),
|
||||
FrameDeleteBlock.Unhashable => ApiErrors.Result(context, StatusCodes.Status409Conflict, "photo_unreadable",
|
||||
plan.Unhashable.Count.ToString(CultureInfo.InvariantCulture), plan.Unhashable.Count > 0 ? Path.GetFileName(plan.Unhashable[0].RelativePath) : "?"),
|
||||
var other => throw new ArgumentOutOfRangeException(nameof(plan), other, "A block without an error code."),
|
||||
};
|
||||
|
||||
/// <summary>A deletion refused under the lease, said as the plan is now (<paramref name="otherwise"/> when nothing blocks it); 404 when the sequence is gone.</summary>
|
||||
private static async Task<IResult> RefusedAgainAsync(HttpContext context, FrameTrash engine, Guid id, IReadOnlyList<Guid> ids, int framesVersion,
|
||||
FrameDeleteBlock otherwise, CancellationToken ct)
|
||||
{
|
||||
FrameDeletePlan again;
|
||||
try
|
||||
{
|
||||
again = await engine.PlanDeleteAsync(id, ids, framesVersion, ct);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
}
|
||||
return Refused(context, again.Blocked.Count > 0 ? again : again with { Blocked = [otherwise] });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves many sequences into the trash as <c>DELETE /sequences/{id}</c> does each (or, with <c>dryRun</c>, plans them):
|
||||
/// one item per id, <c>ok</c> with the trash folder, or <c>skipped</c> with the code that says why (<c>not_found</c>,
|
||||
/// <c>forbidden</c> for a sequence of another user, <c>sequence_busy</c>, <c>archive_root</c>, <c>contains_sequences</c>,
|
||||
/// <c>sidecar_mismatch</c>, <c>folder_missing</c>, <c>archive_offline</c>, <c>folder_in_use</c>). Each sequence moves whole
|
||||
/// or not at all. 400 <c>bad_request</c> (<c>ids</c>).
|
||||
/// </summary>
|
||||
private static async Task<IResult> BulkDeleteAsync(HttpContext context, Caller caller, BulkDeleteRequest request, ChronosDatabase db,
|
||||
[FromServices] ArchiveService? archives, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
var trash = Engine(archives, db).Trash;
|
||||
var items = new Dictionary<Guid, BulkItemResult>();
|
||||
var allowed = new List<Sequence>();
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) items[id] = Skip(context, id, "not_found");
|
||||
else if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) items[id] = Skip(context, id, "forbidden");
|
||||
else allowed.Add(sequence);
|
||||
}
|
||||
var steps = new List<DeleteStep>();
|
||||
foreach (var (sequence, reason, step) in await PlanEachAsync(trash, allowed, ct))
|
||||
{
|
||||
if (step is not null) steps.Add(step);
|
||||
else items[sequence.Id] = Skip(context, sequence.Id, reason!);
|
||||
}
|
||||
var photos = 0;
|
||||
long bytes = 0;
|
||||
foreach (var step in steps)
|
||||
{
|
||||
var sequence = step.Sequence;
|
||||
if (!request.DryRun)
|
||||
{
|
||||
try
|
||||
{
|
||||
await trash.DeleteAsync(new DeletePlan([step], []), caller.User.Username, null, lifetime.ApplicationStopping);
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
items[sequence.Id] = Skip(context, sequence.Id, "archive_offline");
|
||||
continue;
|
||||
}
|
||||
catch (Exception ex) when (ex is StaleDeletePlanException or LeaseUnavailableException)
|
||||
{
|
||||
items[sequence.Id] = Skip(context, sequence.Id, "sequence_busy");
|
||||
continue;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// An interrupted journal could not be settled first: its sidecar is damaged (a scan rebuilds it).
|
||||
items[sequence.Id] = Skip(context, sequence.Id, "sidecar_mismatch");
|
||||
continue;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
items[sequence.Id] = Skip(context, sequence.Id, "folder_in_use");
|
||||
continue;
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "sequence_deleted", "sequence", sequence.Id.ToString(), sequence.DisplayTitle);
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "deleted", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
}
|
||||
items[sequence.Id] = new BulkItemResult(sequence.Id, Ok, TrashFolder: step.TrashFolder);
|
||||
photos += sequence.FrameCount;
|
||||
bytes += step.Bytes;
|
||||
}
|
||||
return Results.Json(Result(ids, items, request.DryRun, photos, bytes), ProtocolJson.Default.BulkResultDto);
|
||||
}
|
||||
|
||||
/// <summary>Each sequence's delete plan: its step, or the code of why it cannot go.</summary>
|
||||
private static async Task<List<(Sequence Sequence, string? Reason, DeleteStep? Step)>> PlanEachAsync(SequenceTrash trash, List<Sequence> sequences,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var planned = new List<(Sequence, string?, DeleteStep?)>();
|
||||
if (sequences.Count == 0) return planned;
|
||||
DeletePlan plan;
|
||||
try
|
||||
{
|
||||
plan = await trash.PlanAsync([.. sequences.Select(s => s.Id)], null, ct);
|
||||
}
|
||||
catch (ArgumentException) when (sequences.Count == 1)
|
||||
{
|
||||
return [(sequences[0], "not_found", null)];
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// One left the index meanwhile: planned one by one, so the others still go.
|
||||
foreach (var sequence in sequences) planned.AddRange(await PlanEachAsync(trash, [sequence], ct));
|
||||
return planned;
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return [.. sequences.Select(s => (s, (string?)"archive_offline", (DeleteStep?)null))];
|
||||
}
|
||||
foreach (var step in plan.Steps) planned.Add((step.Sequence, null, step));
|
||||
foreach (var blocked in plan.Blocked) planned.Add((blocked.Sequence, BlockCode(blocked.Reason), null));
|
||||
return planned;
|
||||
}
|
||||
|
||||
/// <summary>The error code of a sequence that cannot go to the trash, as <c>DELETE /sequences/{id}</c> answers it.</summary>
|
||||
internal static string BlockCode(DeleteBlock reason) => reason switch
|
||||
{
|
||||
DeleteBlock.Offline => "archive_offline",
|
||||
DeleteBlock.Busy => "sequence_busy",
|
||||
DeleteBlock.ArchiveRoot => "archive_root",
|
||||
DeleteBlock.ContainsSequences => "contains_sequences",
|
||||
DeleteBlock.ForeignSidecar => "sidecar_mismatch",
|
||||
_ => "folder_missing",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Adds and removes tags on many sequences, each with the same edit as a PATCH of its tags (case-insensitive, the first
|
||||
/// spelling kept; settings version + 1 when they change). Skipped: <c>not_found</c>, <c>bad_request</c> (more than 50
|
||||
/// tags then). 400 <c>bad_request</c> (<c>ids</c>, <c>tags</c>). Publishes <c>sequenceChanged</c> <c>settings</c>.
|
||||
/// </summary>
|
||||
private static async Task<IResult> BulkRetagAsync(HttpContext context, Caller caller, BulkRetagRequest request, ChronosDatabase db, AuditLog audit,
|
||||
EventHub events)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
if (Tags(request.Add) is not { } add || Tags(request.Remove) is not { } remove || add.Count + remove.Count == 0)
|
||||
return ApiErrors.BadRequest(context, "bad_request", "tags");
|
||||
var items = new Dictionary<Guid, BulkItemResult>();
|
||||
foreach (var id in ids)
|
||||
{
|
||||
items[id] = await RetagAsync(context, caller, db, audit, events, id, add, remove, ct);
|
||||
}
|
||||
return Results.Json(Result(ids, items, false, 0, 0), ProtocolJson.Default.BulkResultDto);
|
||||
}
|
||||
|
||||
private static async Task<BulkItemResult> RetagAsync(HttpContext context, Caller caller, ChronosDatabase db, AuditLog audit, EventHub events, Guid id,
|
||||
IReadOnlyList<string> add, IReadOnlyList<string> remove, CancellationToken ct)
|
||||
{
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return Skip(context, id, "not_found");
|
||||
var tags = sequence.Tags.Where(t => !remove.Contains(t, StringComparer.OrdinalIgnoreCase)).ToList();
|
||||
tags.AddRange(add.Where(t => !tags.Contains(t, StringComparer.OrdinalIgnoreCase)));
|
||||
if (tags.Count > SequenceEndpoints.MaxTags) return Skip(context, id, "bad_request");
|
||||
if (tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(sequence.Tags)) return new BulkItemResult(id, Ok);
|
||||
var result = await db.Sequences.EditAsync(id, new SequenceEdit { Tags = tags }, sequence.SettingsVersion, ct);
|
||||
if (result.Outcome == SequenceEditOutcome.NotFound) return Skip(context, id, "not_found");
|
||||
// Edited meanwhile: the tags apply again on top of that edit.
|
||||
if (result.Outcome == SequenceEditOutcome.Conflict) continue;
|
||||
var updated = result.Sequence!;
|
||||
await audit.WriteAsync(caller, context, "sequence_updated", "sequence", id.ToString(), "tags");
|
||||
events.Publish(new SequenceChangedEvent(id, "settings", updated.FramesVersion, updated.SettingsVersion));
|
||||
return new BulkItemResult(id, Ok);
|
||||
}
|
||||
return Skip(context, id, "settings_conflict");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues one job over many sequences: <c>analyse</c> (light analysis), <c>deep</c> (deep analysis), <c>proxies</c>,
|
||||
/// <c>thumbnails</c> or <c>verify</c> (a verify of those sequences in their archive), at user priority. Sequences not in
|
||||
/// the index are skipped (<c>not_found</c>). 202 with the job when one was queued; 400 <c>invalid_job_kind</c>,
|
||||
/// <c>bad_request</c> (<c>ids</c>); 409 <c>job_unavailable</c> when this server cannot run that kind.
|
||||
/// </summary>
|
||||
private static async Task<IResult> BulkJobsAsync(HttpContext context, Caller caller, BulkJobsRequest request, ChronosDatabase db, ServerArchive archive,
|
||||
JobEngineHost host, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
|
||||
if (BulkKind(request.Kind) is not { } kind) return ApiErrors.BadRequest(context, "invalid_job_kind");
|
||||
if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind));
|
||||
var items = new Dictionary<Guid, BulkItemResult>();
|
||||
var found = new List<Sequence>();
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is { } sequence && sequence.ArchiveId == archive.Id)
|
||||
{
|
||||
found.Add(sequence);
|
||||
items[id] = new BulkItemResult(id, Ok);
|
||||
}
|
||||
else
|
||||
{
|
||||
items[id] = Skip(context, id, "not_found");
|
||||
}
|
||||
}
|
||||
if (found.Count == 0) return Results.Json(Result(ids, items, false, 0, 0), ProtocolJson.Default.BulkResultDto);
|
||||
var targets = found.Select(s => s.Id).ToList();
|
||||
var label = Label(found);
|
||||
var job = await host.Engine.EnqueueAsync(SequenceJob(kind, archive.Current, targets, label) with { Priority = JobPriority.User }, caller.Id, ct);
|
||||
await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {label}");
|
||||
return Results.Json(Result(ids, items, false, 0, 0) with { Job = Dto.Job(job) }, ProtocolJson.Default.BulkResultDto,
|
||||
statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>The kinds a bulk job request names.</summary>
|
||||
private static JobKind? BulkKind(string? kind) => kind?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"analyse" => JobKind.LightAnalyse,
|
||||
"deep" => JobKind.DeepAnalyse,
|
||||
"proxies" => JobKind.Proxies,
|
||||
"thumbnails" => JobKind.Thumbs,
|
||||
"verify" => JobKind.Verify,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The job of a sequence kind over <paramref name="sequenceIds"/>. A verify targets the archive and names the sequences
|
||||
/// in its parameters (<see cref="ArchiveJobs.Verify"/>), as its handler reads it.
|
||||
/// </summary>
|
||||
internal static ArchiveJobRequest SequenceJob(JobKind kind, Archive archive, IReadOnlyList<Guid> sequenceIds, string label) => kind switch
|
||||
{
|
||||
JobKind.Verify => ArchiveJobs.Verify(archive, sequenceIds) with { Label = label },
|
||||
JobKind.LightAnalyse => ProcessingJobs.LightAnalysis(sequenceIds, label),
|
||||
JobKind.DeepAnalyse => ProcessingJobs.DeepAnalysis(sequenceIds, label),
|
||||
JobKind.Proxies => ArchiveJobs.Proxies(sequenceIds, label),
|
||||
JobKind.Thumbs => ArchiveJobs.Thumbnails(sequenceIds, label),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Not a sequence job."),
|
||||
};
|
||||
|
||||
/// <summary>"Harbour sunset", or the first three titles and "…".</summary>
|
||||
internal static string Label(IReadOnlyList<Sequence> sequences) =>
|
||||
sequences.Count == 1 ? sequences[0].DisplayTitle
|
||||
: string.Join(", ", sequences.Take(3).Select(s => s.DisplayTitle)) + (sequences.Count > 3 ? " …" : string.Empty);
|
||||
|
||||
/// <summary>The ids of a bulk request, once each in their order; null when there are none or too many.</summary>
|
||||
private static List<Guid>? Ids(IReadOnlyList<Guid>? ids) =>
|
||||
ids is { Count: > 0 and <= MaxBulkIds } ? [.. ids.Distinct()] : null;
|
||||
|
||||
/// <summary>Tags as a request names them, trimmed, once each; null when one is blank or too long.</summary>
|
||||
private static List<string>? Tags(IReadOnlyList<string>? tags)
|
||||
{
|
||||
if (tags is null) return [];
|
||||
var list = new List<string>();
|
||||
foreach (var tag in tags)
|
||||
{
|
||||
var trimmed = tag?.Trim();
|
||||
if (string.IsNullOrEmpty(trimmed) || trimmed.Length > TagRepository.MaxLength) return null;
|
||||
if (!list.Contains(trimmed, StringComparer.OrdinalIgnoreCase)) list.Add(trimmed);
|
||||
}
|
||||
return list.Count > SequenceEndpoints.MaxTags ? null : list;
|
||||
}
|
||||
|
||||
private static BulkItemResult Skip(HttpContext context, Guid id, string code) => new(id, Skipped, code, ApiErrors.Message(context, code));
|
||||
|
||||
private static BulkResultDto Result(List<Guid> ids, Dictionary<Guid, BulkItemResult> items, bool dryRun, int photos, long bytes)
|
||||
{
|
||||
var ordered = ids.Select(id => items[id]).ToList();
|
||||
var ok = ordered.Count(i => i.Outcome == Ok);
|
||||
return new BulkResultDto(ordered, ok, ordered.Count - ok, dryRun, photos, bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The photo delete route's body limit (<see cref="FrameDeleteBodyLimit"/>), applied by routing as it selects the
|
||||
/// endpoint, as for proxies (<see cref="FileEndpoints"/>): the server's 1 MiB stops at about 26,900 ids.
|
||||
/// </summary>
|
||||
private sealed class FrameDeleteBodyLimitMetadata : IRequestSizeLimitMetadata
|
||||
{
|
||||
public long? MaxRequestBodySize => FrameDeleteBodyLimit;
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,8 @@ public static class SequenceEndpoints
|
||||
{
|
||||
private const int MaxTitle = 200;
|
||||
private const int MaxNotes = 2000;
|
||||
private const int MaxTags = 50;
|
||||
/// <summary>Tags a sequence may carry.</summary>
|
||||
internal const int MaxTags = 50;
|
||||
|
||||
/// <summary>Listings of a sequence's frames read without a lock before one is read under its row lock (<see cref="SnapshotAsync"/>).</summary>
|
||||
private const int SnapshotAttempts = 3;
|
||||
@@ -57,8 +58,13 @@ public static class SequenceEndpoints
|
||||
.Requires(Permissions.Edit);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One page of the library. Filters: <c>year</c>, <c>camera</c> (the exact model), <c>status</c> (flags, <c>-</c> for
|
||||
/// cleared ones), <c>rendered</c> (<c>true</c>: with a render, <c>false</c>: without; the admin panel's Library), <c>tag</c>,
|
||||
/// <c>q</c> (title, camera or tag), <c>owner</c> (<c>me</c> or an id); <c>sort</c>, <c>cursor</c>, <c>limit</c>.
|
||||
/// </summary>
|
||||
private static async Task<IResult> ListAsync(HttpContext context, ChronosDatabase db, ServerArchive archive, int? year, string? camera, string? status,
|
||||
string? tag, string? q, string? owner, string? sort, string? cursor, int? limit, Caller caller)
|
||||
bool? rendered, string? tag, string? q, string? owner, string? sort, string? cursor, int? limit, Caller caller)
|
||||
{
|
||||
if (!TryParseStatus(status, out var with, out var without)) return ApiErrors.BadRequest(context, "invalid_filter", "status");
|
||||
if (!TryParseSort(sort, out var order)) return ApiErrors.BadRequest(context, "invalid_filter", "sort");
|
||||
@@ -74,6 +80,7 @@ public static class SequenceEndpoints
|
||||
Camera = string.IsNullOrWhiteSpace(camera) ? null : camera,
|
||||
WithStatus = with,
|
||||
WithoutStatus = without,
|
||||
Rendered = rendered,
|
||||
Tag = string.IsNullOrWhiteSpace(tag) ? null : tag,
|
||||
Text = string.IsNullOrWhiteSpace(q) ? null : q,
|
||||
OwnerUserId = ownerId,
|
||||
@@ -197,6 +204,11 @@ public static class SequenceEndpoints
|
||||
{
|
||||
return Refused(context, DeleteBlock.Busy);
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// An interrupted journal could not be settled first: the sidecar is damaged (a scan rebuilds it). Nothing moved.
|
||||
return Refused(context, DeleteBlock.ForeignSidecar);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A file of the folder is open elsewhere: nothing moved.
|
||||
@@ -238,9 +250,11 @@ public static class SequenceEndpoints
|
||||
if (context.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified);
|
||||
|
||||
var renders = await db.Renders.ListBySequenceAsync(id, ct);
|
||||
// Tombstones change only with the frames (a deletion bumps the frames version), so the ETag covers them.
|
||||
var removed = await db.FrameRemovals.ListBySequenceAsync(id, ct);
|
||||
context.Response.Headers.ETag = etag;
|
||||
return Results.Json(new SequenceManifest(id, sequence.FramesVersion, sequence.SettingsVersion, sequence.SettingsJson, sequence.Tags, frames,
|
||||
[.. renders.Select(Dto.Render)], spec), ProtocolJson.Default.SequenceManifest);
|
||||
[.. renders.Select(Dto.Render)], spec, removed.Count == 0 ? null : Data.Sync.SyncTombstones.ToDto(removed)), ProtocolJson.Default.SequenceManifest);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Protocol;
|
||||
@@ -28,6 +29,9 @@ public static class SystemEndpoints
|
||||
}
|
||||
})));
|
||||
|
||||
/// <summary>The extensions the archive scanner files as photos (BRIEF §8.1), which the admin panel's uploads keep to.</summary>
|
||||
private static readonly string[] PhotoExtensions = [.. ImageFormatInfo.Known.SelectMany(f => f.Extensions)];
|
||||
|
||||
public static string Version { get; } =
|
||||
typeof(SystemEndpoints).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
|
||||
|
||||
@@ -42,7 +46,8 @@ public static class SystemEndpoints
|
||||
state.Capabilities,
|
||||
state.TlsFingerprint,
|
||||
["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"],
|
||||
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength)), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller();
|
||||
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength),
|
||||
PhotoExtensions), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller();
|
||||
|
||||
api.MapGet("/i18n/{culture}", (string culture) =>
|
||||
{
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/archive/trash</c> (owner review 2, R6; administrators of the archive): the entries of the archive's trash —
|
||||
/// deleted sequences and photos deleted from sequences —, restoring one, and emptying it: a dry run that measures the
|
||||
/// entries and fingerprints them, then an <c>empty-trash</c> job that erases exactly those entries and refuses when the
|
||||
/// trash changed since (BRIEF §0.2 rule 8: the only erase of user files, always an explicit, confirmed action).
|
||||
/// </summary>
|
||||
public static partial class TrashEndpoints
|
||||
{
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var trash = api.MapGroup("/archive/trash").Requires(Permissions.ManageArchive);
|
||||
trash.MapGet("", ListAsync);
|
||||
trash.MapPost("/{name}/restore", RestoreAsync);
|
||||
trash.MapPost("/empty", EmptyAsync);
|
||||
}
|
||||
|
||||
/// <summary>Whether <paramref name="name"/> has the shape of an entry name (a sequence id, a time, <c>photos-</c>): never a path.</summary>
|
||||
public static bool IsEntryName(string? name) => name is not null && EntryName().IsMatch(name);
|
||||
|
||||
public static TrashEntryDto Entry(TrashEntry e) =>
|
||||
new(e.Name, e.Kind.ToString().ToLowerInvariant(), e.SequenceId, e.Title, e.Folder, e.Frames, e.Files, e.Bytes, e.DeletedBy, e.DeletedAt);
|
||||
|
||||
/// <summary>The entries newest first with their total size (a read-only archive lists them too); 503 <c>archive_offline</c>.</summary>
|
||||
private static async Task<IResult> ListAsync(HttpContext context, ChronosDatabase db, ServerArchive archive, [FromServices] ArchiveService? archives)
|
||||
{
|
||||
// An archive that cannot be reached shows no trash folder, which is not an empty trash.
|
||||
if (Availability(archive) == ArchiveAvailability.Offline) return Offline(context);
|
||||
var entries = await LibraryEndpoints.Engine(archives, db).Trash.ListAsync(archive.Current, context.RequestAborted);
|
||||
return Results.Json(new TrashListDto([.. entries.Select(Entry)], entries.Sum(e => e.Bytes)), ProtocolJson.Default.TrashListDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings an entry back: a sequence into its folder and the library, photos into their sequence (a new one when it is
|
||||
/// gone), each photo re-hashed against its record first. 404 <c>not_found</c> (<c>trash_entry</c>); 409
|
||||
/// <c>sequence_in_library</c> (that sequence is in the library already), <c>sequence_busy</c>, <c>sidecar_mismatch</c>
|
||||
/// (the sidecar of the sequence the photos go back into is damaged or another sequence's), <c>folder_in_use</c>; 422
|
||||
/// <c>trash_mismatch</c> (no file matches its record any more, or a deleted sequence's own sidecar no longer names it);
|
||||
/// 503 <c>archive_offline</c>. The answer names the photos that stayed in the trash, why each did and one sentence per
|
||||
/// reason in the request's language (<see cref="TrashRestoreDto"/>). Publishes <c>sequenceChanged</c>: <c>created</c> for
|
||||
/// a sequence, <c>frames</c> for photos.
|
||||
/// </summary>
|
||||
private static async Task<IResult> RestoreAsync(HttpContext context, Caller caller, string name, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
|
||||
{
|
||||
if (!IsEntryName(name)) return ApiErrors.NotFound(context, "trash_entry");
|
||||
TrashRestoreResult result;
|
||||
try
|
||||
{
|
||||
result = await LibraryEndpoints.Engine(archives, db).RestoreEntryAsync(archive.Id, name, host.Engine, lifetime.ApplicationStopping);
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "trash_entry");
|
||||
}
|
||||
catch (SequenceInLibraryException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "sequence_in_library");
|
||||
}
|
||||
catch (ArchiveOfflineException)
|
||||
{
|
||||
return Offline(context);
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "sequence_busy");
|
||||
}
|
||||
catch (TrashMismatchException)
|
||||
{
|
||||
return Mismatch(context);
|
||||
}
|
||||
catch (InvalidDataException) when (!FrameTrash.IsPhotoEntry(name))
|
||||
{
|
||||
// A deleted sequence's own sidecar is damaged or names another sequence: the entry is not what its record says.
|
||||
return Mismatch(context);
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// The sidecar of the sequence the photos go back into is damaged or another sequence's: nothing moved.
|
||||
return ApiErrors.Conflict(context, "sidecar_mismatch");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "folder_in_use");
|
||||
}
|
||||
var sequence = result.Sequence;
|
||||
await audit.WriteAsync(caller, context, "trash_restored", "sequence", sequence.Id.ToString(), $"{name} · {sequence.DisplayTitle}");
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, result.Kind == TrashKind.Sequence || result.NewSequence ? "created" : "frames",
|
||||
sequence.FramesVersion, sequence.SettingsVersion));
|
||||
var culture = RequestCulture.Of(context);
|
||||
return Results.Json(new TrashRestoreDto(name, result.Kind.ToString().ToLowerInvariant(), sequence.Id, result.Kind == TrashKind.Sequence ? sequence.FrameCount : result.Photos,
|
||||
[.. result.Kept.Select(k => k.Name)], result.NewSequence, [.. result.Kept.Select(k => ReasonCode(k.Reason))],
|
||||
result.Kept.Count == 0 ? null : string.Join(" ", KeptPhoto.Sentences(result.Kept, culture))), ProtocolJson.Default.TrashRestoreDto);
|
||||
}
|
||||
|
||||
/// <summary>The code of why a photo stayed in the trash (<see cref="TrashRestoreDto.KeptReasons"/>).</summary>
|
||||
private static string ReasonCode(KeptReason reason) => reason switch
|
||||
{
|
||||
KeptReason.Mismatch => "mismatch",
|
||||
KeptReason.NotMoved => "not_moved",
|
||||
KeptReason.InSequence => "in_sequence",
|
||||
_ => "no_file",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Empties the trash, or the entries <c>names</c> names. With <c>dryRun</c> the plan: the entries measured on disk, their
|
||||
/// totals and a fingerprint, nothing touched. Otherwise the request carries that fingerprint, and the server queues an
|
||||
/// <c>empty-trash</c> job (202) that erases exactly those entries; the job fails, erasing nothing, when the trash changed
|
||||
/// before it ran. The audit log records the request (<c>trash_empty_requested</c>: the entries planned, their size and
|
||||
/// the job); what the job erased is in its log. 400 <c>bad_request</c> (<c>names</c>, <c>fingerprint</c>); 409
|
||||
/// <c>trash_changed</c> (details: the fingerprint now), <c>job_unavailable</c>; 503 <c>archive_offline</c> (offline,
|
||||
/// or read-only for the erase itself).
|
||||
/// </summary>
|
||||
private static async Task<IResult> EmptyAsync(HttpContext context, Caller caller, TrashEmptyRequest request, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (request.Names is { } names && (names.Count == 0 || names.Any(n => !IsEntryName(n)))) return ApiErrors.BadRequest(context, "bad_request", "names");
|
||||
// Offline, the trash cannot be measured (it would plan as empty); read-only, it can be measured but not erased.
|
||||
var availability = Availability(archive);
|
||||
if (availability == ArchiveAvailability.Offline || (!request.DryRun && availability != ArchiveAvailability.Online)) return Offline(context);
|
||||
var plan = await LibraryEndpoints.Engine(archives, db).PlanEmptyTrashAsync(archive.Id, request.Names, ct);
|
||||
if (request.DryRun)
|
||||
{
|
||||
return Results.Json(new TrashEmptyPlanDto([.. plan.Entries.Select(Entry)], plan.Photos, plan.Files, plan.Bytes, plan.Fingerprint, plan.Unknown),
|
||||
ProtocolJson.Default.TrashEmptyPlanDto);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
|
||||
if (plan.Fingerprint != request.Fingerprint || plan.Unknown.Count > 0) return ApiErrors.Conflict(context, "trash_changed", plan.Fingerprint);
|
||||
if (!host.CanRun(JobKind.EmptyTrash)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.EmptyTrash));
|
||||
var job = await host.Engine.EnqueueAsync(ArchiveJobs.EmptyTrash(archive.Current, plan), caller.Id, ct);
|
||||
// A request, not an outcome: the job still checks the plan when it runs and erases nothing if the trash changed.
|
||||
await audit.WriteAsync(caller, context, "trash_empty_requested", "job", job.Id.ToString(),
|
||||
$"{plan.Entries.Count} · {plan.Bytes} · {string.Join(", ", plan.Entries.Take(5).Select(e => e.Name))}");
|
||||
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
private static ArchiveAvailability Availability(ServerArchive archive) => ArchiveVolume.Probe(new ArchivePaths(archive.Root));
|
||||
|
||||
private static IResult Offline(HttpContext context) => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
||||
|
||||
private static IResult Mismatch(HttpContext context) => ApiErrors.Result(context, StatusCodes.Status422UnprocessableEntity, "trash_mismatch");
|
||||
|
||||
[GeneratedRegex("^(photos-)?[0-9a-f]{32}(-[0-9]{14}(-[0-9]{1,6})?)?$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex EntryName();
|
||||
}
|
||||
@@ -27,8 +27,9 @@ public static class UploadEndpoints
|
||||
(await service.GetStateAsync(caller, id, context.RequestAborted)).ToResult(context, s => Results.Json(s, ProtocolJson.Default.UploadState)));
|
||||
uploads.MapDelete("/{id:guid}", async (HttpContext context, Caller caller, Guid id, UploadService service) =>
|
||||
(await service.CancelAsync(caller, id, context.RequestAborted)).ToResult(context, _ => Results.NoContent()));
|
||||
uploads.MapPost("/{id:guid}/complete", async (HttpContext context, Caller caller, Guid id, UploadService service) =>
|
||||
(await service.CompleteAsync(caller, id)).ToResult(context, r => Results.Json(r, ProtocolJson.Default.CompleteUploadResponse)))
|
||||
// ?restore=true repeats the start's StartUploadRequest.Restore: a photo deleted from the sequence meanwhile is filed anyway.
|
||||
uploads.MapPost("/{id:guid}/complete", async (HttpContext context, Caller caller, Guid id, bool? restore, UploadService service) =>
|
||||
(await service.CompleteAsync(caller, id, restore == true)).ToResult(context, r => Results.Json(r, ProtocolJson.Default.CompleteUploadResponse)))
|
||||
.Requires(Permissions.Upload);
|
||||
uploads.MapPost("/cards", ReportCard).Requires(Permissions.Upload);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs,
|
||||
JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move, JobKind.Backup, JobKind.Cleanup,
|
||||
JobKind.EmptyTrash,
|
||||
];
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
|
||||
namespace Chronos.Server.Hosting;
|
||||
|
||||
@@ -8,6 +9,12 @@ namespace Chronos.Server.Hosting;
|
||||
/// Serves the admin panel from embedded resources named <c>admin/…</c> (no build step, single-file friendly),
|
||||
/// with strong ETags, conditional GET and SPA fallback to <c>index.html</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Every file, the modules included, is sent with <c>Cache-Control: no-cache</c>: the browser keeps it but asks again
|
||||
/// before each use, and an unchanged file costs a 304 without a body. The ETag is a hash of the content, so an upgrade
|
||||
/// changes the ETag of exactly the files it changed and a browser never runs new modules next to cached old ones (with
|
||||
/// <c>max-age</c> it could, until the cache expired).
|
||||
/// </remarks>
|
||||
public sealed class EmbeddedStaticFiles
|
||||
{
|
||||
private static readonly FrozenDictionary<string, string> ContentTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
@@ -55,9 +62,9 @@ public sealed class EmbeddedStaticFiles
|
||||
}
|
||||
var response = context.Response;
|
||||
response.Headers.ETag = file.ETag;
|
||||
response.Headers.CacheControl = path.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ? "no-cache" : "public, max-age=3600";
|
||||
response.Headers.CacheControl = "no-cache";
|
||||
response.Headers.XContentTypeOptions = "nosniff";
|
||||
if (context.Request.Headers.IfNoneMatch == file.ETag)
|
||||
if (NoneMatchHolds(context.Request.Headers.IfNoneMatch, file.ETag))
|
||||
{
|
||||
response.StatusCode = StatusCodes.Status304NotModified;
|
||||
return true;
|
||||
@@ -67,4 +74,23 @@ public sealed class EmbeddedStaticFiles
|
||||
if (!HttpMethods.IsHead(context.Request.Method)) await response.Body.WriteAsync(file.Content, context.RequestAborted);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether an <c>If-None-Match</c> header names <paramref name="etag"/>: <c>*</c>, or one of its entity tags under the
|
||||
/// weak comparison GET uses (RFC 9110 §13.1.2), so a tag a proxy marked <c>W/</c> still matches.
|
||||
/// </summary>
|
||||
internal static bool NoneMatchHolds(StringValues header, string etag)
|
||||
{
|
||||
foreach (var value in header)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value)) continue;
|
||||
foreach (var part in value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
if (part == "*") return true;
|
||||
var tag = part.StartsWith("W/", StringComparison.Ordinal) ? part[2..] : part;
|
||||
if (string.Equals(tag, etag, StringComparison.Ordinal)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -173,12 +173,14 @@ public static class ServerHost
|
||||
AuthEndpoints.Map(api);
|
||||
UserEndpoints.Map(api);
|
||||
SequenceEndpoints.Map(api);
|
||||
LibraryEndpoints.Map(api);
|
||||
FileEndpoints.Map(api);
|
||||
UploadEndpoints.Map(api);
|
||||
JobEndpoints.Map(api);
|
||||
ScheduleEndpoints.Map(api);
|
||||
NodeEndpoints.Map(api);
|
||||
ArchiveEndpoints.Map(api);
|
||||
TrashEndpoints.Map(api);
|
||||
AdminEndpoints.Map(api);
|
||||
DiagnosticsEndpoints.Map(api);
|
||||
EventEndpoints.Map(api);
|
||||
|
||||
@@ -35,7 +35,8 @@ internal sealed class ArchiveAssetLocator : IFrameAssetLocator
|
||||
{
|
||||
using var pack = ThumbPackReader.Open(paths.ThumbsPackPath);
|
||||
if (!pack.Entries.TryGetValue(frame.Index, out var entry) || entry.Offset + entry.Length > pack.Length) return null;
|
||||
if (frame.Sha256 is { Length: ThumbPack.HashLength * 2 } sha && !ThumbPack.IsFrom(entry.SourceHash, sha, SequenceFile(paths, frame), frame.Size)) return null;
|
||||
// A frame never hashed is told by its file name and size: after a renumbering its index may hold its neighbour's.
|
||||
if (!ThumbPack.IsFrom(entry.SourceHash, frame.Sha256, SequenceFile(paths, frame), frame.Size)) return null;
|
||||
return new AssetLocation(paths.ThumbsPackPath, entry.Offset, entry.Length, Jpeg);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,25 @@ public static class UploadRules
|
||||
return intact.FirstOrDefault(f => f.SequenceId == target) ?? intact.FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A name the archive scanner would never take as a photo (<c>ArchiveScanner</c>: hidden dot files, among them the
|
||||
/// AppleDouble <c>._</c> companions a Mac leaves on exFAT cards): a frame upload refuses it, so no client files what an
|
||||
/// import of the same folder would leave out.
|
||||
/// </summary>
|
||||
public static bool IsHiddenName(string fileName) => fileName.StartsWith('.');
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="target"/> tombstoned <paramref name="sha256"/> (owner review 2, R6): a photo deleted from that
|
||||
/// sequence (or replaced by a converted file) that an upload must not bring back. The upload is answered as
|
||||
/// <c>alreadyExists</c> without a frame, so a client neither sends the file nor treats the answer as a failure. A
|
||||
/// tombstone of content a frame of the target still holds (<paramref name="copies"/>: another copy of a duplicate, a
|
||||
/// file put back by hand) is stale and refuses nothing, so such a frame can still be repaired.
|
||||
/// </summary>
|
||||
public static async Task<bool> RemovedFromTargetAsync(ChronosDatabase db, string sha256, Guid? target, IReadOnlyCollection<Frame> copies,
|
||||
CancellationToken cancellationToken) =>
|
||||
target is { } sequence && !copies.Any(f => f.SequenceId == sequence)
|
||||
&& await db.FrameRemovals.IsRemovedAsync(sequence, sha256, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>
|
||||
/// The sequence an upload files into: its own, or the one its session key names (the user's own key without one);
|
||||
/// null while that sequence does not exist yet.
|
||||
|
||||
@@ -49,7 +49,8 @@ public sealed class UploadService(
|
||||
|
||||
public async Task<Outcome<StartUploadResponse>> StartAsync(Caller caller, StartUploadRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (UploadRules.SafeFileName(request.FileName) is not { } fileName) return Fail<StartUploadResponse>(400, "invalid_file_name");
|
||||
if (UploadRules.SafeFileName(request.FileName) is not { } fileName || UploadRules.IsHiddenName(fileName))
|
||||
return Fail<StartUploadResponse>(400, "invalid_file_name");
|
||||
if (!UploadRules.IsSha256(request.Sha256)) return Fail<StartUploadResponse>(400, "invalid_hash");
|
||||
if (request.Size <= 0) return Fail<StartUploadResponse>(400, "bad_request", "size");
|
||||
if (request.Size > options.MaxUploadBytes) return Fail<StartUploadResponse>(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture));
|
||||
@@ -60,9 +61,16 @@ public sealed class UploadService(
|
||||
var sha = request.Sha256.ToLowerInvariant();
|
||||
var sessionKey = string.IsNullOrWhiteSpace(request.SessionKey) ? null : request.SessionKey.Trim();
|
||||
var copies = await db.Frames.FindBySha256Async(sha, cancellationToken);
|
||||
var target = copies.Count == 0 ? null : await UploadRules.TargetAsync(db, archive.Id, request.SequenceId, sessionKey, caller.Id, cancellationToken);
|
||||
// Only a copy that is still whole stands for the upload: a client may delete its file on this answer.
|
||||
if (UploadRules.StandIn(archive.Root, copies, target) is { } known)
|
||||
var target = await UploadRules.TargetAsync(db, archive.Id, request.SequenceId, sessionKey, caller.Id, cancellationToken);
|
||||
// A photo deleted from the target sequence is not filed into it again: an old client syncing a copy that still holds
|
||||
// it, or a watch folder sending it again, hears that the server has it (owner review 2, R6). A restore from the trash
|
||||
// brings it back while the trash holds it; a user who uploads it again on purpose asks with Restore, and filing it
|
||||
// drops its tombstone.
|
||||
var removed = await UploadRules.RemovedFromTargetAsync(db, sha, target, copies, cancellationToken);
|
||||
if (removed && !request.Restore) return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null);
|
||||
// Only a copy that is still whole stands for the upload: a client may delete its file on this answer. A photo
|
||||
// brought back is filed into its sequence, whatever other sequences hold it.
|
||||
if (UploadRules.StandIn(archive.Root, removed ? [] : copies, target) is { } known)
|
||||
return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, known.Id);
|
||||
|
||||
var resumable = await db.Uploads.FindReceivingAsync(caller.Id, sha, cancellationToken);
|
||||
@@ -154,9 +162,11 @@ public sealed class UploadService(
|
||||
|
||||
/// <summary>
|
||||
/// Verifies and commits a frame upload. Completing an already committed upload answers its frame again, so a client
|
||||
/// may retry a completion whose response it lost. Runs to the end even if the client disconnects.
|
||||
/// may retry a completion whose response it lost. Runs to the end even if the client disconnects. A photo deleted from
|
||||
/// the target sequence since the upload started is not filed (409 <see cref="UploadErrors.PhotoRemoved"/>, the upload
|
||||
/// cancelled) unless <paramref name="restore"/> repeats the start's <see cref="StartUploadRequest.Restore"/>.
|
||||
/// </summary>
|
||||
public async Task<Outcome<CompleteUploadResponse>> CompleteAsync(Caller caller, Guid id)
|
||||
public async Task<Outcome<CompleteUploadResponse>> CompleteAsync(Caller caller, Guid id, bool restore = false)
|
||||
{
|
||||
var stopping = lifetime.ApplicationStopping;
|
||||
var upload = await db.Uploads.GetAsync(id, stopping);
|
||||
@@ -170,6 +180,10 @@ public sealed class UploadService(
|
||||
if (!ArchiveHasRoom(upload)) return Fail<CompleteUploadResponse>(507, "insufficient_storage");
|
||||
if (!await db.Uploads.TryTransitionAsync(id, UploadState.Receiving, UploadState.Committing, cancellationToken: stopping))
|
||||
return Fail<CompleteUploadResponse>(409, "upload_state");
|
||||
// Deleted from the target while its bytes were on the way (the start checked before): the upload does not bring the
|
||||
// photo back (owner review 2, R6). Asked here to answer early; the ingest asks again under the sequence's lease, which
|
||||
// a deletion takes, so one that lands after this check is caught there.
|
||||
if (!restore && await RemovedFromTargetAsync(upload, stopping)) return await RemovedAsync(upload);
|
||||
|
||||
var user = await db.Users.GetAsync(caller.Id, stopping);
|
||||
if (user is { QuotaBytes: > 0 } && user.UsedBytes + upload.Size > user.QuotaBytes && !await HeldByTargetAsync(upload, stopping))
|
||||
@@ -194,7 +208,13 @@ public sealed class UploadService(
|
||||
upload.Size,
|
||||
upload.Sha256,
|
||||
upload.CapturedAt,
|
||||
caller.Id), stopping);
|
||||
caller.Id,
|
||||
RefuseRemoved: !restore), stopping);
|
||||
}
|
||||
catch (PhotoRemovedException)
|
||||
{
|
||||
UploadStore.TryDelete(staged);
|
||||
return await RemovedAsync(upload);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
@@ -301,6 +321,23 @@ public sealed class UploadService(
|
||||
return copies.Any(f => f.SequenceId == target);
|
||||
}
|
||||
|
||||
/// <summary>An upload whose photo was deleted from its sequence meanwhile: cancelled, its part file gone, 409 <see cref="UploadErrors.PhotoRemoved"/>.</summary>
|
||||
private async Task<Outcome<CompleteUploadResponse>> RemovedAsync(Upload upload)
|
||||
{
|
||||
logger.LogInformation("Upload {Upload} ({File}) not filed: the photo was deleted from its sequence meanwhile", upload.Id, upload.FileName);
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Cancelled, cancellationToken: CancellationToken.None);
|
||||
store.Delete(upload.Id);
|
||||
return Fail<CompleteUploadResponse>(409, UploadErrors.PhotoRemoved);
|
||||
}
|
||||
|
||||
/// <summary>The sequence the upload files into tombstoned its content (<see cref="UploadRules.RemovedFromTargetAsync"/>).</summary>
|
||||
private async Task<bool> RemovedFromTargetAsync(Upload upload, CancellationToken cancellationToken)
|
||||
{
|
||||
var target = await UploadRules.TargetAsync(db, archive.Id, upload.SequenceId, upload.SessionKey, upload.UserId, cancellationToken);
|
||||
return target is not null && await UploadRules.RemovedFromTargetAsync(db, upload.Sha256, target,
|
||||
await db.Frames.FindBySha256Async(upload.Sha256, cancellationToken), cancellationToken);
|
||||
}
|
||||
|
||||
private StartUploadResponse Started(Upload upload) =>
|
||||
new(upload.Id, upload.ChunkSize, UploadRules.ReceivedChunks(upload), AlreadyExists: false, FrameId: null);
|
||||
|
||||
|
||||
Reference in new issue
Block a user